diff --git a/.github/ISSUE_TEMPLATE/Bug_report.md b/.github/ISSUE_TEMPLATE/Bug_report.md index fe94434490c..5711c8f950d 100644 --- a/.github/ISSUE_TEMPLATE/Bug_report.md +++ b/.github/ISSUE_TEMPLATE/Bug_report.md @@ -16,7 +16,7 @@ Please fill in the *entire* template below. --> -**TypeScript Version:** 3.1.0-dev.201xxxxx +**TypeScript Version:** 3.3.0-dev.201xxxxx **Search Terms:** diff --git a/.github/ISSUE_TEMPLATE/Feature_request.md b/.github/ISSUE_TEMPLATE/Feature_request.md index bddacd1f2fc..f40965f503a 100644 --- a/.github/ISSUE_TEMPLATE/Feature_request.md +++ b/.github/ISSUE_TEMPLATE/Feature_request.md @@ -32,8 +32,10 @@ What shortcomings exist with current approaches? ## Checklist My suggestion meets these guidelines: -* [ ] This wouldn't be a breaking change in existing TypeScript / JavaScript code + +* [ ] This wouldn't be a breaking change in existing TypeScript/JavaScript code * [ ] This wouldn't change the runtime behavior of existing JavaScript code * [ ] This could be implemented without emitting different JS based on the types of the expressions -* [ ] This isn't a runtime feature (e.g. new expression-level syntax) +* [ ] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.) +* [ ] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals). diff --git a/.travis.yml b/.travis.yml index 9479fffe763..0f720b7375e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,8 @@ language: node_js node_js: - - 'stable' - - '8' + - 'node' + - '10' - '6' sudo: false @@ -16,10 +16,7 @@ matrix: branches: only: - master - - release-2.7 - - release-2.8 - - release-2.9 - - release-3.0 + - /^release-.*/ install: - npm uninstall typescript --no-save diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000000..65c8a42b8d2 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1 @@ +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 81ffe06e8e2..683c47817b7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,7 +72,7 @@ Your pull request should: * Requests need not be a single commit, but should be a linear sequence of commits (i.e. no merge commits in your PR) * It is desirable, but not necessary, for the tests to pass at each commit * Have clear commit messages - * e.g. "Refactor feature", "Fix issue", "Add tests for issue" + * e.g. "Minor refactor in goToTypeDefinition", "Fix iterated type in for-await-of", "Add test for preserveWatchOutput on command line" * Include adequate tests * At least one test should fail in the absence of your non-test code changes. If your PR does not match this criteria, please specify why * Tests should include reasonable permutations of the target fix/change @@ -82,19 +82,26 @@ Your pull request should: * 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) -Library files in `built/local/` are updated by running -```Shell +There are three relevant locations to be aware of when it comes to TypeScript's library declaration files: + +* `src/lib`: the location of the sources themselves. +* `lib`: the location of the last-known-good (LKG) versions of the files which are updated periodically. +* `built/local`: the build output location, including where `src/lib` files will be copied to. + +Any changes should be made to [src/lib](https://github.com/Microsoft/TypeScript/tree/master/src/lib). **Most** of these files can be updated by hand, with the exception of any generated files (see below). + +Library files in `built/local/` are updated automatically by running the standard build task: + +```sh jake ``` -The files in `lib/` are used to bootstrap compilation and usually do not need to be updated. +The files in `lib/` are used to bootstrap compilation and usually **should not** be updated unless publishing a new version or updating the LKG. -#### `src/lib/dom.generated.d.ts` and `src/lib/webworker.generated.d.ts` +### Modifying generated library files -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 +The files `src/lib/dom.generated.d.ts` and `src/lib/webworker.generated.d.ts` both represent type declarations for the DOM and are auto-generated. To make any modifications to them, you will have to direct changes to https://github.com/Microsoft/TSJS-lib-generator ## Running the Tests @@ -104,7 +111,7 @@ To run all tests, invoke the `runtests-parallel` target using jake: jake runtests-parallel ``` -This run will all tests; to run only a specific subset of tests, use: +This will run all tests; to run only a specific subset of tests, use: ```Shell jake runtests tests= @@ -137,10 +144,10 @@ You can specify which browser to use for debugging. Currently Chrome and IE are jake runtests-browser tests=2dArrays browser=chrome ``` -You can debug with VS Code or Node instead with `jake runtests debug=true`: +You can debug with VS Code or Node instead with `jake runtests inspect=true`: ```Shell -jake runtests tests=2dArrays debug=true +jake runtests tests=2dArrays inspect=true ``` ## Adding a Test @@ -153,7 +160,7 @@ The supported names and values are the same as those supported in the compiler i They are useful for tests relating to modules. See below for examples. -**Note** that if you have a test corresponding to a specific spec compliance item, you can place it in `tests\cases\conformance` in an appropriately-named subfolder. +**Note** that if you have a test corresponding to a specific spec compliance item, you can place it in `tests\cases\conformance` in an appropriately-named subfolder. **Note** that filenames here must be distinct from all other compiler testcase names, so you may have to work a bit to find a unique name if it's something common. ### Tests for multiple files @@ -194,6 +201,6 @@ to establish the new baselines as the desired behavior. This will change the fil ## Localization All strings the user may see are stored in [`diagnosticMessages.json`](./src/compiler/diagnosticMessages.json). -If you make changes to it, run `jake generate-diagnostics` to push them to the `Diagnostic` interface in [`diagnosticInformationMap.generated.ts`](./src/compiler/diagnosticInformationMap.generated.ts). +If you make changes to it, run `jake generate-diagnostics` to push them to the `Diagnostic` interface in `diagnosticInformationMap.generated.ts`. See [coding guidelines on diagnostic messages](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#diagnostic-messages). diff --git a/Gulpfile.js b/Gulpfile.js index 704fbba4447..3616e25ee80 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -26,7 +26,7 @@ const exec = require("./scripts/build/exec"); const browserify = require("./scripts/build/browserify"); const prepend = require("./scripts/build/prepend"); const { removeSourceMaps } = require("./scripts/build/sourcemaps"); -const { CancellationTokenSource, CancelError, delay, Semaphore } = require("prex"); +const { CancellationTokenSource, CancelError, delay, Semaphore } = require("prex"); const { libraryTargets, generateLibs } = require("./scripts/build/lib"); const { runConsoleTests, cleanTestDirs, writeTestConfigFile, refBaseline, localBaseline, refRwcBaseline, localRwcBaseline } = require("./scripts/build/tests"); @@ -117,7 +117,8 @@ const generatedLCGFile = "built/local/enu/diagnosticMessages.generated.json.lcg" * 2. 'src\compiler\diagnosticMessages.generated.json' => 'built\local\ENU\diagnosticMessages.generated.json.lcg' * generate the lcg file (source of messages to localize) from the diagnosticMessages.generated.json */ -const localizationTargets = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-BR", "ru", "tr", "zh-CN", "zh-TW"] +const localizationTargets = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"] + .map(f => f.toLowerCase()) .map(f => `built/local/${f}/diagnosticMessages.generated.json`) .concat(generatedLCGFile); @@ -487,29 +488,28 @@ gulp.task( "Runs 'local'", ["local"]); -gulp.task( - "watch-diagnostics", - /*help*/ false, - [processDiagnosticMessagesJs], - () => gulp.watch([diagnosticMessagesJson], [diagnosticInformationMapTs, builtGeneratedDiagnosticMessagesJson])); - gulp.task( "watch-lib", /*help*/ false, () => gulp.watch(["src/lib/**/*"], ["lib"])); +const watchTscPatterns = [ + "src/tsconfig-base.json", + "src/lib/**/*", + "src/compiler/**/*", + "src/tsc/**/*", +]; gulp.task( "watch-tsc", /*help*/ false, - ["watch-diagnostics", "watch-lib"].concat(useCompilerDeps), - () => project.watch(tscProject, { typescript: useCompiler })); + useCompilerDeps, + () => gulp.watch(watchTscPatterns, ["tsc"])); const watchServicesPatterns = [ "src/compiler/**/*", "src/jsTypings/**/*", "src/services/**/*" ]; - gulp.task( "watch-services", /*help*/ false, @@ -521,39 +521,49 @@ const watchLsslPatterns = [ "src/server/**/*", "src/tsserver/tsconfig.json" ]; - gulp.task( "watch-lssl", /*help*/ false, () => gulp.watch(watchLsslPatterns, ["lssl"])); -gulp.task( - "watch-server", - /*help*/ false, - ["watch-diagnostics", "watch-lib"].concat(useCompilerDeps), - () => project.watch(tsserverProject, { typescript: useCompiler })); - -gulp.task( - "watch-runner", - /*help*/ false, - useCompilerDeps, - () => project.watch(testRunnerProject, { typescript: useCompiler })); - +const watchLocalPatterns = [ + "src/tsconfig-base.json", + "src/lib/**/*", + "src/compiler/**/*", + "src/tsc/**/*", + "src/services/**/*", + "src/jsTyping/**/*", + "src/server/**/*", + "src/tsserver/**/*", + "src/typingsInstallerCore/**/*", + "src/harness/**/*", + "src/testRunner/**/*", +]; gulp.task( "watch-local", "Watches for changes to projects in src/ (but does not execute tests).", - ["watch-lib", "watch-tsc", "watch-services", "watch-server", "watch-runner", "watch-lssl"]); + () => gulp.watch(watchLocalPatterns, "local")); +const watchPatterns = [ + "src/tsconfig-base.json", + "src/lib/**/*", + "src/compiler/**/*", + "src/services/**/*", + "src/jsTyping/**/*", + "src/server/**/*", + "src/tsserver/**/*", + "src/typingsInstallerCore/**/*", + "src/harness/**/*", + "src/testRunner/**/*", +]; gulp.task( "watch", "Watches for changes to the build inputs for built/local/run.js, then runs tests.", - ["build-rules", "watch-runner", "watch-services", "watch-lssl"], + ["build-rules"], () => { const sem = new Semaphore(1); - gulp.watch([runJs, typescriptDts, tsserverlibraryDts], () => { - runTests(); - }); + gulp.watch(watchPatterns, () => { runTests(); }); // NOTE: gulp.watch is far too slow when watching tests/cases/**/* as it first enumerates *every* file const testFilePattern = /(\.ts|[\\/]tsconfig\.json)$/; diff --git a/Jakefile.js b/Jakefile.js index 6ecb67ab9ce..1413230c079 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -24,8 +24,6 @@ else if (process.env.PATH !== undefined) { const host = process.env.TYPESCRIPT_HOST || process.env.host || "node"; -const locales = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-BR", "ru", "tr", "zh-CN", "zh-TW"]; - const defaultTestTimeout = 40000; let useDebugMode = true; @@ -147,14 +145,14 @@ task(TaskNames.local, [ task("default", [TaskNames.local]); const RunTestsPrereqs = [TaskNames.lib, Paths.servicesDefinitionFile, Paths.typescriptDefinitionFile, Paths.tsserverLibraryDefinitionFile]; -desc("Runs all the tests in parallel using the built run.js file. Optional arguments are: t[ests]=category1|category2|... d[ebug]=true."); +desc("Runs all the tests in parallel using the built run.js file. Optional arguments are: t[ests]=category1|category2|... i[nspect]=true."); task(TaskNames.runtestsParallel, RunTestsPrereqs, function () { tsbuild([ConfigFileFor.runjs], true, () => { runConsoleTests("min", /*parallel*/ true); }); }, { async: true }); -desc("Runs all the tests in parallel using the built run.js file. Optional arguments are: t[ests]=category1|category2|... d[ebug]=true."); +desc("Runs all the tests in parallel using the built run.js file. Optional arguments are: t[ests]=category1|category2|... i[nspect]=true."); task(TaskNames.runtests, RunTestsPrereqs, function () { tsbuild([ConfigFileFor.runjs], true, () => { runConsoleTests('mocha-fivemat-progress-reporter', /*runInParallel*/ false); @@ -520,7 +518,6 @@ function runConsoleTests(defaultReporter, runInParallel) { } let testTimeout = process.env.timeout || defaultTestTimeout; - const debug = process.env.debug || process.env["debug-brk"] || process.env.d; const inspect = process.env.inspect || process.env["inspect-brk"] || process.env.i; const runners = process.env.runners || process.env.runner || process.env.ru; const tests = process.env.test || process.env.tests || process.env.t; @@ -710,19 +707,6 @@ const Travis = { } }; -function buildLocalizedTargets() { - /** - * The localization target produces the two following transformations: - * 1. 'src\loc\lcl\\diagnosticMessages.generated.json.lcl' => 'built\local\\diagnosticMessages.generated.json' - * convert localized resources into a .json file the compiler can understand - * 2. 'src\compiler\diagnosticMessages.generated.json' => 'built\local\ENU\diagnosticMessages.generated.json.lcg' - * generate the lcg file (source of messages to localize) from the diagnosticMessages.generated.json - */ - const localizationTargets = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"] - .map(f => path.join(Paths.builtLocal,f)) - .concat(path.dirname(Paths.generatedLCGFile)); -} - function toNs(diff) { return diff[0] * 1e9 + diff[1]; } diff --git a/README.md b/README.md index ede02510dca..a7222668ada 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob * [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in. * Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls). * Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript). -* Join the [#typescript](https://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. +* Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter. * [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). * Read the language specification ([docx](https://github.com/Microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.docx?raw=true), [pdf](https://github.com/Microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.pdf?raw=true), [md](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md)). @@ -61,7 +61,7 @@ Change to the TypeScript directory: cd TypeScript ``` -Install Jake tools and dev dependencies: +Install [Jake](http://jakejs.com/) tools and dev dependencies: ```bash npm install -g jake diff --git a/completionAtDottedNamespace.ts b/completionAtDottedNamespace.ts new file mode 100644 index 00000000000..cbf16435a91 --- /dev/null +++ b/completionAtDottedNamespace.ts @@ -0,0 +1,5 @@ +/// + +////namespace wwer./**/w + +verify.completions({ marker: "", exact: [], isNewIdentifierLocation: true }); diff --git a/doc/spec.md b/doc/spec.md index ed99088443f..c6dd8cb4d06 100644 --- a/doc/spec.md +++ b/doc/spec.md @@ -286,7 +286,7 @@ function f(s) { } ``` -In the JavaScript output, all type annotations have been erased. In general, TypeScript erases all type information before emiting JavaScript. +In the JavaScript output, all type annotations have been erased. In general, TypeScript erases all type information before emitting JavaScript. ## 1.1 Ambient Declarations diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 795136609dc..f7bf53b6755 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -938,7 +938,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Der Typ iterierter Elemente eines \"yield*\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Der Typ eines \"yield\"-Operanden in einem asynchronen Generator muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_parameter_0_has_a_circular_constraint_2313": "Der Typparameter \"{0}\" weist eine zirkuläre Einschränkung auf.", - "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" weist einen zirkulären Standard auf.", + "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" besitzt einen zirkulären Standardwert.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Der Typparameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Der Typparameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Der Typparameter \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 2c93bcf114d..61eb41991c4 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -51,6 +51,12 @@ + + + + + + @@ -63,12 +69,6 @@ - - - - - - @@ -135,9 +135,9 @@ - + - + @@ -693,6 +693,18 @@ + + + + + + + + + + + + @@ -705,12 +717,24 @@ + + + + + + + + + + + + @@ -741,6 +765,18 @@ + + + + + + + + + + + + @@ -861,9 +897,21 @@ - + - + + + + + + + + + + + + + @@ -1053,9 +1101,9 @@ - + - + @@ -1095,6 +1143,12 @@ + + + + + + @@ -1179,9 +1233,9 @@ - + - + @@ -1203,6 +1257,12 @@ + + + + + + @@ -1233,6 +1293,12 @@ + + + + + + @@ -1275,9 +1341,15 @@ - + - + + + + + + + @@ -1401,6 +1473,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2001,6 +2103,24 @@ + + + {1}'?]]> + + + + + + + + + + + + + + + @@ -2259,6 +2379,12 @@ + + + + + + @@ -2349,6 +2475,12 @@ + + + + + + @@ -2421,9 +2553,9 @@ - + - + @@ -2691,12 +2823,24 @@ + + + + + + + + + + + + @@ -2775,12 +2919,30 @@ + + + + + + + + + + + + + + + + + + @@ -2829,12 +2991,6 @@ - - - - - - @@ -3225,6 +3381,12 @@ + + + + + + @@ -3255,6 +3417,12 @@ + + + + + + @@ -3483,6 +3651,12 @@ + + + + + + @@ -3705,6 +3879,12 @@ + + + + + + @@ -3843,6 +4023,12 @@ + + + + + + @@ -3909,9 +4095,9 @@ - + - + @@ -3999,6 +4185,12 @@ + + + + + + @@ -4137,6 +4329,12 @@ + + + + + + @@ -4203,6 +4401,12 @@ + + + + + + @@ -4317,6 +4521,18 @@ + + + + + + + + + + + + @@ -4359,6 +4575,12 @@ + + + + + + @@ -4773,6 +4995,12 @@ + + + + + + @@ -5025,12 +5253,6 @@ - - - - - - @@ -5313,6 +5535,12 @@ + + + + + + @@ -5349,6 +5577,12 @@ + + + + + + @@ -5391,9 +5625,9 @@ - + - + @@ -5481,9 +5715,9 @@ - + - + @@ -5589,6 +5823,12 @@ + + + + + + @@ -5679,6 +5919,18 @@ + + + + + + + + + + + + @@ -6051,6 +6303,12 @@ + + + + + + @@ -6141,6 +6399,12 @@ + + + + + + @@ -6165,6 +6429,18 @@ + + + + + + + + + + + + @@ -6207,6 +6483,12 @@ + + + + + + @@ -6243,6 +6525,12 @@ + + + + + + @@ -6393,6 +6681,12 @@ + + + + + + @@ -6657,12 +6951,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -6831,6 +7149,18 @@ + + + + + + + + + + + + diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 0e0e31a2b11..52840b1208e 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -328,7 +328,7 @@ "Do_not_emit_outputs_if_any_errors_were_reported_6008": "No emitir salidas si se informa de algún error.", "Do_not_emit_use_strict_directives_in_module_output_6112": "No emitir directivas 'use strict' en la salida del módulo.", "Do_not_erase_const_enum_declarations_in_generated_code_6007": "No borrar las declaraciones de enumeración const en el código generado.", - "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones auxiliares personalizadas como \"__extends\" en la salida compilada.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones del asistente personalizadas como \"__extends\" en la salida compilada.", "Do_not_include_the_default_library_file_lib_d_ts_6158": "No incluir el archivo de biblioteca predeterminado (lib.d.ts).", "Do_not_report_errors_on_unreachable_code_6077": "No notificar los errores del código inaccesible.", "Do_not_report_errors_on_unused_labels_6074": "No notificar los errores de las etiquetas no usadas.", @@ -477,7 +477,7 @@ "Import_declaration_0_is_using_private_name_1_4000": "La declaración de importación '{0}' usa el nombre privado '{1}'.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La declaración de importación está en conflicto con la declaración local de \"{0}\".", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Las declaraciones de importación de un espacio de nombres no pueden hacer referencia a un módulo.", - "Import_emit_helpers_from_tslib_6139": "Importe elementos auxiliares de emisión de \"tslib\".", + "Import_emit_helpers_from_tslib_6139": "Importe asistentes de emisión de \"tslib\".", "Import_may_be_converted_to_a_default_import_80003": "La importación puede convertirse a una importación predeterminada.", "Import_name_cannot_be_0_2438": "El nombre de importación no puede ser \"{0}\".", "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La declaración de importación o exportación de una declaración de módulo de ambiente no puede hacer referencia al módulo a través de su nombre relativo.", @@ -892,8 +892,8 @@ "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La declaración de variable de una instrucción \"for...of\" no puede tener un inicializador.", "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "No se admite la instrucción 'with'. Todos los símbolos de un bloque 'with' tendrán el tipo 'any'.", "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Esta función de constructor puede convertirse en una declaración de clase.", - "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere una aplicación auxiliar importada, pero no se puede encontrar el módulo \"{0}\".", - "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Esta sintaxis requiere una aplicación auxiliar importada denominada \"{1}\", pero el módulo \"{0}\" no tiene el miembro exportado \"{1}\".", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere un asistente importado, pero no se puede encontrar el módulo \"{0}\".", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Esta sintaxis requiere un asistente importado denominado \"{1}\", pero el módulo \"{0}\" no tiene el miembro exportado \"{1}\".", "Trailing_comma_not_allowed_1009": "No se permite la coma final.", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilar cada archivo como un módulo aparte (parecido a \"ts.transpileModule\").", "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Pruebe \"npm install @types/{0}\" si existe o agregue un nuevo archivo de declaración (.d.ts) que incluya \"declare module '{0}';\"", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index c5d6cf984db..a1b1320115a 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -3,7 +3,7 @@ "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "'{0}' 한정자는 인터페이스 선언에서 사용할 수 없습니다.", "A_0_parameter_must_be_the_first_parameter_2680": "'{0}' 매개 변수는 첫 번째 매개 변수여야 합니다.", "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "바인딩 패턴 매개 변수는 구현 서명에서 선택 사항이 될 수 없습니다.", - "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' 문은 이 문을 둘러싼 반복 문 또는 switch 문 내에서만 사용할 수 있습니다.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' 문은 이 문을 둘러싼 반복문 또는 switch 문 내에서만 사용할 수 있습니다.", "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "'break' 문은 이 문을 둘러싼 문의 레이블로만 이동할 수 있습니다.", "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "클래스는 선택적 형식 인수가 포함된 식별자/정규화된 이름만 구현할 수 있습니다.", "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "'default' 한정자를 사용하지 않는 클래스 선언에는 이름이 있어야 합니다.", @@ -23,8 +23,8 @@ "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "앰비언트 컨텍스트의 'const' 이니셜라이저는 문자열 또는 숫자 리터럴이어야 합니다.", "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "생성자는 해당 클래스가 'null'을 확장하는 경우 'super' 호출을 포함할 수 없습니다.", "A_constructor_cannot_have_a_this_parameter_2681": "생성자에는 'this' 매개 변수를 사용할 수 없습니다.", - "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' 문은 이 문을 둘러싼 반복 문 내에서만 사용할 수 있습니다.", - "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' 문은 이 문을 둘러싼 반복 문의 레이블로만 이동할 수 있습니다.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' 문은 이 문을 둘러싼 반복문 내에서만 사용할 수 있습니다.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' 문은 이 문을 둘러싼 반복문의 레이블로만 이동할 수 있습니다.", "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "'declare' 한정자는 이미 존재하는 앰비언트 컨텍스트에서 사용할 수 없습니다.", "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "'declare' 한정자는 .d.ts 파일의 최상위 선언에 필요합니다.", "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "데코레이터는 오버로드가 아니라 메서드 구현만 데코레이팅할 수 있습니다.", @@ -68,7 +68,7 @@ "A_rest_parameter_cannot_have_an_initializer_1048": "rest 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 매개 변수는 매개 변수 목록 마지막에 있어야 합니다.", "A_rest_parameter_must_be_of_an_array_type_2370": "rest 매개 변수는 배열 형식이어야 합니다.", - "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest 매개 변수 또는 바인딩 패턴에 후행 쉼표를 사용할 수 없습니다.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest 매개 변수 또는 바인딩 패턴에 후행 쉼표가 없을 수 있습니다.", "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' 문은 함수 본문 내에서만 사용할 수 있습니다.", "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "가져오기를 'baseUrl'에 상대적인 조회 위치로 다시 매핑하는 일련의 항목입니다.", "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' 접근자에는 반환 형식 주석을 사용할 수 없습니다.", @@ -232,7 +232,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null'이거나 '정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", - "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' 집합이 없기 때문에 '{0}' 프로젝트를 추가할 수 없습니다.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' 프로젝트는 'outFile'이 설정되어 있지 않기 때문에 앞에 추가할 수 없습니다.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' 플래그가 제공된 경우 형식을 다시 내보낼 수 없습니다.", "Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.", @@ -274,7 +274,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "구성 파일에 대한 경로 또는 'tsconfig.json'이 포함된 폴더에 대한 경로를 고려하여 프로젝트를 컴파일합니다.", "Compiler_option_0_expects_an_argument_6044": "컴파일러 옵션 '{0}'에는 인수가 필요합니다.", "Compiler_option_0_requires_a_value_of_type_1_5024": "컴파일러 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", - "Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 사용하지 않도록 설정할 수 없습니다.", + "Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 비활성화할 수 없습니다.", "Computed_property_names_are_not_allowed_in_enums_1164": "컴퓨팅된 속성 이름은 열거형에 사용할 수 없습니다.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "계산된 값은 문자열 값 멤버가 포함된 열거형에서 허용되지 않습니다.", "Concatenate_and_emit_output_to_single_file_6001": "출력을 연결하고 단일 파일로 내보냅니다.", @@ -445,7 +445,7 @@ "Function_overload_must_be_static_2387": "함수 오버로드는 정적이어야 합니다.", "Function_overload_must_not_be_static_2388": "함수 오버로드는 정적이 아니어야 합니다.", "Generate_get_and_set_accessors_95046": "'get' 및 'set' 접근자 생성", - "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "해당하는 각 '.d.ts' 파일의 sourcemap을 생성합니다.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "해당하는 각 '.d.ts' 파일에 sourcemap을 생성합니다.", "Generates_corresponding_d_ts_file_6002": "해당 '.d.ts' 파일을 생성합니다.", "Generates_corresponding_map_file_6043": "해당 '.map' 파일을 생성합니다.", "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "생성기는 값을 생성하지 않으므로 암시적으로 '{0}' 형식입니다. 반환 형식을 제공하세요.", @@ -677,13 +677,13 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.", "Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.", "Print_this_message_6017": "이 메시지를 출력합니다.", - "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{1}' 종속성에 오류가 있기 때문에 '{0}' 프로젝트를 빌드할 수 없습니다.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{0}' 프로젝트는 '{1}' 종속성에 오류가 있기 때문에 빌드할 수 없습니다.", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "'{1}' 종속성이 최신 상태가 아니기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "가장 오래된 출력 '{1}'이(가) 최신 입력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "'{1}' 출력 파일이 존재하지 않기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_up_to_date_6361": "'{0}' 프로젝트가 최신 상태입니다.", "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "최신 입력 '{1}'이(가) 가장 오래된 출력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태입니다.", - "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "종속성의 .d.ts 파일이 있기 때문에 '{0}' 프로젝트가 최신 상태입니다.", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "'{0}' 프로젝트는 종속성에 .d.ts 파일이 있는 최신 상태입니다.", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "프로젝트 참조는 순환 그래프를 형성할 수 없습니다. 순환이 발견되었습니다. {0}", "Projects_in_this_build_Colon_0_6355": "이 빌드의 프로젝트: {0}", "Projects_to_reference_6300": "참조할 프로젝트", @@ -803,7 +803,7 @@ "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "빌드될 항목 표시(또는 '--clean'으로 지정된 경우 삭제될 항목 표시)", "Signature_0_must_be_a_type_predicate_1224": "'{0}' 시그니처는 형식 조건자여야 합니다.", "Skip_type_checking_of_declaration_files_6012": "선언 파일 형식 검사를 건너뜁니다.", - "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "'{1}' 종속성에 오류가 있기 때문에 '{0}' 프로젝트 빌드를 건너뜁니다.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "'{0}' 프로젝트의 빌드는 '{1}' 종속성에 오류가 있기 때문에 건너뜁니다.", "Skipping_clean_because_not_all_projects_could_be_located_6371": "일부 프로젝트를 찾을 수 없으므로 정리를 건너뛰는 중입니다.", "Source_Map_Options_6175": "소스 맵 옵션", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "특수화된 오버로드 시그니처는 특수화되지 않은 서명에 할당할 수 없습니다.", @@ -1039,7 +1039,7 @@ "const_declarations_must_be_initialized_1155": "'const' 선언은 초기화해야 합니다.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 열거형 멤버 이니셜라이저가 무한 값에 대해 평가되었습니다.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 열거형 멤버 이니셜라이저가 허용되지 않은 'NaN' 값에 대해 평가되었습니다.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성 또는 인덱스 액세스 식 또는 내보내기 할당 또는 가져오기 선언의 오른쪽 또는 형식 쿼리에서만 사용할 수 있습니다.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성이나 인덱스 액세스 식, 또는 내보내기 할당이나 가져오기 선언의 오른쪽, 또는 형식 쿼리에서만 사용할 수 있습니다.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "strict 모드에서는 식별자에 대해 'delete'를 호출할 수 없습니다.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "이 항목 삭제 - '{0}' 프로젝트는 이전에 빌드되었기 때문에 최신 상태입니다.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum 선언'은 .ts 파일에서만 사용할 수 있습니다.", diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index f08e5d55677..464dea83926 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -162,6 +162,7 @@ interface BiquadFilterOptions extends AudioNodeOptions { } interface BlobPropertyBag { + endings?: EndingType; type?: string; } @@ -220,11 +221,12 @@ interface ComputedEffectTiming extends EffectTiming { progress?: number | null; } -interface ComputedKeyframe extends Record { - composite?: CompositeOperation | null; - computedOffset?: number; - easing?: string; - offset?: number | null; +interface ComputedKeyframe { + composite: CompositeOperationOrAuto; + computedOffset: number; + easing: string; + offset: number | null; + [property: string]: string | number | null | undefined; } interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { @@ -586,10 +588,11 @@ interface KeyboardEventInit extends EventModifierInit { repeat?: boolean; } -interface Keyframe extends Record { - composite?: CompositeOperation | null; +interface Keyframe { + composite?: CompositeOperationOrAuto; easing?: string; offset?: number | null; + [property: string]: string | number | null | undefined; } interface KeyframeAnimationOptions extends KeyframeEffectOptions { @@ -907,6 +910,12 @@ interface PeriodicWaveOptions extends PeriodicWaveConstraints { real?: number[] | Float32Array; } +interface PipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + preventClose?: boolean; +} + interface PointerEventInit extends MouseEventInit { height?: number; isPrimary?: boolean; @@ -941,10 +950,11 @@ interface PromiseRejectionEventInit extends EventInit { reason?: any; } -interface PropertyIndexedKeyframes extends Record { - composite?: CompositeOperation | (CompositeOperation | null)[]; +interface PropertyIndexedKeyframes { + composite?: CompositeOperationOrAuto | CompositeOperationOrAuto[]; easing?: string | string[]; offset?: number | (number | null)[]; + [property: string]: string | string[] | number | null | (number | null)[] | undefined; } interface PushSubscriptionJSON { @@ -958,9 +968,9 @@ interface PushSubscriptionOptionsInit { userVisibleOnly?: boolean; } -interface QueuingStrategy { +interface QueuingStrategy { highWaterMark?: number; - size?: WritableStreamChunkCallback; + size?: QueuingStrategySizeCallback; } interface RTCAnswerOptions extends RTCOfferAnswerOptions { @@ -1516,6 +1526,14 @@ interface TrackEventInit extends EventInit { track?: VideoTrack | AudioTrack | TextTrack | null; } +interface Transformer { + flush?: TransformStreamDefaultControllerCallback; + readableType?: undefined; + start?: TransformStreamDefaultControllerCallback; + transform?: TransformStreamDefaultControllerTransformCallback; + writableType?: undefined; +} + interface TransitionEventInit extends EventInit { elapsedTime?: number; propertyName?: string; @@ -1527,11 +1545,27 @@ interface UIEventInit extends EventInit { view?: Window | null; } -interface UnderlyingSink { +interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; +} + +interface UnderlyingSink { abort?: WritableStreamErrorCallback; - close?: WritableStreamDefaultControllerCallback; - start: WritableStreamDefaultControllerCallback; - write?: WritableStreamChunkCallback; + close?: WritableStreamDefaultControllerCloseCallback; + start?: WritableStreamDefaultControllerStartCallback; + type?: undefined; + write?: WritableStreamDefaultControllerWriteCallback; +} + +interface UnderlyingSource { + cancel?: ReadableStreamErrorCallback; + pull?: ReadableStreamDefaultControllerCallback; + start?: ReadableStreamDefaultControllerCallback; + type?: undefined; } interface VRDisplayEventInit extends EventInit { @@ -1581,6 +1615,12 @@ interface WheelEventInit extends MouseEventInit { deltaZ?: number; } +interface WorkerOptions { + credentials?: RequestCredentials; + name?: string; + type?: WorkerType; +} + interface WorkletOptions { credentials?: RequestCredentials; } @@ -1590,18 +1630,12 @@ interface EventListener { } interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; + drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void; + drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void; + vertexAttribDivisorANGLE(index: GLuint, divisor: GLuint): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum; } -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -}; - interface AbortController { /** * Returns the AbortSignal object associated with this object. @@ -2188,7 +2222,7 @@ declare var Blob: { }; interface Body { - readonly body: ReadableStream | null; + readonly body: ReadableStream | null; readonly bodyUsed: boolean; arrayBuffer(): Promise; blob(): Promise; @@ -2233,14 +2267,14 @@ interface BroadcastChannelEventMap { messageerror: MessageEvent; } -interface ByteLengthQueuingStrategy { +interface ByteLengthQueuingStrategy extends QueuingStrategy { highWaterMark: number; - size(chunk?: any): number; + size(chunk: ArrayBufferView): number; } declare var ByteLengthQueuingStrategy: { prototype: ByteLengthQueuingStrategy; - new(strategy: QueuingStrategy): ByteLengthQueuingStrategy; + new(options: { highWaterMark: number }): ByteLengthQueuingStrategy; }; interface CDATASection extends Text { @@ -2403,15 +2437,15 @@ interface CSSStyleDeclaration { alignItems: string | null; alignSelf: string | null; alignmentBaseline: string | null; - animation: string | null; - animationDelay: string | null; - animationDirection: string | null; - animationDuration: string | null; - animationFillMode: string | null; - animationIterationCount: string | null; - animationName: string | null; - animationPlayState: string | null; - animationTimingFunction: string | null; + animation: string; + animationDelay: string; + animationDirection: string; + animationDuration: string; + animationFillMode: string; + animationIterationCount: string; + animationName: string; + animationPlayState: string; + animationTimingFunction: string; backfaceVisibility: string | null; background: string | null; backgroundAttachment: string | null; @@ -2654,6 +2688,7 @@ interface CSSStyleDeclaration { rubyOverhang: string | null; rubyPosition: string | null; scale: string | null; + scrollBehavior: string; stopColor: string | null; stopOpacity: string | null; stroke: string | null; @@ -2679,50 +2714,79 @@ interface CSSStyleDeclaration { textTransform: string | null; textUnderlinePosition: string | null; top: string | null; - touchAction: string | null; + touchAction: string; transform: string | null; transformOrigin: string | null; transformStyle: string | null; - transition: string | null; - transitionDelay: string | null; - transitionDuration: string | null; - transitionProperty: string | null; - transitionTimingFunction: string | null; + transition: string; + transitionDelay: string; + transitionDuration: string; + transitionProperty: string; + transitionTimingFunction: string; translate: string | null; unicodeBidi: string | null; userSelect: string | null; verticalAlign: string | null; visibility: string | null; - webkitAlignContent: string | null; - webkitAlignItems: string | null; - webkitAlignSelf: string | null; - webkitAnimation: string | null; - webkitAnimationDelay: string | null; - webkitAnimationDirection: string | null; - webkitAnimationDuration: string | null; - webkitAnimationFillMode: string | null; - webkitAnimationIterationCount: string | null; - webkitAnimationName: string | null; - webkitAnimationPlayState: string | null; - webkitAnimationTimingFunction: string | null; - webkitAppearance: string | null; - webkitBackfaceVisibility: string | null; - webkitBackgroundClip: string | null; - webkitBackgroundOrigin: string | null; - webkitBackgroundSize: string | null; - webkitBorderBottomLeftRadius: string | null; - webkitBorderBottomRightRadius: string | null; + /** @deprecated */ + webkitAlignContent: string; + /** @deprecated */ + webkitAlignItems: string; + /** @deprecated */ + webkitAlignSelf: string; + /** @deprecated */ + webkitAnimation: string; + /** @deprecated */ + webkitAnimationDelay: string; + /** @deprecated */ + webkitAnimationDirection: string; + /** @deprecated */ + webkitAnimationDuration: string; + /** @deprecated */ + webkitAnimationFillMode: string; + /** @deprecated */ + webkitAnimationIterationCount: string; + /** @deprecated */ + webkitAnimationName: string; + /** @deprecated */ + webkitAnimationPlayState: string; + /** @deprecated */ + webkitAnimationTimingFunction: string; + /** @deprecated */ + webkitAppearance: string; + /** @deprecated */ + webkitBackfaceVisibility: string; + /** @deprecated */ + webkitBackgroundClip: string; + /** @deprecated */ + webkitBackgroundOrigin: string; + /** @deprecated */ + webkitBackgroundSize: string; + /** @deprecated */ + webkitBorderBottomLeftRadius: string; + /** @deprecated */ + webkitBorderBottomRightRadius: string; webkitBorderImage: string | null; - webkitBorderRadius: string | null; - webkitBorderTopLeftRadius: string | null; - webkitBorderTopRightRadius: string | null; - webkitBoxAlign: string | null; + /** @deprecated */ + webkitBorderRadius: string; + /** @deprecated */ + webkitBorderTopLeftRadius: string; + /** @deprecated */ + webkitBorderTopRightRadius: string; + /** @deprecated */ + webkitBoxAlign: string; webkitBoxDirection: string | null; - webkitBoxFlex: string | null; - webkitBoxOrdinalGroup: string | null; + /** @deprecated */ + webkitBoxFlex: string; + /** @deprecated */ + webkitBoxOrdinalGroup: string; webkitBoxOrient: string | null; - webkitBoxPack: string | null; - webkitBoxSizing: string | null; + /** @deprecated */ + webkitBoxPack: string; + /** @deprecated */ + webkitBoxShadow: string; + /** @deprecated */ + webkitBoxSizing: string; webkitColumnBreakAfter: string | null; webkitColumnBreakBefore: string | null; webkitColumnBreakInside: string | null; @@ -2735,32 +2799,85 @@ interface CSSStyleDeclaration { webkitColumnSpan: string | null; webkitColumnWidth: any; webkitColumns: string | null; - webkitFilter: string | null; - webkitFlex: string | null; - webkitFlexBasis: string | null; - webkitFlexDirection: string | null; - webkitFlexFlow: string | null; - webkitFlexGrow: string | null; - webkitFlexShrink: string | null; - webkitFlexWrap: string | null; - webkitJustifyContent: string | null; - webkitOrder: string | null; - webkitPerspective: string | null; - webkitPerspectiveOrigin: string | null; + /** @deprecated */ + webkitFilter: string; + /** @deprecated */ + webkitFlex: string; + /** @deprecated */ + webkitFlexBasis: string; + /** @deprecated */ + webkitFlexDirection: string; + /** @deprecated */ + webkitFlexFlow: string; + /** @deprecated */ + webkitFlexGrow: string; + /** @deprecated */ + webkitFlexShrink: string; + /** @deprecated */ + webkitFlexWrap: string; + /** @deprecated */ + webkitJustifyContent: string; + /** @deprecated */ + webkitMask: string; + /** @deprecated */ + webkitMaskBoxImage: string; + /** @deprecated */ + webkitMaskBoxImageOutset: string; + /** @deprecated */ + webkitMaskBoxImageRepeat: string; + /** @deprecated */ + webkitMaskBoxImageSlice: string; + /** @deprecated */ + webkitMaskBoxImageSource: string; + /** @deprecated */ + webkitMaskBoxImageWidth: string; + /** @deprecated */ + webkitMaskClip: string; + /** @deprecated */ + webkitMaskComposite: string; + /** @deprecated */ + webkitMaskImage: string; + /** @deprecated */ + webkitMaskOrigin: string; + /** @deprecated */ + webkitMaskPosition: string; + /** @deprecated */ + webkitMaskRepeat: string; + /** @deprecated */ + webkitMaskSize: string; + /** @deprecated */ + webkitOrder: string; + /** @deprecated */ + webkitPerspective: string; + /** @deprecated */ + webkitPerspectiveOrigin: string; webkitTapHighlightColor: string | null; - webkitTextFillColor: string | null; - webkitTextSizeAdjust: any; - webkitTextStroke: string | null; - webkitTextStrokeColor: string | null; - webkitTextStrokeWidth: string | null; - webkitTransform: string | null; - webkitTransformOrigin: string | null; - webkitTransformStyle: string | null; - webkitTransition: string | null; - webkitTransitionDelay: string | null; - webkitTransitionDuration: string | null; - webkitTransitionProperty: string | null; - webkitTransitionTimingFunction: string | null; + /** @deprecated */ + webkitTextFillColor: string; + /** @deprecated */ + webkitTextSizeAdjust: string; + /** @deprecated */ + webkitTextStroke: string; + /** @deprecated */ + webkitTextStrokeColor: string; + /** @deprecated */ + webkitTextStrokeWidth: string; + /** @deprecated */ + webkitTransform: string; + /** @deprecated */ + webkitTransformOrigin: string; + /** @deprecated */ + webkitTransformStyle: string; + /** @deprecated */ + webkitTransition: string; + /** @deprecated */ + webkitTransitionDelay: string; + /** @deprecated */ + webkitTransitionDuration: string; + /** @deprecated */ + webkitTransitionProperty: string; + /** @deprecated */ + webkitTransitionTimingFunction: string; webkitUserModify: string | null; webkitUserSelect: string | null; webkitWritingMode: string | null; @@ -3241,14 +3358,14 @@ interface Coordinates { readonly speed: number | null; } -interface CountQueuingStrategy { +interface CountQueuingStrategy extends QueuingStrategy { highWaterMark: number; - size(): number; + size(chunk: any): 1; } declare var CountQueuingStrategy: { prototype: CountQueuingStrategy; - new(strategy: QueuingStrategy): CountQueuingStrategy; + new(options: { highWaterMark: number }): CountQueuingStrategy; }; interface Crypto { @@ -4004,7 +4121,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** * Gets a reference to the root node of the document. */ - readonly documentElement: HTMLElement | null; + readonly documentElement: HTMLElement; /** * Returns document's URL. */ @@ -4036,7 +4153,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** * Returns the head element. */ - readonly head: HTMLHeadElement | null; + readonly head: HTMLHeadElement; readonly hidden: boolean; /** * Retrieves a collection, in source order, of img objects in the document. @@ -4066,7 +4183,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** * Contains information about the current URL. */ - location: Location | null; + location: Location; onfullscreenchange: ((this: Document, ev: Event) => any) | null; onfullscreenerror: ((this: Document, ev: Event) => any) | null; /** @@ -4116,6 +4233,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** @deprecated */ captureEvents(): void; caretPositionFromPoint(x: number, y: number): CaretPosition | null; + /** @deprecated */ caretRangeFromPoint(x: number, y: number): Range; /** @deprecated */ clear(): void; @@ -4169,6 +4287,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par 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: "cursor"): SVGCursorElement; 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; @@ -4341,7 +4460,9 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par * @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 | null, entityReferenceExpansion?: boolean): TreeWalker; + createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter | null): TreeWalker; + /** @deprecated */ + createTreeWalker(root: Node, whatToShow: number, filter: NodeFilter | null, entityReferenceExpansion?: boolean): TreeWalker; /** * Returns the element for the specified x coordinate and the specified y coordinate. * @param x The x-offset @@ -4349,7 +4470,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par */ elementFromPoint(x: number, y: number): Element | null; elementsFromPoint(x: number, y: number): Element[]; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | ((prefix: string) => string | null) | null, type: number, result: XPathResult | null): XPathResult; /** * Executes a command on the current document, current selection, or the given range. * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. @@ -4570,6 +4691,9 @@ interface DocumentOrShadowRoot { * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. */ readonly styleSheets: StyleSheetList; + caretPositionFromPoint(x: number, y: number): CaretPosition | null; + /** @deprecated */ + caretRangeFromPoint(x: number, y: number): Range; elementFromPoint(x: number, y: number): Element | null; elementsFromPoint(x: number, y: number): Element[]; getSelection(): Selection | null; @@ -4621,35 +4745,28 @@ declare var DynamicsCompressorNode: { }; interface EXT_blend_minmax { - readonly MAX_EXT: number; - readonly MIN_EXT: number; + readonly MAX_EXT: GLenum; + readonly MIN_EXT: GLenum; } interface EXT_frag_depth { } interface EXT_sRGB { - readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; - readonly SRGB8_ALPHA8_EXT: number; - readonly SRGB_ALPHA_EXT: number; - readonly SRGB_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: GLenum; + readonly SRGB8_ALPHA8_EXT: GLenum; + readonly SRGB_ALPHA_EXT: GLenum; + readonly SRGB_EXT: GLenum; } interface EXT_shader_texture_lod { } interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: GLenum; + readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum; } -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -}; - interface ElementEventMap { "fullscreenchange": Event; "fullscreenerror": Event; @@ -4867,6 +4984,7 @@ interface Event { */ readonly isTrusted: boolean; returnValue: boolean; + /** @deprecated */ readonly srcElement: Element | null; /** * Returns the object to which event is dispatched (its target). @@ -5033,7 +5151,7 @@ interface FileReader extends EventTarget { readAsArrayBuffer(blob: Blob): void; readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, label?: string): void; + readAsText(blob: Blob, encoding?: string): void; readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; @@ -6520,6 +6638,7 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the frame name. */ name: string; + readonly referrerPolicy: ReferrerPolicy; readonly sandbox: DOMTokenList; /** * Sets or retrieves whether the frame can be scrolled. @@ -7155,7 +7274,7 @@ interface HTMLMediaElement extends HTMLElement { */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + * Gets a flag that indicates whether the client is currently moving to a new playback position in the media resource. */ readonly seeking: boolean; /** @@ -9304,7 +9423,9 @@ interface Location { /** * Reloads the current page. */ - reload(forcedReload?: boolean): void; + reload(): void; + /** @deprecated */ + reload(forcedReload: boolean): void; /** * Removes the current page from the session history and navigates to the given URL. */ @@ -9725,7 +9846,7 @@ interface MediaQueryList extends EventTarget { /** @deprecated */ addListener(listener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null): void; /** @deprecated */ - removeListener(listener: EventListenerOrEventListenerObject | null): void; + removeListener(listener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null): void; addEventListener(type: K, listener: (this: MediaQueryList, ev: MediaQueryListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: MediaQueryList, ev: MediaQueryListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -10278,6 +10399,7 @@ interface Node extends EventTarget { * Returns the last child. */ readonly lastChild: ChildNode | null; + /** @deprecated */ readonly namespaceURI: string | null; /** * Returns the next sibling. @@ -10550,61 +10672,29 @@ declare var Notification: { interface OES_element_index_uint { } -declare var OES_element_index_uint: { - prototype: OES_element_index_uint; - new(): OES_element_index_uint; -}; - interface OES_standard_derivatives { - readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GLenum; } -declare var OES_standard_derivatives: { - prototype: OES_standard_derivatives; - new(): OES_standard_derivatives; - readonly 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 OES_texture_half_float { - readonly HALF_FLOAT_OES: number; + readonly HALF_FLOAT_OES: GLenum; } -declare var OES_texture_half_float: { - prototype: OES_texture_half_float; - new(): OES_texture_half_float; - readonly HALF_FLOAT_OES: number; -}; - interface OES_texture_half_float_linear { } -declare var OES_texture_half_float_linear: { - prototype: OES_texture_half_float_linear; - new(): OES_texture_half_float_linear; -}; - interface OES_vertex_array_object { - readonly VERTEX_ARRAY_BINDING_OES: number; - bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; - createVertexArrayOES(): WebGLVertexArrayObjectOES; - deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; - isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES | null; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + isVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): GLboolean; + readonly VERTEX_ARRAY_BINDING_OES: GLenum; } interface OfflineAudioCompletionEvent extends Event { @@ -11794,20 +11884,70 @@ declare var Range: { readonly START_TO_START: number; }; -interface ReadableStream { +interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; +} + +interface ReadableStream { readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + pipeThrough({ writable, readable }: { writable: WritableStream, readable: ReadableStream }, options?: PipeOptions): ReadableStream; + pipeTo(dest: WritableStream, options?: PipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; } declare var ReadableStream: { prototype: ReadableStream; - new(): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number, size?: undefined }): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; -interface ReadableStreamReader { +interface ReadableStreamBYOBReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(view: T): Promise>; + releaseLock(): void; +} + +declare var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; +}; + +interface ReadableStreamBYOBRequest { + readonly view: ArrayBufferView; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBufferView): void; +} + +interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: R): void; + error(error?: any): void; +} + +interface ReadableStreamDefaultReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} + +interface ReadableStreamReadResult { + done: boolean; + value: T; +} + +interface ReadableStreamReader { cancel(): Promise; - read(): Promise; + read(): Promise>; releaseLock(): void; } @@ -11819,7 +11959,7 @@ declare var ReadableStreamReader: { interface Request extends Body { /** * Returns the cache mode associated with request, which is a string indicating - * how the the request will interact with the browser's cache when fetching. + * how the request will interact with the browser's cache when fetching. */ readonly cache: RequestCache; /** @@ -11957,6 +12097,42 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_UNSPECIFIED: number; }; +interface SVGAnimateElement extends SVGAnimationElement { + addEventListener(type: K, listener: (this: SVGAnimateElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimateElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimateElement: { + prototype: SVGAnimateElement; + new(): SVGAnimateElement; +}; + +interface SVGAnimateMotionElement extends SVGAnimationElement { + addEventListener(type: K, listener: (this: SVGAnimateMotionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimateMotionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimateMotionElement: { + prototype: SVGAnimateMotionElement; + new(): SVGAnimateMotionElement; +}; + +interface SVGAnimateTransformElement extends SVGAnimationElement { + addEventListener(type: K, listener: (this: SVGAnimateTransformElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimateTransformElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimateTransformElement: { + prototype: SVGAnimateTransformElement; + new(): SVGAnimateTransformElement; +}; + interface SVGAnimatedAngle { readonly animVal: SVGAngle; readonly baseVal: SVGAngle; @@ -12082,6 +12258,22 @@ declare var SVGAnimatedTransformList: { new(): SVGAnimatedTransformList; }; +interface SVGAnimationElement extends SVGElement { + readonly targetElement: SVGElement; + getCurrentTime(): number; + getSimpleDuration(): number; + getStartTime(): number; + addEventListener(type: K, listener: (this: SVGAnimationElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimationElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimationElement: { + prototype: SVGAnimationElement; + new(): SVGAnimationElement; +}; + interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; readonly cy: SVGAnimatedLength; @@ -12141,6 +12333,20 @@ declare var SVGComponentTransferFunctionElement: { readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; }; +interface SVGCursorElement extends SVGElement { + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGCursorElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCursorElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGCursorElement: { + prototype: SVGCursorElement; + new(): SVGCursorElement; +}; + interface SVGDefsElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -14798,6 +15004,23 @@ declare var TrackEvent: { new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; }; +interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; +} + +declare var TransformStream: { + prototype: TransformStream; + new(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy): TransformStream; +}; + +interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk: O): void; + error(reason?: any): void; + terminate(): void; +} + interface TransitionEvent extends Event { readonly elapsedTime: number; readonly propertyName: string; @@ -15115,129 +15338,106 @@ declare var VideoTrackList: { }; interface WEBGL_color_buffer_float { - readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; - readonly RGB32F_EXT: number; - readonly RGBA32F_EXT: number; - readonly UNSIGNED_NORMALIZED_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: GLenum; + readonly RGBA32F_EXT: GLenum; + readonly UNSIGNED_NORMALIZED_EXT: GLenum; } interface WEBGL_compressed_texture_astc { - readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number; - readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number; - readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number; - readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number; - readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number; - readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; - readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number; - readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number; - readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number; - readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number; - readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number; - readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number; - readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number; - readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number; getSupportedProfiles(): string[]; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: GLenum; } interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: GLenum; } -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -}; - interface WEBGL_compressed_texture_s3tc_srgb { - readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: GLenum; } interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; + readonly UNMASKED_RENDERER_WEBGL: GLenum; + readonly UNMASKED_VENDOR_WEBGL: GLenum; } -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -}; - interface WEBGL_debug_shaders { getTranslatedShaderSource(shader: WebGLShader): string; } interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; + readonly UNSIGNED_INT_24_8_WEBGL: GLenum; } -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -}; - interface WEBGL_draw_buffers { - readonly COLOR_ATTACHMENT0_WEBGL: number; - readonly COLOR_ATTACHMENT10_WEBGL: number; - readonly COLOR_ATTACHMENT11_WEBGL: number; - readonly COLOR_ATTACHMENT12_WEBGL: number; - readonly COLOR_ATTACHMENT13_WEBGL: number; - readonly COLOR_ATTACHMENT14_WEBGL: number; - readonly COLOR_ATTACHMENT15_WEBGL: number; - readonly COLOR_ATTACHMENT1_WEBGL: number; - readonly COLOR_ATTACHMENT2_WEBGL: number; - readonly COLOR_ATTACHMENT3_WEBGL: number; - readonly COLOR_ATTACHMENT4_WEBGL: number; - readonly COLOR_ATTACHMENT5_WEBGL: number; - readonly COLOR_ATTACHMENT6_WEBGL: number; - readonly COLOR_ATTACHMENT7_WEBGL: number; - readonly COLOR_ATTACHMENT8_WEBGL: number; - readonly COLOR_ATTACHMENT9_WEBGL: number; - readonly DRAW_BUFFER0_WEBGL: number; - readonly DRAW_BUFFER10_WEBGL: number; - readonly DRAW_BUFFER11_WEBGL: number; - readonly DRAW_BUFFER12_WEBGL: number; - readonly DRAW_BUFFER13_WEBGL: number; - readonly DRAW_BUFFER14_WEBGL: number; - readonly DRAW_BUFFER15_WEBGL: number; - readonly DRAW_BUFFER1_WEBGL: number; - readonly DRAW_BUFFER2_WEBGL: number; - readonly DRAW_BUFFER3_WEBGL: number; - readonly DRAW_BUFFER4_WEBGL: number; - readonly DRAW_BUFFER5_WEBGL: number; - readonly DRAW_BUFFER6_WEBGL: number; - readonly DRAW_BUFFER7_WEBGL: number; - readonly DRAW_BUFFER8_WEBGL: number; - readonly DRAW_BUFFER9_WEBGL: number; - readonly MAX_COLOR_ATTACHMENTS_WEBGL: number; - readonly MAX_DRAW_BUFFERS_WEBGL: number; - drawBuffersWEBGL(buffers: number[]): void; + drawBuffersWEBGL(buffers: GLenum[]): void; + readonly COLOR_ATTACHMENT0_WEBGL: GLenum; + readonly COLOR_ATTACHMENT10_WEBGL: GLenum; + readonly COLOR_ATTACHMENT11_WEBGL: GLenum; + readonly COLOR_ATTACHMENT12_WEBGL: GLenum; + readonly COLOR_ATTACHMENT13_WEBGL: GLenum; + readonly COLOR_ATTACHMENT14_WEBGL: GLenum; + readonly COLOR_ATTACHMENT15_WEBGL: GLenum; + readonly COLOR_ATTACHMENT1_WEBGL: GLenum; + readonly COLOR_ATTACHMENT2_WEBGL: GLenum; + readonly COLOR_ATTACHMENT3_WEBGL: GLenum; + readonly COLOR_ATTACHMENT4_WEBGL: GLenum; + readonly COLOR_ATTACHMENT5_WEBGL: GLenum; + readonly COLOR_ATTACHMENT6_WEBGL: GLenum; + readonly COLOR_ATTACHMENT7_WEBGL: GLenum; + readonly COLOR_ATTACHMENT8_WEBGL: GLenum; + readonly COLOR_ATTACHMENT9_WEBGL: GLenum; + readonly DRAW_BUFFER0_WEBGL: GLenum; + readonly DRAW_BUFFER10_WEBGL: GLenum; + readonly DRAW_BUFFER11_WEBGL: GLenum; + readonly DRAW_BUFFER12_WEBGL: GLenum; + readonly DRAW_BUFFER13_WEBGL: GLenum; + readonly DRAW_BUFFER14_WEBGL: GLenum; + readonly DRAW_BUFFER15_WEBGL: GLenum; + readonly DRAW_BUFFER1_WEBGL: GLenum; + readonly DRAW_BUFFER2_WEBGL: GLenum; + readonly DRAW_BUFFER3_WEBGL: GLenum; + readonly DRAW_BUFFER4_WEBGL: GLenum; + readonly DRAW_BUFFER5_WEBGL: GLenum; + readonly DRAW_BUFFER6_WEBGL: GLenum; + readonly DRAW_BUFFER7_WEBGL: GLenum; + readonly DRAW_BUFFER8_WEBGL: GLenum; + readonly DRAW_BUFFER9_WEBGL: GLenum; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: GLenum; + readonly MAX_DRAW_BUFFERS_WEBGL: GLenum; } interface WEBGL_lose_context { @@ -16139,7 +16339,7 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; -interface WebGLVertexArrayObjectOES { +interface WebGLVertexArrayObjectOES extends WebGLObject { } interface WebKitPoint { @@ -16196,9 +16396,6 @@ interface WheelEvent extends MouseEvent { readonly deltaX: number; readonly deltaY: number; readonly deltaZ: number; - readonly wheelDelta: number; - readonly wheelDeltaX: number; - readonly wheelDeltaY: 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; readonly DOM_DELTA_LINE: number; @@ -16545,7 +16742,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; - new(stringUrl: string): Worker; + new(stringUrl: string, options?: WorkerOptions): Worker; }; interface Worklet { @@ -16557,41 +16754,31 @@ declare var Worklet: { new(): Worklet; }; -interface WritableStream { +interface WritableStream { readonly locked: boolean; abort(reason?: any): Promise; - getWriter(): WritableStreamDefaultWriter; + getWriter(): WritableStreamDefaultWriter; } declare var WritableStream: { prototype: WritableStream; - new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; }; interface WritableStreamDefaultController { error(error?: any): void; } -declare var WritableStreamDefaultController: { - prototype: WritableStreamDefaultController; - new(): WritableStreamDefaultController; -}; - -interface WritableStreamDefaultWriter { +interface WritableStreamDefaultWriter { readonly closed: Promise; - readonly desiredSize: number; + readonly desiredSize: number | null; readonly ready: Promise; abort(reason?: any): Promise; close(): Promise; releaseLock(): void; - write(chunk?: any): Promise; + write(chunk: W): Promise; } -declare var WritableStreamDefaultWriter: { - prototype: WritableStreamDefaultWriter; - new(): WritableStreamDefaultWriter; -}; - interface XMLDocument extends Document { addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -16772,7 +16959,7 @@ declare var XMLSerializer: { interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver?: Node): XPathNSResolver; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | ((prefix: string) => string | null) | null, type: number, result: XPathResult | null): XPathResult; } declare var XPathEvaluator: { @@ -16790,7 +16977,7 @@ declare var XPathExpression: { }; interface XPathNSResolver { - lookupNamespaceURI(prefix: string): string; + lookupNamespaceURI(prefix: string): string | null; } declare var XPathNSResolver: { @@ -16941,6 +17128,10 @@ interface PositionErrorCallback { (positionError: PositionError): void; } +interface QueuingStrategySizeCallback { + (chunk: T): number; +} + interface RTCPeerConnectionErrorCallback { (error: DOMException): void; } @@ -16953,20 +17144,44 @@ interface RTCStatsCallback { (report: RTCStatsReport): void; } +interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; +} + +interface ReadableStreamDefaultControllerCallback { + (controller: ReadableStreamDefaultController): void | PromiseLike; +} + +interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; +} + +interface TransformStreamDefaultControllerCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; +} + +interface TransformStreamDefaultControllerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; +} + interface VoidFunction { (): void; } -interface WritableStreamChunkCallback { - (chunk: any, controller: WritableStreamDefaultController): void; +interface WritableStreamDefaultControllerCloseCallback { + (): void | PromiseLike; } -interface WritableStreamDefaultControllerCallback { - (controller: WritableStreamDefaultController): void; +interface WritableStreamDefaultControllerStartCallback { + (controller: WritableStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamDefaultControllerWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; } interface WritableStreamErrorCallback { - (reason: string): void; + (reason: any): void | PromiseLike; } interface HTMLElementTagNameMap { @@ -17600,7 +17815,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type BlobPart = BufferSource | Blob | string; type HeadersInit = Headers | string[][] | Record; -type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; +type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; type RequestInfo = Request | string; type DOMHighResTimeStamp = number; type RenderingContext = CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext; @@ -17646,6 +17861,7 @@ type IDBKeyPath = string; type Transferable = ArrayBuffer | MessagePort | ImageBitmap; type RTCIceGatherCandidate = RTCIceCandidateDictionary | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; +/** @deprecated */ type MouseWheelEvent = WheelEvent; type WindowProxy = Window; type AlignSetting = "start" | "center" | "end" | "left" | "right"; @@ -17668,11 +17884,13 @@ type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type CompositeOperation = "replace" | "add" | "accumulate"; +type CompositeOperationOrAuto = "replace" | "add" | "accumulate" | "auto"; type DirectionSetting = "" | "rl" | "lr"; type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; type DocumentReadyState = "loading" | "interactive" | "complete"; type EndOfStreamError = "network" | "decode"; +type EndingType = "transparent" | "native"; type FillMode = "none" | "forwards" | "backwards" | "both" | "auto"; type GamepadHand = "" | "left" | "right"; type GamepadHapticActuatorType = "vibration"; @@ -17751,7 +17969,7 @@ type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; type RequestRedirect = "follow" | "error" | "manual"; type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; -type ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollBehavior = "auto" | "smooth"; type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type ScrollRestoration = "auto" | "manual"; type ScrollSetting = "" | "up"; diff --git a/lib/lib.es2015.collection.d.ts b/lib/lib.es2015.collection.d.ts index c6a02b32cc2..2c19919dd20 100644 --- a/lib/lib.es2015.collection.d.ts +++ b/lib/lib.es2015.collection.d.ts @@ -29,7 +29,8 @@ interface Map { } interface MapConstructor { - new (entries?: ReadonlyArray<[K, V]> | null): Map; + new(): Map; + new(entries?: ReadonlyArray<[K, V]> | null): Map; readonly prototype: Map; } declare var Map: MapConstructor; diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index 793f587059b..43b021a197d 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -155,7 +155,7 @@ interface MapConstructor { interface WeakMap { } interface WeakMapConstructor { - new (iterable: Iterable<[K, V]>): WeakMap; + new (iterable: Iterable<[K, V]>): WeakMap; } interface Set { diff --git a/lib/lib.es2015.promise.d.ts b/lib/lib.es2015.promise.d.ts index 9f27b7b59ab..002d69165fd 100644 --- a/lib/lib.es2015.promise.d.ts +++ b/lib/lib.es2015.promise.d.ts @@ -27,7 +27,7 @@ interface PromiseConstructor { /** * 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, + * a resolve callback used to 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; @@ -213,4 +213,4 @@ interface PromiseConstructor { resolve(): Promise; } -declare var Promise: PromiseConstructor; \ No newline at end of file +declare var Promise: PromiseConstructor; diff --git a/lib/lib.es2015.symbol.wellknown.d.ts b/lib/lib.es2015.symbol.wellknown.d.ts index 922cbb35a82..400f70a7f4d 100644 --- a/lib/lib.es2015.symbol.wellknown.d.ts +++ b/lib/lib.es2015.symbol.wellknown.d.ts @@ -83,7 +83,7 @@ interface SymbolConstructor { } interface Symbol { - readonly [Symbol.toStringTag]: "Symbol"; + readonly [Symbol.toStringTag]: string; } interface Array { @@ -127,23 +127,23 @@ interface Date { } interface Map { - readonly [Symbol.toStringTag]: "Map"; + readonly [Symbol.toStringTag]: string; } interface WeakMap { - readonly [Symbol.toStringTag]: "WeakMap"; + readonly [Symbol.toStringTag]: string; } interface Set { - readonly [Symbol.toStringTag]: "Set"; + readonly [Symbol.toStringTag]: string; } interface WeakSet { - readonly [Symbol.toStringTag]: "WeakSet"; + readonly [Symbol.toStringTag]: string; } interface JSON { - readonly [Symbol.toStringTag]: "JSON"; + readonly [Symbol.toStringTag]: string; } interface Function { @@ -158,15 +158,15 @@ interface Function { } interface GeneratorFunction { - readonly [Symbol.toStringTag]: "GeneratorFunction"; + readonly [Symbol.toStringTag]: string; } interface Math { - readonly [Symbol.toStringTag]: "Math"; + readonly [Symbol.toStringTag]: string; } interface Promise { - readonly [Symbol.toStringTag]: "Promise"; + readonly [Symbol.toStringTag]: string; } interface PromiseConstructor { @@ -261,11 +261,11 @@ interface String { } interface ArrayBuffer { - readonly [Symbol.toStringTag]: "ArrayBuffer"; + readonly [Symbol.toStringTag]: string; } interface DataView { - readonly [Symbol.toStringTag]: "DataView"; + readonly [Symbol.toStringTag]: string; } interface Int8Array { diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 840fd682789..d1a9d6f0d2a 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -315,6 +315,66 @@ interface FunctionConstructor { declare const Function: FunctionConstructor; +interface CallableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: (this: T) => R, thisArg: T): R; + apply(this: (this: T, ...args: A) => R, thisArg: T, args: A): R; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R; + + /** + * 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 The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: (this: T, ...args: A) => R, thisArg: T): (...args: A) => R; + bind(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R; + bind(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R; +} + +interface NewableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: new () => T, thisArg: T): void; + apply(this: new (...args: A) => T, thisArg: T, args: A): void; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: new (...args: A) => T, thisArg: T, ...args: A): void; + + /** + * 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 The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: new (...args: A) => R, thisArg: any): new (...args: A) => R; + bind(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2, arg3: A3): new (...args: A) => R; + bind(this: new (...args: AX[]) => R, thisArg: any, ...args: AX[]): new (...args: AX[]) => R; +} + interface IArguments { [index: number]: any; length: number; @@ -1370,7 +1430,7 @@ type Readonly = { }; /** - * From T pick a set of properties K + * From T, pick a set of properties whose keys are in the union K */ type Pick = { [P in K]: T[P]; @@ -1398,6 +1458,16 @@ type Extract = T extends U ? T : never; */ type NonNullable = T extends null | undefined ? never : T; +/** + * Obtain the parameters of a function type in a tuple + */ +type Parameters any> = T extends (...args: infer P) => any ? P : never; + +/** + * Obtain the parameters of a constructor function type in a tuple + */ +type ConstructorParameters any> = T extends new (...args: infer P) => any ? P : never; + /** * Obtain the return type of a function type */ diff --git a/lib/lib.esnext.array.d.ts b/lib/lib.esnext.array.d.ts index 3da8562d2ea..6c751223209 100644 --- a/lib/lib.esnext.array.d.ts +++ b/lib/lib.esnext.array.d.ts @@ -31,7 +31,7 @@ interface ReadonlyArray { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|U[], + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, thisArg?: This ): U[] @@ -145,7 +145,7 @@ interface Array { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|U[], + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, thisArg?: This ): U[] diff --git a/lib/lib.esnext.bigint.d.ts b/lib/lib.esnext.bigint.d.ts new file mode 100644 index 00000000000..ccb73bee761 --- /dev/null +++ b/lib/lib.esnext.bigint.d.ts @@ -0,0 +1,629 @@ +/*! ***************************************************************************** +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. +***************************************************************************** */ + + + +/// + + +interface BigInt { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. + */ + toString(radix?: number): string; + + /** Returns a string representation appropriate to the host environment's current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): bigint; + + readonly [Symbol.toStringTag]: "BigInt"; +} + +interface BigIntConstructor { + (value?: any): bigint; + readonly prototype: BigInt; + + /** + * Interprets the low bits of a BigInt as a 2's-complement signed integer. + * All higher bits are discarded. + * @param bits The number of low bits to use + * @param int The BigInt whose bits to extract + */ + asIntN(bits: number, int: bigint): bigint; + /** + * Interprets the low bits of a BigInt as an unsigned integer. + * All higher bits are discarded. + * @param bits The number of low bits to use + * @param int The BigInt whose bits to extract + */ + asUintN(bits: number, int: bigint): bigint; +} + +declare const BigInt: BigIntConstructor; + +/** + * A typed array of 64-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 BigInt64Array { + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** The ArrayBuffer instance referenced by the array. */ + readonly buffer: ArrayBufferLike; + + /** 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): this; + + /** Yields index, value pairs for every entry in the array. */ + entries(): IterableIterator<[number, bigint]>; + + /** + * 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 the array 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: bigint, index: number, array: BigInt64Array) => 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: bigint, start?: number, end?: number): this; + + /** + * 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: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array; + + /** + * 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: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => 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: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void; + + /** + * 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: bigint, fromIndex?: number): boolean; + + /** + * 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: bigint, 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; + + /** Yields each index in the array. */ + keys(): IterableIterator; + + /** + * 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: bigint, 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: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array; + + /** + * 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: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; + + /** + * 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: bigint, currentIndex: number, array: BigInt64Array) => 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: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; + + /** + * 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: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; + + /** Reverses the elements in the array. */ + reverse(): this; + + /** + * 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): BigInt64Array; + + /** + * 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 the array 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: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts the array. + * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. + */ + sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; + + /** + * Gets a new BigInt64Array 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): BigInt64Array; + + /** Converts the array to a string by using the current locale. */ + toLocaleString(): string; + + /** Returns a string representation of the array. */ + toString(): string; + + /** Yields each value in the array. */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; + + readonly [Symbol.toStringTag]: "BigInt64Array"; + + [index: number]: bigint; +} + +interface BigInt64ArrayConstructor { + readonly prototype: BigInt64Array; + new(length?: number): BigInt64Array; + new(array: Iterable): BigInt64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; + + /** 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: bigint[]): BigInt64Array; + + /** + * 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): BigInt64Array; + from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array; +} + +declare const BigInt64Array: BigInt64ArrayConstructor; + +/** + * A typed array of 64-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 BigUint64Array { + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** The ArrayBuffer instance referenced by the array. */ + readonly buffer: ArrayBufferLike; + + /** 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): this; + + /** Yields index, value pairs for every entry in the array. */ + entries(): IterableIterator<[number, bigint]>; + + /** + * 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 the array 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: bigint, index: number, array: BigUint64Array) => 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: bigint, start?: number, end?: number): this; + + /** + * 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: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array; + + /** + * 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: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: bigint, index: number, array: BigUint64Array) => 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: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void; + + /** + * 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: bigint, fromIndex?: number): boolean; + + /** + * 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: bigint, 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; + + /** Yields each index in the array. */ + keys(): IterableIterator; + + /** + * 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: bigint, 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: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array; + + /** + * 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: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; + + /** + * 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: bigint, currentIndex: number, array: BigUint64Array) => 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: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; + + /** + * 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: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; + + /** Reverses the elements in the array. */ + reverse(): this; + + /** + * 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): BigUint64Array; + + /** + * 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 the array 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: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts the array. + * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. + */ + sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; + + /** + * Gets a new BigUint64Array 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): BigUint64Array; + + /** Converts the array to a string by using the current locale. */ + toLocaleString(): string; + + /** Returns a string representation of the array. */ + toString(): string; + + /** Yields each value in the array. */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; + + readonly [Symbol.toStringTag]: "BigUint64Array"; + + [index: number]: bigint; +} + +interface BigUint64ArrayConstructor { + readonly prototype: BigUint64Array; + new(length?: number): BigUint64Array; + new(array: Iterable): BigUint64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; + + /** 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: bigint[]): BigUint64Array; + + /** + * 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): BigUint64Array; + from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array; +} + +declare const BigUint64Array: BigUint64ArrayConstructor; + +interface DataView { + /** + * Gets the BigInt64 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. + */ + getBigInt64(byteOffset: number, littleEndian?: boolean): bigint; + + /** + * Gets the BigUint64 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. + */ + getBigUint64(byteOffset: number, littleEndian?: boolean): bigint; + + /** + * Stores a BigInt64 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. + */ + setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void; + + /** + * Stores a BigUint64 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. + */ + setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void; +} \ No newline at end of file diff --git a/lib/lib.esnext.d.ts b/lib/lib.esnext.d.ts index 8e8592bd61a..f213999684d 100644 --- a/lib/lib.esnext.d.ts +++ b/lib/lib.esnext.d.ts @@ -21,5 +21,6 @@ and limitations under the License. /// /// /// +/// /// /// diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 2fa70fb2a6b..238702731fd 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -59,6 +59,7 @@ interface Algorithm { } interface BlobPropertyBag { + endings?: EndingType; type?: string; } @@ -302,6 +303,12 @@ interface PerformanceObserverInit { entryTypes: string[]; } +interface PipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + preventClose?: boolean; +} + interface ProgressEventInit extends EventInit { lengthComputable?: boolean; loaded?: number; @@ -333,6 +340,11 @@ interface PushSubscriptionOptionsInit { userVisibleOnly?: boolean; } +interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySizeCallback; +} + interface RegistrationOptions { scope?: string; type?: WorkerType; @@ -407,10 +419,69 @@ interface TextDecoderOptions { ignoreBOM?: boolean; } +interface Transformer { + flush?: TransformStreamDefaultControllerCallback; + readableType?: undefined; + start?: TransformStreamDefaultControllerCallback; + transform?: TransformStreamDefaultControllerTransformCallback; + writableType?: undefined; +} + +interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; +} + +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCloseCallback; + start?: WritableStreamDefaultControllerStartCallback; + type?: undefined; + write?: WritableStreamDefaultControllerWriteCallback; +} + +interface UnderlyingSource { + cancel?: ReadableStreamErrorCallback; + pull?: ReadableStreamDefaultControllerCallback; + start?: ReadableStreamDefaultControllerCallback; + type?: undefined; +} + +interface WebGLContextAttributes { + alpha?: GLboolean; + antialias?: GLboolean; + depth?: GLboolean; + failIfMajorPerformanceCaveat?: boolean; + powerPreference?: WebGLPowerPreference; + premultipliedAlpha?: GLboolean; + preserveDrawingBuffer?: GLboolean; + stencil?: GLboolean; +} + +interface WebGLContextEventInit extends EventInit { + statusMessage?: string; +} + +interface WorkerOptions { + credentials?: RequestCredentials; + name?: string; + type?: WorkerType; +} + interface EventListener { (evt: Event): void; } +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void; + drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void; + vertexAttribDivisorANGLE(index: GLuint, divisor: GLuint): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum; +} + interface AbortController { /** * Returns the AbortSignal object associated with this object. @@ -482,7 +553,7 @@ declare var Blob: { }; interface Body { - readonly body: ReadableStream | null; + readonly body: ReadableStream | null; readonly bodyUsed: boolean; arrayBuffer(): Promise; blob(): Promise; @@ -527,6 +598,16 @@ interface BroadcastChannelEventMap { messageerror: MessageEvent; } +interface ByteLengthQueuingStrategy extends QueuingStrategy { + highWaterMark: number; + size(chunk: ArrayBufferView): number; +} + +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(options: { highWaterMark: number }): ByteLengthQueuingStrategy; +}; + interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; @@ -675,6 +756,16 @@ declare var Console: { new(): Console; }; +interface CountQueuingStrategy extends QueuingStrategy { + highWaterMark: number; + size(chunk: any): 1; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(options: { highWaterMark: number }): CountQueuingStrategy; +}; + interface Crypto { readonly subtle: SubtleCrypto; getRandomValues(array: T): T; @@ -1002,6 +1093,29 @@ interface DhKeyGenParams extends Algorithm { prime: Uint8Array; } +interface EXT_blend_minmax { + readonly MAX_EXT: GLenum; + readonly MIN_EXT: GLenum; +} + +interface EXT_frag_depth { +} + +interface EXT_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: GLenum; + readonly SRGB8_ALPHA8_EXT: GLenum; + readonly SRGB_ALPHA_EXT: GLenum; + readonly SRGB_EXT: GLenum; +} + +interface EXT_shader_texture_lod { +} + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: GLenum; + readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum; +} + interface ErrorEvent extends Event { readonly colno: number; readonly error: any; @@ -1039,7 +1153,6 @@ interface Event { */ readonly isTrusted: boolean; returnValue: boolean; - readonly srcElement: object | null; /** * Returns the object to which event is dispatched (its target). */ @@ -1217,7 +1330,7 @@ interface FileReader extends EventTarget { readAsArrayBuffer(blob: Blob): void; readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, label?: string): void; + readAsText(blob: Blob, encoding?: string): void; readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; @@ -1239,7 +1352,7 @@ interface FileReaderSync { readAsArrayBuffer(blob: Blob): ArrayBuffer; readAsBinaryString(blob: Blob): string; readAsDataURL(blob: Blob): string; - readAsText(blob: Blob, label?: string): string; + readAsText(blob: Blob, encoding?: string): string; } declare var FileReaderSync: { @@ -1994,6 +2107,34 @@ declare var NotificationEvent: { new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; }; +interface OES_element_index_uint { +} + +interface OES_standard_derivatives { + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GLenum; +} + +interface OES_texture_float { +} + +interface OES_texture_float_linear { +} + +interface OES_texture_half_float { + readonly HALF_FLOAT_OES: GLenum; +} + +interface OES_texture_half_float_linear { +} + +interface OES_vertex_array_object { + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES | null; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + isVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): GLboolean; + readonly VERTEX_ARRAY_BINDING_OES: GLenum; +} + interface Path2D extends CanvasPath { addPath(path: Path2D, transform?: DOMMatrix2DInit): void; } @@ -2197,20 +2338,70 @@ declare var PushSubscriptionOptions: { new(): PushSubscriptionOptions; }; -interface ReadableStream { +interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; +} + +interface ReadableStream { readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + pipeThrough({ writable, readable }: { writable: WritableStream, readable: ReadableStream }, options?: PipeOptions): ReadableStream; + pipeTo(dest: WritableStream, options?: PipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; } declare var ReadableStream: { prototype: ReadableStream; - new(): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number, size?: undefined }): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; -interface ReadableStreamReader { +interface ReadableStreamBYOBReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(view: T): Promise>; + releaseLock(): void; +} + +declare var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; +}; + +interface ReadableStreamBYOBRequest { + readonly view: ArrayBufferView; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBufferView): void; +} + +interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: R): void; + error(error?: any): void; +} + +interface ReadableStreamDefaultReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} + +interface ReadableStreamReadResult { + done: boolean; + value: T; +} + +interface ReadableStreamReader { cancel(): Promise; - read(): Promise; + read(): Promise>; releaseLock(): void; } @@ -2222,7 +2413,7 @@ declare var ReadableStreamReader: { interface Request extends Body { /** * Returns the cache mode associated with request, which is a string indicating - * how the the request will interact with the browser's cache when fetching. + * how the request will interact with the browser's cache when fetching. */ readonly cache: RequestCache; /** @@ -2544,6 +2735,46 @@ declare var TextEncoder: { new(): TextEncoder; }; +interface TextMetrics { + readonly actualBoundingBoxAscent: number; + readonly actualBoundingBoxDescent: number; + readonly actualBoundingBoxLeft: number; + readonly actualBoundingBoxRight: number; + readonly alphabeticBaseline: number; + readonly emHeightAscent: number; + readonly emHeightDescent: number; + readonly fontBoundingBoxAscent: number; + readonly fontBoundingBoxDescent: number; + readonly hangingBaseline: number; + /** + * Returns the measurement described below. + */ + readonly ideographicBaseline: number; + readonly width: number; +} + +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +}; + +interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; +} + +declare var TransformStream: { + prototype: TransformStream; + new(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy): TransformStream; +}; + +interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk: O): void; + error(reason?: any): void; + terminate(): void; +} + interface URL { hash: string; host: string; @@ -2601,6 +2832,978 @@ declare var URLSearchParams: { new(init?: string[][] | Record | string | URLSearchParams): URLSearchParams; }; +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: GLenum; + readonly RGBA32F_EXT: GLenum; + readonly UNSIGNED_NORMALIZED_EXT: GLenum; +} + +interface WEBGL_compressed_texture_astc { + getSupportedProfiles(): string[]; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: GLenum; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: GLenum; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: GLenum; +} + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: GLenum; + readonly UNMASKED_VENDOR_WEBGL: GLenum; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: GLenum; +} + +interface WEBGL_draw_buffers { + drawBuffersWEBGL(buffers: GLenum[]): void; + readonly COLOR_ATTACHMENT0_WEBGL: GLenum; + readonly COLOR_ATTACHMENT10_WEBGL: GLenum; + readonly COLOR_ATTACHMENT11_WEBGL: GLenum; + readonly COLOR_ATTACHMENT12_WEBGL: GLenum; + readonly COLOR_ATTACHMENT13_WEBGL: GLenum; + readonly COLOR_ATTACHMENT14_WEBGL: GLenum; + readonly COLOR_ATTACHMENT15_WEBGL: GLenum; + readonly COLOR_ATTACHMENT1_WEBGL: GLenum; + readonly COLOR_ATTACHMENT2_WEBGL: GLenum; + readonly COLOR_ATTACHMENT3_WEBGL: GLenum; + readonly COLOR_ATTACHMENT4_WEBGL: GLenum; + readonly COLOR_ATTACHMENT5_WEBGL: GLenum; + readonly COLOR_ATTACHMENT6_WEBGL: GLenum; + readonly COLOR_ATTACHMENT7_WEBGL: GLenum; + readonly COLOR_ATTACHMENT8_WEBGL: GLenum; + readonly COLOR_ATTACHMENT9_WEBGL: GLenum; + readonly DRAW_BUFFER0_WEBGL: GLenum; + readonly DRAW_BUFFER10_WEBGL: GLenum; + readonly DRAW_BUFFER11_WEBGL: GLenum; + readonly DRAW_BUFFER12_WEBGL: GLenum; + readonly DRAW_BUFFER13_WEBGL: GLenum; + readonly DRAW_BUFFER14_WEBGL: GLenum; + readonly DRAW_BUFFER15_WEBGL: GLenum; + readonly DRAW_BUFFER1_WEBGL: GLenum; + readonly DRAW_BUFFER2_WEBGL: GLenum; + readonly DRAW_BUFFER3_WEBGL: GLenum; + readonly DRAW_BUFFER4_WEBGL: GLenum; + readonly DRAW_BUFFER5_WEBGL: GLenum; + readonly DRAW_BUFFER6_WEBGL: GLenum; + readonly DRAW_BUFFER7_WEBGL: GLenum; + readonly DRAW_BUFFER8_WEBGL: GLenum; + readonly DRAW_BUFFER9_WEBGL: GLenum; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: GLenum; + readonly MAX_DRAW_BUFFERS_WEBGL: GLenum; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + +interface WebGLActiveInfo { + readonly name: string; + readonly size: GLint; + readonly type: GLenum; +} + +declare var WebGLActiveInfo: { + prototype: WebGLActiveInfo; + new(): WebGLActiveInfo; +}; + +interface WebGLBuffer extends WebGLObject { +} + +declare var WebGLBuffer: { + prototype: WebGLBuffer; + new(): WebGLBuffer; +}; + +interface WebGLContextEvent extends Event { + readonly statusMessage: string; +} + +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new(type: string, eventInit?: WebGLContextEventInit): 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 extends WebGLRenderingContextBase { +} + +declare var WebGLRenderingContext: { + prototype: WebGLRenderingContext; + new(): WebGLRenderingContext; + readonly ACTIVE_ATTRIBUTES: GLenum; + readonly ACTIVE_TEXTURE: GLenum; + readonly ACTIVE_UNIFORMS: GLenum; + readonly ALIASED_LINE_WIDTH_RANGE: GLenum; + readonly ALIASED_POINT_SIZE_RANGE: GLenum; + readonly ALPHA: GLenum; + readonly ALPHA_BITS: GLenum; + readonly ALWAYS: GLenum; + readonly ARRAY_BUFFER: GLenum; + readonly ARRAY_BUFFER_BINDING: GLenum; + readonly ATTACHED_SHADERS: GLenum; + readonly BACK: GLenum; + readonly BLEND: GLenum; + readonly BLEND_COLOR: GLenum; + readonly BLEND_DST_ALPHA: GLenum; + readonly BLEND_DST_RGB: GLenum; + readonly BLEND_EQUATION: GLenum; + readonly BLEND_EQUATION_ALPHA: GLenum; + readonly BLEND_EQUATION_RGB: GLenum; + readonly BLEND_SRC_ALPHA: GLenum; + readonly BLEND_SRC_RGB: GLenum; + readonly BLUE_BITS: GLenum; + readonly BOOL: GLenum; + readonly BOOL_VEC2: GLenum; + readonly BOOL_VEC3: GLenum; + readonly BOOL_VEC4: GLenum; + readonly BROWSER_DEFAULT_WEBGL: GLenum; + readonly BUFFER_SIZE: GLenum; + readonly BUFFER_USAGE: GLenum; + readonly BYTE: GLenum; + readonly CCW: GLenum; + readonly CLAMP_TO_EDGE: GLenum; + readonly COLOR_ATTACHMENT0: GLenum; + readonly COLOR_BUFFER_BIT: GLenum; + readonly COLOR_CLEAR_VALUE: GLenum; + readonly COLOR_WRITEMASK: GLenum; + readonly COMPILE_STATUS: GLenum; + readonly COMPRESSED_TEXTURE_FORMATS: GLenum; + readonly CONSTANT_ALPHA: GLenum; + readonly CONSTANT_COLOR: GLenum; + readonly CONTEXT_LOST_WEBGL: GLenum; + readonly CULL_FACE: GLenum; + readonly CULL_FACE_MODE: GLenum; + readonly CURRENT_PROGRAM: GLenum; + readonly CURRENT_VERTEX_ATTRIB: GLenum; + readonly CW: GLenum; + readonly DECR: GLenum; + readonly DECR_WRAP: GLenum; + readonly DELETE_STATUS: GLenum; + readonly DEPTH_ATTACHMENT: GLenum; + readonly DEPTH_BITS: GLenum; + readonly DEPTH_BUFFER_BIT: GLenum; + readonly DEPTH_CLEAR_VALUE: GLenum; + readonly DEPTH_COMPONENT: GLenum; + readonly DEPTH_COMPONENT16: GLenum; + readonly DEPTH_FUNC: GLenum; + readonly DEPTH_RANGE: GLenum; + readonly DEPTH_STENCIL: GLenum; + readonly DEPTH_STENCIL_ATTACHMENT: GLenum; + readonly DEPTH_TEST: GLenum; + readonly DEPTH_WRITEMASK: GLenum; + readonly DITHER: GLenum; + readonly DONT_CARE: GLenum; + readonly DST_ALPHA: GLenum; + readonly DST_COLOR: GLenum; + readonly DYNAMIC_DRAW: GLenum; + readonly ELEMENT_ARRAY_BUFFER: GLenum; + readonly ELEMENT_ARRAY_BUFFER_BINDING: GLenum; + readonly EQUAL: GLenum; + readonly FASTEST: GLenum; + readonly FLOAT: GLenum; + readonly FLOAT_MAT2: GLenum; + readonly FLOAT_MAT3: GLenum; + readonly FLOAT_MAT4: GLenum; + readonly FLOAT_VEC2: GLenum; + readonly FLOAT_VEC3: GLenum; + readonly FLOAT_VEC4: GLenum; + readonly FRAGMENT_SHADER: GLenum; + readonly FRAMEBUFFER: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; + readonly FRAMEBUFFER_BINDING: GLenum; + readonly FRAMEBUFFER_COMPLETE: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_UNSUPPORTED: GLenum; + readonly FRONT: GLenum; + readonly FRONT_AND_BACK: GLenum; + readonly FRONT_FACE: GLenum; + readonly FUNC_ADD: GLenum; + readonly FUNC_REVERSE_SUBTRACT: GLenum; + readonly FUNC_SUBTRACT: GLenum; + readonly GENERATE_MIPMAP_HINT: GLenum; + readonly GEQUAL: GLenum; + readonly GREATER: GLenum; + readonly GREEN_BITS: GLenum; + readonly HIGH_FLOAT: GLenum; + readonly HIGH_INT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_TYPE: GLenum; + readonly INCR: GLenum; + readonly INCR_WRAP: GLenum; + readonly INT: GLenum; + readonly INT_VEC2: GLenum; + readonly INT_VEC3: GLenum; + readonly INT_VEC4: GLenum; + readonly INVALID_ENUM: GLenum; + readonly INVALID_FRAMEBUFFER_OPERATION: GLenum; + readonly INVALID_OPERATION: GLenum; + readonly INVALID_VALUE: GLenum; + readonly INVERT: GLenum; + readonly KEEP: GLenum; + readonly LEQUAL: GLenum; + readonly LESS: GLenum; + readonly LINEAR: GLenum; + readonly LINEAR_MIPMAP_LINEAR: GLenum; + readonly LINEAR_MIPMAP_NEAREST: GLenum; + readonly LINES: GLenum; + readonly LINE_LOOP: GLenum; + readonly LINE_STRIP: GLenum; + readonly LINE_WIDTH: GLenum; + readonly LINK_STATUS: GLenum; + readonly LOW_FLOAT: GLenum; + readonly LOW_INT: GLenum; + readonly LUMINANCE: GLenum; + readonly LUMINANCE_ALPHA: GLenum; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; + readonly MAX_RENDERBUFFER_SIZE: GLenum; + readonly MAX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_TEXTURE_SIZE: GLenum; + readonly MAX_VARYING_VECTORS: GLenum; + readonly MAX_VERTEX_ATTRIBS: GLenum; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_VERTEX_UNIFORM_VECTORS: GLenum; + readonly MAX_VIEWPORT_DIMS: GLenum; + readonly MEDIUM_FLOAT: GLenum; + readonly MEDIUM_INT: GLenum; + readonly MIRRORED_REPEAT: GLenum; + readonly NEAREST: GLenum; + readonly NEAREST_MIPMAP_LINEAR: GLenum; + readonly NEAREST_MIPMAP_NEAREST: GLenum; + readonly NEVER: GLenum; + readonly NICEST: GLenum; + readonly NONE: GLenum; + readonly NOTEQUAL: GLenum; + readonly NO_ERROR: GLenum; + readonly ONE: GLenum; + readonly ONE_MINUS_CONSTANT_ALPHA: GLenum; + readonly ONE_MINUS_CONSTANT_COLOR: GLenum; + readonly ONE_MINUS_DST_ALPHA: GLenum; + readonly ONE_MINUS_DST_COLOR: GLenum; + readonly ONE_MINUS_SRC_ALPHA: GLenum; + readonly ONE_MINUS_SRC_COLOR: GLenum; + readonly OUT_OF_MEMORY: GLenum; + readonly PACK_ALIGNMENT: GLenum; + readonly POINTS: GLenum; + readonly POLYGON_OFFSET_FACTOR: GLenum; + readonly POLYGON_OFFSET_FILL: GLenum; + readonly POLYGON_OFFSET_UNITS: GLenum; + readonly RED_BITS: GLenum; + readonly RENDERBUFFER: GLenum; + readonly RENDERBUFFER_ALPHA_SIZE: GLenum; + readonly RENDERBUFFER_BINDING: GLenum; + readonly RENDERBUFFER_BLUE_SIZE: GLenum; + readonly RENDERBUFFER_DEPTH_SIZE: GLenum; + readonly RENDERBUFFER_GREEN_SIZE: GLenum; + readonly RENDERBUFFER_HEIGHT: GLenum; + readonly RENDERBUFFER_INTERNAL_FORMAT: GLenum; + readonly RENDERBUFFER_RED_SIZE: GLenum; + readonly RENDERBUFFER_STENCIL_SIZE: GLenum; + readonly RENDERBUFFER_WIDTH: GLenum; + readonly RENDERER: GLenum; + readonly REPEAT: GLenum; + readonly REPLACE: GLenum; + readonly RGB: GLenum; + readonly RGB565: GLenum; + readonly RGB5_A1: GLenum; + readonly RGBA: GLenum; + readonly RGBA4: GLenum; + readonly SAMPLER_2D: GLenum; + readonly SAMPLER_CUBE: GLenum; + readonly SAMPLES: GLenum; + readonly SAMPLE_ALPHA_TO_COVERAGE: GLenum; + readonly SAMPLE_BUFFERS: GLenum; + readonly SAMPLE_COVERAGE: GLenum; + readonly SAMPLE_COVERAGE_INVERT: GLenum; + readonly SAMPLE_COVERAGE_VALUE: GLenum; + readonly SCISSOR_BOX: GLenum; + readonly SCISSOR_TEST: GLenum; + readonly SHADER_TYPE: GLenum; + readonly SHADING_LANGUAGE_VERSION: GLenum; + readonly SHORT: GLenum; + readonly SRC_ALPHA: GLenum; + readonly SRC_ALPHA_SATURATE: GLenum; + readonly SRC_COLOR: GLenum; + readonly STATIC_DRAW: GLenum; + readonly STENCIL_ATTACHMENT: GLenum; + readonly STENCIL_BACK_FAIL: GLenum; + readonly STENCIL_BACK_FUNC: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_BACK_REF: GLenum; + readonly STENCIL_BACK_VALUE_MASK: GLenum; + readonly STENCIL_BACK_WRITEMASK: GLenum; + readonly STENCIL_BITS: GLenum; + readonly STENCIL_BUFFER_BIT: GLenum; + readonly STENCIL_CLEAR_VALUE: GLenum; + readonly STENCIL_FAIL: GLenum; + readonly STENCIL_FUNC: GLenum; + readonly STENCIL_INDEX8: GLenum; + readonly STENCIL_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_REF: GLenum; + readonly STENCIL_TEST: GLenum; + readonly STENCIL_VALUE_MASK: GLenum; + readonly STENCIL_WRITEMASK: GLenum; + readonly STREAM_DRAW: GLenum; + readonly SUBPIXEL_BITS: GLenum; + readonly TEXTURE: GLenum; + readonly TEXTURE0: GLenum; + readonly TEXTURE1: GLenum; + readonly TEXTURE10: GLenum; + readonly TEXTURE11: GLenum; + readonly TEXTURE12: GLenum; + readonly TEXTURE13: GLenum; + readonly TEXTURE14: GLenum; + readonly TEXTURE15: GLenum; + readonly TEXTURE16: GLenum; + readonly TEXTURE17: GLenum; + readonly TEXTURE18: GLenum; + readonly TEXTURE19: GLenum; + readonly TEXTURE2: GLenum; + readonly TEXTURE20: GLenum; + readonly TEXTURE21: GLenum; + readonly TEXTURE22: GLenum; + readonly TEXTURE23: GLenum; + readonly TEXTURE24: GLenum; + readonly TEXTURE25: GLenum; + readonly TEXTURE26: GLenum; + readonly TEXTURE27: GLenum; + readonly TEXTURE28: GLenum; + readonly TEXTURE29: GLenum; + readonly TEXTURE3: GLenum; + readonly TEXTURE30: GLenum; + readonly TEXTURE31: GLenum; + readonly TEXTURE4: GLenum; + readonly TEXTURE5: GLenum; + readonly TEXTURE6: GLenum; + readonly TEXTURE7: GLenum; + readonly TEXTURE8: GLenum; + readonly TEXTURE9: GLenum; + readonly TEXTURE_2D: GLenum; + readonly TEXTURE_BINDING_2D: GLenum; + readonly TEXTURE_BINDING_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; + readonly TEXTURE_MAG_FILTER: GLenum; + readonly TEXTURE_MIN_FILTER: GLenum; + readonly TEXTURE_WRAP_S: GLenum; + readonly TEXTURE_WRAP_T: GLenum; + readonly TRIANGLES: GLenum; + readonly TRIANGLE_FAN: GLenum; + readonly TRIANGLE_STRIP: GLenum; + readonly UNPACK_ALIGNMENT: GLenum; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; + readonly UNPACK_FLIP_Y_WEBGL: GLenum; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; + readonly UNSIGNED_BYTE: GLenum; + readonly UNSIGNED_INT: GLenum; + readonly UNSIGNED_SHORT: GLenum; + readonly UNSIGNED_SHORT_4_4_4_4: GLenum; + readonly UNSIGNED_SHORT_5_5_5_1: GLenum; + readonly UNSIGNED_SHORT_5_6_5: GLenum; + readonly VALIDATE_STATUS: GLenum; + readonly VENDOR: GLenum; + readonly VERSION: GLenum; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_POINTER: GLenum; + readonly VERTEX_ATTRIB_ARRAY_SIZE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_TYPE: GLenum; + readonly VERTEX_SHADER: GLenum; + readonly VIEWPORT: GLenum; + readonly ZERO: GLenum; +}; + +interface WebGLRenderingContextBase { + readonly drawingBufferHeight: GLsizei; + readonly drawingBufferWidth: GLsizei; + activeTexture(texture: GLenum): void; + attachShader(program: WebGLProgram, shader: WebGLShader): void; + bindAttribLocation(program: WebGLProgram, index: GLuint, name: string): void; + bindBuffer(target: GLenum, buffer: WebGLBuffer | null): void; + bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer | null): void; + bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer | null): void; + bindTexture(target: GLenum, texture: WebGLTexture | null): void; + blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf): void; + blendEquation(mode: GLenum): void; + blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum): void; + blendFunc(sfactor: GLenum, dfactor: GLenum): void; + blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum): void; + bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum): void; + bufferData(target: GLenum, data: BufferSource | null, usage: GLenum): void; + bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource): void; + checkFramebufferStatus(target: GLenum): GLenum; + clear(mask: GLbitfield): void; + clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf): void; + clearDepth(depth: GLclampf): void; + clearStencil(s: GLint): void; + colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean): void; + compileShader(shader: WebGLShader): void; + compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView): void; + compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView): void; + copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint): void; + copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + createBuffer(): WebGLBuffer | null; + createFramebuffer(): WebGLFramebuffer | null; + createProgram(): WebGLProgram | null; + createRenderbuffer(): WebGLRenderbuffer | null; + createShader(type: GLenum): WebGLShader | null; + createTexture(): WebGLTexture | null; + cullFace(mode: GLenum): void; + deleteBuffer(buffer: WebGLBuffer | null): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; + deleteProgram(program: WebGLProgram | null): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; + deleteShader(shader: WebGLShader | null): void; + deleteTexture(texture: WebGLTexture | null): void; + depthFunc(func: GLenum): void; + depthMask(flag: GLboolean): void; + depthRange(zNear: GLclampf, zFar: GLclampf): void; + detachShader(program: WebGLProgram, shader: WebGLShader): void; + disable(cap: GLenum): void; + disableVertexAttribArray(index: GLuint): void; + drawArrays(mode: GLenum, first: GLint, count: GLsizei): void; + drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr): void; + enable(cap: GLenum): void; + enableVertexAttribArray(index: GLuint): void; + finish(): void; + flush(): void; + framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer | null): void; + framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture | null, level: GLint): void; + frontFace(mode: GLenum): void; + generateMipmap(target: GLenum): void; + getActiveAttrib(program: WebGLProgram, index: GLuint): WebGLActiveInfo | null; + getActiveUniform(program: WebGLProgram, index: GLuint): WebGLActiveInfo | null; + getAttachedShaders(program: WebGLProgram): WebGLShader[] | null; + getAttribLocation(program: WebGLProgram, name: string): GLint; + getBufferParameter(target: GLenum, pname: GLenum): any; + getContextAttributes(): WebGLContextAttributes | null; + getError(): GLenum; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; + getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum): any; + getParameter(pname: GLenum): any; + getProgramInfoLog(program: WebGLProgram): string | null; + getProgramParameter(program: WebGLProgram, pname: GLenum): any; + getRenderbufferParameter(target: GLenum, pname: GLenum): any; + getShaderInfoLog(shader: WebGLShader): string | null; + getShaderParameter(shader: WebGLShader, pname: GLenum): any; + getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum): WebGLShaderPrecisionFormat | null; + getShaderSource(shader: WebGLShader): string | null; + getSupportedExtensions(): string[] | null; + getTexParameter(target: GLenum, pname: GLenum): any; + getUniform(program: WebGLProgram, location: WebGLUniformLocation): any; + getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation | null; + getVertexAttrib(index: GLuint, pname: GLenum): any; + getVertexAttribOffset(index: GLuint, pname: GLenum): GLintptr; + hint(target: GLenum, mode: GLenum): void; + isBuffer(buffer: WebGLBuffer | null): GLboolean; + isContextLost(): boolean; + isEnabled(cap: GLenum): GLboolean; + isFramebuffer(framebuffer: WebGLFramebuffer | null): GLboolean; + isProgram(program: WebGLProgram | null): GLboolean; + isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): GLboolean; + isShader(shader: WebGLShader | null): GLboolean; + isTexture(texture: WebGLTexture | null): GLboolean; + lineWidth(width: GLfloat): void; + linkProgram(program: WebGLProgram): void; + pixelStorei(pname: GLenum, param: GLint): void; + polygonOffset(factor: GLfloat, units: GLfloat): void; + readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei): void; + sampleCoverage(value: GLclampf, invert: GLboolean): void; + scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + shaderSource(shader: WebGLShader, source: string): void; + stencilFunc(func: GLenum, ref: GLint, mask: GLuint): void; + stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint): void; + stencilMask(mask: GLuint): void; + stencilMaskSeparate(face: GLenum, mask: GLuint): void; + stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum): void; + stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum): void; + texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource): void; + texParameterf(target: GLenum, pname: GLenum, param: GLfloat): void; + texParameteri(target: GLenum, pname: GLenum, param: GLint): void; + texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource): void; + uniform1f(location: WebGLUniformLocation | null, x: GLfloat): void; + uniform1fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform1i(location: WebGLUniformLocation | null, x: GLint): void; + uniform1iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform2f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat): void; + uniform2fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform2i(location: WebGLUniformLocation | null, x: GLint, y: GLint): void; + uniform2iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform3f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat, z: GLfloat): void; + uniform3fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform3i(location: WebGLUniformLocation | null, x: GLint, y: GLint, z: GLint): void; + uniform3iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform4f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat): void; + uniform4fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform4i(location: WebGLUniformLocation | null, x: GLint, y: GLint, z: GLint, w: GLint): void; + uniform4iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + useProgram(program: WebGLProgram | null): void; + validateProgram(program: WebGLProgram): void; + vertexAttrib1f(index: GLuint, x: GLfloat): void; + vertexAttrib1fv(index: GLuint, values: Float32List): void; + vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat): void; + vertexAttrib2fv(index: GLuint, values: Float32List): void; + vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat): void; + vertexAttrib3fv(index: GLuint, values: Float32List): void; + vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat): void; + vertexAttrib4fv(index: GLuint, values: Float32List): void; + vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr): void; + viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + readonly ACTIVE_ATTRIBUTES: GLenum; + readonly ACTIVE_TEXTURE: GLenum; + readonly ACTIVE_UNIFORMS: GLenum; + readonly ALIASED_LINE_WIDTH_RANGE: GLenum; + readonly ALIASED_POINT_SIZE_RANGE: GLenum; + readonly ALPHA: GLenum; + readonly ALPHA_BITS: GLenum; + readonly ALWAYS: GLenum; + readonly ARRAY_BUFFER: GLenum; + readonly ARRAY_BUFFER_BINDING: GLenum; + readonly ATTACHED_SHADERS: GLenum; + readonly BACK: GLenum; + readonly BLEND: GLenum; + readonly BLEND_COLOR: GLenum; + readonly BLEND_DST_ALPHA: GLenum; + readonly BLEND_DST_RGB: GLenum; + readonly BLEND_EQUATION: GLenum; + readonly BLEND_EQUATION_ALPHA: GLenum; + readonly BLEND_EQUATION_RGB: GLenum; + readonly BLEND_SRC_ALPHA: GLenum; + readonly BLEND_SRC_RGB: GLenum; + readonly BLUE_BITS: GLenum; + readonly BOOL: GLenum; + readonly BOOL_VEC2: GLenum; + readonly BOOL_VEC3: GLenum; + readonly BOOL_VEC4: GLenum; + readonly BROWSER_DEFAULT_WEBGL: GLenum; + readonly BUFFER_SIZE: GLenum; + readonly BUFFER_USAGE: GLenum; + readonly BYTE: GLenum; + readonly CCW: GLenum; + readonly CLAMP_TO_EDGE: GLenum; + readonly COLOR_ATTACHMENT0: GLenum; + readonly COLOR_BUFFER_BIT: GLenum; + readonly COLOR_CLEAR_VALUE: GLenum; + readonly COLOR_WRITEMASK: GLenum; + readonly COMPILE_STATUS: GLenum; + readonly COMPRESSED_TEXTURE_FORMATS: GLenum; + readonly CONSTANT_ALPHA: GLenum; + readonly CONSTANT_COLOR: GLenum; + readonly CONTEXT_LOST_WEBGL: GLenum; + readonly CULL_FACE: GLenum; + readonly CULL_FACE_MODE: GLenum; + readonly CURRENT_PROGRAM: GLenum; + readonly CURRENT_VERTEX_ATTRIB: GLenum; + readonly CW: GLenum; + readonly DECR: GLenum; + readonly DECR_WRAP: GLenum; + readonly DELETE_STATUS: GLenum; + readonly DEPTH_ATTACHMENT: GLenum; + readonly DEPTH_BITS: GLenum; + readonly DEPTH_BUFFER_BIT: GLenum; + readonly DEPTH_CLEAR_VALUE: GLenum; + readonly DEPTH_COMPONENT: GLenum; + readonly DEPTH_COMPONENT16: GLenum; + readonly DEPTH_FUNC: GLenum; + readonly DEPTH_RANGE: GLenum; + readonly DEPTH_STENCIL: GLenum; + readonly DEPTH_STENCIL_ATTACHMENT: GLenum; + readonly DEPTH_TEST: GLenum; + readonly DEPTH_WRITEMASK: GLenum; + readonly DITHER: GLenum; + readonly DONT_CARE: GLenum; + readonly DST_ALPHA: GLenum; + readonly DST_COLOR: GLenum; + readonly DYNAMIC_DRAW: GLenum; + readonly ELEMENT_ARRAY_BUFFER: GLenum; + readonly ELEMENT_ARRAY_BUFFER_BINDING: GLenum; + readonly EQUAL: GLenum; + readonly FASTEST: GLenum; + readonly FLOAT: GLenum; + readonly FLOAT_MAT2: GLenum; + readonly FLOAT_MAT3: GLenum; + readonly FLOAT_MAT4: GLenum; + readonly FLOAT_VEC2: GLenum; + readonly FLOAT_VEC3: GLenum; + readonly FLOAT_VEC4: GLenum; + readonly FRAGMENT_SHADER: GLenum; + readonly FRAMEBUFFER: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; + readonly FRAMEBUFFER_BINDING: GLenum; + readonly FRAMEBUFFER_COMPLETE: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_UNSUPPORTED: GLenum; + readonly FRONT: GLenum; + readonly FRONT_AND_BACK: GLenum; + readonly FRONT_FACE: GLenum; + readonly FUNC_ADD: GLenum; + readonly FUNC_REVERSE_SUBTRACT: GLenum; + readonly FUNC_SUBTRACT: GLenum; + readonly GENERATE_MIPMAP_HINT: GLenum; + readonly GEQUAL: GLenum; + readonly GREATER: GLenum; + readonly GREEN_BITS: GLenum; + readonly HIGH_FLOAT: GLenum; + readonly HIGH_INT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_TYPE: GLenum; + readonly INCR: GLenum; + readonly INCR_WRAP: GLenum; + readonly INT: GLenum; + readonly INT_VEC2: GLenum; + readonly INT_VEC3: GLenum; + readonly INT_VEC4: GLenum; + readonly INVALID_ENUM: GLenum; + readonly INVALID_FRAMEBUFFER_OPERATION: GLenum; + readonly INVALID_OPERATION: GLenum; + readonly INVALID_VALUE: GLenum; + readonly INVERT: GLenum; + readonly KEEP: GLenum; + readonly LEQUAL: GLenum; + readonly LESS: GLenum; + readonly LINEAR: GLenum; + readonly LINEAR_MIPMAP_LINEAR: GLenum; + readonly LINEAR_MIPMAP_NEAREST: GLenum; + readonly LINES: GLenum; + readonly LINE_LOOP: GLenum; + readonly LINE_STRIP: GLenum; + readonly LINE_WIDTH: GLenum; + readonly LINK_STATUS: GLenum; + readonly LOW_FLOAT: GLenum; + readonly LOW_INT: GLenum; + readonly LUMINANCE: GLenum; + readonly LUMINANCE_ALPHA: GLenum; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; + readonly MAX_RENDERBUFFER_SIZE: GLenum; + readonly MAX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_TEXTURE_SIZE: GLenum; + readonly MAX_VARYING_VECTORS: GLenum; + readonly MAX_VERTEX_ATTRIBS: GLenum; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_VERTEX_UNIFORM_VECTORS: GLenum; + readonly MAX_VIEWPORT_DIMS: GLenum; + readonly MEDIUM_FLOAT: GLenum; + readonly MEDIUM_INT: GLenum; + readonly MIRRORED_REPEAT: GLenum; + readonly NEAREST: GLenum; + readonly NEAREST_MIPMAP_LINEAR: GLenum; + readonly NEAREST_MIPMAP_NEAREST: GLenum; + readonly NEVER: GLenum; + readonly NICEST: GLenum; + readonly NONE: GLenum; + readonly NOTEQUAL: GLenum; + readonly NO_ERROR: GLenum; + readonly ONE: GLenum; + readonly ONE_MINUS_CONSTANT_ALPHA: GLenum; + readonly ONE_MINUS_CONSTANT_COLOR: GLenum; + readonly ONE_MINUS_DST_ALPHA: GLenum; + readonly ONE_MINUS_DST_COLOR: GLenum; + readonly ONE_MINUS_SRC_ALPHA: GLenum; + readonly ONE_MINUS_SRC_COLOR: GLenum; + readonly OUT_OF_MEMORY: GLenum; + readonly PACK_ALIGNMENT: GLenum; + readonly POINTS: GLenum; + readonly POLYGON_OFFSET_FACTOR: GLenum; + readonly POLYGON_OFFSET_FILL: GLenum; + readonly POLYGON_OFFSET_UNITS: GLenum; + readonly RED_BITS: GLenum; + readonly RENDERBUFFER: GLenum; + readonly RENDERBUFFER_ALPHA_SIZE: GLenum; + readonly RENDERBUFFER_BINDING: GLenum; + readonly RENDERBUFFER_BLUE_SIZE: GLenum; + readonly RENDERBUFFER_DEPTH_SIZE: GLenum; + readonly RENDERBUFFER_GREEN_SIZE: GLenum; + readonly RENDERBUFFER_HEIGHT: GLenum; + readonly RENDERBUFFER_INTERNAL_FORMAT: GLenum; + readonly RENDERBUFFER_RED_SIZE: GLenum; + readonly RENDERBUFFER_STENCIL_SIZE: GLenum; + readonly RENDERBUFFER_WIDTH: GLenum; + readonly RENDERER: GLenum; + readonly REPEAT: GLenum; + readonly REPLACE: GLenum; + readonly RGB: GLenum; + readonly RGB565: GLenum; + readonly RGB5_A1: GLenum; + readonly RGBA: GLenum; + readonly RGBA4: GLenum; + readonly SAMPLER_2D: GLenum; + readonly SAMPLER_CUBE: GLenum; + readonly SAMPLES: GLenum; + readonly SAMPLE_ALPHA_TO_COVERAGE: GLenum; + readonly SAMPLE_BUFFERS: GLenum; + readonly SAMPLE_COVERAGE: GLenum; + readonly SAMPLE_COVERAGE_INVERT: GLenum; + readonly SAMPLE_COVERAGE_VALUE: GLenum; + readonly SCISSOR_BOX: GLenum; + readonly SCISSOR_TEST: GLenum; + readonly SHADER_TYPE: GLenum; + readonly SHADING_LANGUAGE_VERSION: GLenum; + readonly SHORT: GLenum; + readonly SRC_ALPHA: GLenum; + readonly SRC_ALPHA_SATURATE: GLenum; + readonly SRC_COLOR: GLenum; + readonly STATIC_DRAW: GLenum; + readonly STENCIL_ATTACHMENT: GLenum; + readonly STENCIL_BACK_FAIL: GLenum; + readonly STENCIL_BACK_FUNC: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_BACK_REF: GLenum; + readonly STENCIL_BACK_VALUE_MASK: GLenum; + readonly STENCIL_BACK_WRITEMASK: GLenum; + readonly STENCIL_BITS: GLenum; + readonly STENCIL_BUFFER_BIT: GLenum; + readonly STENCIL_CLEAR_VALUE: GLenum; + readonly STENCIL_FAIL: GLenum; + readonly STENCIL_FUNC: GLenum; + readonly STENCIL_INDEX8: GLenum; + readonly STENCIL_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_REF: GLenum; + readonly STENCIL_TEST: GLenum; + readonly STENCIL_VALUE_MASK: GLenum; + readonly STENCIL_WRITEMASK: GLenum; + readonly STREAM_DRAW: GLenum; + readonly SUBPIXEL_BITS: GLenum; + readonly TEXTURE: GLenum; + readonly TEXTURE0: GLenum; + readonly TEXTURE1: GLenum; + readonly TEXTURE10: GLenum; + readonly TEXTURE11: GLenum; + readonly TEXTURE12: GLenum; + readonly TEXTURE13: GLenum; + readonly TEXTURE14: GLenum; + readonly TEXTURE15: GLenum; + readonly TEXTURE16: GLenum; + readonly TEXTURE17: GLenum; + readonly TEXTURE18: GLenum; + readonly TEXTURE19: GLenum; + readonly TEXTURE2: GLenum; + readonly TEXTURE20: GLenum; + readonly TEXTURE21: GLenum; + readonly TEXTURE22: GLenum; + readonly TEXTURE23: GLenum; + readonly TEXTURE24: GLenum; + readonly TEXTURE25: GLenum; + readonly TEXTURE26: GLenum; + readonly TEXTURE27: GLenum; + readonly TEXTURE28: GLenum; + readonly TEXTURE29: GLenum; + readonly TEXTURE3: GLenum; + readonly TEXTURE30: GLenum; + readonly TEXTURE31: GLenum; + readonly TEXTURE4: GLenum; + readonly TEXTURE5: GLenum; + readonly TEXTURE6: GLenum; + readonly TEXTURE7: GLenum; + readonly TEXTURE8: GLenum; + readonly TEXTURE9: GLenum; + readonly TEXTURE_2D: GLenum; + readonly TEXTURE_BINDING_2D: GLenum; + readonly TEXTURE_BINDING_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; + readonly TEXTURE_MAG_FILTER: GLenum; + readonly TEXTURE_MIN_FILTER: GLenum; + readonly TEXTURE_WRAP_S: GLenum; + readonly TEXTURE_WRAP_T: GLenum; + readonly TRIANGLES: GLenum; + readonly TRIANGLE_FAN: GLenum; + readonly TRIANGLE_STRIP: GLenum; + readonly UNPACK_ALIGNMENT: GLenum; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; + readonly UNPACK_FLIP_Y_WEBGL: GLenum; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; + readonly UNSIGNED_BYTE: GLenum; + readonly UNSIGNED_INT: GLenum; + readonly UNSIGNED_SHORT: GLenum; + readonly UNSIGNED_SHORT_4_4_4_4: GLenum; + readonly UNSIGNED_SHORT_5_5_5_1: GLenum; + readonly UNSIGNED_SHORT_5_6_5: GLenum; + readonly VALIDATE_STATUS: GLenum; + readonly VENDOR: GLenum; + readonly VERSION: GLenum; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_POINTER: GLenum; + readonly VERTEX_ATTRIB_ARRAY_SIZE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_TYPE: GLenum; + readonly VERTEX_SHADER: GLenum; + readonly VIEWPORT: GLenum; + readonly ZERO: GLenum; +} + +interface WebGLShader extends WebGLObject { +} + +declare var WebGLShader: { + prototype: WebGLShader; + new(): WebGLShader; +}; + +interface WebGLShaderPrecisionFormat { + readonly precision: GLint; + readonly rangeMax: GLint; + readonly rangeMin: GLint; +} + +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 WebGLVertexArrayObjectOES extends WebGLObject { +} + interface WebSocketEventMap { "close": CloseEvent; "error": Event; @@ -2696,7 +3899,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; - new(stringUrl: string): Worker; + new(stringUrl: string, options?: WorkerOptions): Worker; }; interface WorkerGlobalScopeEventMap { @@ -2756,6 +3959,31 @@ interface WorkerUtils extends WindowBase64 { importScripts(...urls: string[]): void; } +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk: W): Promise; +} + interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; } @@ -2917,6 +4145,46 @@ interface PerformanceObserverCallback { (entries: PerformanceObserverEntryList, observer: PerformanceObserver): void; } +interface QueuingStrategySizeCallback { + (chunk: T): number; +} + +interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; +} + +interface ReadableStreamDefaultControllerCallback { + (controller: ReadableStreamDefaultController): void | PromiseLike; +} + +interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; +} + +interface TransformStreamDefaultControllerCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; +} + +interface TransformStreamDefaultControllerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamDefaultControllerCloseCallback { + (): void | PromiseLike; +} + +interface WritableStreamDefaultControllerStartCallback { + (controller: WritableStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamDefaultControllerWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamErrorCallback { + (reason: any): void | PromiseLike; +} + declare var onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null; declare function close(): void; declare function postMessage(message: any, transfer?: Transferable[]): void; @@ -2966,7 +4234,7 @@ declare function removeEventListener; -type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; +type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; type RequestInfo = Request | string; type DOMHighResTimeStamp = number; type CanvasImageSource = ImageBitmap; @@ -2980,6 +4248,19 @@ type AlgorithmIdentifier = string | Algorithm; type HashAlgorithmIdentifier = AlgorithmIdentifier; type BigInteger = Uint8Array; type NamedCurve = string; +type GLenum = number; +type GLboolean = boolean; +type GLbitfield = number; +type GLint = number; +type GLsizei = number; +type GLintptr = number; +type GLsizeiptr = number; +type GLuint = number; +type GLfloat = number; +type GLclampf = number; +type TexImageSource = ImageBitmap | ImageData; +type Float32List = Float32Array | GLfloat[]; +type Int32List = Int32Array | GLint[]; type BufferSource = ArrayBufferView | ArrayBuffer; type DOMTimeStamp = number; type FormDataEntryValue = File | string; @@ -2987,6 +4268,7 @@ type IDBValidKey = number | string | Date | BufferSource | IDBArrayKey; type Transferable = ArrayBuffer | MessagePort | ImageBitmap; type BinaryType = "blob" | "arraybuffer"; type ClientTypes = "window" | "worker" | "sharedworker" | "all"; +type EndingType = "transparent" | "native"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; @@ -3007,5 +4289,6 @@ type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaquer type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type ServiceWorkerUpdateViaCache = "imports" | "all" | "none"; type VisibilityState = "hidden" | "visible" | "prerender"; +type WebGLPowerPreference = "default" | "low-power" | "high-performance"; type WorkerType = "classic" | "module"; type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index e7fcfc6ff5d..49a507b9881 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -61,7 +61,8 @@ declare namespace ts.server.protocol { GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", OrganizeImports = "organizeImports", - GetEditsForFileRename = "getEditsForFileRename" + GetEditsForFileRename = "getEditsForFileRename", + ConfigurePlugin = "configurePlugin" } /** * A TypeScript Server message @@ -136,6 +137,10 @@ declare namespace ts.server.protocol { * Contains message body if success === true. */ body?: any; + /** + * Contains extra information that plugin can include to be passed on + */ + metadata?: unknown; } /** * Arguments for FileRequest messages. @@ -781,7 +786,7 @@ declare namespace ts.server.protocol { /** * The file locations referencing the symbol. */ - refs: ReferencesResponseItem[]; + refs: ReadonlyArray; /** * The name of the symbol. */ @@ -827,15 +832,17 @@ declare namespace ts.server.protocol { /** * Information about the item to be renamed. */ - interface RenameInfo { + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { /** * True if item can be renamed. */ - canRename: boolean; + canRename: true; /** - * Error message if item can not be renamed. + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ - localizedErrorMessage?: string; + fileToRename?: string; /** * Display name of the item to be renamed. */ @@ -852,6 +859,15 @@ declare namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; } /** * A group of text spans, all in 'file'. @@ -860,7 +876,11 @@ declare namespace ts.server.protocol { /** The file to which the spans apply */ file: string; /** The text spans in this group */ - locs: TextSpan[]; + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface RenameResponseBody { /** @@ -995,6 +1015,14 @@ declare namespace ts.server.protocol { */ interface ConfigureResponse extends Response { } + interface ConfigurePluginRequestArguments { + pluginName: string; + configuration: any; + } + interface ConfigurePluginRequest extends Request { + command: CommandTypes.ConfigurePlugin; + arguments: ConfigurePluginRequestArguments; + } /** * Information found in an "open" request. */ @@ -1373,7 +1401,7 @@ declare namespace ts.server.protocol { * begin with prefix. */ interface CompletionsRequest extends FileLocationRequest { - command: CommandTypes.Completions; + command: CommandTypes.Completions | CommandTypes.CompletionInfo; arguments: CompletionsRequestArgs; } /** @@ -1832,6 +1860,7 @@ declare namespace ts.server.protocol { */ interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; + event: DiagnosticEventKind; } interface ConfigFileDiagnosticEventBody { /** @@ -1885,6 +1914,35 @@ declare namespace ts.server.protocol { */ openFiles: string[]; } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } type LargeFileReferencedEventName = "largeFileReferenced"; interface LargeFileReferencedEvent extends Event { event: LargeFileReferencedEventName; @@ -2220,6 +2278,7 @@ declare namespace ts.server.protocol { readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; } interface CompilerOptions { allowJs?: boolean; diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index 509172c0ead..de74fa7bdcd 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -61,7 +61,7 @@ "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Uma propriedade de uma interface ou tipo literal cujo tipo é um tipo de 'unique symbol' deve ser 'readonly'.", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Um parâmetro obrigatório não pode seguir um parâmetro opcional.", "A_rest_element_cannot_contain_a_binding_pattern_2501": "Um elemento rest não pode conter um padrão de associação.", - "A_rest_element_cannot_have_a_property_name_2566": "Um elemento restante não pode ter um nome de propriedade.", + "A_rest_element_cannot_have_a_property_name_2566": "Um elemento rest não pode ter um nome de propriedade.", "A_rest_element_cannot_have_an_initializer_1186": "Um elemento rest não pode ter um inicializador.", "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Um elemento rest deve ser o último em um padrão de desestruturação.", "A_rest_parameter_cannot_be_optional_1047": "Um parâmetro rest não pode ser opcional.", @@ -174,7 +174,7 @@ "An_object_member_cannot_be_declared_optional_1162": "Um membro de objeto não pode ser declarado como opcional.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "A assinatura de sobrecarga não pode ser declarada como geradora.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Uma expressão unária com o operador '{0}' não é permitida no lado esquerdo de uma expressão de exponenciação. Considere delimitar a expressão em parênteses.", - "Annotate_everything_with_types_from_JSDoc_95043": "Anotar tudo com tipos de JSDoc", + "Annotate_everything_with_types_from_JSDoc_95043": "Anotar tudo com tipos do JSDoc", "Annotate_with_type_from_JSDoc_95009": "Anotar com o tipo do JSDoc", "Annotate_with_types_from_JSDoc_95010": "Anotar com os tipos do JSDoc", "Argument_expression_expected_1135": "Expressão de argumento esperada.", @@ -368,7 +368,7 @@ "Enables_experimental_support_for_ES7_decorators_6065": "Habilita o suporte experimental para decoradores ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita o suporte experimental para a emissão de tipo de metadados para decoradores.", "Enum_0_used_before_its_declaration_2450": "A enumeração '{0}' usada antes de sua declaração.", - "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações de enum apenas podem se mescladas com namespaces ou com outras declarações de enum.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações enum só podem ser mescladas com namespaces ou com outras declarações enum.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Declarações de enumeração devem ser const ou não const.", "Enum_member_expected_1132": "Membro de enumeração esperado.", "Enum_member_must_have_initializer_1061": "O membro de enumeração deve ter um inicializador.", @@ -571,7 +571,7 @@ "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "O módulo {0} já exportou um membro denominado '{1}'. Considere reexportar explicitamente para resolver a ambiguidade.", "Module_0_has_no_default_export_1192": "O módulo '{0}' não tem padrão de exportação.", "Module_0_has_no_exported_member_1_2305": "O módulo '{0}' não tem nenhum membro exportado '{1}'.", - "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "O módulo '{0}' não tem nenhum membro exportado '{1}'. Você quis dizer '{2}'?", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "O módulo '{0}' não tem nenhum membro '{1}' exportado. Você quis dizer '{2}'?", "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "O módulo '{0}' está oculto por uma declaração de local com o mesmo nome.", "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "O módulo '{0}' resolve para uma entidade sem módulo e não pode ser importado usando este constructo.", "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "O módulo '{0}' usa 'export =' e não pode ser usado com 'export *'.", @@ -622,7 +622,7 @@ "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "A opção '{0} só pode ser usada quando qualquer uma das opções '--inlineSourceMap' ou '--sourceMap' é fornecida.", "Option_0_cannot_be_specified_with_option_1_5053": "A opção '{0}' não pode ser especificada com a opção '{1}'.", "Option_0_cannot_be_specified_without_specifying_option_1_5052": "A opção '{0}' não pode ser especificada sem especificar a opção '{1}'.", - "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "A opção '{0}' não pode ser especificada sem especificar a opção '{1}' ou a opção '{2}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "A opção '{0}' não pode ser especificada sem a especificação da opção '{1}' ou '{2}'.", "Option_0_should_have_array_of_strings_as_a_value_6103": "A opção '{0}' deve ter matriz de cadeias de um valor.", "Option_build_must_be_the_first_command_line_argument_6369": "A opção '--build' precisa ser o primeiro argumento da linha de comando.", "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "A opção 'isolatedModules' só pode ser usada quando nenhuma opção de '--module' for fornecida ou a opção 'target' for 'ES2015' ou superior.", @@ -686,7 +686,7 @@ "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "O projeto '{0}' está atualizado com os arquivos .d.ts de suas dependências", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Referências de projeto não podem formar um gráfico circular. Ciclo detectado: {0}", "Projects_in_this_build_Colon_0_6355": "Projetos neste build: {0}", - "Projects_to_reference_6300": "Projetos para referência", + "Projects_to_reference_6300": "Projetos a serem referenciados", "Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe na enumeração 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "A propriedade '{0}' não existe no tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "A propriedade '{0}' não existe no tipo '{1}'. Você esqueceu de usar 'await'?", @@ -740,7 +740,7 @@ "Remove_braces_from_arrow_function_95060": "Remover chaves da função de seta", "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'", "Remove_destructuring_90009": "Remover desestruturação", - "Remove_import_from_0_90005": "Remover importação do '{0}'", + "Remove_import_from_0_90005": "Remover importação de '{0}'", "Remove_unreachable_code_95050": "Remover código inacessível", "Remove_unused_label_95053": "Remover rótulo não utilizado", "Remove_variable_statement_90010": "Remover instrução de variável", @@ -752,7 +752,7 @@ "Report_errors_on_unused_parameters_6135": "Relatar erros nos parâmetros não utilizados.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Os parâmetros de tipo necessários podem não seguir os parâmetros de tipo opcionais.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "A resolução para o módulo '{0}' foi encontrada no cache do local '{1}'.", - "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolva 'keyof' para nomes de propriedades com valores de cadeia de caracteres somente (sem números ou símbolos).", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolva 'keyof' somente para nomes de propriedades com valores de cadeia de caracteres (sem números nem símbolos).", "Resolving_from_node_modules_folder_6118": "Resolvendo na pasta node_modules...", "Resolving_module_0_from_1_6086": "======== Resolvendo módulo '{0}' de '{1}'. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolvendo nome de módulo '{0}' relativo à URL base '{1}' - '{2}'.", @@ -803,8 +803,8 @@ "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Mostrar o que seria compilado (ou excluído, se especificado com '--clean')", "Signature_0_must_be_a_type_predicate_1224": "A assinatura '{0}' deve ser um predicado de tipo.", "Skip_type_checking_of_declaration_files_6012": "Ignorar a verificação de tipo dos arquivos de declaração.", - "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Ignorando build do projeto '{0}' porque sua dependência '{1}' tem erros", - "Skipping_clean_because_not_all_projects_could_be_located_6371": "Ignorando a limpeza porque nem todos os projetos foram localizados", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Ignorando o build do projeto '{0}' porque a dependência '{1}' tem erros", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Ignorando a limpeza porque não foram localizados todos os projetos", "Source_Map_Options_6175": "Opções do Sourcemap", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "A assinatura de sobrecarga especializada não pode ser atribuída a qualquer assinatura não especializada.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "O especificador de importação dinâmica não pode ser o elemento de difusão.", @@ -966,7 +966,7 @@ "Unexpected_end_of_text_1126": "Fim inesperado do texto.", "Unexpected_token_1012": "Token inesperado.", "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token inesperado. Um construtor, método, acessador ou propriedade era esperado.", - "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Um nome de parâmetro de tipo era esperado sem chaves.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Era esperado um nome de parâmetro de tipo sem chaves.", "Unexpected_token_expected_1179": "Token inesperado. '{' esperado.", "Unknown_compiler_option_0_5023": "Opção do compilador '{0}' desconhecida.", "Unknown_option_excludes_Did_you_mean_exclude_6114": "Opção desconhecida 'excludes'. Você quis dizer 'exclude'?", @@ -993,7 +993,7 @@ "Variable_declaration_list_cannot_be_empty_1123": "A lista de declaração de variável não pode estar vazia.", "Version_0_6029": "Versão {0}", "Watch_input_files_6005": "Observe os arquivos de entrada.", - "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se se deve manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se é necessário manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Não é possível renomear elementos que são definidos na biblioteca TypeScript padrão.", "You_cannot_rename_this_element_8000": "Você não pode renomear este elemento.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' aceita muito poucos argumentos para serem usados como um decorador aqui. Você quis dizer para chamá-lo primeiro e gravar '@{0}()'?", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 611ccb3a4ad..284c223d0cd 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -49,8 +49,8 @@ "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden önce gelemez.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Ad alanı bildirimine yalnızca bir ad alanında veya modülde izin verilir.", "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Bir ad alanı stili içeri aktarma işlemi çağrılamadığından veya oluşturulamadığından çalışma zamanında hataya yol açacak.", - "A_non_dry_build_would_build_project_0_6357": "non-dry bir derleme '{0}' projesini derler", - "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "non-dry bir derleme şu dosyaları siler: {0}", + "A_non_dry_build_would_build_project_0_6357": "-dry bayrağı kullanılmayan bir derleme '{0}' projesini derler", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "-dry bayrağı kullanılmayan bir derleme şu dosyaları siler: {0}", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Parametre başlatıcısına yalnızca bir işlevde veya oluşturucu uygulamasında izin verilir.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Parametre özelliği, rest parametresi kullanılarak bildirilemez.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Parametre özelliğine yalnızca bir oluşturucu uygulamasında izin verilir.", @@ -110,7 +110,7 @@ "Add_initializers_to_all_uninitialized_properties_95027": "Tüm başlatılmamış özelliklere başlatıcılar ekle", "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekle", "Add_missing_typeof_95052": "Eksik 'typeof' öğesini ekle", - "Add_or_remove_braces_in_an_arrow_function_95058": "Ok işlevine küme ayracı ekleyin veya kaldırın", + "Add_or_remove_braces_in_an_arrow_function_95058": "Ok işlevine küme ayracı ekle veya kaldır", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Bir üye adıyla eşleşen tüm çözülmemiş değişkenlere niteleyici ekle", "Add_to_all_uncalled_decorators_95044": "Çağrılmayan tüm dekoratörlere '()' ekle", "Add_ts_ignore_to_all_error_messages_95042": "Tüm hata iletilerine '@ts-ignore' ekle", @@ -122,7 +122,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Tüm '{0}' bildirimleri aynı değiştiricilere sahip olmalıdır.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tüm '{0}' bildirimleri özdeş tür parametrelerine sahip olmalıdır.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Soyut metoda ait tüm bildirimler ardışık olmalıdır.", - "All_destructured_elements_are_unused_6198": "Yok edilen öğelerin hiçbiri kullanılmamış.", + "All_destructured_elements_are_unused_6198": "Yapısı bozulan öğelerin hiçbiri kullanılmıyor.", "All_imports_in_import_declaration_are_unused_6192": "İçeri aktarma bildirimindeki hiçbir içeri aktarma kullanılmadı.", "All_variables_are_unused_6199": "Hiçbir değişken kullanılmıyor.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.", @@ -232,7 +232,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Muhtemelen 'null' olan bir nesne çağrılamıyor.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Muhtemelen 'null' veya 'undefined' olan bir nesne çağrılamıyor.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Muhtemelen 'undefined' olan bir nesne çağrılamıyor.", - "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' projesi, 'outFile' kümesi içermediğinden başa eklenemiyor", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "{0}' projesi için 'outFile' ayarlanmadığından başa eklenemiyor", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' bayrağı sağlandığında bir tür yeniden dışarı aktarılamaz.", "Cannot_read_file_0_Colon_1_5012": "'{0}' dosyası okunamıyor: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Blok kapsamlı değişken '{0}', yeniden bildirilemiyor.", @@ -311,7 +311,7 @@ "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekoratörler aynı ada sahip birden fazla get/set erişimcisine uygulanamaz.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Modülün varsayılan dışarı aktarımı '{0}' özel adına sahip veya bu adı kullanıyor.", "Delete_all_unused_declarations_95024": "Kullanılmayan tüm bildirimleri sil", - "Delete_the_outputs_of_all_projects_6365": "Tüm projelerin çıkışlarını silin", + "Delete_the_outputs_of_all_projects_6365": "Tüm projelerin çıkışlarını sil", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Kullanım Dışı] Bunun yerine '--jsxFactory' kullanın. 'react' JSX gösterimi hedefleniyorsa, createElement için çağrılan nesneyi belirtin", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Kullanım Dışı] Bunun yerine '--outFile' kullanın. Çıkışı tek bir dosya olarak birleştirin ve gösterin", "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Kullanım Dışı] Bunun yerine '--skipLibCheck' kullanın. Varsayılan kitaplık bildirim dosyalarının tür denetimini atlayın.", @@ -362,13 +362,13 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Sınıflarda sıkı özellik başlatma denetimini etkinleştirin.", "Enable_strict_null_checks_6113": "Katı null denetimlerini etkinleştir.", "Enable_tracing_of_the_name_resolution_process_6085": "Ad çözümleme işlemini izlemeyi etkinleştir.", - "Enable_verbose_logging_6366": "Ayrıntılı günlüğe yazmayı etkinleştirin", + "Enable_verbose_logging_6366": "Ayrıntılı günlüğe yazmayı etkinleştir", "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Tüm içeri aktarma işlemleri için ad alanı nesnelerinin oluşturulması aracılığıyla CommonJS ile ES Modülleri arasında yayımlama birlikte çalışabilirliğine imkan tanır. Şu anlama gelir: 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Zaman uyumsuz ES7 işlevleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_ES7_decorators_6065": "ES7 dekoratörleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Dekoratörlere tür meta verisi gönderme için deneysel desteği etkinleştirir.", "Enum_0_used_before_its_declaration_2450": "'{0}' sabit listesi, bildiriminden önce kullanıldı.", - "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Enum bildirimleri yalnızca ad alanı veya diğer enum bildirimleri ile birleştirilebilir.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Sabit listesi bildirimleri yalnızca ad alanı veya diğer sabit listesi bildirimleri ile birleştirilebilir.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Sabit listesi bildirimlerinin tümü const veya const olmayan değerler olmalıdır.", "Enum_member_expected_1132": "Sabit listesi üyesi bekleniyor.", "Enum_member_must_have_initializer_1061": "Sabit listesi üyesi bir başlatıcıya sahip olmalıdır.", @@ -571,7 +571,7 @@ "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "{0} modülü, '{1}' adlı bir üyeyi zaten dışarı aktardı. Belirsizliği çözmek için açık olarak yeniden dışarı aktarmayı göz önünde bulundurun.", "Module_0_has_no_default_export_1192": "'{0}' modülü için varsayılan dışarı aktarma yok.", "Module_0_has_no_exported_member_1_2305": "'{0}' modülü, dışarı aktarılan '{1}' üyesine sahip değil.", - "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "'{0}' modülünün dışa aktarılan '{1}' adlı bir üyesi yok. Şunu mu demek istediniz: '{2}'?", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "{0}' modülünün dışarı aktarılan '{1}' adlı bir üyesi yok. Şunu mu demek istediniz: '{2}'?", "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "'{0}' modülü, aynı ada sahip bir yerel bildirim tarafından gizleniyor.", "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "'{0}' modülü, modül olmayan bir varlığa çözümleniyor ve bu oluşturma ile içeri aktarılamaz.", "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "'{0}' modülü 'export =' kullanıyor ve 'export *' ile birlikte kullanılamaz.", @@ -737,7 +737,7 @@ "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Başvurulan proje '{0}' \"composite\": true ayarına sahip olmalıdır.", "Remove_all_unreachable_code_95051": "Tüm erişilemeyen kodları kaldır", "Remove_all_unused_labels_95054": "Kullanılmayan tüm etiketleri kaldır", - "Remove_braces_from_arrow_function_95060": "Ok işlevinden köşeli ayraçları kaldırın", + "Remove_braces_from_arrow_function_95060": "Ok işlevinden küme ayraçlarını kaldır", "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldır", "Remove_destructuring_90009": "Yıkmayı kaldır", "Remove_import_from_0_90005": "'{0}' öğesinden içeri aktarmayı kaldır", diff --git a/lib/tsc.js b/lib/tsc.js index 7a7216cf020..537612cb376 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -14,7 +14,8 @@ and limitations under the License. ***************************************************************************** */ -"use strict";"use strict"; +"use strict"; +"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { @@ -59,10 +60,11 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook }; var ts; (function (ts) { - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.3"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -428,7 +430,24 @@ var ts; function flatMap(array, mapfn) { var result; if (array) { - result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { for (var i = 0; i < array.length; i++) { var v = mapfn(array[i], i); if (v) { @@ -443,7 +462,7 @@ var ts; } return result; } - ts.flatMap = flatMap; + ts.flatMapToMutable = flatMapToMutable; function flatMapIterator(iter, mapfn) { var first = iter.next(); if (first.done) { @@ -661,18 +680,15 @@ var ts; return result; } function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) - return []; + return ts.emptyArray; var last = array[0]; var deduplicated = [last]; for (var i = 1; i < array.length; i++) { @@ -700,7 +716,7 @@ var ts; } ts.insertSorted = insertSorted; function sortAndDeduplicate(array, comparer, equalityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); } ts.sortAndDeduplicate = sortAndDeduplicate; function arrayIsEqualTo(array1, array2, equalityComparer) { @@ -712,7 +728,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -823,7 +839,7 @@ var ts; indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); } function sort(array, comparer) { - return array.slice().sort(comparer); + return (array.length === 0 ? array : array.slice().sort(comparer)); } ts.sort = sort; function arrayIterator(array) { @@ -902,12 +918,15 @@ var ts; } ts.replaceElement = replaceElement; function binarySearch(array, value, keySelector, keyComparer, offset) { - if (!array || array.length === 0) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { return -1; } var low = offset || 0; var high = array.length - 1; - var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); var midKey = keySelector(array[middle]); @@ -924,7 +943,7 @@ var ts; } return ~low; } - ts.binarySearch = binarySearch; + ts.binarySearchKey = binarySearchKey; function reduceLeft(array, f, initial, start, count) { if (array && array.length > 0) { var size = array.length; @@ -1011,7 +1030,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1125,6 +1144,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1276,7 +1299,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1673,6 +1698,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); var ts; (function (ts) { @@ -1687,6 +1716,33 @@ var ts; var counts; var marks; var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; function mark(markName) { if (enabled) { marks.set(markName, ts.timestamp()); @@ -1732,6 +1788,287 @@ var ts; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + var Version = (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + if (this === other) + return 0; + if (other === undefined) + return 1; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + if (left === right) + return 0; + if (left.length === 0) + return right.length === 0 ? 0 : 1; + if (right.length === 0) + return -1; + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 : 1; + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + return ts.compareValues(left.length, right.length); + } + var VersionRange = (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); +var ts; (function (ts) { var OperationCanceledException = (function () { function OperationCanceledException() { @@ -1751,13 +2088,14 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { @@ -1840,19 +2178,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; ts.missingFileModifiedTime = new Date(0); function createPollingIntervalBasedLevels(levels) { var _a; @@ -2048,17 +2373,20 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; function createRecursiveDirectoryWatcher(host) { var cache = ts.createMap(); var callbackCache = ts.createMultiMap(); @@ -2331,10 +2659,11 @@ var ts; } function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { - var fileName = !ts.isString(relativeFileName) - ? undefined - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -2885,7 +3214,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -2924,6 +3253,11 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -2936,7 +3270,7 @@ var ts; An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), - An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), @@ -2980,14 +3314,14 @@ var ts; Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), @@ -3043,7 +3377,7 @@ var ts; Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), - A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), @@ -3126,7 +3460,7 @@ var ts; _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), - Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), @@ -3157,7 +3491,7 @@ var ts; Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), @@ -3167,7 +3501,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -3195,6 +3528,15 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -3286,6 +3628,15 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -3399,7 +3750,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -3493,7 +3846,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -3591,6 +3944,18 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -3621,9 +3986,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -3631,6 +3996,7 @@ var ts; _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), @@ -3658,6 +4024,15 @@ var ts; If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -3688,6 +4063,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -3752,6 +4128,7 @@ var ts; Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -3816,148 +4193,106 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; function tokenIsIdentifierOrKeyword(token) { - return token >= 71; + return token >= 72; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; function tokenIsIdentifierOrKeywordOrGreaterThan(token) { - return token === 29 || tokenIsIdentifierOrKeyword(token); + return token === 30 || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117, - "any": 119, - "as": 118, - "boolean": 122, - "break": 72, - "case": 73, - "catch": 74, - "class": 75, - "continue": 77, - "const": 76, - "constructor": 123, - "debugger": 78, - "declare": 124, - "default": 79, - "delete": 80, - "do": 81, - "else": 82, - "enum": 83, - "export": 84, - "extends": 85, - "false": 86, - "finally": 87, - "for": 88, - "from": 143, - "function": 89, - "get": 125, - "if": 90, - "implements": 108, - "import": 91, - "in": 92, - "infer": 126, - "instanceof": 93, - "interface": 109, - "is": 127, - "keyof": 128, - "let": 110, - "module": 129, - "namespace": 130, - "never": 131, - "new": 94, - "null": 95, - "number": 134, - "object": 135, - "package": 111, - "private": 112, - "protected": 113, - "public": 114, - "readonly": 132, - "require": 133, - "global": 144, - "return": 96, - "set": 136, - "static": 115, - "string": 137, - "super": 97, - "switch": 98, - "symbol": 138, - "this": 99, - "throw": 100, - "true": 101, - "try": 102, - "type": 139, - "typeof": 103, - "undefined": 140, - "unique": 141, - "unknown": 142, - "var": 104, - "void": 105, - "while": 106, - "with": 107, - "yield": 116, - "async": 120, - "await": 121, - "of": 145, - "{": 17, - "}": 18, - "(": 19, - ")": 20, - "[": 21, - "]": 22, - ".": 23, - "...": 24, - ";": 25, - ",": 26, - "<": 27, - ">": 29, - "<=": 30, - ">=": 31, - "==": 32, - "!=": 33, - "===": 34, - "!==": 35, - "=>": 36, - "+": 37, - "-": 38, - "**": 40, - "*": 39, - "/": 41, - "%": 42, - "++": 43, - "--": 44, - "<<": 45, - ">": 46, - ">>>": 47, - "&": 48, - "|": 49, - "^": 50, - "!": 51, - "~": 52, - "&&": 53, - "||": 54, - "?": 55, - ":": 56, - "=": 58, - "+=": 59, - "-=": 60, - "*=": 61, - "**=": 62, - "/=": 63, - "%=": 64, - "<<=": 65, - ">>=": 66, - ">>>=": 67, - "&=": 68, - "|=": 69, - "^=": 70, - "@": 57, - }); + var textToKeywordObj = (_a = { + abstract: 118, + any: 120, + as: 119, + bigint: 146, + boolean: 123, + break: 73, + case: 74, + catch: 75, + class: 76, + continue: 78, + const: 77 + }, + _a["" + "constructor"] = 124, + _a.debugger = 79, + _a.declare = 125, + _a.default = 80, + _a.delete = 81, + _a.do = 82, + _a.else = 83, + _a.enum = 84, + _a.export = 85, + _a.extends = 86, + _a.false = 87, + _a.finally = 88, + _a.for = 89, + _a.from = 144, + _a.function = 90, + _a.get = 126, + _a.if = 91, + _a.implements = 109, + _a.import = 92, + _a.in = 93, + _a.infer = 127, + _a.instanceof = 94, + _a.interface = 110, + _a.is = 128, + _a.keyof = 129, + _a.let = 111, + _a.module = 130, + _a.namespace = 131, + _a.never = 132, + _a.new = 95, + _a.null = 96, + _a.number = 135, + _a.object = 136, + _a.package = 112, + _a.private = 113, + _a.protected = 114, + _a.public = 115, + _a.readonly = 133, + _a.require = 134, + _a.global = 145, + _a.return = 97, + _a.set = 137, + _a.static = 116, + _a.string = 138, + _a.super = 98, + _a.switch = 99, + _a.symbol = 139, + _a.this = 100, + _a.throw = 101, + _a.true = 102, + _a.try = 103, + _a.type = 140, + _a.typeof = 104, + _a.undefined = 141, + _a.unique = 142, + _a.unknown = 143, + _a.var = 105, + _a.void = 106, + _a.while = 107, + _a.with = 108, + _a.yield = 117, + _a.async = 121, + _a.await = 122, + _a.of = 147, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18, "}": 19, "(": 20, ")": 21, "[": 22, "]": 23, ".": 24, "...": 25, ";": 26, ",": 27, "<": 28, ">": 30, "<=": 31, ">=": 32, "==": 33, "!=": 34, "===": 35, "!==": 36, "=>": 37, "+": 38, "-": 39, "**": 41, "*": 40, "/": 42, "%": 43, "++": 44, "--": 45, "<<": 46, ">": 47, ">>>": 48, "&": 49, "|": 50, "^": 51, "!": 52, "~": 53, "&&": 54, "||": 55, "?": 56, ":": 57, "=": 59, "+=": 60, "-=": 61, "*=": 62, "**=": 63, "/=": 64, "%=": 65, "<<=": 66, ">>=": 67, ">>>=": 68, "&=": 69, "|=": 70, "^=": 71, "@": 58 })); var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -4043,11 +4378,23 @@ var ts; return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; - function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { - ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + if (allowEdits) { + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } } var res = lineStarts[line] + character; + if (allowEdits) { + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } if (line < lineStarts.length - 1) { ts.Debug.assert(res < lineStarts[line + 1]); } @@ -4418,6 +4765,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -4428,8 +4776,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return (tokenFlags & 8) !== 0; }, hasPrecedingLineBreak: function () { return (tokenFlags & 1) !== 0; }, - isIdentifier: function () { return token === 71 || token > 107; }, - isReservedWord: function () { return token >= 72 && token <= 107; }, + isIdentifier: function () { return token === 72 || token > 108; }, + isReservedWord: function () { return token >= 73 && token <= 108; }, isUnterminated: function () { return (tokenFlags & 4) !== 0; }, getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, @@ -4447,6 +4795,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -4522,18 +4871,29 @@ var ts; end = pos; } } + var result; if (tokenFlags & 512) { - var result = mainFragment; + result = mainFragment; if (decimalFragment) { result += "." + decimalFragment; } if (scientificFragment) { result += scientificFragment; } - return "" + +result; } else { - return "" + +(text.substring(start, end)); + result = text.substring(start, end); + } + if (decimalFragment !== undefined || tokenFlags & 16) { + return { + type: 8, + value: "" + +result + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); + return { type: type, value: tokenValue }; } } function scanOctalDigits() { @@ -4544,17 +4904,17 @@ var ts; return +(text.substring(start, pos)); } function scanExactNumberOfHexDigits(count, canHaveSeparators) { - return scanHexDigits(count, false, canHaveSeparators); + var valueString = scanHexDigits(count, false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; } function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { return scanHexDigits(count, true, canHaveSeparators); } function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { - var digits = 0; - var value = 0; + var valueChars = []; var allowSeparator = false; var isPreviousTokenSeparator = false; - while (digits < minCount || scanAsManyAsPossible) { + while (valueChars.length < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); if (canHaveSeparators && ch === 95) { tokenFlags |= 512; @@ -4572,29 +4932,24 @@ var ts; continue; } allowSeparator = canHaveSeparators; - if (ch >= 48 && ch <= 57) { - value = value * 16 + ch - 48; + if (ch >= 65 && ch <= 70) { + ch += 97 - 65; } - else if (ch >= 65 && ch <= 70) { - value = value * 16 + ch - 65 + 10; - } - else if (ch >= 97 && ch <= 102) { - value = value * 16 + ch - 97 + 10; - } - else { + else if (!((ch >= 48 && ch <= 57) || + (ch >= 97 && ch <= 102))) { break; } + valueChars.push(ch); pos++; - digits++; isPreviousTokenSeparator = false; } - if (digits < minCount) { - value = -1; + if (valueChars.length < minCount) { + valueChars = []; } if (text.charCodeAt(pos - 1) === 95) { error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } - return value; + return String.fromCharCode.apply(String, valueChars); } function scanString(jsxAttributeString) { if (jsxAttributeString === void 0) { jsxAttributeString = false; } @@ -4642,20 +4997,20 @@ var ts; contents += text.substring(start, pos); tokenFlags |= 4; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 13 : 16; + resultingToken = startedWithBacktick ? 14 : 17; break; } var currChar = text.charCodeAt(pos); if (currChar === 96) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 13 : 16; + resultingToken = startedWithBacktick ? 14 : 17; break; } if (currChar === 36 && pos + 1 < end && text.charCodeAt(pos + 1) === 123) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 14 : 15; + resultingToken = startedWithBacktick ? 15 : 16; break; } if (currChar === 92) { @@ -4739,7 +5094,8 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1, false); + var escapedValueString = scanMinimumNumberOfHexDigits(1, false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; var isInvalidExtendedEscape = false; if (escapedValue < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); @@ -4814,18 +5170,16 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 && ch <= 122) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } - return token = 71; + return token = 72; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); - var value = 0; - var numberOfDigits = 0; + var value = ""; var separatorAllowed = false; var isPreviousTokenSeparator = false; while (true) { @@ -4846,27 +5200,42 @@ var ts; continue; } separatorAllowed = true; - var valueOfCh = ch - 48; - if (!isDigit(ch) || valueOfCh >= base) { + if (!isDigit(ch) || ch - 48 >= base) { break; } - value = value * base + valueOfCh; + value += text[pos]; pos++; - numberOfDigits++; isPreviousTokenSeparator = false; } - if (numberOfDigits === 0) { - return -1; - } if (text.charCodeAt(pos - 1) === 95) { error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); - return value; } return value; } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110) { + tokenValue += "n"; + if (tokenFlags & 384) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9; + } + else { + var numericValue = tokenFlags & 128 + ? parseInt(tokenValue.slice(2), 2) + : tokenFlags & 256 + ? parseInt(tokenValue.slice(2), 8) + : +tokenValue; + tokenValue = "" + numericValue; + return 8; + } + } function scan() { + var _a; startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -4903,6 +5272,24 @@ var ts; case 11: case 12: case 32: + case 160: + case 5760: + case 8192: + case 8193: + case 8194: + case 8195: + case 8196: + case 8197: + case 8198: + case 8199: + case 8200: + case 8201: + case 8202: + case 8203: + case 8239: + case 8287: + case 12288: + case 65279: if (skipTrivia) { pos++; continue; @@ -4916,65 +5303,57 @@ var ts; case 33: if (text.charCodeAt(pos + 1) === 61) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 35; + return pos += 3, token = 36; } - return pos += 2, token = 33; + return pos += 2, token = 34; } pos++; - return token = 51; + return token = 52; case 34: case 39: tokenValue = scanString(); - return token = 9; + return token = 10; case 96: return token = scanTemplateAndSetTokenValue(); case 37: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 64; + return pos += 2, token = 65; } pos++; - return token = 42; + return token = 43; case 38: if (text.charCodeAt(pos + 1) === 38) { - return pos += 2, token = 53; + return pos += 2, token = 54; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 68; + return pos += 2, token = 69; } pos++; - return token = 48; + return token = 49; case 40: pos++; - return token = 19; + return token = 20; case 41: pos++; - return token = 20; + return token = 21; case 42: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 61; + return pos += 2, token = 62; } if (text.charCodeAt(pos + 1) === 42) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 62; + return pos += 3, token = 63; } - return pos += 2, token = 40; + return pos += 2, token = 41; } pos++; - return token = 39; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1)) { + asteriskSeen = true; + continue; + } + return token = 40; case 43: if (text.charCodeAt(pos + 1) === 43) { - return pos += 2, token = 43; - } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 59; - } - pos++; - return token = 37; - case 44: - pos++; - return token = 26; - case 45: - if (text.charCodeAt(pos + 1) === 45) { return pos += 2, token = 44; } if (text.charCodeAt(pos + 1) === 61) { @@ -4982,16 +5361,28 @@ var ts; } pos++; return token = 38; + case 44: + pos++; + return token = 27; + case 45: + if (text.charCodeAt(pos + 1) === 45) { + return pos += 2, token = 45; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 61; + } + pos++; + return token = 39; case 46: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber(); + tokenValue = scanNumber().value; return token = 8; } if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { - return pos += 3, token = 24; + return pos += 3, token = 25; } pos++; - return token = 23; + return token = 24; case 47: if (text.charCodeAt(pos + 1) === 47) { pos += 2; @@ -5040,43 +5431,43 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 63; + return pos += 2, token = 64; } pos++; - return token = 41; + return token = 42; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1, true); - if (value < 0) { + tokenValue = scanMinimumNumberOfHexDigits(1, true); + if (!tokenValue) { error(ts.Diagnostics.Hexadecimal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0x" + tokenValue; tokenFlags |= 64; - return token = 8; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 || text.charCodeAt(pos + 1) === 98)) { pos += 2; - var value = scanBinaryOrOctalDigits(2); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(2); + if (!tokenValue) { error(ts.Diagnostics.Binary_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0b" + tokenValue; tokenFlags |= 128; - return token = 8; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 || text.charCodeAt(pos + 1) === 111)) { pos += 2; - var value = scanBinaryOrOctalDigits(8); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(8); + if (!tokenValue) { error(ts.Diagnostics.Octal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0o" + tokenValue; tokenFlags |= 256; - return token = 8; + return token = checkBigIntSuffix(); } if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { tokenValue = "" + scanOctalDigits(); @@ -5092,14 +5483,14 @@ var ts; case 55: case 56: case 57: - tokenValue = scanNumber(); - return token = 8; + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; case 58: pos++; - return token = 56; + return token = 57; case 59: pos++; - return token = 25; + return token = 26; case 60: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -5112,20 +5503,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 65; + return pos += 3, token = 66; } - return pos += 2, token = 45; + return pos += 2, token = 46; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 30; + return pos += 2, token = 31; } if (languageVariant === 1 && text.charCodeAt(pos + 1) === 47 && text.charCodeAt(pos + 2) !== 42) { - return pos += 2, token = 28; + return pos += 2, token = 29; } pos++; - return token = 27; + return token = 28; case 61: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -5138,15 +5529,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 34; + return pos += 3, token = 35; } - return pos += 2, token = 32; + return pos += 2, token = 33; } if (text.charCodeAt(pos + 1) === 62) { - return pos += 2, token = 36; + return pos += 2, token = 37; } pos++; - return token = 58; + return token = 59; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -5158,25 +5549,25 @@ var ts; } } pos++; - return token = 29; + return token = 30; case 63: pos++; - return token = 55; + return token = 56; case 91: pos++; - return token = 21; + return token = 22; case 93: pos++; - return token = 22; + return token = 23; case 94: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 70; + return pos += 2, token = 71; } pos++; - return token = 50; + return token = 51; case 123: pos++; - return token = 17; + return token = 18; case 124: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -5188,22 +5579,22 @@ var ts; } } if (text.charCodeAt(pos + 1) === 124) { - return pos += 2, token = 54; + return pos += 2, token = 55; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 69; + return pos += 2, token = 70; } pos++; - return token = 49; + return token = 50; case 125: pos++; - return token = 18; + return token = 19; case 126: pos++; - return token = 52; + return token = 53; case 64: pos++; - return token = 57; + return token = 58; case 92: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -5241,29 +5632,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 29) { + if (token === 30) { if (text.charCodeAt(pos) === 62) { if (text.charCodeAt(pos + 1) === 62) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 67; + return pos += 3, token = 68; } - return pos += 2, token = 47; + return pos += 2, token = 48; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 66; + return pos += 2, token = 67; } pos++; - return token = 46; + return token = 47; } if (text.charCodeAt(pos) === 61) { pos++; - return token = 31; + return token = 32; } } return token; } function reScanSlashToken() { - if (token === 41 || token === 63) { + if (token === 42 || token === 64) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -5302,12 +5693,12 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12; + token = 13; } return token; } function reScanTemplateToken() { - ts.Debug.assert(token === 18, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 19, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -5324,14 +5715,14 @@ var ts; if (char === 60) { if (text.charCodeAt(pos + 1) === 47) { pos += 2; - return token = 28; + return token = 29; } pos++; - return token = 27; + return token = 28; } if (char === 123) { pos++; - return token = 17; + return token = 18; } var firstNonWhitespace = 0; while (pos < end) { @@ -5354,7 +5745,7 @@ var ts; } pos++; } - return firstNonWhitespace === -1 ? 11 : 10; + return firstNonWhitespace === -1 ? 12 : 11; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { @@ -5378,7 +5769,7 @@ var ts; case 34: case 39: tokenValue = scanString(true); - return token = 9; + return token = 10; default: return scan(); } @@ -5401,43 +5792,43 @@ var ts; } return token = 5; case 64: - return token = 57; + return token = 58; case 10: case 13: tokenFlags |= 1; return token = 4; case 42: - return token = 39; + return token = 40; case 123: - return token = 17; - case 125: return token = 18; + case 125: + return token = 19; case 91: - return token = 21; - case 93: return token = 22; - case 60: - return token = 27; - case 61: - return token = 58; - case 44: - return token = 26; - case 46: + case 93: return token = 23; + case 60: + return token = 28; + case 61: + return token = 59; + case 44: + return token = 27; + case 46: + return token = 24; case 96: while (pos < end && text.charCodeAt(pos) !== 96) { pos++; } tokenValue = text.substring(tokenPos + 1, pos); pos++; - return token = 13; + return token = 14; } if (isIdentifierStart(ch, 6)) { while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71; + return token = getIdentifierToken(); } else { return token = 0; @@ -5512,6 +5903,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -5527,7 +5921,6 @@ var ts; ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; })(ts || (ts = {})); (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -5573,7 +5966,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -5582,7 +5974,9 @@ var ts; writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, - writeSymbol: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, getTextPos: function () { return str.length; }, getLine: function () { return 0; }, getColumn: function () { return 0; }, @@ -5606,22 +6000,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -5726,6 +6107,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -5778,7 +6165,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 277) { + while (node && node.kind !== 279) { node = node.parent; } return node; @@ -5786,11 +6173,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 216: - case 244: - case 223: - case 224: + case 218: + case 246: case 225: + case 226: + case 227: return true; } return false; @@ -5883,7 +6270,7 @@ var ts; if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 304 && node._children.length > 0) { + if (node.kind === 306 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -5901,12 +6288,19 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -5926,29 +6320,31 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { - if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512)) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512) || + ts.isBigIntLiteral(node))) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216) ? escapeString : escapeNonAsciiString; switch (node.kind) { - case 9: + case 10: if (node.singleQuote) { return "'" + escapeText(node.text, 39) + "'"; } else { return '"' + escapeText(node.text, 34) + '"'; } - case 13: - return "`" + escapeText(node.text, 96) + "`"; case 14: - return "`" + escapeText(node.text, 96) + "${"; + return "`" + escapeText(node.text, 96) + "`"; case 15: - return "}" + escapeText(node.text, 96) + "${"; + return "`" + escapeText(node.text, 96) + "${"; case 16: + return "}" + escapeText(node.text, 96) + "${"; + case 17: return "}" + escapeText(node.text, 96) + "`"; case 8: - case 12: + case 9: + case 13: return node.text; } return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -5969,15 +6365,15 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 235 && node.parent.kind === 272; + return node.kind === 237 && node.parent.kind === 274; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return ts.isModuleDeclaration(node) && (node.name.kind === 9 || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 10 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { - return ts.isModuleDeclaration(node) && node.name.kind === 9; + return ts.isModuleDeclaration(node) && node.name.kind === 10; } ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { @@ -5993,11 +6389,11 @@ var ts; } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { - return node && node.kind === 242 && (!node.body); + return node && node.kind === 244 && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 277 || - node.kind === 242 || + return node.kind === 279 || + node.kind === 244 || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -6011,9 +6407,9 @@ var ts; ts.isExternalModuleAugmentation = isExternalModuleAugmentation; function isModuleAugmentationExternal(node) { switch (node.parent.kind) { - case 277: + case 279: return ts.isExternalModule(node.parent); - case 243: + case 245: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; @@ -6029,22 +6425,22 @@ var ts; ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 277: + case 279: + case 246: + case 274: case 244: - case 272: - case 242: - case 223: - case 224: case 225: - case 155: - case 154: - case 156: + case 226: + case 227: case 157: - case 237: - case 194: - case 195: + case 156: + case 158: + case 159: + case 239: + case 196: + case 197: return true; - case 216: + case 218: return !ts.isFunctionLike(parentNode); } return false; @@ -6052,9 +6448,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 295: - case 302: - case 291: + case 297: + case 304: + case 293: return true; default: ts.assertType(node); @@ -6064,25 +6460,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 158: - case 159: - case 153: case 160: - case 163: - case 164: - case 287: - case 238: - case 207: - case 239: - case 240: - case 301: - case 237: - case 154: + case 161: case 155: + case 162: + case 165: + case 166: + case 289: + case 240: + case 209: + case 241: + case 242: + case 303: + case 239: case 156: case 157: - case 194: - case 195: + case 158: + case 159: + case 196: + case 197: return true; default: ts.assertType(node); @@ -6092,8 +6488,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 247: - case 246: + case 249: + case 248: return true; default: return false; @@ -6102,15 +6498,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 247: - case 246: - case 217: - case 238: - case 237: - case 242: + case 249: + case 248: + case 219: case 240: case 239: + case 244: + case 242: case 241: + case 243: return true; default: return false; @@ -6135,12 +6531,13 @@ var ts; ts.getNameFromIndexInfo = getNameFromIndexInfo; function getTextOfPropertyName(name) { switch (name.kind) { - case 71: + case 72: return name.escapedText; - case 9: + case 10: case 8: + case 14: return ts.escapeLeadingUnderscores(name.text); - case 147: + case 149: return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; default: return ts.Debug.assertNever(name); @@ -6149,11 +6546,11 @@ var ts; ts.getTextOfPropertyName = getTextOfPropertyName; function entityNameToString(name) { switch (name.kind) { - case 71: + case 72: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 146: + case 148: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 187: + case 189: return entityNameToString(name.expression) + "." + entityNameToString(name.name); default: throw ts.Debug.assertNever(name); @@ -6198,7 +6595,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 216) { + if (node.body && node.body.kind === 218) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -6210,31 +6607,31 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 277: + case 279: 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 235: - case 184: - case 238: - case 207: - case 239: - case 242: - case 241: - case 276: case 237: - case 194: - case 154: - case 156: - case 157: + case 186: case 240: - case 152: - case 151: + case 209: + case 241: + case 244: + case 243: + case 278: + case 239: + case 196: + case 156: + case 158: + case 159: + case 242: + case 154: + case 153: errorNode = node.name; break; - case 195: + case 197: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -6267,6 +6664,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2); } @@ -6276,11 +6677,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 189 && n.expression.kind === 97; + return n.kind === 191 && n.expression.kind === 98; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 189 && n.expression.kind === 91; + return n.kind === 191 && n.expression.kind === 92; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { @@ -6288,20 +6689,20 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 219 - && node.expression.kind === 9; + return node.kind === 221 + && node.expression.kind === 10; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return node.kind !== 10 ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + return node.kind !== 11 ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 149 || - node.kind === 148 || - node.kind === 194 || - node.kind === 195 || - node.kind === 193) ? + var commentRanges = (node.kind === 151 || + node.kind === 150 || + node.kind === 196 || + node.kind === 197 || + node.kind === 195) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); return ts.filter(commentRanges, function (comment) { @@ -6316,77 +6717,79 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (161 <= node.kind && node.kind <= 181) { + if (163 <= node.kind && node.kind <= 183) { return true; } switch (node.kind) { - case 119: - case 142: - case 134: - case 137: - case 122: - case 138: - case 140: - case 131: - return true; - case 105: - return node.parent.kind !== 198; - case 209: - return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 148: - return node.parent.kind === 179 || node.parent.kind === 174; - case 71: - if (node.parent.kind === 146 && node.parent.right === node) { - node = node.parent; - } - else if (node.parent.kind === 187 && node.parent.name === node) { - node = node.parent; - } - ts.Debug.assert(node.kind === 71 || node.kind === 146 || node.kind === 187, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 120: + case 143: + case 135: case 146: - case 187: - case 99: { + case 138: + case 123: + case 139: + case 136: + case 141: + case 132: + return true; + case 106: + return node.parent.kind !== 200; + case 211: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 150: + return node.parent.kind === 181 || node.parent.kind === 176; + case 72: + if (node.parent.kind === 148 && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 189 && node.parent.name === node) { + node = node.parent; + } + ts.Debug.assert(node.kind === 72 || node.kind === 148 || node.kind === 189, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 148: + case 189: + case 100: { var parent = node.parent; - if (parent.kind === 165) { + if (parent.kind === 167) { return false; } - if (parent.kind === 181) { + if (parent.kind === 183) { return !parent.isTypeOf; } - if (161 <= parent.kind && parent.kind <= 181) { + if (163 <= parent.kind && parent.kind <= 183) { return true; } switch (parent.kind) { - case 209: + case 211: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 148: + case 150: return node === parent.constraint; - case 301: + case 303: return node === parent.constraint; - case 152: - case 151: - case 149: - case 235: - return node === parent.type; - case 237: - case 194: - case 195: - case 155: case 154: case 153: - case 156: - case 157: + case 151: + case 237: return node === parent.type; + case 239: + case 196: + case 197: + case 157: + case 156: + case 155: case 158: case 159: + return node === parent.type; case 160: + case 161: + case 162: return node === parent.type; - case 192: + case 194: return node === parent.type; - case 189: - case 190: - return ts.contains(parent.typeArguments, node); case 191: + case 192: + return ts.contains(parent.typeArguments, node); + case 193: return false; } } @@ -6408,23 +6811,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 228: + case 230: return visitor(node); - case 244: - case 216: - case 220: - case 221: + case 246: + case 218: case 222: case 223: case 224: case 225: - case 229: - case 230: - case 269: - case 270: + case 226: + case 227: case 231: - case 233: + case 232: + case 271: case 272: + case 233: + case 235: + case 274: return ts.forEachChild(node, traverse); } } @@ -6434,23 +6837,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 205: + case 207: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; + case 243: case 241: - case 239: + case 244: case 242: case 240: - case 238: - case 207: + case 209: return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 147) { + if (node.name && node.name.kind === 149) { traverse(node.name.expression); return; } @@ -6463,10 +6866,10 @@ var ts; } ts.forEachYieldExpression = forEachYieldExpression; function getRestParameterElementType(node) { - if (node && node.kind === 167) { + if (node && node.kind === 169) { return node.elementType; } - else if (node && node.kind === 162) { + else if (node && node.kind === 164) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -6476,12 +6879,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 239: - case 238: - case 207: - case 166: + case 241: + case 240: + case 209: + case 168: return node.members; - case 186: + case 188: return node.properties; } } @@ -6489,14 +6892,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 184: - case 276: - case 149: - case 273: - case 152: + case 186: + case 278: case 151: - case 274: - case 235: + case 275: + case 154: + case 153: + case 276: + case 237: return true; } } @@ -6508,8 +6911,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 236 - && node.parent.parent.kind === 217; + return node.parent.kind === 238 + && node.parent.parent.kind === 219; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -6520,13 +6923,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 154: - case 153: - case 155: case 156: + case 155: case 157: - case 237: - case 194: + case 158: + case 159: + case 239: + case 196: return true; } return false; @@ -6537,7 +6940,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 231) { + if (node.statement.kind !== 233) { return node.statement; } node = node.statement; @@ -6545,17 +6948,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 216 && ts.isFunctionLike(node.parent); + return node && node.kind === 218 && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 154 && node.parent.kind === 186; + return node && node.kind === 156 && node.parent.kind === 188; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 154 && - (node.parent.kind === 186 || - node.parent.kind === 207); + return node.kind === 156 && + (node.parent.kind === 188 || + node.parent.kind === 209); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -6568,7 +6971,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 273) { + if (property.kind === 275) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -6605,46 +7008,46 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 277); + ts.Debug.assert(node.kind !== 279); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); } switch (node.kind) { - case 147: + case 149: if (ts.isClassLike(node.parent.parent)) { return node; } node = node.parent; break; - case 150: - if (node.parent.kind === 149 && ts.isClassElement(node.parent.parent)) { + case 152: + if (node.parent.kind === 151 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { node = node.parent; } break; - case 195: + case 197: if (!includeArrowFunctions) { continue; } - case 237: - case 194: - case 242: - case 152: - case 151: + case 239: + case 196: + case 244: case 154: case 153: - case 155: case 156: + case 155: case 157: case 158: case 159: case 160: - case 241: - case 277: + case 161: + case 162: + case 243: + case 279: return node; } } @@ -6654,9 +7057,9 @@ var ts; var container = getThisContainer(node, false); if (container) { switch (container.kind) { - case 155: - case 237: - case 194: + case 157: + case 239: + case 196: return container; } } @@ -6670,25 +7073,25 @@ var ts; return node; } switch (node.kind) { - case 147: + case 149: node = node.parent; break; - case 237: - case 194: - case 195: + case 239: + case 196: + case 197: if (!stopOnFunctions) { continue; } - case 152: - case 151: case 154: case 153: - case 155: case 156: + case 155: case 157: + case 158: + case 159: return node; - case 150: - if (node.parent.kind === 149 && ts.isClassElement(node.parent.parent)) { + case 152: + if (node.parent.kind === 151 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { @@ -6700,14 +7103,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 194 || func.kind === 195) { + if (func.kind === 196 || func.kind === 197) { var prev = func; var parent = func.parent; - while (parent.kind === 193) { + while (parent.kind === 195) { prev = parent; parent = parent.parent; } - if (parent.kind === 189 && parent.expression === prev) { + if (parent.kind === 191 && parent.expression === prev) { return parent; } } @@ -6715,26 +7118,26 @@ var ts; ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; function isSuperProperty(node) { var kind = node.kind; - return (kind === 187 || kind === 188) - && node.expression.kind === 97; + return (kind === 189 || kind === 190) + && node.expression.kind === 98; } ts.isSuperProperty = isSuperProperty; function isThisProperty(node) { var kind = node.kind; - return (kind === 187 || kind === 188) - && node.expression.kind === 99; + return (kind === 189 || kind === 190) + && node.expression.kind === 100; } ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 162: + case 164: return node.typeName; - case 209: + case 211: return isEntityNameExpression(node.expression) ? node.expression : undefined; - case 71: - case 146: + case 72: + case 148: return node; } return undefined; @@ -6742,10 +7145,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 191: + case 193: return node.tag; - case 260: - case 259: + case 262: + case 261: return node.tagName; default: return node.expression; @@ -6754,21 +7157,21 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 238: + case 240: return true; - case 152: - return parent.kind === 238; - case 156: - case 157: case 154: + return parent.kind === 240; + case 158: + case 159: + case 156: return node.body !== undefined - && parent.kind === 238; - case 149: + && parent.kind === 240; + case 151: return parent.body !== undefined - && (parent.kind === 155 - || parent.kind === 154 - || parent.kind === 157) - && grandparent.kind === 238; + && (parent.kind === 157 + || parent.kind === 156 + || parent.kind === 159) + && grandparent.kind === 240; } return false; } @@ -6784,10 +7187,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 238: + case 240: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); - case 154: - case 157: + case 156: + case 159: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); default: return false; @@ -6796,9 +7199,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 260 || - parent.kind === 259 || - parent.kind === 261) { + if (parent.kind === 262 || + parent.kind === 261 || + parent.kind === 263) { return parent.tagName === node; } return false; @@ -6806,55 +7209,56 @@ var ts; ts.isJSXTagName = isJSXTagName; function isExpressionNode(node) { switch (node.kind) { - case 97: - case 95: - case 101: - case 86: - case 12: - case 185: - case 186: + case 98: + case 96: + case 102: + case 87: + case 13: case 187: case 188: case 189: case 190: case 191: - case 210: case 192: - case 211: case 193: + case 212: case 194: - case 207: + case 213: case 195: - case 198: case 196: + case 209: case 197: case 200: - case 201: + case 198: + case 199: case 202: case 203: - case 206: case 204: - case 13: - case 208: - case 258: - case 259: - case 262: case 205: - case 199: - case 212: + case 208: + case 206: + case 14: + case 210: + case 260: + case 261: + case 264: + case 207: + case 201: + case 214: return true; - case 146: - while (node.parent.kind === 146) { + case 148: + while (node.parent.kind === 148) { node = node.parent; } - return node.parent.kind === 165 || isJSXTagName(node); - case 71: - if (node.parent.kind === 165 || isJSXTagName(node)) { + return node.parent.kind === 167 || isJSXTagName(node); + case 72: + if (node.parent.kind === 167 || isJSXTagName(node)) { return true; } case 8: case 9: - case 99: + case 10: + case 100: return isInExpressionContext(node); default: return false; @@ -6864,49 +7268,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 235: - case 149: - case 152: + case 237: case 151: - case 276: - case 273: - case 184: + case 154: + case 153: + case 278: + case 275: + case 186: return parent.initializer === node; - case 219: - case 220: case 221: case 222: - case 228: - case 229: - case 230: - case 269: - case 232: - return parent.expression === node; case 223: + case 224: + case 230: + case 231: + case 232: + case 271: + case 234: + return parent.expression === node; + case 225: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 236) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 238) || forStatement.condition === node || forStatement.incrementor === node; - case 224: - case 225: + case 226: + case 227: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 236) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238) || forInStatement.expression === node; - case 192: - case 210: + case 194: + case 212: return node === parent.expression; - case 214: + case 216: return node === parent.expression; - case 147: + case 149: return node === parent.expression; - case 150: - case 268: - case 267: - case 275: + case 152: + case 270: + case 269: + case 277: return true; - case 209: + case 211: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 274: + case 276: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -6914,7 +7318,7 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 && node.moduleReference.kind === 257; + return node.kind === 248 && node.moduleReference.kind === 259; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -6923,21 +7327,21 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 && node.moduleReference.kind !== 257; + return node.kind === 248 && node.moduleReference.kind !== 259; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216); } @@ -6951,15 +7355,15 @@ var ts; ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && - (node.typeArguments[0].kind === 137 || node.typeArguments[0].kind === 134); + (node.typeArguments[0].kind === 138 || node.typeArguments[0].kind === 135); } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { - if (callExpression.kind !== 189) { + if (callExpression.kind !== 191) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 || expression.escapedText !== "require") { + if (expression.kind !== 72 || expression.escapedText !== "require") { return false; } if (args.length !== 1) { @@ -6977,29 +7381,29 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; decl = node.parent; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 && node.parent.right === node) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 && node.parent.right === node) { name = node.parent.left; decl = name; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55) { if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { name = node.parent.parent.name; decl = node.parent.parent; } - else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 && node.parent.parent.right === node.parent) { + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 && node.parent.parent.right === node.parent) { name = node.parent.parent.left; decl = name; } @@ -7007,66 +7411,79 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && - ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 && + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; } return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - function getDeclaredJavascriptInitializer(node) { + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; - function getAssignedJavascriptInitializer(node) { - if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58) { + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); + } + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 194 || e.kind === 195 ? initializer : undefined; + return e.kind === 196 || e.kind === 197 ? initializer : undefined; } - if (initializer.kind === 194 || - initializer.kind === 207 || - initializer.kind === 195) { + if (initializer.kind === 196 || + initializer.kind === 209 || + initializer.kind === 197) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + ts.getExpandoInitializer = getExpandoInitializer; + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : - ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 ? node.parent.left : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { - var parent = (node.parent.operatorToken.kind === 54 && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; - if (parent.operatorToken.kind === 58 && ts.isIdentifier(parent.left)) { + var parent = (node.parent.operatorToken.kind === 55 && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 && ts.isIdentifier(parent.left)) { return parent.left; } } @@ -7074,13 +7491,13 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; function isSameEntityName(name, initializer) { if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { return name.escapedText === initializer.escapedText; } if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { - return (initializer.expression.kind === 99 || + return (initializer.expression.kind === 100 || ts.isIdentifier(initializer.expression) && (initializer.expression.escapedText === "window" || initializer.expression.escapedText === "self" || @@ -7107,13 +7524,36 @@ var ts; return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 || isInJavaScriptFile(expr) ? special : 0; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 || isInJSFile(expr) ? special : 0; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { - if (expr.operatorToken.kind !== 58 || + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9; + } + return 7; + } + if (expr.operatorToken.kind !== 59 || !ts.isPropertyAccessExpression(expr.left)) { return 0; } @@ -7121,13 +7561,13 @@ var ts; if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { return 6; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { - if (lhs.expression.kind === 99) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100) { return 4; } - else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + else if (isModuleExportsPropertyAccessExpression(lhs)) { return 2; } else if (isEntityNameExpression(lhs.expression)) { @@ -7148,7 +7588,7 @@ var ts; } return 0; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -7157,12 +7597,12 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && - expr.parent && expr.parent.kind === 219 && + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; @@ -7171,7 +7611,7 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 237 || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 239 || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { @@ -7180,14 +7620,14 @@ var ts; ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 247: - case 253: + case 249: + case 255: return node.parent; - case 257: + case 259: return node.parent.parent; - case 189: - return node.parent; - case 180: + case 191: + return isImportCall(node.parent) || isRequireCall(node.parent, false) ? node.parent : undefined; + case 182: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -7197,12 +7637,12 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 247: - case 253: + case 249: + case 255: return node.moduleSpecifier; - case 246: - return node.moduleReference.kind === 257 ? node.moduleReference.expression : undefined; - case 181: + case 248: + return node.moduleReference.kind === 259 ? node.moduleReference.expression : undefined; + case 183: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; default: return ts.Debug.assertNever(node); @@ -7211,11 +7651,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 247: + case 249: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 246: + case 248: return node; - case 253: + case 255: return undefined; default: return ts.Debug.assertNever(node); @@ -7223,19 +7663,19 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 247 && !!node.importClause && !!node.importClause.name; + return node.kind === 249 && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 149: + case 151: + case 156: + case 155: + case 276: + case 275: case 154: case 153: - case 274: - case 273: - case 152: - case 151: return node.questionToken !== undefined; } } @@ -7243,14 +7683,13 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 287 && - node.parameters.length > 0 && - node.parameters[0].name && - node.parameters[0].name.escapedText === "new"; + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 302 || node.kind === 295; + return node.kind === 304 || node.kind === 297; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -7260,27 +7699,27 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 + node.expression.operatorToken.kind === 59 ? node.expression.right : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 && + getAssignmentDeclarationKind(node.expression) !== 0 && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 + node.expression.right.operatorToken.kind === 55 ? node.expression.right.right : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 217: + case 219: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 152: + case 154: return node.initializer; - case 273: + case 275: return node.initializer; } } @@ -7290,7 +7729,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 242 + node.body.kind === 244 ? node.body : undefined; } @@ -7304,10 +7743,14 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.addRange(result, node.jsDoc); } - if (node.kind === 149) { + if (node.kind === 151) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 150) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -7315,16 +7758,16 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 273 || - parent.kind === 152 || - parent.kind === 219 && node.kind === 187 || + if (parent.kind === 275 || + parent.kind === 154 || + parent.kind === 221 && node.kind === 189 || getNestedModuleDeclaration(parent) || - ts.isBinaryExpression(node) && node.operatorToken.kind === 58) { + ts.isBinaryExpression(node) && node.operatorToken.kind === 59) { return parent; } else if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node || - ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58)) { + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59)) { return parent.parent; } else if (parent.parent && parent.parent.parent && @@ -7346,7 +7789,7 @@ var ts; if (!decl) { return undefined; } - var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 && p.name.escapedText === name; }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; @@ -7381,38 +7824,38 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 288; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290; } ts.isRestParameter = isRestParameter; function getAssignmentTargetKind(node) { var parent = node.parent; while (true) { switch (parent.kind) { - case 202: + case 204: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? - binaryOperator === 58 ? 1 : 2 : + binaryOperator === 59 ? 1 : 2 : 0; - case 200: - case 201: + case 202: + case 203: var unaryOperator = parent.operator; - return unaryOperator === 43 || unaryOperator === 44 ? 2 : 0; - case 224: - case 225: + return unaryOperator === 44 || unaryOperator === 45 ? 2 : 0; + case 226: + case 227: return parent.initializer === node ? 1 : 0; - case 193: - case 185: - case 206: - case 211: + case 195: + case 187: + case 208: + case 213: node = parent; break; - case 274: + case 276: if (parent.name !== node) { return 0; } node = parent.parent; break; - case 273: + case 275: if (parent.name === node) { return 0; } @@ -7431,22 +7874,22 @@ var ts; ts.isAssignmentTarget = isAssignmentTarget; function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 216: - case 217: - case 229: - case 220: - case 230: - case 244: - case 269: - case 270: + case 218: + case 219: case 231: + case 222: + case 232: + case 246: + case 271: + case 272: + case 233: + case 225: + case 226: + case 227: case 223: case 224: - case 225: - case 221: - case 222: - case 233: - case 272: + case 235: + case 274: return true; } return false; @@ -7463,26 +7906,32 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 175); + return walkUp(node, 177); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 193); + return walkUp(node, 195); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function skipParentheses(node) { - while (node.kind === 193) { + while (node.kind === 195) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195) { + node = node.parent; + } + return node; + } function isDeleteTarget(node) { - if (node.kind !== 187 && node.kind !== 188) { + if (node.kind !== 189 && node.kind !== 190) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 196; + return node && node.kind === 198; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -7498,78 +7947,81 @@ var ts; return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } ts.isDeclarationName = isDeclarationName; - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71: - case 9: - case 8: { - var parent = name.parent; + case 10: + case 8: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + case 72: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 && + getAssignmentDeclarationKind(binExp) !== 0 && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { - return (node.kind === 9 || node.kind === 8) && - node.parent.kind === 147 && + return (node.kind === 10 || node.kind === 8) && + node.parent.kind === 149 && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 152: - case 151: case 154: case 153: case 156: - case 157: - case 276: - case 273: - case 187: + case 155: + case 158: + case 159: + case 278: + case 275: + case 189: return parent.name === node; - case 146: + case 148: if (parent.right === node) { - while (parent.kind === 146) { + while (parent.kind === 148) { parent = parent.parent; } - return parent.kind === 165 || parent.kind === 162; + return parent.kind === 167 || parent.kind === 164; } return false; - case 184: - case 251: + case 186: + case 253: return parent.propertyName === node; - case 255: - case 265: + case 257: + case 267: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 246 || - node.kind === 245 || - node.kind === 248 && !!node.name || - node.kind === 249 || + return node.kind === 248 || + node.kind === 247 || + node.kind === 250 && !!node.name || node.kind === 251 || - node.kind === 255 || - node.kind === 252 && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2; + node.kind === 253 || + node.kind === 257 || + node.kind === 254 && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -7578,7 +8030,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { var tag = ts.getJSDocAugmentsTag(node); if (tag) { return tag.class; @@ -7588,12 +8040,12 @@ var ts; } ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; function getClassExtendsHeritageElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85); + var heritageClause = getHeritageClause(node.heritageClauses, 86); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 108); + var heritageClause = getHeritageClause(node.heritageClauses, 109); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; @@ -7604,7 +8056,7 @@ var ts; } ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85); + var heritageClause = getHeritageClause(node.heritageClauses, 86); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -7638,11 +8090,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 72 <= token && token <= 145; + return 73 <= token && token <= 147; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 117 <= token && token <= 145; + return 118 <= token && token <= 147; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -7654,6 +8106,11 @@ var ts; return token !== undefined && isNonContextualKeyword(token); } ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; function isTrivia(token) { return 2 <= token && token <= 7; } @@ -7664,13 +8121,13 @@ var ts; } var flags = 0; switch (node.kind) { - case 237: - case 194: - case 154: + case 239: + case 196: + case 156: if (node.asteriskToken) { flags |= 1; } - case 195: + case 197: if (hasModifier(node, 256)) { flags |= 2; } @@ -7684,10 +8141,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 237: - case 194: - case 195: - case 154: + case 239: + case 196: + case 197: + case 156: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256); @@ -7705,7 +8162,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 147 && + return name.kind === 149 && !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -7716,12 +8173,12 @@ var ts; ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { - case 71: + case 72: return name.escapedText; - case 9: + case 10: case 8: return ts.escapeLeadingUnderscores(name.text); - case 147: + case 149: var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); @@ -7737,9 +8194,9 @@ var ts; ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { switch (node.kind) { - case 71: - case 9: - case 13: + case 72: + case 10: + case 14: case 8: return true; default: @@ -7748,11 +8205,11 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return node.kind === 71 ? ts.idText(node) : node.text; + return node.kind === 72 ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return node.kind === 72 ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -7764,7 +8221,7 @@ var ts; } ts.isKnownSymbol = isKnownSymbol; function isESSymbolIdentifier(node) { - return node.kind === 71 && node.escapedText === "Symbol"; + return node.kind === 72 && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { @@ -7773,11 +8230,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 149; + return root.kind === 151; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 184) { + while (node.kind === 186) { node = node.parent.parent; } return node; @@ -7785,15 +8242,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 155 - || kind === 194 - || kind === 237 - || kind === 195 - || kind === 154 + return kind === 157 + || kind === 196 + || kind === 239 + || kind === 197 || kind === 156 - || kind === 157 - || kind === 242 - || kind === 277; + || kind === 158 + || kind === 159 + || kind === 244 + || kind === 279; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -7807,38 +8264,38 @@ var ts; ts.getOriginalSourceFile = getOriginalSourceFile; function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 190: + case 192: return hasArguments ? 0 : 1; - case 200: - case 197: - case 198: - case 196: - case 199: - case 203: - case 205: - return 1; case 202: + case 199: + case 200: + case 198: + case 201: + case 205: + case 207: + return 1; + case 204: switch (operator) { - case 40: - case 58: + case 41: case 59: case 60: - case 62: case 61: case 63: + case 62: case 64: case 65: case 66: case 67: case 68: - case 70: case 69: + case 71: + case 70: return 1; } } @@ -7847,15 +8304,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 202) { + if (expression.kind === 204) { return expression.operatorToken.kind; } - else if (expression.kind === 200 || expression.kind === 201) { + else if (expression.kind === 202 || expression.kind === 203) { return expression.operator; } else { @@ -7865,72 +8322,73 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 307: + case 309: return 0; - case 206: + case 208: return 1; - case 205: + case 207: return 2; - case 203: + case 205: return 4; - case 202: + case 204: switch (operatorKind) { - case 26: + case 27: return 0; - case 58: case 59: case 60: - case 62: case 61: case 63: + case 62: case 64: case 65: case 66: case 67: case 68: - case 70: case 69: + case 71: + case 70: return 3; default: return getBinaryOperatorPrecedence(operatorKind); } - case 200: - case 197: - case 198: - case 196: + case 202: case 199: - return 16; + case 200: + case 198: case 201: + return 16; + case 203: return 17; - case 189: - return 18; - case 190: - return hasArguments ? 19 : 18; case 191: - case 187: - case 188: + return 18; + case 192: + return hasArguments ? 19 : 18; + case 193: + case 189: + case 190: return 19; - case 99: - case 97: - case 71: - case 95: - case 101: - case 86: + case 100: + case 98: + case 72: + case 96: + case 102: + case 87: case 8: case 9: - case 185: - case 186: - case 194: - case 195: - case 207: - case 258: - case 259: - case 262: - case 12: + case 10: + case 187: + case 188: + case 196: + case 197: + case 209: + case 260: + case 261: + case 264: case 13: - case 204: - case 193: - case 208: + case 14: + case 206: + case 195: + case 210: return 20; default: return -1; @@ -7939,41 +8397,41 @@ var ts; ts.getOperatorPrecedence = getOperatorPrecedence; function getBinaryOperatorPrecedence(kind) { switch (kind) { - case 54: + case 55: return 5; - case 53: + case 54: return 6; - case 49: - return 7; case 50: + return 7; + case 51: return 8; - case 48: + case 49: return 9; - case 32: case 33: case 34: case 35: + case 36: return 10; - case 27: - case 29: + case 28: case 30: case 31: + case 32: + case 94: case 93: - case 92: - case 118: + case 119: return 11; - case 45: case 46: case 47: + case 48: return 12; - case 37: case 38: - return 13; case 39: - case 41: - case 42: - return 14; + return 13; case 40: + case 42: + case 43: + return 14; + case 41: return 15; } return -1; @@ -8038,7 +8496,7 @@ var ts; if (fileName) { return fileDiagnostics.get(fileName) || []; } - var fileDiags = ts.flatMap(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); if (!nonFileDiagnostics.length) { return fileDiags; } @@ -8084,7 +8542,7 @@ var ts; } function isIntrinsicJsxName(name) { var ch = name.charCodeAt(0); - return (ch >= 97 && ch <= 122) || name.indexOf("-") > -1; + return (ch >= 97 && ch <= 122) || ts.stringContains(name, "-"); } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -8165,16 +8623,10 @@ var ts; lineStart = true; } } - function writeTextOfNode(text, node) { - var s = getTextOfNodeFromSourceText(text, node); - write(s); - updateLineCountAndPosFor(s); - } reset(); return { write: write, rawWrite: rawWrite, - writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, increaseIndent: function () { indent++; }, @@ -8197,10 +8649,77 @@ var ts; writePunctuation: write, writeSpace: write, writeStringLiteral: write, - writeSymbol: write + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write }; } ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; function getResolvedExternalModuleName(host, file, referenceFile) { return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } @@ -8251,7 +8770,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); @@ -8263,7 +8782,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -8320,11 +8839,11 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return !!node && node.kind === 71 && identifierIsThisKeyword(node); + return !!node && node.kind === 72 && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { - return id.originalKeywordKind === 99; + return id.originalKeywordKind === 100; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { @@ -8334,10 +8853,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 156) { + if (accessor.kind === 158) { getAccessor = accessor; } - else if (accessor.kind === 157) { + else if (accessor.kind === 159) { setAccessor = accessor; } else { @@ -8357,10 +8876,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 156 && !getAccessor) { + if (member.kind === 158 && !getAccessor) { getAccessor = member; } - if (member.kind === 157 && !setAccessor) { + if (member.kind === 159 && !setAccessor) { setAccessor = member; } } @@ -8377,7 +8896,7 @@ var ts; ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -8389,7 +8908,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -8397,7 +8916,7 @@ var ts; } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 289 && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 && tag.parent.tags.some(isJSDocTypeAlias)); } function getEffectiveSetAccessorTypeAnnotationNode(node) { var parameter = getSetAccessorValueParameter(node); @@ -8425,13 +8944,13 @@ var ts; function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { if (comments && comments.length > 0) { if (leadingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } var emitInterveningSeparator = false; for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { var comment = comments_1[_i]; if (emitInterveningSeparator) { - writer.write(" "); + writer.writeSpace(" "); emitInterveningSeparator = false; } writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); @@ -8443,7 +8962,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -8523,7 +9042,7 @@ var ts; } } else { - writer.write(text.substring(commentPos, commentEnd)); + writer.writeComment(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; @@ -8531,13 +9050,13 @@ var ts; var end = Math.min(commentEnd, nextLineStart - 1); var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { - writer.write(currentLineText); + writer.writeComment(currentLineText); if (end !== commentEnd) { writer.writeLine(); } } else { - writer.writeLiteral(newLine); + writer.rawWrite(newLine); } } function calculateIndent(text, pos, end) { @@ -8589,7 +9108,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4 || (node.kind === 71 && node.isInJSDocNamespace)) { + if (node.flags & 4 || (node.kind === 72 && node.isInJSDocNamespace)) { flags |= 1; } return flags; @@ -8597,43 +9116,48 @@ var ts; ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { - case 115: return 32; - case 114: return 4; - case 113: return 16; - case 112: return 8; - case 117: return 128; - case 84: return 1; - case 124: return 2; - case 76: return 2048; - case 79: return 512; - case 120: return 256; - case 132: return 64; + case 116: return 32; + case 115: return 4; + case 114: return 16; + case 113: return 8; + case 118: return 128; + case 85: return 1; + case 125: return 2; + case 77: return 2048; + case 80: return 512; + case 121: return 256; + case 133: return 64; } return 0; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 54 - || token === 53 - || token === 51; + return token === 55 + || token === 54 + || token === 52; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 58 && token <= 70; + return token >= 59 && token <= 71; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment - ? node.operatorToken.kind === 58 + ? node.operatorToken.kind === 59 : isAssignmentOperator(node.operatorToken.kind)) && ts.isLeftHandSideExpression(node.left); } @@ -8641,8 +9165,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, true)) { var kind = node.left.kind; - return kind === 186 - || kind === 185; + return kind === 188 + || kind === 187; } return false; } @@ -8651,17 +9175,8 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 || isPropertyAccessEntityNameExpression(node); + return node.kind === 72 || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; function isPropertyAccessEntityNameExpression(node) { @@ -8673,17 +9188,17 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 146 && node.parent.right === node) || - (node.parent.kind === 187 && node.parent.name === node); + return (node.parent.kind === 148 && node.parent.right === node) || + (node.parent.kind === 189 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 186 && + return expression.kind === 188 && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 185 && + return expression.kind === 187 && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -8694,10 +9209,10 @@ var ts; function isExportDefaultSymbol(symbol) { return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512); } - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -8818,6 +9333,26 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -8899,6 +9434,8 @@ var ts; } ts.formatObjectFlags = formatObjectFlags; function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -8963,8 +9500,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 241: - case 242: + case 243: + case 244: return parseNode === parseNode.parent.name; } } @@ -9030,22 +9567,44 @@ var ts; if (!parent) return 0; switch (parent.kind) { - case 201: - case 200: - var operator = parent.operator; - return operator === 43 || operator === 44 ? writeOrReadWrite() : 0; + case 195: + return accessKind(parent); + case 203: case 202: + var operator = parent.operator; + return operator === 44 || operator === 45 ? writeOrReadWrite() : 0; + case 204: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? - operatorToken.kind === 58 ? 1 : writeOrReadWrite() + operatorToken.kind === 59 ? 1 : writeOrReadWrite() : 0; - case 187: + case 189: return parent.name !== node ? 0 : accessKind(parent); + case 275: { + var parentAccess = accessKind(parent.parent); + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276: + return node === parent.objectAssignmentInitializer ? 0 : accessKind(parent.parent); + case 187: + return accessKind(parent); default: return 0; } function writeOrReadWrite() { - return parent.parent && parent.parent.kind === 219 ? 1 : 2; + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 ? 1 : 2; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0: + return 1; + case 1: + return 0; + case 2: + return 2; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -9122,7 +9681,7 @@ var ts; } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { - return type.flags & 131072 ? type.objectFlags : 0; + return type.flags & 524288 ? type.objectFlags : 0; } ts.getObjectFlags = getObjectFlags; function typeHasCallOrConstructSignatures(type, checker) { @@ -9172,6 +9731,31 @@ var ts; return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 && kind <= 183) + || kind === 120 + || kind === 143 + || kind === 135 + || kind === 146 + || kind === 136 + || kind === 123 + || kind === 138 + || kind === 139 + || kind === 100 + || kind === 106 + || kind === 141 + || kind === 96 + || kind === 132 + || kind === 211 + || kind === 284 + || kind === 285 + || kind === 286 + || kind === 287 + || kind === 288 + || kind === 289 + || kind === 290; + } + ts.isTypeNodeKind = isTypeNodeKind; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9254,12 +9838,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -9307,9 +9885,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 148) { + if (d && d.kind === 150) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 239) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241) { return current; } } @@ -9317,7 +9895,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92) && node.parent.kind === 155; + return ts.hasModifier(node, 92) && node.parent.kind === 157; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -9347,14 +9925,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 235) { + if (node.kind === 237) { node = node.parent; } - if (node && node.kind === 236) { + if (node && node.kind === 238) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 217) { + if (node && node.kind === 219) { flags |= getFlags(node); } return flags; @@ -9465,36 +10043,32 @@ var ts; return getDeclarationIdentifier(hostNode); } switch (hostNode.kind) { - case 217: + case 219: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; - case 219: + break; + case 221: var expr = hostNode.expression; switch (expr.kind) { - case 187: + case 189: return expr.name; - case 188: + case 190: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } - return undefined; - case 1: - return undefined; - case 193: { + break; + case 195: { return getDeclarationIdentifier(hostNode.expression); } - case 231: { + case 233: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -9511,31 +10085,36 @@ var ts; ts.isNamedDeclaration = isNamedDeclaration; function getNonAssignedNameOfDeclaration(declaration) { switch (declaration.kind) { - case 71: + case 72: return declaration; - case 303: - case 297: { + case 305: + case 299: { var name = declaration.name; - if (name.kind === 146) { + if (name.kind === 148) { return name.right; } break; } - case 202: { + case 191: + case 204: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1: case 4: case 5: case 3: return expr.left.name; + case 7: + case 8: + case 9: + return expr.arguments[1]; default: return undefined; } } - case 302: + case 304: return getNameOfJSDocTypedef(declaration); - case 252: { + case 254: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } @@ -9584,6 +10163,13 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; function hasJSDocParameterTags(node) { return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } @@ -9668,10 +10254,23 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289); + ts.Debug.assert(node.parent.kind === 291); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -9687,673 +10286,677 @@ var ts; return node.kind === 8; } ts.isNumericLiteral = isNumericLiteral; - function isStringLiteral(node) { + function isBigIntLiteral(node) { return node.kind === 9; } + ts.isBigIntLiteral = isBigIntLiteral; + function isStringLiteral(node) { + return node.kind === 10; + } ts.isStringLiteral = isStringLiteral; function isJsxText(node) { - return node.kind === 10; + return node.kind === 11; } ts.isJsxText = isJsxText; function isRegularExpressionLiteral(node) { - return node.kind === 12; + return node.kind === 13; } ts.isRegularExpressionLiteral = isRegularExpressionLiteral; function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13; + return node.kind === 14; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; function isTemplateHead(node) { - return node.kind === 14; + return node.kind === 15; } ts.isTemplateHead = isTemplateHead; function isTemplateMiddle(node) { - return node.kind === 15; + return node.kind === 16; } ts.isTemplateMiddle = isTemplateMiddle; function isTemplateTail(node) { - return node.kind === 16; + return node.kind === 17; } ts.isTemplateTail = isTemplateTail; function isIdentifier(node) { - return node.kind === 71; + return node.kind === 72; } ts.isIdentifier = isIdentifier; function isQualifiedName(node) { - return node.kind === 146; + return node.kind === 148; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 147; + return node.kind === 149; } ts.isComputedPropertyName = isComputedPropertyName; function isTypeParameterDeclaration(node) { - return node.kind === 148; + return node.kind === 150; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 149; + return node.kind === 151; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 150; + return node.kind === 152; } ts.isDecorator = isDecorator; function isPropertySignature(node) { - return node.kind === 151; + return node.kind === 153; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 152; + return node.kind === 154; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 153; + return node.kind === 155; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 154; + return node.kind === 156; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 155; + return node.kind === 157; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 156; + return node.kind === 158; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 157; + return node.kind === 159; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 158; + return node.kind === 160; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 159; + return node.kind === 161; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 160; + return node.kind === 162; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; function isGetOrSetAccessorDeclaration(node) { - return node.kind === 157 || node.kind === 156; + return node.kind === 159 || node.kind === 158; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isTypePredicateNode(node) { - return node.kind === 161; + return node.kind === 163; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 162; + return node.kind === 164; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 163; + return node.kind === 165; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 164; + return node.kind === 166; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 165; + return node.kind === 167; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 166; + return node.kind === 168; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 167; + return node.kind === 169; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 168; + return node.kind === 170; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 171; + return node.kind === 173; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 172; + return node.kind === 174; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 173; + return node.kind === 175; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 174; + return node.kind === 176; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 175; + return node.kind === 177; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 176; + return node.kind === 178; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 177; + return node.kind === 179; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 178; + return node.kind === 180; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 179; + return node.kind === 181; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 180; + return node.kind === 182; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 181; + return node.kind === 183; } ts.isImportTypeNode = isImportTypeNode; function isObjectBindingPattern(node) { - return node.kind === 182; + return node.kind === 184; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 183; + return node.kind === 185; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 184; + return node.kind === 186; } ts.isBindingElement = isBindingElement; function isArrayLiteralExpression(node) { - return node.kind === 185; + return node.kind === 187; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 186; + return node.kind === 188; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 187; + return node.kind === 189; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 188; + return node.kind === 190; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 189; + return node.kind === 191; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 190; + return node.kind === 192; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 191; + return node.kind === 193; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 192; + return node.kind === 194; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 193; + return node.kind === 195; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 306) { + while (node.kind === 308) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 194; + return node.kind === 196; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 195; + return node.kind === 197; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 196; + return node.kind === 198; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 197; + return node.kind === 199; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 198; + return node.kind === 200; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 199; + return node.kind === 201; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 200; + return node.kind === 202; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 201; + return node.kind === 203; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 202; + return node.kind === 204; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 203; + return node.kind === 205; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 204; + return node.kind === 206; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 205; + return node.kind === 207; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 206; + return node.kind === 208; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 207; + return node.kind === 209; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 208; + return node.kind === 210; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 209; + return node.kind === 211; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 210; + return node.kind === 212; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 211; + return node.kind === 213; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 212; + return node.kind === 214; } ts.isMetaProperty = isMetaProperty; function isTemplateSpan(node) { - return node.kind === 214; + return node.kind === 216; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 215; + return node.kind === 217; } ts.isSemicolonClassElement = isSemicolonClassElement; function isBlock(node) { - return node.kind === 216; + return node.kind === 218; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 217; + return node.kind === 219; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 218; + return node.kind === 220; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 219; + return node.kind === 221; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 220; + return node.kind === 222; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 221; + return node.kind === 223; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 222; + return node.kind === 224; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 223; + return node.kind === 225; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 224; + return node.kind === 226; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 225; + return node.kind === 227; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 226; + return node.kind === 228; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 227; + return node.kind === 229; } ts.isBreakStatement = isBreakStatement; function isBreakOrContinueStatement(node) { - return node.kind === 227 || node.kind === 226; + return node.kind === 229 || node.kind === 228; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 228; + return node.kind === 230; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 229; + return node.kind === 231; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 230; + return node.kind === 232; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 231; + return node.kind === 233; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 232; + return node.kind === 234; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 233; + return node.kind === 235; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 234; + return node.kind === 236; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 235; + return node.kind === 237; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 236; + return node.kind === 238; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 237; + return node.kind === 239; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 238; + return node.kind === 240; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 239; + return node.kind === 241; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 240; + return node.kind === 242; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 241; + return node.kind === 243; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 242; + return node.kind === 244; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 243; + return node.kind === 245; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 244; + return node.kind === 246; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 245; + return node.kind === 247; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 246; + return node.kind === 248; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 247; + return node.kind === 249; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 248; + return node.kind === 250; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 249; + return node.kind === 251; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 250; + return node.kind === 252; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 251; + return node.kind === 253; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 252; + return node.kind === 254; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 253; + return node.kind === 255; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 254; + return node.kind === 256; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 255; + return node.kind === 257; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 256; + return node.kind === 258; } ts.isMissingDeclaration = isMissingDeclaration; function isExternalModuleReference(node) { - return node.kind === 257; + return node.kind === 259; } ts.isExternalModuleReference = isExternalModuleReference; function isJsxElement(node) { - return node.kind === 258; + return node.kind === 260; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 259; + return node.kind === 261; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 260; + return node.kind === 262; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 261; + return node.kind === 263; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 262; + return node.kind === 264; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 263; + return node.kind === 265; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 264; + return node.kind === 266; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 265; + return node.kind === 267; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 266; + return node.kind === 268; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 267; + return node.kind === 269; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 268; + return node.kind === 270; } ts.isJsxExpression = isJsxExpression; function isCaseClause(node) { - return node.kind === 269; + return node.kind === 271; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 270; + return node.kind === 272; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 271; + return node.kind === 273; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 272; + return node.kind === 274; } ts.isCatchClause = isCatchClause; function isPropertyAssignment(node) { - return node.kind === 273; + return node.kind === 275; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 274; + return node.kind === 276; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 275; + return node.kind === 277; } ts.isSpreadAssignment = isSpreadAssignment; function isEnumMember(node) { - return node.kind === 276; + return node.kind === 278; } ts.isEnumMember = isEnumMember; function isSourceFile(node) { - return node.kind === 277; + return node.kind === 279; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 278; + return node.kind === 280; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 279; + return node.kind === 281; } ts.isUnparsedSource = isUnparsedSource; function isJSDocTypeExpression(node) { - return node.kind === 281; + return node.kind === 283; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 282; + return node.kind === 284; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 283; + return node.kind === 285; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 284; + return node.kind === 286; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 285; + return node.kind === 287; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 286; + return node.kind === 288; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 287; + return node.kind === 289; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 288; + return node.kind === 290; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 289; + return node.kind === 291; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 293; + return node.kind === 295; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 294; + return node.kind === 296; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocEnumTag(node) { - return node.kind === 296; + return node.kind === 298; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 299; + return node.kind === 301; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 297; + return node.kind === 299; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 298; + return node.kind === 300; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 300; + return node.kind === 302; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 301; + return node.kind === 303; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 302; + return node.kind === 304; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 303; + return node.kind === 305; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 303 || node.kind === 297; + return node.kind === 305 || node.kind === 299; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 290; + return node.kind === 292; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocCallbackTag(node) { - return node.kind === 295; + return node.kind === 297; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocSignature(node) { - return node.kind === 291; + return node.kind === 293; } ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); (function (ts) { function isSyntaxList(n) { - return n.kind === 304; + return n.kind === 306; } ts.isSyntaxList = isSyntaxList; function isNode(node) { @@ -10361,11 +10964,11 @@ var ts; } ts.isNode = isNode; function isNodeKind(kind) { - return kind >= 146; + return kind >= 148; } ts.isNodeKind = isNodeKind; function isToken(n) { - return n.kind >= 0 && n.kind <= 145; + return n.kind >= 0 && n.kind <= 147; } ts.isToken = isToken; function isNodeArray(array) { @@ -10373,7 +10976,7 @@ var ts; } ts.isNodeArray = isNodeArray; function isLiteralKind(kind) { - return 8 <= kind && kind <= 13; + return 8 <= kind && kind <= 14; } ts.isLiteralKind = isLiteralKind; function isLiteralExpression(node) { @@ -10381,7 +10984,7 @@ var ts; } ts.isLiteralExpression = isLiteralExpression; function isTemplateLiteralKind(kind) { - return 13 <= kind && kind <= 16; + return 14 <= kind && kind <= 17; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isTemplateLiteralToken(node) { @@ -10390,12 +10993,16 @@ var ts; ts.isTemplateLiteralToken = isTemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node) { var kind = node.kind; - return kind === 15 - || kind === 16; + return kind === 16 + || kind === 17; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isStringTextContainingNode(node) { - return node.kind === 9 || isTemplateLiteralKind(node.kind); + return node.kind === 10 || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { @@ -10404,17 +11011,17 @@ var ts; ts.isGeneratedIdentifier = isGeneratedIdentifier; function isModifierKind(token) { switch (token) { - case 117: - case 120: - case 76: - case 124: - case 79: - case 84: - case 114: - case 112: - case 113: - case 132: + case 118: + case 121: + case 77: + case 125: + case 80: + case 85: case 115: + case 113: + case 114: + case 133: + case 116: return true; } return false; @@ -10425,7 +11032,7 @@ var ts; } ts.isParameterPropertyModifier = isParameterPropertyModifier; function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 115; + return isParameterPropertyModifier(idToken) || idToken === 116; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -10434,23 +11041,23 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 146 - || kind === 71; + return kind === 148 + || kind === 72; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 71 - || kind === 9 + return kind === 72 + || kind === 10 || kind === 8 - || kind === 147; + || kind === 149; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; - return kind === 71 - || kind === 182 - || kind === 183; + return kind === 72 + || kind === 184 + || kind === 185; } ts.isBindingName = isBindingName; function isFunctionLike(node) { @@ -10463,13 +11070,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 237: - case 154: - case 155: + case 239: case 156: case 157: - case 194: - case 195: + case 158: + case 159: + case 196: + case 197: return true; default: return false; @@ -10477,14 +11084,14 @@ var ts; } function isFunctionLikeKind(kind) { switch (kind) { - case 153: - case 158: - case 291: - case 159: + case 155: case 160: - case 163: - case 287: - case 164: + case 293: + case 161: + case 162: + case 165: + case 289: + case 166: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -10497,28 +11104,28 @@ var ts; ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; function isClassElement(node) { var kind = node.kind; - return kind === 155 - || kind === 152 + return kind === 157 || kind === 154 || kind === 156 - || kind === 157 - || kind === 160 - || kind === 215; + || kind === 158 + || kind === 159 + || kind === 162 + || kind === 217; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 238 || node.kind === 207); + return node && (node.kind === 240 || node.kind === 209); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 156 || node.kind === 157); + return node && (node.kind === 158 || node.kind === 159); } ts.isAccessor = isAccessor; function isMethodOrAccessor(node) { switch (node.kind) { - case 154: case 156: - case 157: + case 158: + case 159: return true; default: return false; @@ -10527,11 +11134,11 @@ var ts; ts.isMethodOrAccessor = isMethodOrAccessor; function isTypeElement(node) { var kind = node.kind; - return kind === 159 - || kind === 158 - || kind === 151 + return kind === 161 + || kind === 160 || kind === 153 - || kind === 160; + || kind === 155 + || kind === 162; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -10540,45 +11147,22 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 273 - || kind === 274 - || kind === 275 - || kind === 154 + return kind === 275 + || kind === 276 + || kind === 277 || kind === 156 - || kind === 157; + || kind === 158 + || kind === 159; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; - function isTypeNodeKind(kind) { - return (kind >= 161 && kind <= 181) - || kind === 119 - || kind === 142 - || kind === 134 - || kind === 135 - || kind === 122 - || kind === 137 - || kind === 138 - || kind === 99 - || kind === 105 - || kind === 140 - || kind === 95 - || kind === 131 - || kind === 209 - || kind === 282 - || kind === 283 - || kind === 284 - || kind === 285 - || kind === 286 - || kind === 287 - || kind === 288; - } function isTypeNode(node) { - return isTypeNodeKind(node.kind); + return ts.isTypeNodeKind(node.kind); } ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 163: - case 164: + case 165: + case 166: return true; } return false; @@ -10587,29 +11171,29 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 183 - || kind === 182; + return kind === 185 + || kind === 184; } return false; } ts.isBindingPattern = isBindingPattern; function isAssignmentPattern(node) { var kind = node.kind; - return kind === 185 - || kind === 186; + return kind === 187 + || kind === 188; } ts.isAssignmentPattern = isAssignmentPattern; function isArrayBindingElement(node) { var kind = node.kind; - return kind === 184 - || kind === 208; + return kind === 186 + || kind === 210; } ts.isArrayBindingElement = isArrayBindingElement; function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 235: - case 149: - case 184: + case 237: + case 151: + case 186: return true; } return false; @@ -10622,8 +11206,8 @@ var ts; ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 182: - case 186: + case 184: + case 188: return true; } return false; @@ -10631,8 +11215,8 @@ var ts; ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 183: case 185: + case 187: return true; } return false; @@ -10640,25 +11224,25 @@ var ts; ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 187 - || kind === 146 - || kind === 181; + return kind === 189 + || kind === 148 + || kind === 183; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 187 - || kind === 146; + return kind === 189 + || kind === 148; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 260: - case 259: - case 189: - case 190: + case 262: + case 261: case 191: - case 150: + case 192: + case 193: + case 152: return true; default: return false; @@ -10666,13 +11250,13 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 189 || node.kind === 190; + return node.kind === 191 || node.kind === 192; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 204 - || kind === 13; + return kind === 206 + || kind === 14; } ts.isTemplateLiteral = isTemplateLiteral; function isLeftHandSideExpression(node) { @@ -10681,33 +11265,34 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 187: - case 188: - case 190: case 189: - case 258: - case 259: - case 262: + case 190: + case 192: case 191: - case 185: + case 260: + case 261: + case 264: case 193: - case 186: - case 207: - case 194: - case 71: - case 12: + case 187: + case 195: + case 188: + case 209: + case 196: + case 72: + case 13: case 8: case 9: - case 13: - case 204: - case 86: - case 95: - case 99: - case 101: - case 97: - case 211: - case 212: - case 91: + case 10: + case 14: + case 206: + case 87: + case 96: + case 100: + case 102: + case 98: + case 213: + case 214: + case 92: return true; default: return false; @@ -10719,13 +11304,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 200: - case 201: - case 196: - case 197: + case 202: + case 203: case 198: case 199: - case 192: + case 200: + case 201: + case 194: return true; default: return isLeftHandSideExpressionKind(kind); @@ -10733,11 +11318,11 @@ var ts; } function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 201: + case 203: return true; - case 200: - return expr.operator === 43 || - expr.operator === 44; + case 202: + return expr.operator === 44 || + expr.operator === 45; default: return false; } @@ -10749,15 +11334,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 203: case 205: - case 195: - case 202: - case 206: - case 210: + case 207: + case 197: + case 204: case 208: - case 307: - case 306: + case 212: + case 210: + case 309: + case 308: return true; default: return isUnaryExpressionKind(kind); @@ -10765,16 +11350,16 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 192 - || kind === 210; + return kind === 194 + || kind === 212; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 306; + return node.kind === 308; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 305; + return node.kind === 307; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -10784,20 +11369,20 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { + case 225: + case 226: + case 227: case 223: case 224: - case 225: - case 221: - case 222: return true; - case 231: + case 233: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isForInOrOfStatement(node) { - return node.kind === 224 || node.kind === 225; + return node.kind === 226 || node.kind === 227; } ts.isForInOrOfStatement = isForInOrOfStatement; function isConciseBody(node) { @@ -10816,108 +11401,108 @@ var ts; ts.isForInitializer = isForInitializer; function isModuleBody(node) { var kind = node.kind; - return kind === 243 - || kind === 242 - || kind === 71; + return kind === 245 + || kind === 244 + || kind === 72; } ts.isModuleBody = isModuleBody; function isNamespaceBody(node) { var kind = node.kind; - return kind === 243 - || kind === 242; + return kind === 245 + || kind === 244; } ts.isNamespaceBody = isNamespaceBody; function isJSDocNamespaceBody(node) { var kind = node.kind; - return kind === 71 - || kind === 242; + return kind === 72 + || kind === 244; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; function isNamedImportBindings(node) { var kind = node.kind; - return kind === 250 - || kind === 249; + return kind === 252 + || kind === 251; } ts.isNamedImportBindings = isNamedImportBindings; function isModuleOrEnumDeclaration(node) { - return node.kind === 242 || node.kind === 241; + return node.kind === 244 || node.kind === 243; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 195 - || kind === 184 - || kind === 238 - || kind === 207 - || kind === 155 - || kind === 241 - || kind === 276 - || kind === 255 - || kind === 237 - || kind === 194 - || kind === 156 - || kind === 248 - || kind === 246 - || kind === 251 + return kind === 197 + || kind === 186 + || kind === 240 + || kind === 209 + || kind === 157 + || kind === 243 + || kind === 278 + || kind === 257 || kind === 239 - || kind === 265 + || kind === 196 + || kind === 158 + || kind === 250 + || kind === 248 + || kind === 253 + || kind === 241 + || kind === 267 + || kind === 156 + || kind === 155 + || kind === 244 + || kind === 247 + || kind === 251 + || kind === 151 + || kind === 275 || kind === 154 || kind === 153 + || kind === 159 + || kind === 276 || kind === 242 - || kind === 245 - || kind === 249 - || kind === 149 - || kind === 273 - || kind === 152 - || kind === 151 - || kind === 157 - || kind === 274 - || kind === 240 - || kind === 148 - || kind === 235 - || kind === 302 - || kind === 295 - || kind === 303; + || kind === 150 + || kind === 237 + || kind === 304 + || kind === 297 + || kind === 305; } function isDeclarationStatementKind(kind) { - return kind === 237 - || kind === 256 - || kind === 238 - || kind === 239 + return kind === 239 + || kind === 258 || kind === 240 || kind === 241 || kind === 242 - || kind === 247 - || kind === 246 - || kind === 253 - || kind === 252 - || kind === 245; + || kind === 243 + || kind === 244 + || kind === 249 + || kind === 248 + || kind === 255 + || kind === 254 + || kind === 247; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 227 - || kind === 226 - || kind === 234 - || kind === 221 - || kind === 219 - || kind === 218 - || kind === 224 - || kind === 225 - || kind === 223 - || kind === 220 - || kind === 231 + return kind === 229 || kind === 228 + || kind === 236 + || kind === 223 + || kind === 221 + || kind === 220 + || kind === 226 + || kind === 227 + || kind === 225 + || kind === 222 + || kind === 233 || kind === 230 || kind === 232 - || kind === 233 - || kind === 217 - || kind === 222 - || kind === 229 - || kind === 305 - || kind === 309 - || kind === 308; + || kind === 234 + || kind === 235 + || kind === 219 + || kind === 224 + || kind === 231 + || kind === 307 + || kind === 311 + || kind === 310; } function isDeclaration(node) { - if (node.kind === 148) { - return node.parent.kind !== 301 || ts.isInJavaScriptFile(node); + if (node.kind === 150) { + return node.parent.kind !== 303 || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -10938,10 +11523,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 216) + if (node.kind !== 218) return false; if (node.parent !== undefined) { - if (node.parent.kind === 233 || node.parent.kind === 272) { + if (node.parent.kind === 235 || node.parent.kind === 274) { return false; } } @@ -10949,69 +11534,69 @@ var ts; } function isModuleReference(node) { var kind = node.kind; - return kind === 257 - || kind === 146 - || kind === 71; + return kind === 259 + || kind === 148 + || kind === 72; } ts.isModuleReference = isModuleReference; function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 99 - || kind === 71 - || kind === 187; + return kind === 100 + || kind === 72 + || kind === 189; } ts.isJsxTagNameExpression = isJsxTagNameExpression; function isJsxChild(node) { var kind = node.kind; - return kind === 258 - || kind === 268 - || kind === 259 - || kind === 10 - || kind === 262; + return kind === 260 + || kind === 270 + || kind === 261 + || kind === 11 + || kind === 264; } ts.isJsxChild = isJsxChild; function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 265 - || kind === 267; + return kind === 267 + || kind === 269; } ts.isJsxAttributeLike = isJsxAttributeLike; function isStringLiteralOrJsxExpression(node) { var kind = node.kind; - return kind === 9 - || kind === 268; + return kind === 10 + || kind === 270; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 260 - || kind === 259; + return kind === 262 + || kind === 261; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 269 - || kind === 270; + return kind === 271 + || kind === 272; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isJSDocNode(node) { - return node.kind >= 281 && node.kind <= 303; + return node.kind >= 283 && node.kind <= 305; } ts.isJSDocNode = isJSDocNode; function isJSDocCommentContainingNode(node) { - return node.kind === 289 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 291 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; function isJSDocTag(node) { - return node.kind >= 292 && node.kind <= 303; + return node.kind >= 294 && node.kind <= 305; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 157; + return node.kind === 159; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 156; + return node.kind === 158; } ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { @@ -11032,11 +11617,11 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 265 || node.kind === 267 || isObjectLiteralElementLike(node); + return node.kind === 267 || node.kind === 269 || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; function isTypeReferenceType(node) { - return node.kind === 162 || node.kind === 209; + return node.kind === 164 || node.kind === 211; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -11064,13 +11649,13 @@ var ts; } ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { - return node.kind === 9 || node.kind === 13; + return node.kind === 10 || node.kind === 14; } ts.isStringLiteralLike = isStringLiteralLike; })(ts || (ts = {})); (function (ts) { function isNamedImportsOrExports(node) { - return node.kind === 250 || node.kind === 254; + return node.kind === 252 || node.kind === 256; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function Symbol(flags, name) { @@ -11117,7 +11702,7 @@ var ts; }; function formatStringFromArgs(text, args, baseIndex) { if (baseIndex === void 0) { baseIndex = 0; } - return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); }); + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; function getLocaleSpecificMessage(message) { @@ -11269,6 +11854,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -11285,9 +11882,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -11299,13 +11895,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -11498,8 +12095,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -11694,6 +12289,13 @@ var ts; } ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42, 63]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -11739,6 +12341,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; function isImplicitGlob(lastPathComponent) { return !/[.*?]/.test(lastPathComponent); } @@ -11925,35 +12528,56 @@ var ts; } } ts.getScriptKindFromFileName = getScriptKindFromFileName; - ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; - ts.supportedJavascriptExtensions = [".js", ".jsx"]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedTSExtensionsWithJson = [".ts", ".tsx", ".d.ts", ".json"]; + ts.supportedTSExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; + ts.supportedJSExtensions = [".js", ".jsx"]; + ts.supportedJSAndJsonExtensions = [".js", ".jsx", ".json"]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json"]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json"]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 || scriptKind === 2; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -12057,14 +12681,14 @@ var ts; return !(pos >= 0); } ts.positionIsSynthesized = positionIsSynthesized; - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json"; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json"; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); @@ -12219,6 +12843,87 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { + case 98: + case 66: + log2Base = 1; + break; + case 111: + case 79: + log2Base = 3; + break; + case 120: + case 88: + log2Base = 4; + break; + default: + var nIndex = stringValue.length - 1; + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + var digit = digitChar <= 57 + ? digitChar - 48 + : 10 + digitChar - + (digitChar <= 70 ? 65 : 97); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; + } + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; })(ts || (ts = {})); var ts; (function (ts) { @@ -12227,10 +12932,10 @@ var ts; var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 277) { + if (kind === 279) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 71) { + else if (kind === 72) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } else if (!ts.isNodeKind(kind)) { @@ -12265,28 +12970,29 @@ var ts; } ts.isJSDocLikeText = isJSDocLikeText; function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 145) { + if (!node || node.kind <= 147) { return; } switch (node.kind) { - case 146: + case 148: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 148: + case 150: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 274: + case 276: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 275: + case 277: return visitNode(cbNode, node.expression); - case 149: + case 151: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -12294,7 +13000,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 152: + case 154: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -12302,405 +13008,399 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 151: + case 153: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 273: + case 275: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 235: + case 237: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 184: + case 186: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 163: - case 164: - case 158: - case 159: + case 165: + case 166: case 160: + case 161: + case 162: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 154: - case 153: - case 155: case 156: + case 155: case 157: - case 194: - case 237: - case 195: + case 158: + case 159: + case 196: + case 239: + case 197: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 162: + case 164: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 161: + case 163: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 165: - return visitNode(cbNode, node.exprName); - case 166: - return visitNodes(cbNode, cbNodes, node.members); case 167: - return visitNode(cbNode, node.elementType); + return visitNode(cbNode, node.exprName); case 168: + return visitNodes(cbNode, cbNodes, node.members); + case 169: + return visitNode(cbNode, node.elementType); + case 170: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 171: - case 172: - return visitNodes(cbNode, cbNodes, node.types); case 173: + case 174: + return visitNodes(cbNode, cbNodes, node.types); + case 175: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 174: + case 176: return visitNode(cbNode, node.typeParameter); - case 181: + case 183: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 175: case 177: + case 179: return visitNode(cbNode, node.type); - case 178: + case 180: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 179: + case 181: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 180: - return visitNode(cbNode, node.literal); case 182: - case 183: - return visitNodes(cbNode, cbNodes, node.elements); + return visitNode(cbNode, node.literal); + case 184: case 185: return visitNodes(cbNode, cbNodes, node.elements); - case 186: - return visitNodes(cbNode, cbNodes, node.properties); case 187: + return visitNodes(cbNode, cbNodes, node.elements); + case 188: + return visitNodes(cbNode, cbNodes, node.properties); + case 189: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 188: + case 190: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 189: - case 190: + case 191: + case 192: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 191: + case 193: return visitNode(cbNode, node.tag) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 192: + case 194: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 193: - return visitNode(cbNode, node.expression); - case 196: - return visitNode(cbNode, node.expression); - case 197: + case 195: return visitNode(cbNode, node.expression); case 198: return visitNode(cbNode, node.expression); - case 200: - return visitNode(cbNode, node.operand); - case 205: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); case 199: return visitNode(cbNode, node.expression); - case 201: - return visitNode(cbNode, node.operand); + case 200: + return visitNode(cbNode, node.expression); case 202: + return visitNode(cbNode, node.operand); + case 207: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 201: + return visitNode(cbNode, node.expression); + case 203: + return visitNode(cbNode, node.operand); + case 204: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 210: + case 212: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 211: + case 213: return visitNode(cbNode, node.expression); - case 212: + case 214: return visitNode(cbNode, node.name); - case 203: + case 205: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 206: + case 208: return visitNode(cbNode, node.expression); - case 216: - case 243: + case 218: + case 245: return visitNodes(cbNode, cbNodes, node.statements); - case 277: + case 279: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 217: + case 219: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 236: + case 238: return visitNodes(cbNode, cbNodes, node.declarations); - case 219: + case 221: return visitNode(cbNode, node.expression); - case 220: + case 222: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 221: + case 223: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 222: + case 224: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 223: + case 225: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 224: + case 226: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 225: + case 227: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 226: - case 227: - return visitNode(cbNode, node.label); case 228: - return visitNode(cbNode, node.expression); case 229: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); + return visitNode(cbNode, node.label); case 230: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 244: - return visitNodes(cbNode, cbNodes, node.clauses); - case 269: - return visitNode(cbNode, node.expression) || - visitNodes(cbNode, cbNodes, node.statements); - case 270: - return visitNodes(cbNode, cbNodes, node.statements); + return visitNode(cbNode, node.expression); case 231: - return visitNode(cbNode, node.label) || + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); case 232: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 246: + return visitNodes(cbNode, cbNodes, node.clauses); + case 271: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 272: + return visitNodes(cbNode, cbNodes, node.statements); case 233: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 234: + return visitNode(cbNode, node.expression); + case 235: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 272: + case 274: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 150: + case 152: return visitNode(cbNode, node.expression); - case 238: - case 207: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.heritageClauses) || - visitNodes(cbNode, cbNodes, node.members); - case 239: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.heritageClauses) || - visitNodes(cbNode, cbNodes, node.members); case 240: + case 209: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNode(cbNode, node.type); + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); case 241: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 276: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); case 242: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 243: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 278: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 244: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 246: + case 248: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 247: + case 249: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 248: + case 250: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 245: + case 247: return visitNode(cbNode, node.name); - case 249: + case 251: return visitNode(cbNode, node.name); - case 250: - case 254: + case 252: + case 256: return visitNodes(cbNode, cbNodes, node.elements); - case 253: + case 255: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 251: - case 255: + case 253: + case 257: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 252: + case 254: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 204: + case 206: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 214: + case 216: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 147: + case 149: return visitNode(cbNode, node.expression); - case 271: + case 273: return visitNodes(cbNode, cbNodes, node.types); - case 209: + case 211: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 257: + case 259: return visitNode(cbNode, node.expression); - case 256: - return visitNodes(cbNode, cbNodes, node.decorators); - case 307: - return visitNodes(cbNode, cbNodes, node.elements); case 258: + return visitNodes(cbNode, cbNodes, node.decorators); + case 309: + return visitNodes(cbNode, cbNodes, node.elements); + case 260: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 262: + case 264: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 259: - case 260: + case 261: + case 262: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 266: + case 268: return visitNodes(cbNode, cbNodes, node.properties); - case 265: + case 267: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 267: + case 269: return visitNode(cbNode, node.expression); - case 268: + case 270: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 261: + case 263: return visitNode(cbNode, node.tagName); - case 169: - case 170: - case 281: - case 285: - case 284: + case 171: + case 172: + case 283: + case 287: case 286: case 288: + case 290: return visitNode(cbNode, node.type); - case 287: + case 289: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 289: - return visitNodes(cbNode, cbNodes, node.tags); - case 297: - case 303: - if (node.isNameFirst) { - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression); - } - else { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - } - case 298: - return visitNode(cbNode, node.typeExpression); - case 300: - return visitNode(cbNode, node.typeExpression); - case 293: - return visitNode(cbNode, node.class); - case 301: - return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302: - if (node.typeExpression && - node.typeExpression.kind === 281) { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName); - } - else { - return visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - } - case 295: - return visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - case 299: - return visitNode(cbNode, node.typeExpression); - case 296: - return visitNode(cbNode, node.typeExpression); case 291: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - ts.forEach(node.typeParameters, cbNode) || + return visitNodes(cbNode, cbNodes, node.tags); + case 299: + case 305: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 300: + case 302: + case 301: + case 298: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293: + return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290: - if (node.jsDocPropertyTags) { - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); - } - } - return; - case 306: + case 292: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294: + case 296: + return visitNode(cbNode, node.tagName); + case 308: return visitNode(cbNode, node.expression); } } @@ -12710,7 +13410,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, 6); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); @@ -12776,8 +13476,12 @@ var ts; if (scriptKind === 6) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -12807,18 +13511,18 @@ var ts; sourceFile.endOfFileToken = parseTokenNode(); } else { - var statement = createNode(219); + var statement = createNode(221); switch (token()) { - case 21: + case 22: statement.expression = parseArrayLiteralExpression(); break; - case 101: - case 86: - case 95: + case 102: + case 87: + case 96: statement.expression = parseTokenNode(); break; - case 38: - if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 56; })) { + case 39: + if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 57; })) { statement.expression = parsePrefixUnaryExpression(); } else { @@ -12826,8 +13530,8 @@ var ts; } break; case 8: - case 9: - if (lookAhead(function () { return nextToken() !== 56; })) { + case 10: + if (lookAhead(function () { return nextToken() !== 57; })) { statement.expression = parseLiteralNode(); break; } @@ -12947,7 +13651,7 @@ var ts; } Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { - var sourceFile = new SourceFileConstructor(277, 0, sourceText.length); + var sourceFile = new SourceFileConstructor(279, 0, sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -13104,16 +13808,16 @@ var ts; return speculationHelper(callback, false); } function isIdentifier() { - if (token() === 71) { + if (token() === 72) { return true; } - if (token() === 116 && inYieldContext()) { + if (token() === 117 && inYieldContext()) { return false; } - if (token() === 121 && inAwaitContext()) { + if (token() === 122 && inAwaitContext()) { return false; } - return token() > 107; + return token() > 108; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -13154,27 +13858,27 @@ var ts; return finishNode(node); } function canParseSemicolon() { - if (token() === 25) { + if (token() === 26) { return true; } - return token() === 18 || token() === 1 || scanner.hasPrecedingLineBreak(); + return token() === 19 || token() === 1 || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 25) { + if (token() === 26) { nextToken(); } return true; } else { - return parseExpected(25); + return parseExpected(26); } } function createNode(kind, pos) { nodeCount++; var p = pos >= 0 ? pos : scanner.getStartPos(); return ts.isNodeKind(kind) || kind === 0 ? new NodeConstructor(kind, p, p) : - kind === 71 ? new IdentifierConstructor(kind, p, p) : + kind === 72 ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } function createNodeWithJSDoc(kind, pos) { @@ -13210,7 +13914,7 @@ var ts; parseErrorAtCurrentToken(diagnosticMessage, arg0); } var result = createNode(kind); - if (kind === 71) { + if (kind === 72) { result.escapedText = ""; } else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { @@ -13228,8 +13932,8 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(71); - if (token() !== 71) { + var node = createNode(72); + if (token() !== 72) { node.originalKeywordKind = token(); } node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); @@ -13237,7 +13941,7 @@ var ts; return finishNode(node); } var reportAtCurrentPosition = token() === 1; - return createMissingNode(71, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(72, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -13247,16 +13951,16 @@ var ts; } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || + token() === 10 || token() === 8; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 || token() === 8) { + if (token() === 10 || token() === 8) { var node = parseLiteralNode(); node.text = internIdentifier(node.text); return node; } - if (allowComputedPropertyNames && token() === 21) { + if (allowComputedPropertyNames && token() === 22) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -13265,10 +13969,10 @@ var ts; return parsePropertyNameWorker(true); } function parseComputedPropertyName() { - var node = createNode(147); - parseExpected(21); - node.expression = allowInAnd(parseExpression); + var node = createNode(149); parseExpected(22); + node.expression = allowInAnd(parseExpression); + parseExpected(23); return finishNode(node); } function parseContextualModifier(t) { @@ -13283,19 +13987,19 @@ var ts; } function nextTokenCanFollowModifier() { switch (token()) { - case 76: - return nextToken() === 83; - case 84: + case 77: + return nextToken() === 84; + case 85: nextToken(); - if (token() === 79) { + if (token() === 80) { return lookAhead(nextTokenCanFollowDefaultKeyword); } - return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); - case 79: + return token() !== 40 && token() !== 119 && token() !== 18 && canFollowModifier(); + case 80: return nextTokenCanFollowDefaultKeyword(); - case 115: - case 125: - case 136: + case 116: + case 126: + case 137: nextToken(); return canFollowModifier(); default: @@ -13306,18 +14010,18 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 21 - || token() === 17 - || token() === 39 - || token() === 24 + return token() === 22 + || token() === 18 + || token() === 40 + || token() === 25 || isLiteralPropertyName(); } function nextTokenCanFollowDefaultKeyword() { nextToken(); - return token() === 75 || token() === 89 || - token() === 109 || - (token() === 117 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 76 || token() === 90 || + token() === 110 || + (token() === 118 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -13328,23 +14032,31 @@ var ts; case 0: case 1: case 3: - return !(token() === 25 && inErrorRecovery) && isStartOfStatement(); + return !(token() === 26 && inErrorRecovery) && isStartOfStatement(); case 2: - return token() === 73 || token() === 79; + return token() === 74 || token() === 80; case 4: return lookAhead(isTypeMemberStart); case 5: - return lookAhead(isClassMemberStart) || (token() === 25 && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 26 && !inErrorRecovery); case 6: - return token() === 21 || isLiteralPropertyName(); + return token() === 22 || isLiteralPropertyName(); case 12: - return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); + switch (token()) { + case 22: + case 40: + case 25: + case 24: + return true; + default: + return isLiteralPropertyName(); + } case 18: return isLiteralPropertyName(); case 9: - return token() === 21 || token() === 24 || isLiteralPropertyName(); + return token() === 22 || token() === 25 || isLiteralPropertyName(); case 7: - if (token() === 17) { + if (token() === 18) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -13356,38 +14068,40 @@ var ts; case 8: return isIdentifierOrPattern(); case 10: - return token() === 26 || token() === 24 || isIdentifierOrPattern(); + return token() === 27 || token() === 25 || isIdentifierOrPattern(); case 19: return isIdentifier(); case 15: - if (token() === 26) { - return true; + switch (token()) { + case 27: + case 24: + return true; } case 11: - return token() === 24 || isStartOfExpression(); + return token() === 25 || isStartOfExpression(); case 16: return isStartOfParameter(false); case 17: return isStartOfParameter(true); case 20: case 21: - return token() === 26 || isStartOfType(); + return token() === 27 || isStartOfType(); case 22: return isHeritageClause(); case 23: return ts.tokenIsIdentifierOrKeyword(token()); case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18; case 14: return true; } return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17); - if (nextToken() === 18) { + ts.Debug.assert(token() === 18); + if (nextToken() === 19) { var next = nextToken(); - return next === 26 || next === 17 || next === 85 || next === 108; + return next === 27 || next === 18 || next === 86 || next === 109; } return true; } @@ -13404,8 +14118,8 @@ var ts; return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 || - token() === 85) { + if (token() === 109 || + token() === 86) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -13431,33 +14145,33 @@ var ts; case 12: case 9: case 23: - return token() === 18; + return token() === 19; case 3: - return token() === 18 || token() === 73 || token() === 79; + return token() === 19 || token() === 74 || token() === 80; case 7: - return token() === 17 || token() === 85 || token() === 108; + return token() === 18 || token() === 86 || token() === 109; case 8: return isVariableDeclaratorListTerminator(); case 19: - return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108; + return token() === 30 || token() === 20 || token() === 18 || token() === 86 || token() === 109; case 11: - return token() === 20 || token() === 25; + return token() === 21 || token() === 26; case 15: case 21: case 10: - return token() === 22; + return token() === 23; case 17: case 16: case 18: - return token() === 20 || token() === 22; + return token() === 21 || token() === 23; case 20: - return token() !== 26; + return token() !== 27; case 22: - return token() === 17 || token() === 18; + return token() === 18 || token() === 19; case 13: - return token() === 29 || token() === 41; + return token() === 30 || token() === 42; case 14: - return token() === 27 && lookAhead(nextTokenIsSlash); + return token() === 28 && lookAhead(nextTokenIsSlash); default: return false; } @@ -13469,7 +14183,7 @@ var ts; if (isInOrOfKeyword(token())) { return true; } - if (token() === 36) { + if (token() === 37) { return true; } return false; @@ -13579,17 +14293,17 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 155: - case 160: - case 156: case 157: - case 152: - case 215: - return true; + case 162: + case 158: + case 159: case 154: + case 217: + return true; + case 156: var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 && - methodDeclaration.name.originalKeywordKind === 123; + var nameIsConstructor = methodDeclaration.name.kind === 72 && + methodDeclaration.name.originalKeywordKind === 124; return !nameIsConstructor; } } @@ -13598,8 +14312,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 269: - case 270: + case 271: + case 272: return true; } } @@ -13608,65 +14322,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 237: - case 217: - case 216: - case 220: + case 239: case 219: - case 232: - case 228: - case 230: - case 227: - case 226: - case 224: - case 225: - case 223: - case 222: - case 229: case 218: - case 233: - case 231: + case 222: case 221: case 234: - case 247: - case 246: - case 253: - case 252: - case 242: - case 238: - case 239: - case 241: + case 230: + case 232: + case 229: + case 228: + case 226: + case 227: + case 225: + case 224: + case 231: + case 220: + case 235: + case 233: + case 223: + case 236: + case 249: + case 248: + case 255: + case 254: + case 244: case 240: + case 241: + case 243: + case 242: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 276; + return node.kind === 278; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 159: + case 161: + case 155: + case 162: case 153: case 160: - case 151: - case 158: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 235) { + if (node.kind !== 237) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 149) { + if (node.kind !== 151) { return false; } var parameter = node; @@ -13720,15 +14434,15 @@ var ts; var startPos = scanner.getStartPos(); list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(26)) { + if (parseOptional(27)) { continue; } commaStart = -1; if (isListTerminator(kind)) { break; } - parseExpected(26); - if (considerSemicolonAsDelimiter && token() === 25 && !scanner.hasPrecedingLineBreak()) { + parseExpected(27); + if (considerSemicolonAsDelimiter && token() === 26 && !scanner.hasPrecedingLineBreak()) { nextToken(); } if (startPos === scanner.getStartPos()) { @@ -13769,8 +14483,8 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); - while (parseOptional(23)) { - if (token() === 27) { + while (parseOptional(24)) { + if (token() === 28) { entity.jsdocDotPos = dotPos; break; } @@ -13780,7 +14494,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(146, entity.pos); + var node = createNode(148, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -13789,33 +14503,33 @@ var ts; if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { - return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + return createMissingNode(72, true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(204); + var template = createNode(206); template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); + ts.Debug.assert(template.head.kind === 15, "Template head has wrong token kind"); var list = []; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.last(list).literal.kind === 15); + } while (ts.last(list).literal.kind === 16); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { - var span = createNode(214); + var span = createNode(216); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 18) { + if (token() === 19) { reScanTemplateToken(); literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(16, ts.Diagnostics._0_expected, ts.tokenToString(18)); + literal = parseExpectedToken(17, ts.Diagnostics._0_expected, ts.tokenToString(19)); } span.literal = literal; return finishNode(span); @@ -13825,18 +14539,17 @@ var ts; } function parseTemplateHead() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 14, "Template head has wrong token kind"); + ts.Debug.assert(fragment.kind === 15, "Template head has wrong token kind"); return fragment; } function parseTemplateMiddleOrTemplateTail() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 15 || fragment.kind === 16, "Template fragment has wrong token kind"); + ts.Debug.assert(fragment.kind === 16 || fragment.kind === 17, "Template fragment has wrong token kind"); return fragment; } function parseLiteralLikeNode(kind) { var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = text; + node.text = scanner.getTokenValue(); if (scanner.hasExtendedUnicodeEscape()) { node.hasExtendedUnicodeEscape = true; } @@ -13851,23 +14564,23 @@ var ts; return node; } function parseTypeReference() { - var node = createNode(162); + var node = createNode(164); node.typeName = parseEntityName(true, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27) { - node.typeArguments = parseBracketedList(20, parseType, 27, 29); + if (!scanner.hasPrecedingLineBreak() && token() === 28) { + node.typeArguments = parseBracketedList(20, parseType, 28, 30); } return finishNode(node); } function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 162: + case 164: return ts.nodeIsMissing(node.typeName); - case 163: - case 164: { + case 165: + case 166: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 175: + case 177: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -13875,20 +14588,20 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(161, lhs.pos); + var node = createNode(163, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(176); + var node = createNode(178); nextToken(); return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(282); + var result = createNode(284); if (postFixEquals) { - return createPostfixType(286, result); + return createPostfixType(288, result); } else { nextToken(); @@ -13896,7 +14609,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(285); + var result = createNode(287); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -13904,64 +14617,66 @@ var ts; function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); nextToken(); - if (token() === 26 || - token() === 18 || - token() === 20 || - token() === 29 || - token() === 58 || - token() === 49) { - var result = createNode(283, pos); + if (token() === 27 || + token() === 19 || + token() === 21 || + token() === 30 || + token() === 59 || + token() === 50) { + var result = createNode(285, pos); return finishNode(result); } else { - var result = createNode(284, pos); + var result = createNode(286, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(287); + var result = createNodeWithJSDoc(289); nextToken(); - fillSignature(56, 4 | 32, result); + fillSignature(57, 4 | 32, result); return finishNode(result); } - var node = createNode(162); + var node = createNode(164); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(149); - if (token() === 99 || token() === 94) { + var parameter = createNode(151); + if (token() === 100 || token() === 95) { parameter.name = parseIdentifierName(); - parseExpected(56); + parseExpected(57); } parameter.type = parseJSDocType(); return finishNode(parameter); } function parseJSDocType() { - var dotdotdot = parseOptionalToken(24); + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { - var variadic = createNode(288, dotdotdot.pos); + var variadic = createNode(290, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } - if (token() === 58) { - return createPostfixType(286, type); + if (token() === 59) { + return createPostfixType(288, type); } return type; } function parseTypeQuery() { - var node = createNode(165); - parseExpected(103); + var node = createNode(167); + parseExpected(104); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(148); + var node = createNode(150); node.name = parseIdentifier(); - if (parseOptional(85)) { + if (parseOptional(86)) { if (isStartOfType() || !isStartOfExpression()) { node.constraint = parseType(); } @@ -13969,44 +14684,44 @@ var ts; node.expression = parseUnaryExpressionOrHigher(); } } - if (parseOptional(58)) { + if (parseOptional(59)) { node.default = parseType(); } return finishNode(node); } function parseTypeParameters() { - if (token() === 27) { - return parseBracketedList(19, parseTypeParameter, 27, 29); + if (token() === 28) { + return parseBracketedList(19, parseTypeParameter, 28, 30); } } function parseParameterType() { - if (parseOptional(56)) { + if (parseOptional(57)) { return parseType(); } return undefined; } function isStartOfParameter(isJSDocParameter) { - return token() === 24 || + return token() === 25 || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 || + token() === 58 || isStartOfType(!isJSDocParameter); } function parseParameter() { - var node = createNodeWithJSDoc(149); - if (token() === 99) { + var node = createNodeWithJSDoc(151); + if (token() === 100) { node.name = createIdentifier(true); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24); + node.dotDotDotToken = parseOptionalToken(25); node.name = parseIdentifierOrPattern(); if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { nextToken(); } - node.questionToken = parseOptionalToken(55); + node.questionToken = parseOptionalToken(56); node.type = parseParameterType(); node.initializer = parseInitializer(); return finishNode(node); @@ -14024,22 +14739,22 @@ var ts; return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { - if (returnToken === 36) { + if (returnToken === 37) { parseExpected(returnToken); return true; } - else if (parseOptional(56)) { + else if (parseOptional(57)) { return true; } - else if (isType && token() === 36) { - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56)); + else if (isType && token() === 37) { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57)); nextToken(); return true; } return false; } function parseParameterList(signature, flags) { - if (!parseExpected(19)) { + if (!parseExpected(20)) { signature.parameters = createMissingList(); return false; } @@ -14052,29 +14767,29 @@ var ts; parseDelimitedList(16, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - return parseExpected(20); + return parseExpected(21); } function parseTypeMemberSemicolon() { - if (parseOptional(26)) { + if (parseOptional(27)) { return; } parseSemicolon(); } function parseSignatureMember(kind) { var node = createNodeWithJSDoc(kind); - if (kind === 159) { - parseExpected(94); + if (kind === 161) { + parseExpected(95); } - fillSignature(56, 4, node); + fillSignature(57, 4, node); parseTypeMemberSemicolon(); return finishNode(node); } function isIndexSignature() { - return token() === 21 && lookAhead(isUnambiguouslyIndexSignature); + return token() === 22 && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token() === 24 || token() === 22) { + if (token() === 25 || token() === 23) { return true; } if (ts.isModifierKind(token())) { @@ -14089,33 +14804,33 @@ var ts; else { nextToken(); } - if (token() === 56 || token() === 26) { + if (token() === 57 || token() === 27) { return true; } - if (token() !== 55) { + if (token() !== 56) { return false; } nextToken(); - return token() === 56 || token() === 26 || token() === 22; + return token() === 57 || token() === 27 || token() === 23; } function parseIndexSignatureDeclaration(node) { - node.kind = 160; - node.parameters = parseBracketedList(16, parseParameter, 21, 22); + node.kind = 162; + node.parameters = parseBracketedList(16, parseParameter, 22, 23); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(node) { node.name = parsePropertyName(); - node.questionToken = parseOptionalToken(55); - if (token() === 19 || token() === 27) { - node.kind = 153; - fillSignature(56, 4, node); + node.questionToken = parseOptionalToken(56); + if (token() === 20 || token() === 28) { + node.kind = 155; + fillSignature(57, 4, node); } else { - node.kind = 151; + node.kind = 153; node.type = parseTypeAnnotation(); - if (token() === 58) { + if (token() === 59) { node.initializer = parseInitializer(); } } @@ -14123,7 +14838,7 @@ var ts; return finishNode(node); } function isTypeMemberStart() { - if (token() === 19 || token() === 27) { + if (token() === 20 || token() === 28) { return true; } var idToken = false; @@ -14131,7 +14846,7 @@ var ts; idToken = true; nextToken(); } - if (token() === 21) { + if (token() === 22) { return true; } if (isLiteralPropertyName()) { @@ -14139,21 +14854,21 @@ var ts; nextToken(); } if (idToken) { - return token() === 19 || - token() === 27 || - token() === 55 || + return token() === 20 || + token() === 28 || token() === 56 || - token() === 26 || + token() === 57 || + token() === 27 || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 19 || token() === 27) { - return parseSignatureMember(158); + if (token() === 20 || token() === 28) { + return parseSignatureMember(160); } - if (token() === 94 && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(159); + if (token() === 95 && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161); } var node = createNodeWithJSDoc(0); node.modifiers = parseModifiers(); @@ -14164,30 +14879,30 @@ var ts; } function nextTokenIsOpenParenOrLessThan() { nextToken(); - return token() === 19 || token() === 27; + return token() === 20 || token() === 28; } function nextTokenIsDot() { - return nextToken() === 23; + return nextToken() === 24; } function nextTokenIsOpenParenOrLessThanOrDot() { switch (nextToken()) { - case 19: - case 27: - case 23: + case 20: + case 28: + case 24: return true; } return false; } function parseTypeLiteral() { - var node = createNode(166); + var node = createNode(168); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(17)) { + if (parseExpected(18)) { members = parseList(4, parseTypeMember); - parseExpected(18); + parseExpected(19); } else { members = createMissingList(); @@ -14196,89 +14911,89 @@ var ts; } function isStartOfMappedType() { nextToken(); - if (token() === 37 || token() === 38) { - return nextToken() === 132; + if (token() === 38 || token() === 39) { + return nextToken() === 133; } - if (token() === 132) { + if (token() === 133) { nextToken(); } - return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; + return token() === 22 && nextTokenIsIdentifier() && nextToken() === 93; } function parseMappedTypeParameter() { - var node = createNode(148); + var node = createNode(150); node.name = parseIdentifier(); - parseExpected(92); + parseExpected(93); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(179); - parseExpected(17); - if (token() === 132 || token() === 37 || token() === 38) { + var node = createNode(181); + parseExpected(18); + if (token() === 133 || token() === 38 || token() === 39) { node.readonlyToken = parseTokenNode(); - if (node.readonlyToken.kind !== 132) { - parseExpectedToken(132); + if (node.readonlyToken.kind !== 133) { + parseExpectedToken(133); } } - parseExpected(21); - node.typeParameter = parseMappedTypeParameter(); parseExpected(22); - if (token() === 55 || token() === 37 || token() === 38) { + node.typeParameter = parseMappedTypeParameter(); + parseExpected(23); + if (token() === 56 || token() === 38 || token() === 39) { node.questionToken = parseTokenNode(); - if (node.questionToken.kind !== 55) { - parseExpectedToken(55); + if (node.questionToken.kind !== 56) { + parseExpectedToken(56); } } node.type = parseTypeAnnotation(); parseSemicolon(); - parseExpected(18); + parseExpected(19); return finishNode(node); } function parseTupleElementType() { var pos = getNodePos(); - if (parseOptional(24)) { - var node = createNode(170, pos); + if (parseOptional(25)) { + var node = createNode(172, pos); node.type = parseType(); return finishNode(node); } var type = parseType(); - if (!(contextFlags & 2097152) && type.kind === 284 && type.pos === type.type.pos) { - type.kind = 169; + if (!(contextFlags & 2097152) && type.kind === 286 && type.pos === type.type.pos) { + type.kind = 171; } return type; } function parseTupleType() { - var node = createNode(168); - node.elementTypes = parseBracketedList(21, parseTupleElementType, 21, 22); + var node = createNode(170); + node.elementTypes = parseBracketedList(21, parseTupleElementType, 22, 23); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(175); - parseExpected(19); - node.type = parseType(); + var node = createNode(177); parseExpected(20); + node.type = parseType(); + parseExpected(21); return finishNode(node); } function parseFunctionOrConstructorType() { var pos = getNodePos(); - var kind = parseOptional(94) ? 164 : 163; + var kind = parseOptional(95) ? 166 : 165; var node = createNodeWithJSDoc(kind, pos); - fillSignature(36, 4, node); + fillSignature(37, 4, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 23 ? undefined : node; + return token() === 24 ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(180); + var node = createNode(182); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(200); - unaryMinusExpression.operator = 38; + unaryMinusExpression = createNode(202); + unaryMinusExpression.operator = 39; nextToken(); } - var expression = token() === 101 || token() === 86 + var expression = token() === 102 || token() === 87 ? parseTokenNode() : parseLiteralLikeNode(token()); if (negative) { @@ -14291,78 +15006,81 @@ var ts; } function isStartOfTypeOfImportType() { nextToken(); - return token() === 91; + return token() === 92; } function parseImportType() { sourceFile.flags |= 524288; - var node = createNode(181); - if (parseOptional(103)) { + var node = createNode(183); + if (parseOptional(104)) { node.isTypeOf = true; } - parseExpected(91); - parseExpected(19); - node.argument = parseType(); + parseExpected(92); parseExpected(20); - if (parseOptional(23)) { + node.argument = parseType(); + parseExpected(21); + if (parseOptional(24)) { node.qualifier = parseEntityName(true, ts.Diagnostics.Type_expected); } node.typeArguments = tryParseTypeArguments(); return finishNode(node); } - function nextTokenIsNumericLiteral() { - return nextToken() === 8; + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 || token() === 9; } function parseNonArrayType() { switch (token()) { - case 119: - case 142: - case 137: - case 134: + case 120: + case 143: case 138: - case 122: - case 140: - case 131: case 135: + case 146: + case 139: + case 123: + case 141: + case 132: + case 136: return tryParse(parseKeywordAndNoDot) || parseTypeReference(); - case 39: + case 40: return parseJSDocAllType(false); - case 61: + case 62: return parseJSDocAllType(true); - case 55: + case 56: return parseJSDocUnknownOrNullableType(); - case 89: + case 90: return parseJSDocFunctionType(); - case 51: + case 52: return parseJSDocNonNullableType(); - case 13: - case 9: + case 14: + case 10: case 8: - case 101: - case 86: + case 9: + case 102: + case 87: return parseLiteralTypeNode(); - case 38: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(true) : parseTypeReference(); - case 105: - case 95: + case 39: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(true) : parseTypeReference(); + case 106: + case 96: return parseTokenNode(); - case 99: { + case 100: { var thisKeyword = parseThisTypeNode(); - if (token() === 127 && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 103: + case 104: return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); - case 17: + case 18: return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21: + case 22: return parseTupleType(); - case 19: + case 20: return parseParenthesizedType(); - case 91: + case 92: return parseImportType(); default: return parseTypeReference(); @@ -14370,42 +15088,44 @@ var ts; } function isStartOfType(inStartOfParameter) { switch (token()) { - case 119: - case 142: - case 137: - case 134: - case 122: + case 120: + case 143: case 138: - case 141: - case 105: - case 140: - case 95: - case 99: - case 103: - case 131: - case 17: - case 21: - case 27: - case 49: - case 48: - case 94: - case 9: - case 8: - case 101: - case 86: case 135: - case 39: - case 55: - case 51: - case 24: - case 126: - case 91: + case 146: + case 123: + case 139: + case 142: + case 106: + case 141: + case 96: + case 100: + case 104: + case 132: + case 18: + case 22: + case 28: + case 50: + case 49: + case 95: + case 10: + case 8: + case 9: + case 102: + case 87: + case 136: + case 40: + case 56: + case 52: + case 25: + case 127: + case 92: return true; - case 89: + case 90: return !inStartOfParameter; - case 38: - return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); - case 19: + case 39: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20: return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); @@ -14413,34 +15133,34 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 || isStartOfParameter(false) || isStartOfType(); + return token() === 21 || isStartOfParameter(false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 51: - type = createPostfixType(285, type); + case 52: + type = createPostfixType(287, type); break; - case 55: + case 56: if (!(contextFlags & 2097152) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createPostfixType(284, type); + type = createPostfixType(286, type); break; - case 21: - parseExpected(21); + case 22: + parseExpected(22); if (isStartOfType()) { - var node = createNode(178, type.pos); + var node = createNode(180, type.pos); node.objectType = type; node.indexType = parseType(); - parseExpected(22); + parseExpected(23); type = finishNode(node); } else { - var node = createNode(167, type.pos); + var node = createNode(169, type.pos); node.elementType = type; - parseExpected(22); + parseExpected(23); type = finishNode(node); } break; @@ -14457,16 +15177,16 @@ var ts; return finishNode(postfix); } function parseTypeOperator(operator) { - var node = createNode(177); + var node = createNode(179); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseInferType() { - var node = createNode(174); - parseExpected(126); - var typeParameter = createNode(148); + var node = createNode(176); + parseExpected(127); + var typeParameter = createNode(150); typeParameter.name = parseIdentifier(); node.typeParameter = finishNode(typeParameter); return finishNode(node); @@ -14474,10 +15194,10 @@ var ts; function parseTypeOperatorOrHigher() { var operator = token(); switch (operator) { - case 128: - case 141: + case 129: + case 142: return parseTypeOperator(operator); - case 126: + case 127: return parseInferType(); } return parsePostfixTypeOrHigher(); @@ -14497,26 +15217,26 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(172, parseTypeOperatorOrHigher, 48); + return parseUnionOrIntersectionType(174, parseTypeOperatorOrHigher, 49); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(171, parseIntersectionTypeOrHigher, 49); + return parseUnionOrIntersectionType(173, parseIntersectionTypeOrHigher, 50); } function isStartOfFunctionType() { - if (token() === 27) { + if (token() === 28) { return true; } - return token() === 19 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 20 && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { parseModifiers(); } - if (isIdentifier() || token() === 99) { + if (isIdentifier() || token() === 100) { nextToken(); return true; } - if (token() === 21 || token() === 17) { + if (token() === 22 || token() === 18) { var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -14525,17 +15245,17 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 || token() === 24) { + if (token() === 21 || token() === 25) { return true; } if (skipParameterStart()) { - if (token() === 56 || token() === 26 || - token() === 55 || token() === 58) { + if (token() === 57 || token() === 27 || + token() === 56 || token() === 59) { return true; } - if (token() === 20) { + if (token() === 21) { nextToken(); - if (token() === 36) { + if (token() === 37) { return true; } } @@ -14546,7 +15266,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(161, typePredicateVariable.pos); + var node = createNode(163, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -14557,7 +15277,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 127 && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -14566,47 +15286,48 @@ var ts; return doOutsideOfContext(20480, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType() || token() === 94) { + if (isStartOfFunctionType() || token() === 95) { return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); - if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85)) { - var node = createNode(173, type.pos); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86)) { + var node = createNode(175, type.pos); node.checkType = type; node.extendsType = parseTypeWorker(true); - parseExpected(55); - node.trueType = parseTypeWorker(); parseExpected(56); + node.trueType = parseTypeWorker(); + parseExpected(57); node.falseType = parseTypeWorker(); return finishNode(node); } return type; } function parseTypeAnnotation() { - return parseOptional(56) ? parseType() : undefined; + return parseOptional(57) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { switch (token()) { - case 99: - case 97: - case 95: - case 101: - case 86: + case 100: + case 98: + case 96: + case 102: + case 87: case 8: case 9: - case 13: + case 10: case 14: - case 19: - case 21: - case 17: - case 89: - case 75: - case 94: - case 41: - case 63: - case 71: + case 15: + case 20: + case 22: + case 18: + case 90: + case 76: + case 95: + case 42: + case 64: + case 72: return true; - case 91: + case 92: return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); default: return isIdentifier(); @@ -14617,18 +15338,18 @@ var ts; return true; } switch (token()) { - case 37: case 38: + case 39: + case 53: case 52: - case 51: - case 80: - case 103: - case 105: - case 43: + case 81: + case 104: + case 106: case 44: - case 27: - case 121: - case 116: + case 45: + case 28: + case 122: + case 117: return true; default: if (isBinaryOperator()) { @@ -14638,10 +15359,10 @@ var ts; } } function isStartOfExpressionStatement() { - return token() !== 17 && - token() !== 89 && - token() !== 75 && - token() !== 57 && + return token() !== 18 && + token() !== 90 && + token() !== 76 && + token() !== 58 && isStartOfExpression(); } function parseExpression() { @@ -14651,7 +15372,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(26))) { + while ((operatorToken = parseOptionalToken(27))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -14660,7 +15381,7 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(58) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(59) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { if (isYieldExpression()) { @@ -14671,7 +15392,7 @@ var ts; return arrowExpression; } var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 71 && token() === 36) { + if (expr.kind === 72 && token() === 37) { return parseSimpleArrowFunctionExpression(expr); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { @@ -14680,7 +15401,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 116) { + if (token() === 117) { if (inYieldContext()) { return true; } @@ -14693,11 +15414,11 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(205); + var node = createNode(207); nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 39 || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39); + (token() === 40 || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -14706,20 +15427,20 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 37, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(195, asyncModifier.pos); + node = createNode(197, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(195, identifier.pos); + node = createNode(197, identifier.pos); } - var parameter = createNode(149, identifier.pos); + var parameter = createNode(151, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); - node.equalsGreaterThanToken = parseExpectedToken(36); + node.equalsGreaterThanToken = parseExpectedToken(37); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -14736,92 +15457,92 @@ var ts; } var isAsync = ts.hasModifier(arrowFunction, 256); var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36); - arrowFunction.body = (lastToken === 36 || lastToken === 17) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37); + arrowFunction.body = (lastToken === 37 || lastToken === 18) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return finishNode(arrowFunction); } function isParenthesizedArrowFunctionExpression() { - if (token() === 19 || token() === 27 || token() === 120) { + if (token() === 20 || token() === 28 || token() === 121) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 36) { + if (token() === 37) { return 1; } return 0; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120) { + if (token() === 121) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0; } - if (token() !== 19 && token() !== 27) { + if (token() !== 20 && token() !== 28) { return 0; } } var first = token(); var second = nextToken(); - if (first === 19) { - if (second === 20) { + if (first === 20) { + if (second === 21) { var third = nextToken(); switch (third) { - case 36: - case 56: - case 17: + case 37: + case 57: + case 18: return 1; default: return 0; } } - if (second === 21 || second === 17) { + if (second === 22 || second === 18) { return 2; } - if (second === 24) { + if (second === 25) { return 1; } - if (ts.isModifierKind(second) && second !== 120 && lookAhead(nextTokenIsIdentifier)) { + if (ts.isModifierKind(second) && second !== 121 && lookAhead(nextTokenIsIdentifier)) { return 1; } - if (!isIdentifier() && second !== 99) { + if (!isIdentifier() && second !== 100) { return 0; } switch (nextToken()) { - case 56: + case 57: return 1; - case 55: + case 56: nextToken(); - if (token() === 56 || token() === 26 || token() === 58 || token() === 20) { + if (token() === 57 || token() === 27 || token() === 59 || token() === 21) { return 1; } return 0; - case 26: - case 58: - case 20: + case 27: + case 59: + case 21: return 2; } return 0; } else { - ts.Debug.assert(first === 27); + ts.Debug.assert(first === 28); if (!isIdentifier()) { return 0; } if (sourceFile.languageVariant === 1) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 85) { + if (third === 86) { var fourth = nextToken(); switch (fourth) { - case 58: - case 29: + case 59: + case 30: return false; default: return true; } } - else if (third === 26) { + else if (third === 27) { return true; } return false; @@ -14838,7 +15559,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 120) { + if (token() === 121) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0); @@ -14848,37 +15569,37 @@ var ts; return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 120) { + if (token() === 121) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 36) { + if (scanner.hasPrecedingLineBreak() || token() === 37) { return 0; } var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 && token() === 36) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 && token() === 37) { return 1; } } return 0; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNodeWithJSDoc(195); + var node = createNodeWithJSDoc(197); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - if (!fillSignature(56, isAsync, node) && !allowAmbiguity) { + if (!fillSignature(57, isAsync, node) && !allowAmbiguity) { return undefined; } - if (!allowAmbiguity && token() !== 36 && token() !== 17) { + if (!allowAmbiguity && token() !== 37 && token() !== 18) { return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17) { + if (token() === 18) { return parseFunctionBlock(isAsync ? 2 : 0); } - if (token() !== 25 && - token() !== 89 && - token() !== 75 && + if (token() !== 26 && + token() !== 90 && + token() !== 76 && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(16 | (isAsync ? 2 : 0)); @@ -14888,18 +15609,18 @@ var ts; : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); } function parseConditionalExpressionRest(leftOperand) { - var questionToken = parseOptionalToken(55); + var questionToken = parseOptionalToken(56); if (!questionToken) { return leftOperand; } - var node = createNode(203, leftOperand.pos); + var node = createNode(205, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56); + node.colonToken = parseExpectedToken(57); node.whenFalse = ts.nodeIsPresent(node.colonToken) ? parseAssignmentExpressionOrHigher() - : createMissingNode(71, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); + : createMissingNode(72, false, ts.Diagnostics._0_expected, ts.tokenToString(57)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -14907,22 +15628,22 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 || t === 145; + return t === 93 || t === 147; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { reScanGreaterToken(); var newPrecedence = ts.getBinaryOperatorPrecedence(token()); - var consumeCurrentOperator = token() === 40 ? + var consumeCurrentOperator = token() === 41 ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 92 && inDisallowInContext()) { + if (token() === 93 && inDisallowInContext()) { break; } - if (token() === 118) { + if (token() === 119) { if (scanner.hasPrecedingLineBreak()) { break; } @@ -14938,51 +15659,51 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 92) { + if (inDisallowInContext() && token() === 93) { return false; } return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(202, left.pos); + var node = createNode(204, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(210, left.pos); + var node = createNode(212, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(200); + var node = createNode(202); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(196); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseTypeOfExpression() { - var node = createNode(197); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseVoidExpression() { var node = createNode(198); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } + function parseTypeOfExpression() { + var node = createNode(199); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(200); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } function isAwaitExpression() { - if (token() === 121) { + if (token() === 122) { if (inAwaitContext()) { return true; } @@ -14991,7 +15712,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(199); + var node = createNode(201); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -14999,16 +15720,16 @@ var ts; function parseUnaryExpressionOrHigher() { if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 ? + return token() === 41 ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40) { + if (token() === 41) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 192) { + if (simpleUnaryExpression.kind === 194) { parseErrorAt(pos, end, 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 { @@ -15019,20 +15740,20 @@ var ts; } function parseSimpleUnaryExpression() { switch (token()) { - case 37: case 38: + case 39: + case 53: case 52: - case 51: return parsePrefixUnaryExpression(); - case 80: + case 81: return parseDeleteExpression(); - case 103: + case 104: return parseTypeOfExpression(); - case 105: + case 106: return parseVoidExpression(); - case 27: + case 28: return parseTypeAssertion(); - case 121: + case 122: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -15042,16 +15763,16 @@ var ts; } function isUpdateExpression() { switch (token()) { - case 37: case 38: + case 39: + case 53: case 52: - case 51: - case 80: - case 103: - case 105: - case 121: + case 81: + case 104: + case 106: + case 122: return false; - case 27: + case 28: if (sourceFile.languageVariant !== 1) { return false; } @@ -15060,20 +15781,20 @@ var ts; } } function parseUpdateExpression() { - if (token() === 43 || token() === 44) { - var node = createNode(200); + if (token() === 44 || token() === 45) { + var node = createNode(202); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + else if (sourceFile.languageVariant === 1 && token() === 28 && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { return parseJsxElementOrSelfClosingElementOrFragment(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(201, expression.pos); + if ((token() === 44 || token() === 45) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -15083,7 +15804,7 @@ var ts; } function parseLeftHandSideExpressionOrHigher() { var expression; - if (token() === 91) { + if (token() === 92) { if (lookAhead(nextTokenIsOpenParenOrLessThan)) { sourceFile.flags |= 524288; expression = parseTokenNode(); @@ -15092,8 +15813,8 @@ var ts; var fullStart = scanner.getStartPos(); nextToken(); nextToken(); - var node = createNode(212, fullStart); - node.keywordToken = 91; + var node = createNode(214, fullStart); + node.keywordToken = 92; node.name = parseIdentifierName(); expression = finishNode(node); sourceFile.flags |= 1048576; @@ -15103,7 +15824,7 @@ var ts; } } else { - expression = token() === 97 ? parseSuperExpression() : parseMemberExpressionOrHigher(); + expression = token() === 98 ? parseSuperExpression() : parseMemberExpressionOrHigher(); } return parseCallExpressionRest(expression); } @@ -15113,20 +15834,20 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 19 || token() === 23 || token() === 21) { + if (token() === 20 || token() === 24 || token() === 22) { return expression; } - var node = createNode(187, expression.pos); + var node = createNode(189, expression.pos); node.expression = expression; - parseExpectedToken(23, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(24, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 260) { - var node = createNode(258, opening.pos); + if (opening.kind === 262) { + var node = createNode(260, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -15135,26 +15856,26 @@ var ts; } result = finishNode(node); } - else if (opening.kind === 263) { - var node = createNode(262, opening.pos); + else if (opening.kind === 265) { + var node = createNode(264, opening.pos); node.openingFragment = opening; node.children = parseJsxChildren(node.openingFragment); node.closingFragment = parseJsxClosingFragment(inExpressionContext); result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 259); + ts.Debug.assert(opening.kind === 261); result = opening; } - if (inExpressionContext && token() === 27) { + if (inExpressionContext && token() === 28) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(202, result.pos); + var badNode = createNode(204, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26, false, undefined); + badNode.operatorToken = createMissingNode(27, false, undefined); badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -15162,8 +15883,8 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10); - node.containsOnlyWhiteSpaces = currentToken === 11; + var node = createNode(11); + node.containsOnlyWhiteSpaces = currentToken === 12; currentToken = scanner.scanJsxToken(); return finishNode(node); } @@ -15177,15 +15898,15 @@ var ts; parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); } return undefined; - case 28: + case 29: case 7: return undefined; - case 10: case 11: + case 12: return parseJsxText(); - case 17: + case 18: return parseJsxExpression(false); - case 27: + case 28: return parseJsxElementOrSelfClosingElementOrFragment(false); default: return ts.Debug.assertNever(token); @@ -15206,15 +15927,15 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(266); + var jsxAttributes = createNode(268); jsxAttributes.properties = parseList(13, parseJsxAttribute); return finishNode(jsxAttributes); } function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(27); - if (token() === 29) { - var node_1 = createNode(263, fullStart); + parseExpected(28); + if (token() === 30) { + var node_1 = createNode(265, fullStart); scanJsxText(); return finishNode(node_1); } @@ -15222,20 +15943,20 @@ var ts; var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; - if (token() === 29) { - node = createNode(260, fullStart); + if (token() === 30) { + node = createNode(262, fullStart); scanJsxText(); } else { - parseExpected(41); + parseExpected(42); if (inExpressionContext) { - parseExpected(29); + parseExpected(30); } else { - parseExpected(29, undefined, false); + parseExpected(30, undefined, false); scanJsxText(); } - node = createNode(259, fullStart); + node = createNode(261, fullStart); } node.tagName = tagName; node.typeArguments = typeArguments; @@ -15244,10 +15965,10 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token() === 99 ? + var expression = token() === 100 ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(23)) { - var propertyAccess = createNode(187, expression.pos); + while (parseOptional(24)) { + var propertyAccess = createNode(189, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); @@ -15255,33 +15976,33 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(268); - if (!parseExpected(17)) { + var node = createNode(270); + if (!parseExpected(18)) { return undefined; } - if (token() !== 18) { - node.dotDotDotToken = parseOptionalToken(24); + if (token() !== 19) { + node.dotDotDotToken = parseOptionalToken(25); node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(18); + parseExpected(19); } else { - parseExpected(18, undefined, false); + parseExpected(19, undefined, false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 17) { + if (token() === 18) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(265); + var node = createNode(267); node.name = parseIdentifierName(); - if (token() === 58) { + if (token() === 59) { switch (scanJsxAttributeValue()) { - case 9: + case 10: node.initializer = parseLiteralNode(); break; default: @@ -15292,71 +16013,71 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(267); - parseExpected(17); - parseExpected(24); - node.expression = parseExpression(); + var node = createNode(269); parseExpected(18); + parseExpected(25); + node.expression = parseExpression(); + parseExpected(19); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(261); - parseExpected(28); + var node = createNode(263); + parseExpected(29); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(29); + parseExpected(30); } else { - parseExpected(29, undefined, false); + parseExpected(30, undefined, false); scanJsxText(); } return finishNode(node); } function parseJsxClosingFragment(inExpressionContext) { - var node = createNode(264); - parseExpected(28); + var node = createNode(266); + parseExpected(29); if (ts.tokenIsIdentifierOrKeyword(token())) { parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { - parseExpected(29); + parseExpected(30); } else { - parseExpected(29, undefined, false); + parseExpected(30, undefined, false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(192); - parseExpected(27); + var node = createNode(194); + parseExpected(28); node.type = parseType(); - parseExpected(29); + parseExpected(30); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(23); + var dotToken = parseOptionalToken(24); if (dotToken) { - var propertyAccess = createNode(187, expression.pos); + var propertyAccess = createNode(189, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); continue; } - if (token() === 51 && !scanner.hasPrecedingLineBreak()) { + if (token() === 52 && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(211, expression.pos); + var nonNullExpression = createNode(213, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } - if (!inDecoratorContext() && parseOptional(21)) { - var indexedAccess = createNode(188, expression.pos); + if (!inDecoratorContext() && parseOptional(22)) { + var indexedAccess = createNode(190, expression.pos); indexedAccess.expression = expression; - if (token() === 22) { - indexedAccess.argumentExpression = createMissingNode(71, true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + if (token() === 23) { + indexedAccess.argumentExpression = createMissingNode(72, true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); } else { var argument = allowInAnd(parseExpression); @@ -15365,7 +16086,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22); + parseExpected(23); expression = finishNode(indexedAccess); continue; } @@ -15377,13 +16098,13 @@ var ts; } } function isTemplateStartOfTaggedTemplate() { - return token() === 13 || token() === 14; + return token() === 14 || token() === 15; } function parseTaggedTemplateRest(tag, typeArguments) { - var tagExpression = createNode(191, tag.pos); + var tagExpression = createNode(193, tag.pos); tagExpression.tag = tag; tagExpression.typeArguments = typeArguments; - tagExpression.template = token() === 13 + tagExpression.template = token() === 14 ? parseLiteralNode() : parseTemplateExpression(); return finishNode(tagExpression); @@ -15391,7 +16112,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 27) { + if (token() === 28) { var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; @@ -15400,15 +16121,15 @@ var ts; expression = parseTaggedTemplateRest(expression, typeArguments); continue; } - var callExpr = createNode(189, expression.pos); + var callExpr = createNode(191, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 19) { - var callExpr = createNode(189, expression.pos); + else if (token() === 20) { + var callExpr = createNode(191, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -15418,17 +16139,17 @@ var ts; } } function parseArgumentList() { - parseExpected(19); - var result = parseDelimitedList(11, parseArgumentExpression); parseExpected(20); + var result = parseDelimitedList(11, parseArgumentExpression); + parseExpected(21); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(27)) { + if (!parseOptional(28)) { return undefined; } var typeArguments = parseDelimitedList(20, parseType); - if (!parseExpected(29)) { + if (!parseExpected(30)) { return undefined; } return typeArguments && canFollowTypeArgumentsInExpression() @@ -15437,29 +16158,29 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 19: - case 13: - case 14: - case 23: case 20: - case 22: + case 14: + case 15: + case 24: + case 21: + case 23: + case 57: + case 26: case 56: - case 25: - case 55: - case 32: - case 34: case 33: case 35: - case 53: + case 34: + case 36: case 54: - case 50: - case 48: + case 55: + case 51: case 49: - case 18: + case 50: + case 19: case 1: return true; - case 26: - case 17: + case 27: + case 18: default: return false; } @@ -15468,119 +16189,121 @@ var ts; switch (token()) { case 8: case 9: - case 13: + case 10: + case 14: return parseLiteralNode(); - case 99: - case 97: - case 95: - case 101: - case 86: + case 100: + case 98: + case 96: + case 102: + case 87: return parseTokenNode(); - case 19: + case 20: return parseParenthesizedExpression(); - case 21: + case 22: return parseArrayLiteralExpression(); - case 17: + case 18: return parseObjectLiteralExpression(); - case 120: + case 121: if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { break; } return parseFunctionExpression(); - case 75: + case 76: return parseClassExpression(); - case 89: + case 90: return parseFunctionExpression(); - case 94: + case 95: return parseNewExpressionOrNewDotTarget(); - case 41: - case 63: - if (reScanSlashToken() === 12) { + case 42: + case 64: + if (reScanSlashToken() === 13) { return parseLiteralNode(); } break; - case 14: + case 15: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNodeWithJSDoc(193); - parseExpected(19); - node.expression = allowInAnd(parseExpression); + var node = createNodeWithJSDoc(195); parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); return finishNode(node); } function parseSpreadElement() { - var node = createNode(206); - parseExpected(24); + var node = createNode(208); + parseExpected(25); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 24 ? parseSpreadElement() : - token() === 26 ? createNode(208) : + return token() === 25 ? parseSpreadElement() : + token() === 27 ? createNode(210) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(185); - parseExpected(21); + var node = createNode(187); + parseExpected(22); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); - parseExpected(22); + parseExpected(23); return finishNode(node); } function parseObjectLiteralElement() { var node = createNodeWithJSDoc(0); - if (parseOptionalToken(24)) { - node.kind = 275; + if (parseOptionalToken(25)) { + node.kind = 277; node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - if (parseContextualModifier(125)) { - return parseAccessorDeclaration(node, 156); + if (parseContextualModifier(126)) { + return parseAccessorDeclaration(node, 158); } - if (parseContextualModifier(136)) { - return parseAccessorDeclaration(node, 157); + if (parseContextualModifier(137)) { + return parseAccessorDeclaration(node, 159); } - var asteriskToken = parseOptionalToken(39); + var asteriskToken = parseOptionalToken(40); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - node.questionToken = parseOptionalToken(55); - if (asteriskToken || token() === 19 || token() === 27) { + node.questionToken = parseOptionalToken(56); + node.exclamationToken = parseOptionalToken(52); + if (asteriskToken || token() === 20 || token() === 28) { return parseMethodDeclaration(node, asteriskToken); } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57); if (isShorthandPropertyAssignment) { - node.kind = 274; - var equalsToken = parseOptionalToken(58); + node.kind = 276; + var equalsToken = parseOptionalToken(59); if (equalsToken) { node.equalsToken = equalsToken; node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } } else { - node.kind = 273; - parseExpected(56); + node.kind = 275; + parseExpected(57); node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(186); - parseExpected(17); + var node = createNode(188); + parseExpected(18); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); - parseExpected(18); + parseExpected(19); return finishNode(node); } function parseFunctionExpression() { @@ -15588,10 +16311,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNodeWithJSDoc(194); + var node = createNodeWithJSDoc(196); node.modifiers = parseModifiers(); - parseExpected(89); - node.asteriskToken = parseOptionalToken(39); + parseExpected(90); + node.asteriskToken = parseOptionalToken(40); var isGenerator = node.asteriskToken ? 1 : 0; var isAsync = ts.hasModifier(node, 256) ? 2 : 0; node.name = @@ -15599,7 +16322,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(56, isGenerator | isAsync, node); + fillSignature(57, isGenerator | isAsync, node); node.body = parseFunctionBlock(isGenerator | isAsync); if (saveDecoratorContext) { setDecoratorContext(true); @@ -15611,10 +16334,10 @@ var ts; } function parseNewExpressionOrNewDotTarget() { var fullStart = scanner.getStartPos(); - parseExpected(94); - if (parseOptional(23)) { - var node_2 = createNode(212, fullStart); - node_2.keywordToken = 94; + parseExpected(95); + if (parseOptional(24)) { + var node_2 = createNode(214, fullStart); + node_2.keywordToken = 95; node_2.name = parseIdentifierName(); return finishNode(node_2); } @@ -15630,22 +16353,22 @@ var ts; } break; } - var node = createNode(190, fullStart); + var node = createNode(192, fullStart); node.expression = expression; node.typeArguments = typeArguments; - if (node.typeArguments || token() === 19) { + if (node.typeArguments || token() === 20) { node.arguments = parseArgumentList(); } return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(216); - if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(218); + if (parseExpected(18, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1, parseStatement); - parseExpected(18); + parseExpected(19); } else { node.statements = createMissingList(); @@ -15670,48 +16393,48 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(218); - parseExpected(25); + var node = createNode(220); + parseExpected(26); return finishNode(node); } function parseIfStatement() { - var node = createNode(220); - parseExpected(90); - parseExpected(19); - node.expression = allowInAnd(parseExpression); + var node = createNode(222); + parseExpected(91); parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82) ? parseStatement() : undefined; + node.elseStatement = parseOptional(83) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(221); - parseExpected(81); + var node = createNode(223); + parseExpected(82); node.statement = parseStatement(); - parseExpected(106); - parseExpected(19); - node.expression = allowInAnd(parseExpression); + parseExpected(107); parseExpected(20); - parseOptional(25); + node.expression = allowInAnd(parseExpression); + parseExpected(21); + parseOptional(26); return finishNode(node); } function parseWhileStatement() { - var node = createNode(222); - parseExpected(106); - parseExpected(19); - node.expression = allowInAnd(parseExpression); + var node = createNode(224); + parseExpected(107); parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(88); - var awaitToken = parseOptionalToken(121); - parseExpected(19); + parseExpected(89); + var awaitToken = parseOptionalToken(122); + parseExpected(20); var initializer; - if (token() !== 25) { - if (token() === 104 || token() === 110 || token() === 76) { + if (token() !== 26) { + if (token() === 105 || token() === 111 || token() === 77) { initializer = parseVariableDeclarationList(true); } else { @@ -15719,33 +16442,33 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(145) : parseOptional(145)) { - var forOfStatement = createNode(225, pos); + if (awaitToken ? parseExpected(147) : parseOptional(147)) { + var forOfStatement = createNode(227, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20); + parseExpected(21); forOrForInOrForOfStatement = forOfStatement; } - else if (parseOptional(92)) { - var forInStatement = createNode(224, pos); + else if (parseOptional(93)) { + var forInStatement = createNode(226, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20); + parseExpected(21); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(223, pos); + var forStatement = createNode(225, pos); forStatement.initializer = initializer; - parseExpected(25); - if (token() !== 25 && token() !== 20) { + parseExpected(26); + if (token() !== 26 && token() !== 21) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(25); - if (token() !== 20) { + parseExpected(26); + if (token() !== 21) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(20); + parseExpected(21); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -15753,7 +16476,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 227 ? 72 : 77); + parseExpected(kind === 229 ? 73 : 78); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -15761,8 +16484,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(228); - parseExpected(96); + var node = createNode(230); + parseExpected(97); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -15770,69 +16493,69 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(229); - parseExpected(107); - parseExpected(19); - node.expression = allowInAnd(parseExpression); + var node = createNode(231); + parseExpected(108); parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); node.statement = doInsideOfContext(8388608, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(269); - parseExpected(73); + var node = createNode(271); + parseExpected(74); node.expression = allowInAnd(parseExpression); - parseExpected(56); + parseExpected(57); node.statements = parseList(3, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(270); - parseExpected(79); - parseExpected(56); + var node = createNode(272); + parseExpected(80); + parseExpected(57); node.statements = parseList(3, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 73 ? parseCaseClause() : parseDefaultClause(); + return token() === 74 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(230); - parseExpected(98); - parseExpected(19); - node.expression = allowInAnd(parseExpression); + var node = createNode(232); + parseExpected(99); parseExpected(20); - var caseBlock = createNode(244); - parseExpected(17); - caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + node.expression = allowInAnd(parseExpression); + parseExpected(21); + var caseBlock = createNode(246); parseExpected(18); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + parseExpected(19); node.caseBlock = finishNode(caseBlock); return finishNode(node); } function parseThrowStatement() { - var node = createNode(232); - parseExpected(100); + var node = createNode(234); + parseExpected(101); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(233); - parseExpected(102); + var node = createNode(235); + parseExpected(103); node.tryBlock = parseBlock(false); - node.catchClause = token() === 74 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 87) { - parseExpected(87); + node.catchClause = token() === 75 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 88) { + parseExpected(88); node.finallyBlock = parseBlock(false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(272); - parseExpected(74); - if (parseOptional(19)) { + var result = createNode(274); + parseExpected(75); + if (parseOptional(20)) { result.variableDeclaration = parseVariableDeclaration(); - parseExpected(20); + parseExpected(21); } else { result.variableDeclaration = undefined; @@ -15841,21 +16564,21 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(234); - parseExpected(78); + var node = createNode(236); + parseExpected(79); parseSemicolon(); return finishNode(node); } function parseExpressionOrLabeledStatement() { var node = createNodeWithJSDoc(0); var expression = allowInAnd(parseExpression); - if (expression.kind === 71 && parseOptional(56)) { - node.kind = 231; + if (expression.kind === 72 && parseOptional(57)) { + node.kind = 233; node.label = expression; node.statement = parseStatement(); } else { - node.kind = 219; + node.kind = 221; node.expression = expression; parseSemicolon(); } @@ -15867,60 +16590,60 @@ var ts; } function nextTokenIsClassKeywordOnSameLine() { nextToken(); - return token() === 75 && !scanner.hasPrecedingLineBreak(); + return token() === 76 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 89 && !scanner.hasPrecedingLineBreak(); + return token() === 90 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 || token() === 9) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 || token() === 9 || token() === 10) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { switch (token()) { - case 104: - case 110: + case 105: + case 111: + case 77: + case 90: case 76: - case 89: - case 75: - case 83: + case 84: return true; - case 109: - case 139: + case 110: + case 140: return nextTokenIsIdentifierOnSameLine(); - case 129: case 130: + case 131: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117: - case 120: - case 124: - case 112: + case 118: + case 121: + case 125: case 113: case 114: - case 132: + case 115: + case 133: nextToken(); if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 144: + case 145: nextToken(); - return token() === 17 || token() === 71 || token() === 84; - case 91: + return token() === 18 || token() === 72 || token() === 85; + case 92: nextToken(); - return token() === 9 || token() === 39 || - token() === 17 || ts.tokenIsIdentifierOrKeyword(token()); - case 84: + return token() === 10 || token() === 40 || + token() === 18 || ts.tokenIsIdentifierOrKeyword(token()); + case 85: nextToken(); - if (token() === 58 || token() === 39 || - token() === 17 || token() === 79 || - token() === 118) { + if (token() === 59 || token() === 40 || + token() === 18 || token() === 80 || + token() === 119) { return true; } continue; - case 115: + case 116: nextToken(); continue; default: @@ -15933,47 +16656,47 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 57: - case 25: - case 17: - case 104: - case 110: - case 89: - case 75: - case 83: + case 58: + case 26: + case 18: + case 105: + case 111: case 90: - case 81: - case 106: - case 88: - case 77: - case 72: - case 96: - case 107: - case 98: - case 100: - case 102: - case 78: - case 74: - case 87: - return true; - case 91: - return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); case 76: case 84: + case 91: + case 82: + case 107: + case 89: + case 78: + case 73: + case 97: + case 108: + case 99: + case 101: + case 103: + case 79: + case 75: + case 88: + return true; + case 92: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + case 77: + case 85: return isStartOfDeclaration(); - case 120: - case 124: - case 109: - case 129: + case 121: + case 125: + case 110: case 130: - case 139: - case 144: + case 131: + case 140: + case 145: return true; - case 114: - case 112: - case 113: case 115: - case 132: + case 113: + case 114: + case 116: + case 133: return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); default: return isStartOfExpression(); @@ -15981,73 +16704,73 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 17 || token() === 21; + return isIdentifier() || token() === 18 || token() === 22; } function isLetDeclaration() { return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { switch (token()) { - case 25: + case 26: return parseEmptyStatement(); - case 17: + case 18: return parseBlock(false); - case 104: - return parseVariableStatement(createNodeWithJSDoc(235)); - case 110: + case 105: + return parseVariableStatement(createNodeWithJSDoc(237)); + case 111: if (isLetDeclaration()) { - return parseVariableStatement(createNodeWithJSDoc(235)); + return parseVariableStatement(createNodeWithJSDoc(237)); } break; - case 89: - return parseFunctionDeclaration(createNodeWithJSDoc(237)); - case 75: - return parseClassDeclaration(createNodeWithJSDoc(238)); case 90: - return parseIfStatement(); - case 81: - return parseDoStatement(); - case 106: - return parseWhileStatement(); - case 88: - return parseForOrForInOrForOfStatement(); - case 77: - return parseBreakOrContinueStatement(226); - case 72: - return parseBreakOrContinueStatement(227); - case 96: - return parseReturnStatement(); - case 107: - return parseWithStatement(); - case 98: - return parseSwitchStatement(); - case 100: - return parseThrowStatement(); - case 102: - case 74: - case 87: - return parseTryStatement(); - case 78: - return parseDebuggerStatement(); - case 57: - return parseDeclaration(); - case 120: - case 109: - case 139: - case 129: - case 130: - case 124: + return parseFunctionDeclaration(createNodeWithJSDoc(239)); case 76: - case 83: - case 84: + return parseClassDeclaration(createNodeWithJSDoc(240)); case 91: - case 112: + return parseIfStatement(); + case 82: + return parseDoStatement(); + case 107: + return parseWhileStatement(); + case 89: + return parseForOrForInOrForOfStatement(); + case 78: + return parseBreakOrContinueStatement(228); + case 73: + return parseBreakOrContinueStatement(229); + case 97: + return parseReturnStatement(); + case 108: + return parseWithStatement(); + case 99: + return parseSwitchStatement(); + case 101: + return parseThrowStatement(); + case 103: + case 75: + case 88: + return parseTryStatement(); + case 79: + return parseDebuggerStatement(); + case 58: + return parseDeclaration(); + case 121: + case 110: + case 140: + case 130: + case 131: + case 125: + case 77: + case 84: + case 85: + case 92: case 113: case 114: - case 117: case 115: - case 132: - case 144: + case 118: + case 116: + case 133: + case 145: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -16056,7 +16779,7 @@ var ts; return parseExpressionOrLabeledStatement(); } function isDeclareModifier(modifier) { - return modifier.kind === 124; + return modifier.kind === 125; } function parseDeclaration() { var node = createNodeWithJSDoc(0); @@ -16075,40 +16798,40 @@ var ts; } function parseDeclarationWorker(node) { switch (token()) { - case 104: - case 110: - case 76: + case 105: + case 111: + case 77: return parseVariableStatement(node); - case 89: + case 90: return parseFunctionDeclaration(node); - case 75: + case 76: return parseClassDeclaration(node); - case 109: + case 110: return parseInterfaceDeclaration(node); - case 139: + case 140: return parseTypeAliasDeclaration(node); - case 83: - return parseEnumDeclaration(node); - case 144: - case 129: - case 130: - return parseModuleDeclaration(node); - case 91: - return parseImportDeclarationOrImportEqualsDeclaration(node); case 84: + return parseEnumDeclaration(node); + case 145: + case 130: + case 131: + return parseModuleDeclaration(node); + case 92: + return parseImportDeclarationOrImportEqualsDeclaration(node); + case 85: nextToken(); switch (token()) { - case 79: - case 58: + case 80: + case 59: return parseExportAssignment(node); - case 118: + case 119: return parseNamespaceExportDeclaration(node); default: return parseExportDeclaration(node); } default: if (node.decorators || node.modifiers) { - var missing = createMissingNode(256, true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(258, true, ts.Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; @@ -16119,35 +16842,35 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 17 && canParseSemicolon()) { + if (token() !== 18 && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(flags, diagnosticMessage); } function parseArrayBindingElement() { - if (token() === 26) { - return createNode(208); + if (token() === 27) { + return createNode(210); } - var node = createNode(184); - node.dotDotDotToken = parseOptionalToken(24); + var node = createNode(186); + node.dotDotDotToken = parseOptionalToken(25); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(184); - node.dotDotDotToken = parseOptionalToken(24); + var node = createNode(186); + node.dotDotDotToken = parseOptionalToken(25); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56) { + if (tokenIsIdentifier && token() !== 57) { node.name = propertyName; } else { - parseExpected(56); + parseExpected(57); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -16155,27 +16878,27 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(182); - parseExpected(17); - node.elements = parseDelimitedList(9, parseObjectBindingElement); + var node = createNode(184); parseExpected(18); + node.elements = parseDelimitedList(9, parseObjectBindingElement); + parseExpected(19); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(183); - parseExpected(21); - node.elements = parseDelimitedList(10, parseArrayBindingElement); + var node = createNode(185); parseExpected(22); + node.elements = parseDelimitedList(10, parseArrayBindingElement); + parseExpected(23); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 17 || token() === 21 || isIdentifier(); + return token() === 18 || token() === 22 || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 21) { + if (token() === 22) { return parseArrayBindingPattern(); } - if (token() === 17) { + if (token() === 18) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -16184,10 +16907,10 @@ var ts; return parseVariableDeclaration(true); } function parseVariableDeclaration(allowExclamation) { - var node = createNode(235); + var node = createNode(237); node.name = parseIdentifierOrPattern(); - if (allowExclamation && node.name.kind === 71 && - token() === 51 && !scanner.hasPrecedingLineBreak()) { + if (allowExclamation && node.name.kind === 72 && + token() === 52 && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -16197,21 +16920,21 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(236); + var node = createNode(238); switch (token()) { - case 104: + case 105: break; - case 110: + case 111: node.flags |= 1; break; - case 76: + case 77: node.flags |= 2; break; default: ts.Debug.fail(); } nextToken(); - if (token() === 145 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 147 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -16223,44 +16946,44 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20; + return nextTokenIsIdentifier() && nextToken() === 21; } function parseVariableStatement(node) { - node.kind = 217; + node.kind = 219; node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); return finishNode(node); } function parseFunctionDeclaration(node) { - node.kind = 237; - parseExpected(89); - node.asteriskToken = parseOptionalToken(39); + node.kind = 239; + parseExpected(90); + node.asteriskToken = parseOptionalToken(40); node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = node.asteriskToken ? 1 : 0; var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - fillSignature(56, isGenerator | isAsync, node); + fillSignature(57, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); return finishNode(node); } function parseConstructorDeclaration(node) { - node.kind = 155; - parseExpected(123); - fillSignature(56, 0, node); + node.kind = 157; + parseExpected(124); + fillSignature(57, 0, node); node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); return finishNode(node); } function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { - node.kind = 154; + node.kind = 156; node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 : 0; var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - fillSignature(56, isGenerator | isAsync, node); + fillSignature(57, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); return finishNode(node); } function parsePropertyDeclaration(node) { - node.kind = 152; - if (!node.questionToken && token() === 51 && !scanner.hasPrecedingLineBreak()) { + node.kind = 154; + if (!node.questionToken && token() === 52 && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -16271,10 +16994,10 @@ var ts; return finishNode(node); } function parsePropertyOrMethodDeclaration(node) { - var asteriskToken = parseOptionalToken(39); + var asteriskToken = parseOptionalToken(40); node.name = parsePropertyName(); - node.questionToken = parseOptionalToken(55); - if (asteriskToken || token() === 19 || token() === 27) { + node.questionToken = parseOptionalToken(56); + if (asteriskToken || token() === 20 || token() === 28) { return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } return parsePropertyDeclaration(node); @@ -16282,13 +17005,13 @@ var ts; function parseAccessorDeclaration(node, kind) { node.kind = kind; node.name = parsePropertyName(); - fillSignature(56, 0, node); + fillSignature(57, 0, node); node.body = parseFunctionBlockOrSemicolon(0); return finishNode(node); } function isClassMemberStart() { var idToken; - if (token() === 57) { + if (token() === 58) { return true; } while (ts.isModifierKind(token())) { @@ -16298,27 +17021,27 @@ var ts; } nextToken(); } - if (token() === 39) { + if (token() === 40) { return true; } if (isLiteralPropertyName()) { idToken = token(); nextToken(); } - if (token() === 21) { + if (token() === 22) { return true; } if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 136 || idToken === 125) { + if (!ts.isKeyword(idToken) || idToken === 137 || idToken === 126) { return true; } switch (token()) { - case 19: - case 27: - case 51: + case 20: + case 28: + case 52: + case 57: + case 59: case 56: - case 58: - case 55: return true; default: return canParseSemicolon(); @@ -16331,10 +17054,10 @@ var ts; var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(57)) { + if (!parseOptional(58)) { break; } - var decorator = createNode(150, decoratorStart); + var decorator = createNode(152, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -16347,7 +17070,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 76 && permitInvalidConstAsModifier) { + if (token() === 77 && permitInvalidConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -16364,7 +17087,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 120) { + if (token() === 121) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -16374,54 +17097,54 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 25) { - var result = createNode(215); + if (token() === 26) { + var result = createNode(217); nextToken(); return finishNode(result); } var node = createNodeWithJSDoc(0); node.decorators = parseDecorators(); node.modifiers = parseModifiers(true); - if (parseContextualModifier(125)) { - return parseAccessorDeclaration(node, 156); + if (parseContextualModifier(126)) { + return parseAccessorDeclaration(node, 158); } - if (parseContextualModifier(136)) { - return parseAccessorDeclaration(node, 157); + if (parseContextualModifier(137)) { + return parseAccessorDeclaration(node, 159); } - if (token() === 123) { + if (token() === 124) { return parseConstructorDeclaration(node); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(node); } if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || + token() === 10 || token() === 8 || - token() === 39 || - token() === 21) { + token() === 40 || + token() === 22) { return parsePropertyOrMethodDeclaration(node); } if (node.decorators || node.modifiers) { - node.name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); + node.name = createMissingNode(72, true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(node); } return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(createNodeWithJSDoc(0), 207); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0), 209); } function parseClassDeclaration(node) { - return parseClassDeclarationOrExpression(node, 238); + return parseClassDeclarationOrExpression(node, 240); } function parseClassDeclarationOrExpression(node, kind) { node.kind = kind; - parseExpected(75); + parseExpected(76); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17)) { + if (parseExpected(18)) { node.members = parseClassMembers(); - parseExpected(18); + parseExpected(19); } else { node.members = createMissingList(); @@ -16434,7 +17157,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 109 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses() { if (isHeritageClause()) { @@ -16444,33 +17167,33 @@ var ts; } function parseHeritageClause() { var tok = token(); - ts.Debug.assert(tok === 85 || tok === 108); - var node = createNode(271); + ts.Debug.assert(tok === 86 || tok === 109); + var node = createNode(273); node.token = tok; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); return finishNode(node); } function parseExpressionWithTypeArguments() { - var node = createNode(209); + var node = createNode(211); node.expression = parseLeftHandSideExpressionOrHigher(); node.typeArguments = tryParseTypeArguments(); return finishNode(node); } function tryParseTypeArguments() { - return token() === 27 - ? parseBracketedList(20, parseType, 27, 29) + return token() === 28 + ? parseBracketedList(20, parseType, 28, 30) : undefined; } function isHeritageClause() { - return token() === 85 || token() === 108; + return token() === 86 || token() === 109; } function parseClassMembers() { return parseList(5, parseClassElement); } function parseInterfaceDeclaration(node) { - node.kind = 239; - parseExpected(109); + node.kind = 241; + parseExpected(110); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); @@ -16478,28 +17201,28 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(node) { - node.kind = 240; - parseExpected(139); + node.kind = 242; + parseExpected(140); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(58); + parseExpected(59); node.type = parseType(); parseSemicolon(); return finishNode(node); } function parseEnumMember() { - var node = createNodeWithJSDoc(276); + var node = createNodeWithJSDoc(278); node.name = parsePropertyName(); node.initializer = allowInAnd(parseInitializer); return finishNode(node); } function parseEnumDeclaration(node) { - node.kind = 241; - parseExpected(83); + node.kind = 243; + parseExpected(84); node.name = parseIdentifier(); - if (parseExpected(17)) { + if (parseExpected(18)) { node.members = parseDelimitedList(6, parseEnumMember); - parseExpected(18); + parseExpected(19); } else { node.members = createMissingList(); @@ -16507,10 +17230,10 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(243); - if (parseExpected(17)) { + var node = createNode(245); + if (parseExpected(18)) { node.statements = parseList(1, parseStatement); - parseExpected(18); + parseExpected(19); } else { node.statements = createMissingList(); @@ -16518,18 +17241,18 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(node, flags) { - node.kind = 242; + node.kind = 244; var namespaceFlag = flags & 16; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(23) + node.body = parseOptional(24) ? parseModuleOrNamespaceDeclaration(createNode(0), 4 | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(node) { - node.kind = 242; - if (token() === 144) { + node.kind = 244; + if (token() === 145) { node.name = parseIdentifier(); node.flags |= 512; } @@ -16537,7 +17260,7 @@ var ts; node.name = parseLiteralNode(); node.name.text = internIdentifier(node.name.text); } - if (token() === 17) { + if (token() === 18) { node.body = parseModuleBlock(); } else { @@ -16547,75 +17270,75 @@ var ts; } function parseModuleDeclaration(node) { var flags = 0; - if (token() === 144) { + if (token() === 145) { return parseAmbientExternalModuleDeclaration(node); } - else if (parseOptional(130)) { + else if (parseOptional(131)) { flags |= 16; } else { - parseExpected(129); - if (token() === 9) { + parseExpected(130); + if (token() === 10) { return parseAmbientExternalModuleDeclaration(node); } } return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { - return token() === 133 && + return token() === 134 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 19; + return nextToken() === 20; } function nextTokenIsSlash() { - return nextToken() === 41; + return nextToken() === 42; } function parseNamespaceExportDeclaration(node) { - node.kind = 245; - parseExpected(118); - parseExpected(130); + node.kind = 247; + parseExpected(119); + parseExpected(131); node.name = parseIdentifier(); parseSemicolon(); return finishNode(node); } function parseImportDeclarationOrImportEqualsDeclaration(node) { - parseExpected(91); + parseExpected(92); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 && token() !== 143) { + if (token() !== 27 && token() !== 144) { return parseImportEqualsDeclaration(node, identifier); } } - node.kind = 247; + node.kind = 249; if (identifier || - token() === 39 || - token() === 17) { + token() === 40 || + token() === 18) { node.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(143); + parseExpected(144); } node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(node); } function parseImportEqualsDeclaration(node, identifier) { - node.kind = 246; + node.kind = 248; node.name = identifier; - parseExpected(58); + parseExpected(59); node.moduleReference = parseModuleReference(); parseSemicolon(); return finishNode(node); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(248, fullStart); + var importClause = createNode(250, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || - parseOptional(26)) { - importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(250); + parseOptional(27)) { + importClause.namedBindings = token() === 40 ? parseNamespaceImport() : parseNamedImportsOrExports(252); } return finishNode(importClause); } @@ -16625,15 +17348,15 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(257); - parseExpected(133); - parseExpected(19); - node.expression = parseModuleSpecifier(); + var node = createNode(259); + parseExpected(134); parseExpected(20); + node.expression = parseModuleSpecifier(); + parseExpected(21); return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9) { + if (token() === 10) { var result = parseLiteralNode(); result.text = internIdentifier(result.text); return result; @@ -16643,22 +17366,22 @@ var ts; } } function parseNamespaceImport() { - var namespaceImport = createNode(249); - parseExpected(39); - parseExpected(118); + var namespaceImport = createNode(251); + parseExpected(40); + parseExpected(119); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(23, kind === 250 ? parseImportSpecifier : parseExportSpecifier, 17, 18); + node.elements = parseBracketedList(23, kind === 252 ? parseImportSpecifier : parseExportSpecifier, 18, 19); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(255); + return parseImportOrExportSpecifier(257); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(251); + return parseImportOrExportSpecifier(253); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -16666,9 +17389,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 118) { + if (token() === 119) { node.propertyName = identifierName; - parseExpected(118); + parseExpected(119); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -16677,21 +17400,21 @@ var ts; else { node.name = identifierName; } - if (kind === 251 && checkIdentifierIsKeyword) { + if (kind === 253 && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(node) { - node.kind = 253; - if (parseOptional(39)) { - parseExpected(143); + node.kind = 255; + if (parseOptional(40)) { + parseExpected(144); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(254); - if (token() === 143 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(143); + node.exportClause = parseNamedImportsOrExports(256); + if (token() === 144 || (token() === 10 && !scanner.hasPrecedingLineBreak())) { + parseExpected(144); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -16699,12 +17422,12 @@ var ts; return finishNode(node); } function parseExportAssignment(node) { - node.kind = 252; - if (parseOptional(58)) { + node.kind = 254; + if (parseOptional(59)) { node.isExportEquals = true; } else { - parseExpected(79); + parseExpected(80); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -16717,10 +17440,10 @@ var ts; } function isAnExternalModuleIndicatorNode(node) { return ts.hasModifier(node, 1) - || node.kind === 246 && node.moduleReference.kind === 257 - || node.kind === 247 - || node.kind === 252 - || node.kind === 253 + || node.kind === 248 && node.moduleReference.kind === 259 + || node.kind === 249 + || node.kind === 254 + || node.kind === 255 ? node : undefined; } @@ -16733,7 +17456,7 @@ var ts; return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); } function isImportMeta(node) { - return ts.isMetaProperty(node) && node.keywordToken === 91 && node.name.escapedText === "meta"; + return ts.isMetaProperty(node) && node.keywordToken === 92 && node.name.escapedText === "meta"; } var JSDocParser; (function (JSDocParser) { @@ -16749,11 +17472,11 @@ var ts; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281, scanner.getTokenPos()); - var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17); + var result = createNode(283); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18); result.type = doInsideOfContext(2097152, parseJSDocType); if (!mayOmitBraces || hasBrace) { - parseExpected(18); + parseExpected(19); } fixupParentReferences(result); return finishNode(result); @@ -16824,7 +17547,7 @@ var ts; } loop: while (true) { switch (token()) { - case 57: + case 58: if (state === 0 || state === 1) { removeTrailingWhitespace(comments); addTag(parseTag(indent)); @@ -16841,7 +17564,7 @@ var ts; state = 0; indent = 0; break; - case 39: + case 40: var asterisk = scanner.getTokenText(); if (state === 1 || state === 2) { state = 2; @@ -16852,10 +17575,6 @@ var ts; indent += asterisk.length; } break; - case 71: - pushComment(scanner.getTokenText()); - state = 2; - break; case 5: var whitespace = scanner.getTokenText(); if (state === 2) { @@ -16890,7 +17609,7 @@ var ts; } } function createJSDocComment() { - var result = createNode(289, start); + var result = createNode(291, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -16923,61 +17642,60 @@ var ts; } } var precedingLineBreak = scanner.hasPrecedingLineBreak(); - while ((precedingLineBreak && token() === 39) || token() === 5 || token() === 4) { + while ((precedingLineBreak && token() === 40) || token() === 5 || token() === 4) { if (token() === 4) { precedingLineBreak = true; } - else if (token() === 39) { + else if (token() === 40) { precedingLineBreak = false; } nextJSDocToken(); } } function parseTag(indent) { - ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); + ts.Debug.assert(token() === 58); + var start = scanner.getTokenPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": case "extends": - tag = parseAugmentsTag(atToken, tagName); + tag = parseAugmentsTag(start, tagName); break; case "class": case "constructor": - tag = parseClassTag(atToken, tagName); + tag = parseClassTag(start, tagName); break; case "this": - tag = parseThisTag(atToken, tagName); + tag = parseThisTag(start, tagName); break; case "enum": - tag = parseEnumTag(atToken, tagName); + tag = parseEnumTag(start, tagName); break; case "arg": case "argument": case "param": - return parseParameterOrPropertyTag(atToken, tagName, 2, indent); + return parseParameterOrPropertyTag(start, tagName, 2, indent); case "return": case "returns": - tag = parseReturnTag(atToken, tagName); + tag = parseReturnTag(start, tagName); break; case "template": - tag = parseTemplateTag(atToken, tagName); + tag = parseTemplateTag(start, tagName); break; case "type": - tag = parseTypeTag(atToken, tagName); + tag = parseTypeTag(start, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName, indent); + tag = parseTypedefTag(start, tagName, indent); break; case "callback": - tag = parseCallbackTag(atToken, tagName, indent); + tag = parseCallbackTag(start, tagName, indent); break; default: - tag = parseUnknownTag(atToken, tagName); + tag = parseUnknownTag(start, tagName); break; } if (!tag.comment) { @@ -17006,7 +17724,7 @@ var ts; } indent = 0; break; - case 57: + case 58: scanner.setTextPos(scanner.getTextPos() - 1); case 1: break loop; @@ -17022,9 +17740,9 @@ var ts; indent += whitespace.length; } break; - case 17: + case 18: state = 2; - if (lookAhead(function () { return nextJSDocToken() === 57 && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + if (lookAhead(function () { return nextJSDocToken() === 58 && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { pushComment(scanner.getTokenText()); nextJSDocToken(); pushComment(scanner.getTokenText()); @@ -17032,7 +17750,7 @@ var ts; } pushComment(scanner.getTokenText()); break; - case 39: + case 40: if (state === 0) { state = 1; indent += 1; @@ -17049,9 +17767,8 @@ var ts; removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } - function parseUnknownTag(atToken, tagName) { - var result = createNode(292, atToken.pos); - result.atToken = atToken; + function parseUnknownTag(start, tagName) { + var result = createNode(294, start); result.tagName = tagName; return finishNode(result); } @@ -17070,34 +17787,34 @@ var ts; } function tryParseTypeExpression() { skipWhitespaceOrAsterisk(); - return token() === 17 ? parseJSDocTypeExpression() : undefined; + return token() === 18 ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { - if (token() === 13) { + if (token() === 14) { return { name: createIdentifier(true), isBracketed: false }; } - var isBracketed = parseOptional(21); + var isBracketed = parseOptional(22); var name = parseJSDocEntityName(); if (isBracketed) { skipWhitespace(); - if (parseOptionalToken(58)) { + if (parseOptionalToken(59)) { parseExpression(); } - parseExpected(22); + parseExpected(23); } return { name: name, isBracketed: isBracketed }; } function isObjectOrObjectArrayTypeReference(node) { switch (node.kind) { - case 135: + case 136: return true; - case 167: + case 169: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; } } - function parseParameterOrPropertyTag(atToken, tagName, target, indent) { + function parseParameterOrPropertyTag(start, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -17107,17 +17824,14 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 ? - createNode(303, atToken.pos) : - createNode(297, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target); + createNode(305, start) : + createNode(299, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; } - result.atToken = atToken; result.tagName = tagName; result.typeExpression = typeExpression; result.name = name; @@ -17126,22 +17840,22 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(281, scanner.getTokenPos()); + var typeLiteralExpression = createNode(283, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 297 || child.kind === 303) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 || child.kind === 305) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(290, start_2); + jsdocTypeLiteral = createNode(292, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 167) { + if (typeExpression.type.kind === 169) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -17149,81 +17863,74 @@ var ts; } } } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 298; })) { + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(298, atToken.pos); - result.atToken = atToken; + var result = createNode(300, start); result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 300; })) { + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(300, atToken.pos); - result.atToken = atToken; + var result = createNode(302, start); result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } - function parseAugmentsTag(atToken, tagName) { - var result = createNode(293, atToken.pos); - result.atToken = atToken; + function parseAugmentsTag(start, tagName) { + var result = createNode(295, start); result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } function parseExpressionWithTypeArgumentsForAugments() { - var usedBrace = parseOptional(17); - var node = createNode(209); + var usedBrace = parseOptional(18); + var node = createNode(211); node.expression = parsePropertyAccessEntityNameExpression(); node.typeArguments = tryParseTypeArguments(); var res = finishNode(node); if (usedBrace) { - parseExpected(18); + parseExpected(19); } return res; } function parsePropertyAccessEntityNameExpression() { var node = parseJSDocIdentifierName(); - while (parseOptional(23)) { - var prop = createNode(187, node.pos); + while (parseOptional(24)) { + var prop = createNode(189, node.pos); prop.expression = node; prop.name = parseJSDocIdentifierName(); node = finishNode(prop); } return node; } - function parseClassTag(atToken, tagName) { - var tag = createNode(294, atToken.pos); - tag.atToken = atToken; + function parseClassTag(start, tagName) { + var tag = createNode(296, start); tag.tagName = tagName; return finishNode(tag); } - function parseThisTag(atToken, tagName) { - var tag = createNode(299, atToken.pos); - tag.atToken = atToken; + function parseThisTag(start, tagName) { + var tag = createNode(301, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(true); skipWhitespace(); return finishNode(tag); } - function parseEnumTag(atToken, tagName) { - var tag = createNode(296, atToken.pos); - tag.atToken = atToken; + function parseEnumTag(start, tagName) { + var tag = createNode(298, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(true); skipWhitespace(); return finishNode(tag); } - function parseTypedefTag(atToken, tagName, indent) { + function parseTypedefTag(start, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(302, atToken.pos); - typedefTag.atToken = atToken; + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304, start); typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); @@ -17235,12 +17942,11 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(290, start_3); + jsdocTypeLiteral = createNode(292, start); } - if (child.kind === 300) { + if (child.kind === 302) { if (childTypeTag) { break; } @@ -17253,7 +17959,7 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 167) { + if (typeExpression && typeExpression.type.kind === 169) { jsdocTypeLiteral.isArrayType = true; } typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? @@ -17270,8 +17976,8 @@ var ts; return undefined; } var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (parseOptional(23)) { - var jsDocNamespaceNode = createNode(242, pos); + if (parseOptional(24)) { + var jsDocNamespaceNode = createNode(244, pos); if (nested) { jsDocNamespaceNode.flags |= 4; } @@ -17284,25 +17990,23 @@ var ts; } return typeNameOrNamespaceName; } - function parseCallbackTag(atToken, tagName, indent) { - var callbackTag = createNode(295, atToken.pos); - callbackTag.atToken = atToken; + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297, start); callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); skipWhitespace(); callbackTag.comment = parseTagComments(indent); var child; - var start = scanner.getStartPos(); - var jsdocSignature = createNode(291, start); + var jsdocSignature = createNode(293, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { - if (parseOptionalJsdoc(57)) { + if (parseOptionalJsdoc(58)) { var tag = parseTag(indent); - if (tag && tag.kind === 298) { + if (tag && tag.kind === 300) { return tag; } } @@ -17336,18 +18040,18 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { - case 57: + case 58: if (canParseTag) { - var child = tryParseChildTag(target); - if (child && (child.kind === 297 || child.kind === 303) && + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 || child.kind === 305) && target !== 4 && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -17360,13 +18064,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 39: + case 40: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 71: + case 72: canParseTag = false; break; case 1: @@ -17374,17 +18078,16 @@ var ts; } } } - function tryParseChildTag(target) { - ts.Debug.assert(token() === 57); - var atToken = createNode(57); - atToken.end = scanner.getTextPos(); + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58); + var start = scanner.getStartPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); skipWhitespace(); var t; switch (tagName.escapedText) { case "type": - return target === 1 && parseTypeTag(atToken, tagName); + return target === 1 && parseTypeTag(start, tagName); case "prop": case "property": t = 1; @@ -17400,27 +18103,24 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(start, tagName, target, indent); } - function parseTemplateTag(atToken, tagName) { + function parseTemplateTag(start, tagName) { var constraint; - if (token() === 17) { + if (token() === 18) { constraint = parseJSDocTypeExpression(); } var typeParameters = []; var typeParametersPos = getNodePos(); do { skipWhitespace(); - var typeParameter = createNode(148); + var typeParameter = createNode(150); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); finishNode(typeParameter); skipWhitespace(); typeParameters.push(typeParameter); - } while (parseOptionalJsdoc(26)); - var result = createNode(301, atToken.pos); - result.atToken = atToken; + } while (parseOptionalJsdoc(27)); + var result = createNode(303, start); result.tagName = tagName; result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -17439,13 +18139,13 @@ var ts; } function parseJSDocEntityName() { var entity = parseJSDocIdentifierName(); - if (parseOptional(21)) { - parseExpected(22); + if (parseOptional(22)) { + parseExpected(23); } - while (parseOptional(23)) { + while (parseOptional(24)) { var name = parseJSDocIdentifierName(); - if (parseOptional(21)) { - parseExpected(22); + if (parseOptional(22)) { + parseExpected(23); } entity = createQualifiedName(entity, name); } @@ -17453,11 +18153,11 @@ var ts; } function parseJSDocIdentifierName(message) { if (!ts.tokenIsIdentifierOrKeyword(token())) { - return createMissingNode(71, !message, message || ts.Diagnostics.Identifier_expected); + return createMissingNode(72, !message, message || ts.Diagnostics.Identifier_expected); } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(71, pos); + var result = createNode(72, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); @@ -17536,9 +18236,9 @@ var ts; } function shouldCheckNode(node) { switch (node.kind) { - case 9: + case 10: case 8: - case 71: + case 72: return true; } return false; @@ -17961,10 +18661,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 71) { + if (lhs.kind === 72) { return lhs.escapedText === rhs.escapedText; } - if (lhs.kind === 99) { + if (lhs.kind === 100) { return true; } return lhs.name.escapedText === rhs.name.escapedText && @@ -18010,11 +18710,12 @@ var ts; ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.symbol", "lib.esnext.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], - ["esnext.intl", "lib.esnext.intl.d.ts"] + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] ]; ts.libs = libEntries.map(function (entry) { return entry[0]; }); ts.libMap = ts.createMapFromEntries(libEntries); - ts.optionDeclarations = [ + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -18028,6 +18729,60 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -18069,26 +18824,11 @@ var ts; description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date }, { - name: "pretty", + name: "showConfig", type: "boolean", - showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental - }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, { name: "target", @@ -18103,6 +18843,8 @@ var ts; es2018: 5, esnext: 6, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18121,6 +18863,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18133,6 +18876,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -18140,6 +18884,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -18157,6 +18902,7 @@ var ts; "react-native": 3, "react": 2 }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18265,6 +19011,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18273,6 +19020,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18281,14 +19029,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18297,6 +19055,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18305,6 +19064,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18337,6 +19097,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -18348,6 +19109,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -18355,6 +19117,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -18362,6 +19125,7 @@ var ts; { name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -18375,6 +19139,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -18386,6 +19151,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -18396,6 +19162,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -18465,42 +19232,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h }, - { - name: "diagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_diagnostic_information - }, - { - name: "extendedDiagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_verbose_diagnostic_information - }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -18558,12 +19295,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -18576,6 +19315,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -18621,6 +19361,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -18628,6 +19369,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -18655,6 +19397,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -18681,7 +19424,41 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); ts.typeAcquisitionDeclarations = [ { name: "enableAutoDiscovery", @@ -18727,20 +19504,20 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } @@ -18773,16 +19550,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -18794,14 +19570,14 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); } else { if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -18834,7 +19610,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -18877,8 +19653,18 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -18890,7 +19676,32 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + projects.push("."); + } + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -19002,6 +19813,9 @@ var ts; } var result = ts.parseJsonText(configFileName, configFileText); var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; @@ -19119,7 +19933,7 @@ var ts; var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 273) { + if (element.kind !== 275) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -19162,20 +19976,23 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { - case 101: + case 102: reportInvalidOptionValue(option && option.type !== "boolean"); return true; - case 86: + case 87: reportInvalidOptionValue(option && option.type !== "boolean"); return false; - case 95: + case 96: reportInvalidOptionValue(option && option.name === "extends"); return null; - case 9: + case 10: if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } @@ -19191,13 +20008,13 @@ var ts; case 8: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 200: - if (valueExpression.operator !== 38 || valueExpression.operand.kind !== 8) { + case 202: + if (valueExpression.operator !== 39 || valueExpression.operand.kind !== 8) { break; } reportInvalidOptionValue(option && option.type !== "number"); return -Number(valueExpression.operand.text); - case 186: + case 188: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; if (option) { @@ -19207,7 +20024,7 @@ var ts; else { return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); } - case 185: + case 187: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -19246,59 +20063,105 @@ var ts; } return false; } + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return false; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + } + return function (path) { return includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return !excludeRe.test(path); }; + } + return function (_) { return false; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); + } + else { + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - return ts.forEachEntry(customTypeMap, function (mapValue, key) { - if (mapValue === value) { - return key; - } - }); - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_3 = function (name) { - if (ts.hasProperty(options, name)) { - if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - return "continue"; - } - var value = options[name]; - var optionDefinition = optionsNameMap.get(name.toLowerCase()); - if (optionDefinition) { - var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap_1) { - result.set(name, value); - } - else { - if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); - } - else { - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); - } - } - } - } - }; - for (var name in options) { - _loop_3(name); - } - return result; - } function getDefaultValueForOption(option) { switch (option.type) { case "number": @@ -19414,7 +20277,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -19431,8 +20295,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -19468,19 +20346,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -19488,7 +20365,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -19505,12 +20381,28 @@ var ts; function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -19588,11 +20480,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -19620,25 +20507,29 @@ var ts; } function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { - errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return undefined; - } - var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return undefined; + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } } + return extendedConfigPath; } - return extendedConfigPath; + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, undefined, undefined, true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -19646,7 +20537,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -19792,7 +20683,7 @@ var ts; validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { @@ -19801,8 +20692,10 @@ var ts; var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); if (filesSpecs) { for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { var fileName = filesSpecs_1[_i]; @@ -19810,27 +20703,42 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json")) { + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json"); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -19981,18 +20889,25 @@ var ts; function noPackageId(r) { return withPackageId(undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } var Extensions; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; Extensions[Extensions["Json"] = 2] = "Json"; - Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; })(Extensions || (Extensions = {})); function resolvedTypeScriptOnly(resolved) { if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -20001,45 +20916,95 @@ var ts; failedLookupLocations: failedLookupLocations }; } - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return path; } } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; - } - return result.config; - } - catch (e) { - return {}; - } - } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -20071,9 +21036,13 @@ var ts; return typeRoots; } var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -20092,8 +21061,10 @@ var ts; trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -20102,13 +21073,12 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - if (!options.preserveSymlinks) { - resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); - } + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -20116,14 +21086,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } - return ts.forEach(typeRoots, function (typeRoot) { + return ts.firstDefined(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -20138,8 +21108,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined); - var resolvedFile = resolvedTypeScriptOnly(result && result.value); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, undefined, undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, false, moduleResolutionState, true); + } + var resolvedFile = resolvedTypeScriptOnly(result); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -20167,10 +21145,13 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + if (baseFileName.charCodeAt(0) !== 46) { + result.push(baseFileName); + } } } } @@ -20181,28 +21162,54 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); } ts.createModuleResolutionCache = createModuleResolutionCache; + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName) { + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); - var perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = ts.createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); } - function getOrCreateCacheForModuleName(nonRelativeModuleName) { + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); - var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); } - return perModuleNameCache; + return result; } function createPerModuleNameCache() { var directoryPathMap = ts.createMap(); @@ -20258,13 +21265,19 @@ var ts; return perFolderCache && perFolderCache.get(moduleName); } ts.resolveModuleNameFromCache = resolveModuleNameFromCache; - function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } var containingDirectory = ts.getDirectoryPath(containingFile); - var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { @@ -20286,10 +21299,10 @@ var ts; } switch (moduleResolution) { case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; default: return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); @@ -20297,7 +21310,7 @@ var ts; if (perFolderCache) { perFolderCache.set(moduleName, result); if (!ts.isExternalModuleNameRelative(moduleName)) { - cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); } } } @@ -20312,15 +21325,28 @@ var ts; return result; } ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -20354,7 +21380,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -20371,7 +21397,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -20382,87 +21408,65 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!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); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - var matchedPattern; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; - function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { + ts.resolveJSModule = resolveJSModule; + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, jsOnlyExtensions, undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? - tryResolve(Extensions.JavaScript) : - (tryResolve(Extensions.TypeScript) || - tryResolve(Extensions.JavaScript) || - (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); if (result && result.value) { var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -20475,7 +21479,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, false, state, true); return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } @@ -20491,29 +21495,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -20521,9 +21526,13 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } ts.nodeModulesPathPart = "/node_modules/"; + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; function parseNodeModuleFromPath(resolved) { var path = ts.normalizePath(resolved.path); var idx = path.lastIndexOf(ts.nodeModulesPathPart); @@ -20550,41 +21559,37 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); - } - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - if (extensions === Extensions.Json) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { var extensionLess = ts.tryRemoveExtension(candidate, ".json"); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); } - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -20594,15 +21599,16 @@ var ts; return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts"); case Extensions.JavaScript: return tryExtension(".js") || tryExtension(".jsx"); + case Extensions.TSConfig: case Extensions.Json: return tryExtension(".json"); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -20616,40 +21622,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { - var path = tryReadPackageJsonFields(true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts"; } @@ -20661,6 +21660,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts")) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -20672,46 +21672,67 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { - file = tryReadPackageJsonFields(false, jsonContent, candidate, state); - if (!file) { - return undefined; + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); - if (result) { - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } function resolvedIfExtensionMatches(extensions, path) { var ext = ts.tryGetExtensionFromPath(path); @@ -20721,6 +21742,7 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" || extension === ".jsx"; + case Extensions.TSConfig: case Extensions.Json: return extension === ".json"; case Extensions.TypeScript: @@ -20729,90 +21751,132 @@ var ts; return extension === ".d.ts"; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, false, cache, redirectedReference); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, true, undefined); + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, true, undefined, undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } return mangled; } function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -20821,63 +21885,64 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; - function getPackageNameFromAtTypesDirectory(mangledName) { + ts.mangleScopedPackageName = mangleScopedPackageName; + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; - function getUnmangledNameForScopedPackage(typesPackageName) { + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } - function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } if (!ts.isExternalModuleNameRelative(moduleName)) { - var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, false, state)); } } } @@ -20887,9 +21952,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, false); return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -20905,21 +21970,21 @@ var ts; ts.getModuleInstanceState = getModuleInstanceState; function getModuleInstanceStateWorker(node) { switch (node.kind) { - case 239: - case 240: - return 0; case 241: + case 242: + return 0; + case 243: if (ts.isEnumConst(node)) { return 2; } break; - case 247: - case 246: + case 249: + case 248: if (!(ts.hasModifier(node, 1))) { return 0; } break; - case 243: { + case 245: { var state_1 = 0; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateWorker(n); @@ -20938,9 +22003,9 @@ var ts; }); return state_1; } - case 242: + case 244: return getModuleInstanceState(node); - case 71: + case 72: if (node.isInJSDocNamespace) { return 0; } @@ -21046,16 +22111,20 @@ var ts; if (symbolFlags & (32 | 64 | 2048 | 4096) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + symbol.valueDeclaration = node; } } function getDeclarationName(node) { - if (node.kind === 252) { + if (node.kind === 254) { return node.isExportEquals ? "export=" : "default"; } var name = ts.getNameOfDeclaration(node); @@ -21064,7 +22133,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 147) { + if (name.kind === 149) { var nameExpression = name.expression; if (ts.isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); @@ -21075,31 +22144,31 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 155: + case 157: return "__constructor"; - case 163: - case 158: - case 291: - return "__call"; - case 164: - case 159: - return "__new"; + case 165: case 160: + case 293: + return "__call"; + case 166: + case 161: + return "__new"; + case 162: return "__index"; - case 253: + case 255: return "__export"; - case 277: + case 279: return "export="; - case 202: - if (ts.getSpecialPropertyAssignmentKind(node) === 2) { + case 204: + if (ts.getAssignmentDeclarationKind(node) === 2) { return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 287: + case 289: return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); - case 149: - ts.Debug.assert(node.parent.kind === 287, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + case 151: + ts.Debug.assert(node.parent.kind === 289, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -21133,7 +22202,7 @@ var ts; if (symbol.isReplaceableByMethod) { symbolTable.set(name, symbol = createSymbol(0, name)); } - else { + else if (!(includes & 3 && symbol.flags & 67108864)) { if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -21152,7 +22221,7 @@ var ts; } else { if (symbol.declarations && symbol.declarations.length && - (node.kind === 252 && !node.isExportEquals)) { + (node.kind === 254 && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; } @@ -21179,7 +22248,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; if (symbolFlags & 2097152) { - if (node.kind === 255 || (node.kind === 246 && hasExportModifier)) { + if (node.kind === 257 || (node.kind === 248 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -21188,12 +22257,12 @@ var ts; } else { if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } - var exportKind = symbolFlags & 67216319 ? 1048576 : 0; + var exportKind = symbolFlags & 67220415 ? 1048576 : 0; var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -21209,7 +22278,7 @@ var ts; var saveThisParentContainer = thisParentContainer; var savedBlockScopeContainer = blockScopeContainer; if (containerFlags & 1) { - if (node.kind !== 195) { + if (node.kind !== 197) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -21237,7 +22306,7 @@ var ts; currentFlow.container = node; } } - currentReturnTarget = isIIFE || node.kind === 155 ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 157 ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; @@ -21249,13 +22318,13 @@ var ts; if (hasExplicitReturn) node.flags |= 256; } - if (node.kind === 277) { + if (node.kind === 279) { node.flags |= emitFlags; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 155) { + if (node.kind === 157) { node.returnFlowNode = currentFlow; } } @@ -21298,8 +22367,8 @@ var ts; } } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 237 ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 237 ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 239 ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -21328,80 +22397,81 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { - case 222: + case 224: bindWhileStatement(node); break; - case 221: + case 223: bindDoStatement(node); break; - case 223: + case 225: bindForStatement(node); break; - case 224: - case 225: + case 226: + case 227: bindForInOrForOfStatement(node); break; - case 220: + case 222: bindIfStatement(node); break; - case 228: - case 232: + case 230: + case 234: bindReturnOrThrow(node); break; - case 227: - case 226: + case 229: + case 228: bindBreakOrContinueStatement(node); break; - case 233: + case 235: bindTryStatement(node); break; - case 230: + case 232: bindSwitchStatement(node); break; - case 244: + case 246: bindCaseBlock(node); break; - case 269: + case 271: bindCaseClause(node); break; - case 231: + case 233: bindLabeledStatement(node); break; - case 200: + case 202: bindPrefixUnaryExpressionFlow(node); break; - case 201: + case 203: bindPostfixUnaryExpressionFlow(node); break; - case 202: + case 204: bindBinaryExpressionFlow(node); break; - case 196: + case 198: bindDeleteExpressionFlow(node); break; - case 203: + case 205: bindConditionalExpressionFlow(node); break; - case 235: + case 237: bindVariableDeclarationFlow(node); break; - case 189: + case 191: bindCallExpressionFlow(node); break; - case 302: - case 295: + case 304: + case 297: bindJSDocTypeAlias(node); break; - case 277: { + case 279: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 216: - case 243: + case 218: + case 245: bindEachFunctionsFirst(node.statements); break; default: @@ -21412,24 +22482,26 @@ var ts; } function isNarrowingExpression(expr) { switch (expr.kind) { - case 71: - case 99: - case 187: - case 188: - return isNarrowableReference(expr); + case 72: + case 100: case 189: + case 190: + return isNarrowableReference(expr); + case 191: return hasNarrowableArgument(expr); - case 193: + case 195: return isNarrowingExpression(expr.expression); - case 202: + case 204: return isNarrowingBinaryExpression(expr); - case 200: - return expr.operator === 51 && isNarrowingExpression(expr.operand); + case 202: + return expr.operator === 52 && isNarrowingExpression(expr.operand); + case 199: + return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 71 || expr.kind === 99 || expr.kind === 97 || + return expr.kind === 72 || expr.kind === 100 || expr.kind === 98 || ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && @@ -21444,7 +22516,7 @@ var ts; } } } - if (expr.expression.kind === 187 && + if (expr.expression.kind === 189 && isNarrowableReference(expr.expression.expression)) { return true; } @@ -21458,32 +22530,32 @@ var ts; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 58: + case 59: return isNarrowableReference(expr.left); - case 32: case 33: case 34: case 35: + case 36: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93: + case 94: return isNarrowableOperand(expr.left); - case 92: + case 93: return isNarrowableInOperands(expr.left, expr.right); - case 26: + case 27: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 193: + case 195: return isNarrowableOperand(expr.expression); - case 202: + case 204: switch (expr.operatorToken.kind) { - case 58: + case 59: return isNarrowableOperand(expr.left); - case 26: + case 27: return isNarrowableOperand(expr.right); } } @@ -21517,8 +22589,8 @@ var ts; if (!expression) { return flags & 32 ? antecedent : unreachableFlow; } - if (expression.kind === 101 && flags & 64 || - expression.kind === 86 && flags & 32) { + if (expression.kind === 102 && flags & 64 || + expression.kind === 87 && flags & 32) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -21556,34 +22628,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 220: case 222: - case 221: - return parent.expression === node; + case 224: case 223: - case 203: + return parent.expression === node; + case 225: + case 205: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 193) { + if (node.kind === 195) { node = node.expression; } - else if (node.kind === 200 && node.operator === 51) { + else if (node.kind === 202 && node.operator === 52) { node = node.operand; } else { - return node.kind === 202 && (node.operatorToken.kind === 53 || - node.operatorToken.kind === 54); + return node.kind === 204 && (node.operatorToken.kind === 54 || + node.operatorToken.kind === 55); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 193 || - node.parent.kind === 200 && - node.parent.operator === 51) { + while (node.parent.kind === 195 || + node.parent.kind === 202 && + node.parent.operator === 52) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -21624,7 +22696,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 231 + var enclosingLabeledStatement = node.parent.kind === 233 ? ts.lastOrUndefined(activeLabels) : undefined; var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); @@ -21656,13 +22728,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 225) { + if (node.kind === 227) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 236) { + if (node.initializer.kind !== 238) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -21684,7 +22756,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 228) { + if (node.kind === 230) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -21704,7 +22776,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 227 ? breakTarget : continueTarget; + var flowLabel = node.kind === 229 ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -21767,7 +22839,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 270; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272; }); node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; if (!hasDefault) { addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); @@ -21789,7 +22861,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -21833,13 +22904,13 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } - if (!node.statement || node.statement.kind !== 221) { + if (!node.statement || node.statement.kind !== 223) { addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 202 && node.operatorToken.kind === 58) { + if (node.kind === 204 && node.operatorToken.kind === 59) { bindAssignmentTargetFlow(node.left); } else { @@ -21850,10 +22921,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 185) { + else if (node.kind === 187) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 206) { + if (e.kind === 208) { bindAssignmentTargetFlow(e.expression); } else { @@ -21861,16 +22932,16 @@ var ts; } } } - else if (node.kind === 186) { + else if (node.kind === 188) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 273) { + if (p.kind === 275) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 274) { + else if (p.kind === 276) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 275) { + else if (p.kind === 277) { bindAssignmentTargetFlow(p.expression); } } @@ -21878,7 +22949,7 @@ var ts; } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53) { + if (node.operatorToken.kind === 54) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -21889,7 +22960,7 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51) { + if (node.operator === 52) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; @@ -21899,20 +22970,20 @@ var ts; } else { bindEachChild(node); - if (node.operator === 43 || node.operator === 44) { + if (node.operator === 44 || node.operator === 45) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { bindEachChild(node); - if (node.operator === 43 || node.operator === 44) { + if (node.operator === 44 || node.operator === 45) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 53 || operator === 54) { + if (operator === 54 || operator === 55) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -21926,7 +22997,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 && node.left.kind === 188) { + if (operator === 59 && node.left.kind === 190) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -21937,7 +23008,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187) { + if (node.expression.kind === 189) { bindAssignmentTargetFlow(node.expression); } } @@ -21975,16 +23046,17 @@ var ts; } } function bindJSDocTypeAlias(node) { + node.tagName.parent = node; if (node.fullName) { setParentPointers(node, node.fullName); } } function bindCallExpressionFlow(node) { var expr = node.expression; - while (expr.kind === 193) { + while (expr.kind === 195) { expr = expr.expression; } - if (expr.kind === 194 || expr.kind === 195) { + if (expr.kind === 196 || expr.kind === 197) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -21992,7 +23064,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 187) { + if (node.expression.kind === 189) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -22001,53 +23073,53 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 207: - case 238: - case 241: - case 186: - case 166: - case 290: - case 266: - return 1; - case 239: - return 1 | 64; - case 242: + case 209: case 240: - case 179: + case 243: + case 188: + case 168: + case 292: + case 268: + return 1; + case 241: + return 1 | 64; + case 244: + case 242: + case 181: return 1 | 32; - case 277: + case 279: return 1 | 4 | 32; - case 154: + case 156: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 | 4 | 32 | 8 | 128; } - case 155: - case 237: - case 153: - case 156: case 157: + case 239: + case 155: case 158: - case 291: - case 287: - case 163: case 159: case 160: - case 164: + case 293: + case 289: + case 165: + case 161: + case 162: + case 166: return 1 | 4 | 32 | 8; - case 194: - case 195: + case 196: + case 197: return 1 | 4 | 32 | 8 | 16; - case 243: + case 245: return 4; - case 152: + case 154: return node.initializer ? 4 : 0; - case 272: - case 223: - case 224: + case 274: case 225: - case 244: + case 226: + case 227: + case 246: return 2; - case 216: + case 218: return ts.isFunctionLike(node.parent) ? 0 : 2; } return 0; @@ -22060,40 +23132,40 @@ var ts; } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 242: + case 244: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 277: + case 279: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 207: - case 238: + case 209: + case 240: return declareClassMember(node, symbolFlags, symbolExcludes); - case 241: + case 243: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 166: - case 290: - case 186: - case 239: - case 266: + case 168: + case 292: + case 188: + case 241: + case 268: return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 163: - case 164: + case 165: + case 166: + case 160: + case 161: + case 293: + case 162: + case 156: + case 155: + case 157: case 158: case 159: - case 291: - case 160: - case 154: - case 153: - case 155: - case 156: - case 157: - case 237: - case 194: - case 195: - case 287: - case 302: - case 295: - case 240: - case 179: + case 239: + case 196: + case 197: + case 289: + case 304: + case 297: + case 242: + case 181: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } @@ -22108,11 +23180,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 277 ? node : node.body; - if (body && (body.kind === 277 || body.kind === 243)) { + var body = node.kind === 279 ? node : node.body; + if (body && (body.kind === 279 || body.kind === 245)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 253 || stat.kind === 252) { + if (stat.kind === 255 || stat.kind === 254) { return true; } } @@ -22138,7 +23210,7 @@ var ts; } else { var pattern = void 0; - if (node.name.kind === 9) { + if (node.name.kind === 10) { var text = node.name.text; if (ts.hasZeroOrOneAsteriskCharacter(text)) { pattern = ts.tryParsePattern(text); @@ -22147,7 +23219,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512, 67215503); + var symbol = declareSymbolAndAddToSymbolTable(node, 512, 110735); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -22164,7 +23236,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 67215503 : 0); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 110735 : 0); return state; } function bindFunctionOrConstructorType(node) { @@ -22180,11 +23252,11 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 || prop.name.kind !== 71) { + if (prop.kind === 277 || prop.name.kind !== 72) { continue; } var identifier = prop.name; - var currentKind = prop.kind === 273 || prop.kind === 274 || prop.kind === 154 + var currentKind = prop.kind === 275 || prop.kind === 276 || prop.kind === 156 ? 1 : 2; var existingKind = seen.get(identifier.escapedText); @@ -22216,10 +23288,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 242: + case 244: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 277: + case 279: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -22232,9 +23304,6 @@ var ts; declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 67216319); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -22252,9 +23321,9 @@ var ts; currentFlow = { flags: 2 }; parent = typeAlias; bind(typeAlias.typeExpression); - if (!typeAlias.fullName || typeAlias.fullName.kind === 71) { + if (!typeAlias.fullName || typeAlias.fullName.kind === 72) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288, 67901928); + bindBlockScopedDeclaration(typeAlias, 524288, 67897832); } else { bind(typeAlias.fullName); @@ -22268,8 +23337,8 @@ var ts; } function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 108 && - node.originalKeywordKind <= 116 && + node.originalKeywordKind >= 109 && + node.originalKeywordKind <= 117 && !ts.isIdentifierName(node) && !(node.flags & 4194304)) { if (!file.parseDiagnostics.length) { @@ -22297,7 +23366,7 @@ var ts; } } function checkStrictModeDeleteExpression(node) { - if (inStrictMode && node.expression.kind === 71) { + if (inStrictMode && node.expression.kind === 72) { 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)); } @@ -22306,7 +23375,7 @@ var ts; return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71) { + if (name && name.kind === 72) { var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { var span = ts.getErrorSpanForNode(file, name); @@ -22339,8 +23408,8 @@ var ts; } function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2) { - if (blockScopeContainer.kind !== 277 && - blockScopeContainer.kind !== 242 && + if (blockScopeContainer.kind !== 279 && + blockScopeContainer.kind !== 244 && !ts.isFunctionLike(blockScopeContainer)) { var errorSpan = ts.getErrorSpanForNode(file, node); file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); @@ -22359,7 +23428,7 @@ var ts; } function checkStrictModePrefixUnaryExpression(node) { if (inStrictMode) { - if (node.operator === 43 || node.operator === 44) { + if (node.operator === 44 || node.operator === 45) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -22402,7 +23471,7 @@ var ts; node.parent = parent; var saveInStrictMode = inStrictMode; bindWorker(node); - if (node.kind > 145) { + if (node.kind > 147) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -22426,7 +23495,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -22460,37 +23529,37 @@ var ts; } function bindWorker(node) { switch (node.kind) { - case 71: + case 72: if (node.isInJSDocNamespace) { var parentNode = node.parent; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288, 67901928); + bindBlockScopedDeclaration(parentNode, 524288, 67897832); break; } - case 99: - if (currentFlow && (ts.isExpression(node) || parent.kind === 274)) { + case 100: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 187: - case 188: + case 189: + case 190: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, undefined, node.expression, 1 | 134217728, 67216318); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, undefined, node.expression, 1 | 134217728, 67220414); } break; - case 202: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + case 204: + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1: bindExportsPropertyAssignment(node); @@ -22513,132 +23582,145 @@ var ts; case 0: break; default: - ts.Debug.fail("Unknown special property assignment kind"); + ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 272: + case 274: return checkStrictModeCatchClause(node); - case 196: + case 198: return checkStrictModeDeleteExpression(node); case 8: return checkStrictModeNumericLiteral(node); - case 201: + case 203: return checkStrictModePostfixUnaryExpression(node); - case 200: + case 202: return checkStrictModePrefixUnaryExpression(node); - case 229: - return checkStrictModeWithStatement(node); case 231: + return checkStrictModeWithStatement(node); + case 233: return checkStrictModeLabeledStatement(node); - case 176: + case 178: seenThisKeyword = true; return; - case 161: + case 163: break; - case 148: + case 150: return bindTypeParameter(node); - case 149: + case 151: return bindParameter(node); - case 235: + case 237: return bindVariableDeclarationOrBindingElement(node); - case 184: + case 186: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 152: - case 151: - return bindPropertyWorker(node); - case 273: - case 274: - return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 276: - return bindPropertyOrMethodOrAccessor(node, 8, 68008959); - case 158: - case 159: - case 160: - return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 154: case 153: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67208127); - case 237: - return bindFunctionDeclaration(node); - case 155: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); + return bindPropertyWorker(node); + case 275: + case 276: + return bindPropertyOrMethodOrAccessor(node, 4, 0); + case 278: + return bindPropertyOrMethodOrAccessor(node, 8, 68008959); + case 160: + case 161: + case 162: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 156: - return bindPropertyOrMethodOrAccessor(node, 32768, 67150783); + case 155: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67212223); + case 239: + return bindFunctionDeclaration(node); case 157: - return bindPropertyOrMethodOrAccessor(node, 65536, 67183551); - case 163: - case 287: - case 291: - case 164: - return bindFunctionOrConstructorType(node); + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 158: + return bindPropertyOrMethodOrAccessor(node, 32768, 67154879); + case 159: + return bindPropertyOrMethodOrAccessor(node, 65536, 67187647); + case 165: + case 289: + case 293: case 166: - case 290: - case 179: + return bindFunctionOrConstructorType(node); + case 168: + case 292: + case 181: return bindAnonymousTypeWorker(node); - case 186: + case 188: return bindObjectLiteralExpression(node); - case 194: - case 195: + case 196: + case 197: return bindFunctionExpression(node); - case 189: - if (ts.isInJavaScriptFile(node)) { + case 191: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7: + return bindObjectDefinePropertyAssignment(node); + case 8: + return bindObjectDefinePropertyExport(node); + case 9: + return bindObjectDefinePrototypeProperty(node); + case 0: + break; + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; - case 207: - case 238: + case 209: + case 240: inStrictMode = true; return bindClassLikeDeclaration(node); - case 239: - return bindBlockScopedDeclaration(node, 64, 67901832); - case 240: - return bindBlockScopedDeclaration(node, 524288, 67901928); case 241: - return bindEnumDeclaration(node); + return bindBlockScopedDeclaration(node, 64, 67897736); case 242: + return bindBlockScopedDeclaration(node, 524288, 67897832); + case 243: + return bindEnumDeclaration(node); + case 244: return bindModuleDeclaration(node); - case 266: + case 268: return bindJsxAttributes(node); - case 265: + case 267: return bindJsxAttribute(node, 4, 0); - case 246: - case 249: - case 251: - case 255: - return declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); - case 245: - return bindNamespaceExportDeclaration(node); case 248: - return bindImportClause(node); + case 251: case 253: + case 257: + return declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); + case 247: + return bindNamespaceExportDeclaration(node); + case 250: + return bindImportClause(node); + case 255: return bindExportDeclaration(node); - case 252: + case 254: return bindExportAssignment(node); - case 277: + case 279: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 216: + case 218: if (!ts.isFunctionLike(node.parent)) { return; } - case 243: + case 245: return updateStrictModeStatementList(node.statements); - case 297: - if (node.parent.kind === 291) { + case 299: + if (node.parent.kind === 293) { return bindParameter(node); } - if (node.parent.kind !== 290) { + if (node.parent.kind !== 292) { break; } - case 303: + case 305: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 ? 4 | 16777216 : 4; return declareSymbolAndAddToSymbolTable(propTag, flags, 0); - case 302: - case 295: + case 304: + case 297: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -22668,33 +23750,30 @@ var ts; bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); } else { - var flags = node.kind === 252 && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) ? 2097152 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); + if (node.isExportEquals) { + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -22719,6 +23798,21 @@ var ts; } return true; } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 | 67108864); + } + return symbol; + }); + if (symbol) { + var flags = 4 | 1048576; + declareSymbol(symbol.exports, symbol, node, flags, 0); + } + } function bindExportsPropertyAssignment(node) { if (!setCommonJsModuleIndicator(node)) { return; @@ -22748,16 +23842,16 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 : 4 | 1048576 | 512; - declareSymbol(file.symbol.exports, file.symbol, node, flags, 0); + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864, 0); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, false); switch (thisContainer.kind) { - case 237: - case 194: + case 239: + case 196: var constructorSymbol = thisContainer.symbol; - if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58) { + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59) { var l = thisContainer.parent.left; if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); @@ -22768,26 +23862,26 @@ var ts; declareSymbol(constructorSymbol.members, constructorSymbol, node, 4, 0 & ~4); } break; - case 155: - case 152: + case 157: case 154: case 156: - case 157: + case 158: + case 159: var containingClass = thisContainer.parent; var symbolTable = ts.hasModifier(thisContainer, 32) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true); break; - case 277: + case 279: break; default: ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); } } function bindSpecialPropertyDeclaration(node) { - if (node.expression.kind === 99) { + if (node.expression.kind === 100) { bindThisPropertyAssignment(node); } - else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 277) { + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -22800,7 +23894,11 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, false); + bindPropertyAssignment(lhs.expression, lhs, false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, true); } function bindPrototypePropertyAssignment(lhs, parent) { var classPrototype = lhs.expression; @@ -22810,10 +23908,16 @@ var ts; classPrototype.parent = lhs; bindPropertyAssignment(constructorFunction, lhs, true); } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, false); + } function bindSpecialPropertyAssignment(node) { var lhs = node.left; var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } node.left.parent = node; @@ -22829,42 +23933,52 @@ var ts; node.expression.parent = node; bindPropertyAssignment(node.expression, node, false); } - function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) - : propertyAccess.parent.parent.kind === 277; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920)) && isToplevelNamespaceableInitializer) { + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920))) { var flags_1 = 1536 | 67108864; - var excludeFlags_1 = 67215503 & ~67108864; - namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { + var excludeFlags_1 = 110735 & ~67108864; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 : 4) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 : 0) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 : 4; + var excludes = isMethod ? 67212223 : 0; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864, excludes & ~67108864); } - function isJavascriptContainer(symbol) { + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 + : propertyAccess.parent.parent.kind === 279; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); + } + function isExpandoSymbol(symbol) { if (symbol.flags & (16 | 32 | 1024)) { return true; } var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -22873,7 +23987,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 ? init.right : init, isPrototypeAssignment); } return false; } @@ -22913,7 +24027,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 238) { + if (node.kind === 240) { bindBlockScopedDeclaration(node, 32, 68008383); } else { @@ -22945,19 +24059,22 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 : 0); + var enumExcludes = (isEnum ? 68008191 : 0); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 | enumFlags, 67220415 | enumExcludes); } else if (ts.isParameterDeclaration(node)) { - declareSymbolAndAddToSymbolTable(node, 1, 67216319); + declareSymbolAndAddToSymbolTable(node, 1, 67220415); } else { - declareSymbolAndAddToSymbolTable(node, 1, 67216318); + declareSymbolAndAddToSymbolTable(node, 1 | enumFlags, 67220414 | enumExcludes); } } } function bindParameter(node) { - if (node.kind === 297 && container.kind !== 291) { + if (node.kind === 299 && container.kind !== 293) { return; } if (inStrictMode && !(node.flags & 4194304)) { @@ -22967,7 +24084,7 @@ var ts; bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1, 67216319); + declareSymbolAndAddToSymbolTable(node, 1, 67220415); } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; @@ -22983,10 +24100,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16, 67215791); + bindBlockScopedDeclaration(node, 16, 67219887); } else { - declareSymbolAndAddToSymbolTable(node, 16, 67215791); + declareSymbolAndAddToSymbolTable(node, 16, 67219887); } } function bindFunctionExpression(node) { @@ -23024,26 +24141,26 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, undefined, node, 262144, 67639784); + declareSymbol(container_1.locals, undefined, node, 262144, 67635688); } else { - declareSymbolAndAddToSymbolTable(node, 262144, 67639784); + declareSymbolAndAddToSymbolTable(node, 262144, 67635688); } } - else if (node.parent.kind === 174) { + else if (node.parent.kind === 176) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, undefined, node, 262144, 67639784); + declareSymbol(container_2.locals, undefined, node, 262144, 67635688); } else { bindAnonymousDeclaration(node, 262144, getDeclarationName(node)); } } else { - declareSymbolAndAddToSymbolTable(node, 262144, 67639784); + declareSymbolAndAddToSymbolTable(node, 262144, 67635688); } } function shouldReportErrorOnModuleDeclaration(node) { @@ -23055,10 +24172,9 @@ var ts; return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 218) || - node.kind === 238 || - (node.kind === 242 && shouldReportErrorOnModuleDeclaration(node)) || - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 220) || + node.kind === 240 || + (node.kind === 244 && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -23085,17 +24201,17 @@ var ts; } } function isExecutableStatement(s) { - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 | 2)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 239: - case 240: - return true; - case 242: - return getModuleInstanceState(s) !== 1; case 241: + case 242: + return true; + case 244: + return getModuleInstanceState(s) !== 1; + case 243: return ts.hasModifier(s, 2048); default: return false; @@ -23121,63 +24237,66 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 189: + case 191: return computeCallExpression(node, subtreeFlags); - case 190: + case 192: return computeNewExpression(node, subtreeFlags); - case 242: + case 244: return computeModuleDeclaration(node, subtreeFlags); - case 193: - return computeParenthesizedExpression(node, subtreeFlags); - case 202: - return computeBinaryExpression(node, subtreeFlags); - case 219: - return computeExpressionStatement(node, subtreeFlags); - case 149: - return computeParameter(node, subtreeFlags); case 195: + return computeParenthesizedExpression(node, subtreeFlags); + case 204: + return computeBinaryExpression(node, subtreeFlags); + case 221: + return computeExpressionStatement(node, subtreeFlags); + case 151: + return computeParameter(node, subtreeFlags); + case 197: return computeArrowFunction(node, subtreeFlags); - case 194: + case 196: return computeFunctionExpression(node, subtreeFlags); - case 237: + case 239: return computeFunctionDeclaration(node, subtreeFlags); - case 235: + case 237: return computeVariableDeclaration(node, subtreeFlags); - case 236: - return computeVariableDeclarationList(node, subtreeFlags); - case 217: - return computeVariableStatement(node, subtreeFlags); - case 231: - return computeLabeledStatement(node, subtreeFlags); case 238: + return computeVariableDeclarationList(node, subtreeFlags); + case 219: + return computeVariableStatement(node, subtreeFlags); + case 233: + return computeLabeledStatement(node, subtreeFlags); + case 240: return computeClassDeclaration(node, subtreeFlags); - case 207: - return computeClassExpression(node, subtreeFlags); - case 271: - return computeHeritageClause(node, subtreeFlags); - case 272: - return computeCatchClause(node, subtreeFlags); case 209: + return computeClassExpression(node, subtreeFlags); + case 273: + return computeHeritageClause(node, subtreeFlags); + case 274: + return computeCatchClause(node, subtreeFlags); + case 211: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 155: - return computeConstructor(node, subtreeFlags); - case 152: - return computePropertyDeclaration(node, subtreeFlags); - case 154: - return computeMethod(node, subtreeFlags); - case 156: case 157: + return computeConstructor(node, subtreeFlags); + case 154: + return computePropertyDeclaration(node, subtreeFlags); + case 156: + return computeMethod(node, subtreeFlags); + case 158: + case 159: return computeAccessor(node, subtreeFlags); - case 246: + case 248: return computeImportEquals(node, subtreeFlags); - case 187: + case 189: return computePropertyAccess(node, subtreeFlags); - case 188: + case 190: return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -23190,49 +24309,49 @@ var ts; if (node.typeArguments) { transformFlags |= 3; } - if (subtreeFlags & 524288 - || (expression.transformFlags & (134217728 | 268435456))) { + if (subtreeFlags & 131072 + || (expression.transformFlags & (33554432 | 67108864))) { transformFlags |= 192; - if (expression.transformFlags & 268435456) { + if (expression.transformFlags & 67108864) { + transformFlags |= 8192; + } + } + if (expression.kind === 92) { + transformFlags |= 16777216; + if (subtreeFlags & 8192) { transformFlags |= 16384; } } - if (expression.kind === 91) { - transformFlags |= 67108864; - if (subtreeFlags & 16384) { - transformFlags |= 32768; - } - } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~940049729; + return transformFlags & ~637666625; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3; } - if (subtreeFlags & 524288) { + if (subtreeFlags & 131072) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~940049729; + return transformFlags & ~637666625; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 && leftKind === 186) { + if (operatorTokenKind === 59 && leftKind === 188) { transformFlags |= 8 | 192 | 3072; } - else if (operatorTokenKind === 58 && leftKind === 185) { + else if (operatorTokenKind === 59 && leftKind === 187) { transformFlags |= 192 | 3072; } - else if (operatorTokenKind === 40 - || operatorTokenKind === 62) { + else if (operatorTokenKind === 41 + || operatorTokenKind === 63) { transformFlags |= 32; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23241,29 +24360,29 @@ var ts; var dotDotDotToken = node.dotDotDotToken; if (node.questionToken || node.type - || subtreeFlags & 4096 + || (subtreeFlags & 4096 && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (ts.hasModifier(node, 92)) { - transformFlags |= 3 | 262144; + transformFlags |= 3 | 4096; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { - transformFlags |= 192 | 131072; + if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { + transformFlags |= 192 | 65536; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; var expressionTransformFlags = expression.transformFlags; - if (expressionKind === 210 - || expressionKind === 192) { + if (expressionKind === 212 + || expressionKind === 194) { transformFlags |= 3; } if (expressionTransformFlags & 1024) { @@ -23279,36 +24398,36 @@ var ts; } else { transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 274432) + if ((subtreeFlags & 4096) || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 32768) { + transformFlags |= 8192; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~942011713; + return transformFlags & ~638121281; } function computeClassExpression(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 274432 + if (subtreeFlags & 4096 || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 32768) { + transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~942011713; + return transformFlags & ~638121281; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 85: + case 86: transformFlags |= 192; break; - case 108: + case 109: transformFlags |= 3; break; default: @@ -23316,7 +24435,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23327,7 +24446,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~940574017; + return transformFlags & ~637797697; } function computeExpressionWithTypeArguments(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -23335,7 +24454,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23343,11 +24462,11 @@ var ts; || !node.body) { transformFlags |= 3; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003668801; + return transformFlags & ~653616449; } function computeMethod(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -23359,7 +24478,7 @@ var ts; || !node.body) { transformFlags |= 3; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } if (ts.hasModifier(node, 256)) { @@ -23369,7 +24488,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003668801; + return transformFlags & ~653616449; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23380,19 +24499,19 @@ var ts; || !node.body) { transformFlags |= 3; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003668801; + return transformFlags & ~653616449; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192; + transformFlags |= 4096; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -23402,7 +24521,7 @@ var ts; transformFlags = 3; } else { - transformFlags = subtreeFlags | 33554432; + transformFlags = subtreeFlags | 8388608; if (modifierFlags & 2270 || node.typeParameters || node.type) { @@ -23411,10 +24530,10 @@ var ts; if (modifierFlags & 256) { transformFlags |= node.asteriskToken ? 8 : 16; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 163840) { + if (subtreeFlags & 81920) { transformFlags |= 192; } if (node.asteriskToken) { @@ -23422,7 +24541,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003935041; + return transformFlags & ~653620545; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23434,17 +24553,17 @@ var ts; if (ts.hasModifier(node, 256)) { transformFlags |= node.asteriskToken ? 8 : 16; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 163840) { + if (subtreeFlags & 81920) { transformFlags |= 192; } if (node.asteriskToken) { transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003935041; + return transformFlags & ~653620545; } function computeArrowFunction(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -23456,46 +24575,46 @@ var ts; if (ts.hasModifier(node, 256)) { transformFlags |= 16; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 16384) { - transformFlags |= 32768; + if (subtreeFlags & 8192) { + transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003902273; + return transformFlags & ~653604161; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (transformFlags & 134217728) { - transformFlags ^= 134217728; - transformFlags |= 268435456; + if (transformFlags & 33554432) { + transformFlags ^= 33554432; + transformFlags |= 67108864 | 16 | 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~671089985; + return transformFlags & ~570426689; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionFlags = expression.transformFlags; - if (expressionFlags & 134217728) { - transformFlags &= ~134217728; - transformFlags |= 268435456; + if (expressionFlags & 33554432) { + transformFlags &= ~33554432; + transformFlags |= 67108864 | 16 | 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~671089985; + return transformFlags & ~570426689; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 | 8388608; - if (subtreeFlags & 1048576) { + transformFlags |= 192 | 2097152; + if (subtreeFlags & 262144) { transformFlags |= 8; } if (node.type) { transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -23505,21 +24624,21 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608) { + if (declarationListTransformFlags & 2097152) { transformFlags |= 192; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (subtreeFlags & 4194304 + if (subtreeFlags & 1048576 && ts.isIterationStatement(node, true)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23527,7 +24646,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23535,7 +24654,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -23544,71 +24663,71 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~977327425; + return transformFlags & ~647001409; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432; - if (subtreeFlags & 8388608) { + var transformFlags = subtreeFlags | 8388608; + if (subtreeFlags & 2097152) { transformFlags |= 192; } if (node.flags & 3) { - transformFlags |= 192 | 4194304; + transformFlags |= 192 | 1048576; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~948962625; + return transformFlags & ~639894849; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 939525441; + var excludeFlags = 637535553; switch (kind) { - case 120: - case 199: + case 121: + case 201: transformFlags |= 8 | 16; break; - case 192: - case 210: - case 306: + case 194: + case 212: + case 308: transformFlags |= 3; excludeFlags = 536872257; break; - case 114: - case 112: + case 115: case 113: - case 117: - case 124: - case 76: - case 241: - case 276: - case 211: - case 132: + case 114: + case 118: + case 125: + case 77: + case 243: + case 278: + case 213: + case 133: transformFlags |= 3; break; - case 258: - case 259: case 260: - case 10: case 261: case 262: + case 11: case 263: case 264: case 265: case 266: case 267: case 268: + case 269: + case 270: transformFlags |= 4; break; - case 13: case 14: case 15: case 16: - case 204: - case 191: - case 274: - case 115: - case 212: + case 17: + case 206: + case 193: + case 276: + case 116: + case 214: transformFlags |= 192; break; - case 9: + case 10: if (node.hasExtendedUnicodeEscape) { transformFlags |= 192; } @@ -23618,28 +24737,30 @@ var ts; transformFlags |= 192; } break; - case 225: + case 9: + transformFlags |= 8; + break; + case 227: if (node.awaitModifier) { transformFlags |= 8; } transformFlags |= 192; break; - case 205: - transformFlags |= 8 | 192 | 16777216; + case 207: + transformFlags |= 8 | 192 | 4194304; break; - case 119: - case 134: - case 131: + case 120: case 135: - case 137: - case 122: + case 146: + case 132: + case 136: case 138: - case 105: - case 148: - case 151: + case 123: + case 139: + case 106: + case 150: case 153: - case 158: - case 159: + case 155: case 160: case 161: case 162: @@ -23656,163 +24777,166 @@ var ts; case 173: case 174: case 175: - case 239: - case 240: case 176: case 177: + case 241: + case 242: case 178: case 179: case 180: - case 245: + case 181: + case 182: + case 247: transformFlags = 3; excludeFlags = -3; break; - case 147: - transformFlags |= 2097152; - if (subtreeFlags & 16384) { - transformFlags |= 65536; + case 149: + transformFlags |= 524288; + if (subtreeFlags & 8192) { + transformFlags |= 32768; } break; - case 206: - transformFlags |= 192 | 524288; + case 208: + transformFlags |= 192 | 131072; break; - case 275: - transformFlags |= 8 | 1048576; + case 277: + transformFlags |= 8 | 262144; break; - case 97: - transformFlags |= 192 | 134217728; + case 98: + transformFlags |= 192 | 33554432; excludeFlags = 536872257; break; - case 99: - transformFlags |= 16384; - break; - case 182: - transformFlags |= 192 | 8388608; - if (subtreeFlags & 524288) { - transformFlags |= 8 | 1048576; - } - excludeFlags = 940049729; - break; - case 183: - transformFlags |= 192 | 8388608; - excludeFlags = 940049729; + case 100: + transformFlags |= 8192; break; case 184: - transformFlags |= 192; - if (node.dotDotDotToken) { - transformFlags |= 524288; + transformFlags |= 192 | 2097152; + if (subtreeFlags & 131072) { + transformFlags |= 8 | 262144; } + excludeFlags = 637666625; break; - case 150: - transformFlags |= 3 | 4096; + case 185: + transformFlags |= 192 | 2097152; + excludeFlags = 637666625; break; case 186: - excludeFlags = 942740801; - if (subtreeFlags & 2097152) { + transformFlags |= 192; + if (node.dotDotDotToken) { + transformFlags |= 131072; + } + break; + case 152: + transformFlags |= 3 | 4096; + break; + case 188: + excludeFlags = 638358849; + if (subtreeFlags & 524288) { transformFlags |= 192; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 32768) { + transformFlags |= 8192; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } break; - case 185: - case 190: - excludeFlags = 940049729; - if (subtreeFlags & 524288) { + case 187: + case 192: + excludeFlags = 637666625; + if (subtreeFlags & 131072) { transformFlags |= 192; } break; - case 221: - case 222: case 223: case 224: - if (subtreeFlags & 4194304) { + case 225: + case 226: + if (subtreeFlags & 1048576) { transformFlags |= 192; } break; - case 277: - if (subtreeFlags & 32768) { + case 279: + if (subtreeFlags & 16384) { transformFlags |= 192; } break; + case 230: + transformFlags |= 8388608 | 8; + break; case 228: - transformFlags |= 33554432 | 8; - break; - case 226: - case 227: - transformFlags |= 33554432; + case 229: + transformFlags |= 8388608; break; } node.transformFlags = transformFlags | 536870912; return transformFlags & ~excludeFlags; } function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 161 && kind <= 181) { + if (kind >= 163 && kind <= 183) { return -3; } switch (kind) { - case 189: - case 190: - case 185: - return 940049729; - case 242: - return 977327425; - case 149: - return 939525441; - case 195: - return 1003902273; - case 194: - case 237: - return 1003935041; - case 236: - return 948962625; - case 238: - case 207: - return 942011713; - case 155: - return 1003668801; - case 154: - case 156: - case 157: - return 1003668801; - case 119: - case 134: - case 131: - case 137: - case 135: - case 122: - case 138: - case 105: - case 148: + case 191: + case 192: + case 187: + return 637666625; + case 244: + return 647001409; case 151: - case 153: + return 637535553; + case 197: + return 653604161; + case 196: + case 239: + return 653620545; + case 238: + return 639894849; + case 240: + case 209: + return 638121281; + case 157: + return 653616449; + case 156: case 158: case 159: + return 653616449; + case 120: + case 135: + case 146: + case 132: + case 138: + case 136: + case 123: + case 139: + case 106: + case 150: + case 153: + case 155: case 160: - case 239: - case 240: + case 161: + case 162: + case 241: + case 242: return -3; - case 186: - return 942740801; - case 272: - return 940574017; - case 182: - case 183: - return 940049729; - case 192: - case 210: - case 306: - case 193: - case 97: - return 536872257; - case 187: case 188: - return 671089985; + return 638358849; + case 274: + return 637797697; + case 184: + case 185: + return 637666625; + case 194: + case 212: + case 308: + case 195: + case 98: + return 536872257; + case 189: + case 190: + return 570426689; default: - return 939525441; + return 637535553; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -23862,7 +24986,7 @@ var ts; var shouldBail = visitSymbol(type.symbol); if (shouldBail) return; - if (type.flags & 131072) { + if (type.flags & 524288) { var objectType = type; var objectFlags = objectType.objectFlags; if (objectFlags & 4) { @@ -23878,16 +25002,16 @@ var ts; visitObjectType(objectType); } } - if (type.flags & 65536) { + if (type.flags & 262144) { visitTypeParameter(type); } - if (type.flags & 786432) { + if (type.flags & 3145728) { visitUnionOrIntersectionType(type); } - if (type.flags & 1048576) { + if (type.flags & 4194304) { visitIndexType(type); } - if (type.flags & 2097152) { + if (type.flags & 8388608) { visitIndexedAccessType(type); } } @@ -23971,7 +25095,7 @@ var ts; symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { - if (d.type && d.type.kind === 165) { + if (d.type && d.type.kind === 167) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -24013,6 +25137,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); var cancellationToken; var requestedExternalEmitHelpers; var externalHelpersModule; @@ -24022,7 +25158,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -24031,10 +25168,12 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768; var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4, "undefined"); @@ -24187,27 +25326,13 @@ var ts; var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); return parsed ? isImplementationOfOverload(parsed) : undefined; }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return ts.Debug.fail(); - links.immediateTarget = getTargetOfAliasDeclaration(node, true); - } - return links.immediateTarget; - }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { - var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isParameter); @@ -24229,15 +25354,17 @@ var ts; getNumberType: function () { return numberType; }, createPromiseType: createPromiseType, createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, getESSymbolType: function () { return esSymbolType; }, getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -24245,7 +25372,7 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, - getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 ? getDefaultFromTypeParameter(type) : undefined; }, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false, excludeGlobals); }, @@ -24295,7 +25422,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -24318,24 +25446,41 @@ var ts; var wildcardType = createIntrinsicType(1, "any"); var errorType = createIntrinsicType(1, "error"); var unknownType = createIntrinsicType(2, "unknown"); - var undefinedType = createIntrinsicType(8192, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(8192 | 134217728, "undefined"); - var nullType = createIntrinsicType(16384, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(16384 | 134217728, "null"); + var undefinedType = createIntrinsicType(32768, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 | 134217728, "undefined"); + var nullType = createIntrinsicType(65536, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 | 134217728, "null"); var stringType = createIntrinsicType(4, "string"); var numberType = createIntrinsicType(8, "number"); - var falseType = createIntrinsicType(256, "false"); - var trueType = createIntrinsicType(256, "true"); - var booleanType = createBooleanType([falseType, trueType]); - var esSymbolType = createIntrinsicType(1024, "symbol"); - var voidType = createIntrinsicType(4096, "void"); - var neverType = createIntrinsicType(32768, "never"); - var silentNeverType = createIntrinsicType(32768, "never"); - var implicitNeverType = createIntrinsicType(32768, "never"); - var nonPrimitiveType = createIntrinsicType(16777216, "object"); + var bigintType = createIntrinsicType(64, "bigint"); + var falseType = createIntrinsicType(512, "false"); + var regularFalseType = createIntrinsicType(512, "false"); + var trueType = createIntrinsicType(512, "true"); + var regularTrueType = createIntrinsicType(512, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096, "symbol"); + var voidType = createIntrinsicType(16384, "void"); + var neverType = createIntrinsicType(131072, "never"); + var silentNeverType = createIntrinsicType(131072, "never"); + var implicitNeverType = createIntrinsicType(131072, "never"); + var nonPrimitiveType = createIntrinsicType(67108864, "object"); var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096; var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -24346,16 +25491,15 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(65536); - var markerSubType = createType(65536); + var markerSuperType = createType(262144); + var markerSubType = createType(262144); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(65536); + var markerOtherType = createType(262144); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, undefined, 0, false, false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); - var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, true); var globals = ts.createSymbolTable(); var amalgamatedDuplicates; @@ -24364,6 +25508,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -24379,6 +25525,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -24390,7 +25537,9 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; var allPotentiallyUnusedIdentifiers = ts.createMap(); var flowLoopStart = 0; var flowLoopCount = 0; @@ -24398,6 +25547,7 @@ var ts; var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -24420,24 +25570,27 @@ var ts; var typeofEQFacts = ts.createMapFromTemplate({ string: 1, number: 2, - boolean: 4, - symbol: 8, - undefined: 16384, - object: 16, - function: 32 + bigint: 4, + boolean: 8, + symbol: 16, + undefined: 65536, + object: 32, + function: 64 }); var typeofNEFacts = ts.createMapFromTemplate({ - string: 128, - number: 256, - boolean: 512, - symbol: 1024, - undefined: 131072, - object: 2048, - function: 4096 + string: 256, + number: 512, + bigint: 1024, + boolean: 2048, + symbol: 4096, + undefined: 524288, + object: 8192, + function: 16384 }); var typeofTypesByName = ts.createMapFromTemplate({ string: stringType, number: numberType, + bigint: bigintType, boolean: booleanType, symbol: esSymbolType, undefined: undefinedType @@ -24546,35 +25699,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2) - result |= 67216319; + result |= 67220415; if (flags & 1) - result |= 67216318; + result |= 67220414; if (flags & 4) result |= 0; if (flags & 8) result |= 68008959; if (flags & 16) - result |= 67215791; + result |= 67219887; if (flags & 32) result |= 68008383; if (flags & 64) - result |= 67901832; + result |= 67897736; if (flags & 256) result |= 68008191; if (flags & 128) result |= 68008831; if (flags & 512) - result |= 67215503; + result |= 110735; if (flags & 8192) - result |= 67208127; + result |= 67212223; if (flags & 32768) - result |= 67150783; + result |= 67154879; if (flags & 65536) - result |= 67183551; + result |= 67187647; if (flags & 262144) - result |= 67639784; + result |= 67635688; if (flags & 524288) - result |= 67901928; + result |= 67897832; if (flags & 2097152) result |= 2097152; return result; @@ -24606,7 +25759,11 @@ var ts; (source.flags | target.flags) & 67108864) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432)) { - target = cloneSymbol(target); + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); } if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; @@ -24614,6 +25771,7 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { target.valueDeclaration = source.valueDeclaration; } @@ -24635,52 +25793,53 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 || source.flags & 384); - var isEitherBlockScoped = !!(target.flags & 2 || source.flags & 2); + var isEitherBlockScoped_1 = !!(target.flags & 2 || source.flags & 2); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -24696,7 +25855,8 @@ var ts; } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { - target.set(id, target.has(id) ? mergeSymbol(target.get(id), sourceSymbol) : sourceSymbol); + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); }); } function mergeModuleAugmentation(moduleName) { @@ -24750,7 +25910,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { - return node.kind === 277 && !ts.isExternalOrCommonJsModule(node); + return node.kind === 279 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -24772,8 +25932,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -24796,15 +25956,15 @@ var ts; return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { - if (declaration.kind === 184) { - var errorBindingElement = ts.getAncestor(usage, 184); + if (declaration.kind === 186) { + var errorBindingElement = ts.getAncestor(usage, 186); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 235), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237), usage); } - else if (declaration.kind === 235) { + else if (declaration.kind === 237) { return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } else if (ts.isClassDeclaration(declaration)) { @@ -24812,10 +25972,10 @@ var ts; } return true; } - if (usage.parent.kind === 255 || (usage.parent.kind === 252 && usage.parent.isExportEquals)) { + if (usage.parent.kind === 257 || (usage.parent.kind === 254 && usage.parent.isExportEquals)) { return true; } - if (usage.kind === 252 && usage.isExportEquals) { + if (usage.kind === 254 && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -24823,9 +25983,9 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 217: - case 223: + case 219: case 225: + case 227: if (isSameScopeDescendentOf(usage, declaration, container)) { return true; } @@ -24843,16 +26003,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 152 && + current.parent.kind === 154 && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32)) { - if (declaration.kind === 154) { + if (declaration.kind === 156) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 152 && !ts.hasModifier(declaration, 32); + var isDeclarationInstanceProperty = declaration.kind === 154 && !ts.hasModifier(declaration, 32); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -24880,21 +26040,28 @@ var ts; if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 67901928 && lastLocation.kind !== 289) { + if (meaning & result.flags & 67897832 && lastLocation.kind !== 291) { useResult = result.flags & 262144 ? lastLocation === location.type || - lastLocation.kind === 149 || - lastLocation.kind === 148 + lastLocation.kind === 151 || + lastLocation.kind === 150 : false; } - if (meaning & 67216319 && result.flags & 1) { - useResult = - lastLocation.kind === 149 || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3) { + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1) { + useResult = + lastLocation.kind === 151 || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } - else if (location.kind === 173) { + else if (location.kind === 175) { useResult = lastLocation === location.trueType; } if (useResult) { @@ -24906,13 +26073,13 @@ var ts; } } switch (location.kind) { - case 277: + case 279: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 242: + case 244: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 277 || ts.isAmbientModule(location)) { + if (location.kind === 279 || ts.isAmbientModule(location)) { if (result = moduleExports.get("default")) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { @@ -24923,7 +26090,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 && - ts.getDeclarationOfKind(moduleExport, 255)) { + ts.getDeclarationOfKind(moduleExport, 257)) { break; } } @@ -24936,26 +26103,26 @@ var ts; } } break; - case 241: + case 243: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; - case 152: - case 151: + case 154: + case 153: if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319)) { + if (lookup(ctor.locals, name, meaning & 67220415)) { propertyWithInvalidInitializer = location; } } } break; - case 238: - case 207: - case 239: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928)) { + case 240: + case 209: + case 241: + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -24966,7 +26133,7 @@ var ts; } break loop; } - if (location.kind === 207 && meaning & 32) { + if (location.kind === 209 && meaning & 32) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -24974,10 +26141,10 @@ var ts; } } break; - case 209: - if (lastLocation === location.expression && location.parent.token === 85) { + case 211: + if (lastLocation === location.expression && location.parent.token === 86) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -24985,28 +26152,28 @@ var ts; } } break; - case 147: + case 149: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 239) { - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928)) { + if (ts.isClassLike(grandparent) || grandparent.kind === 241) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 154: - case 153: - case 155: case 156: + case 155: case 157: - case 237: - case 195: + case 158: + case 159: + case 239: + case 197: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 194: + case 196: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -25019,16 +26186,16 @@ var ts; } } break; - case 150: - if (location.parent && location.parent.kind === 149) { + case 152: + if (location.parent && location.parent.kind === 151) { location = location.parent; } if (location.parent && ts.isClassElement(location.parent)) { location = location.parent; } break; - case 302: - case 295: + case 304: + case 297: location = ts.getJSDocHost(location); break; } @@ -25038,13 +26205,13 @@ var ts; lastLocation = location; location = location.parent; } - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { result.isReferenced |= meaning; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 277); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + ts.Debug.assert(lastLocation.kind === 279); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -25053,7 +26220,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, false)) { return requireSymbol; } @@ -25094,15 +26261,14 @@ var ts; } if (errorLocation && (meaning & 2 || - ((meaning & 32 || meaning & 384) && (meaning & 67216319) === 67216319))) { + ((meaning & 32 || meaning & 384) && (meaning & 67220415) === 67220415))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule && (meaning & 67216319) === 67216319 && !(originalLocation.flags & 2097152)) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 245) { + if (result && isInExternalModule && (meaning & 67220415) === 67220415 && !(originalLocation.flags & 2097152)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } @@ -25111,12 +26277,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 237: - case 238: case 239: - case 241: case 240: + case 241: + case 243: case 242: + case 244: return true; default: return false; @@ -25128,7 +26294,7 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 148) { + if (decl.kind === 150) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); @@ -25176,10 +26342,10 @@ var ts; } function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 71: - case 187: + case 72: + case 189: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 209: + case 211: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -25188,9 +26354,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(errorLocation) ? 67216319 : 0); + var namespaceMeaning = 1920 | (ts.isInJSFile(errorLocation) ? 67220415 : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~namespaceMeaning, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~namespaceMeaning, undefined, undefined, false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -25209,29 +26375,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 & ~1024)) { + if (meaning & (67220415 & ~1024)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~67216319, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~67220415, undefined, undefined, false)); if (symbol && !(symbol.flags & 1024)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 & ~1024 & ~67901928)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67216319, undefined, undefined, false)); + if (meaning & (67220415 & ~1024 & ~67897832)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67220415, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 & ~1024 & ~67216319)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67901928, undefined, undefined, false)); + else if (meaning & (67897832 & ~1024 & ~67220415)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67897832, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -25241,7 +26410,7 @@ var ts; } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -25258,6 +26427,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -25269,13 +26441,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 246: - return node; case 248: + return node; + case 250: return node.parent; - case 249: - return node.parent.parent; case 251: + return node.parent.parent; + case 253: return node.parent.parent.parent; default: return undefined; @@ -25285,7 +26457,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 257) { + if (node.moduleReference.kind === 259) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -25313,7 +26485,7 @@ var ts; } return true; } - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); @@ -25347,7 +26519,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 | 1920)) { + if (valueSymbol.flags & (67897832 | 1920)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -25400,7 +26572,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -25434,7 +26606,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 | 67901928 | 1920, true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 | 67897832 | 1920, true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -25444,27 +26616,27 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 246: - return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); case 248: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 250: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 249: - return getTargetOfNamespaceImport(node, dontRecursivelyResolve); case 251: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 253: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 255: - return getTargetOfExportSpecifier(node, 67216319 | 67901928 | 1920, dontRecursivelyResolve); - case 252: - case 202: + case 257: + return getTargetOfExportSpecifier(node, 67220415 | 67897832 | 1920, dontRecursivelyResolve); + case 254: + case 204: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 245: + case 247: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); default: return ts.Debug.fail(); } } function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 | 67901928 | 1920; } + if (excludes === void 0) { excludes = 67220415 | 67897832 | 1920; } if (!symbol) return false; return (symbol.flags & (2097152 | excludes)) === 2097152 || !!(symbol.flags & 2097152 && symbol.flags & 67108864); @@ -25498,7 +26670,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -25511,10 +26683,10 @@ var ts; var node = getDeclarationOfAliasSymbol(symbol); if (!node) return ts.Debug.fail(); - if (node.kind === 252) { + if (node.kind === 254) { checkExpressionCached(node.expression); } - else if (node.kind === 255) { + else if (node.kind === 257) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -25523,37 +26695,37 @@ var ts; } } function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { - if (entityName.kind === 71 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + if (entityName.kind === 72 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 71 || entityName.parent.kind === 146) { + if (entityName.kind === 72 || entityName.parent.kind === 148) { return resolveEntityName(entityName, 1920, false, dontResolveAlias); } else { - ts.Debug.assert(entityName.parent.kind === 246); - return resolveEntityName(entityName, 67216319 | 67901928 | 1920, false, dontResolveAlias); + ts.Debug.assert(entityName.parent.kind === 248); + return resolveEntityName(entityName, 67220415 | 67897832 | 1920, false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, undefined, 16 | 4); } function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(name) ? meaning & 67216319 : 0); + var namespaceMeaning = 1920 | (ts.isInJSFile(name) ? meaning & 67220415 : 0); var symbol; - if (name.kind === 71) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + if (name.kind === 72) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true); if (!symbol) { return symbolFromJSPrototype; } } - else if (name.kind === 146 || name.kind === 187) { - var left = name.kind === 146 ? name.left : name.expression; - var right = name.kind === 146 ? name.right : name.name; + else if (name.kind === 148 || name.kind === 189) { + var left = name.kind === 148 ? name.left : name.expression; + var right = name.kind === 148 ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -25561,7 +26733,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -25590,15 +26762,15 @@ var ts; ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, undefined, name, true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -25606,9 +26778,19 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3) { + ts.getAssignmentDeclarationKind(host.expression) === 3) { var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6) { + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -25616,8 +26798,18 @@ var ts; return symbol && symbol.valueDeclaration; } } - function resolveExternalModuleName(location, moduleReferenceExpression) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); } function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { if (isForAugmentation === void 0) { isForAugmentation = false; } @@ -25645,7 +26837,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { errorOnImplicitAnyModule(false, errorNode, resolvedModule, moduleReference); } return getMergedSymbol(sourceFile.symbol); @@ -25661,7 +26853,7 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -25691,7 +26883,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -25699,7 +26891,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json") && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -25711,23 +26903,26 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages(undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages(undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias), moduleSymbol)) || moduleSymbol; + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152) { return exported; } var merged = cloneSymbol(exported); @@ -25745,7 +26940,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!(symbol.flags & (1536 | 3)) && !ts.getDeclarationOfKind(symbol, 277)) { + if (!(symbol.flags & (1536 | 3)) && !ts.getDeclarationOfKind(symbol, 279)) { error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); return symbol; } @@ -25812,7 +27007,7 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 32764 ? undefined : getPropertyOfType(type, memberName); + return type.flags & 131068 ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { return symbol.flags & 32 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports") : @@ -25893,14 +27088,58 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } function getContainersOfSymbol(symbol, enclosingDeclaration) { var container = getParentOfSymbol(symbol); if (container) { var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920, false)) { - return ts.concatenate([container], additionalContainers); + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); } - return ts.append(additionalContainers, container); + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); } var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); if (!ts.length(candidates)) { @@ -25937,13 +27176,13 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67216319); + return !!(symbol.flags & 67220415 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67220415); } function findConstructorDeclaration(node) { var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 155 && ts.nodeIsPresent(member.body)) { + if (member.kind === 157 && ts.nodeIsPresent(member.body)) { return member; } } @@ -25966,7 +27205,7 @@ var ts; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(131072); + var type = createType(524288); type.objectFlags = objectFlags; type.symbol = symbol; type.members = undefined; @@ -26016,11 +27255,11 @@ var ts; } } switch (location.kind) { - case 277: + case 279: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 242: + case 244: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -26030,7 +27269,7 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 67216319 ? 67216319 : 1920; + return rightMeaning === 67220415 ? 67220415 : 1920; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -26069,7 +27308,8 @@ var ts; && symbolFromSymbolTable.escapedName !== "export=" && symbolFromSymbolTable.escapedName !== "default" && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -26098,7 +27338,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 255)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -26112,10 +27352,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 152: case 154: case 156: - case 157: + case 158: + case 159: continue; default: return false; @@ -26126,11 +27366,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832, false); return access.accessibility === 0; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415, false); return access.accessibility === 0; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -26154,7 +27394,14 @@ var ts; }; } } - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -26196,10 +27443,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 277 && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 279 && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 277 && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -26239,17 +27486,17 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 165 || + if (entityName.parent.kind === 167 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 147) { - meaning = 67216319 | 1048576; + entityName.parent.kind === 149) { + meaning = 67220415 | 1048576; } - else if (entityName.kind === 146 || entityName.kind === 187 || - entityName.parent.kind === 246) { + else if (entityName.kind === 148 || entityName.kind === 189 || + entityName.parent.kind === 248) { meaning = 1920; } else { - meaning = 67901928; + meaning = 67897832; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); @@ -26261,7 +27508,7 @@ var ts; } function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { if (flags === void 0) { flags = 4; } - var nodeFlags = 3112960; + var nodeFlags = 70221824; if (flags & 2) { nodeFlags |= 128; } @@ -26271,6 +27518,9 @@ var ts; if (flags & 8) { nodeFlags |= 16384; } + if (flags & 16) { + nodeFlags |= 134217728; + } var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -26287,15 +27537,15 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144) { - sigOutput = kind === 1 ? 164 : 163; + sigOutput = kind === 1 ? 166 : 165; } else { - sigOutput = kind === 1 ? 159 : 158; + sigOutput = kind === 1 ? 161 : 160; } - var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512); + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 | 512); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4, sig, sourceFile, writer); + printer.writeNode(4, sig, sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); return writer; } } @@ -26303,7 +27553,7 @@ var ts; if (flags === void 0) { flags = 1048576 | 16384; } if (writer === void 0) { writer = ts.createTextWriter(""); } var noTruncation = compilerOptions.noErrorTruncation || flags & 1; - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | (noTruncation ? 1 : 0), writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 | (noTruncation ? 1 : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -26353,9 +27603,14 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, - visitedSymbols: undefined, + visitedTypes: undefined, + symbolDepth: undefined, inferTypeParameters: undefined, approximateLength: 0 }; @@ -26379,85 +27634,92 @@ var ts; } if (type.flags & 1) { context.approximateLength += 3; - return ts.createKeywordTypeNode(119); + return ts.createKeywordTypeNode(120); } if (type.flags & 2) { - return ts.createKeywordTypeNode(142); + return ts.createKeywordTypeNode(143); } if (type.flags & 4) { context.approximateLength += 6; - return ts.createKeywordTypeNode(137); + return ts.createKeywordTypeNode(138); } if (type.flags & 8) { context.approximateLength += 6; - return ts.createKeywordTypeNode(134); + return ts.createKeywordTypeNode(135); + } + if (type.flags & 64) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146); } if (type.flags & 16) { context.approximateLength += 7; - return ts.createKeywordTypeNode(122); + return ts.createKeywordTypeNode(123); } - if (type.flags & 512 && !(type.flags & 262144)) { + if (type.flags & 1024 && !(type.flags & 1048576)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928, false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(enumLiteralName, undefined); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), undefined)); + return enumLiteralName; } - if (type.flags & 544) { - var name = symbolToName(type.symbol, context, 67901928, false); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(name, undefined); + if (type.flags & 1056) { + return symbolToTypeNode(type.symbol, context, 67897832); } - if (type.flags & 64) { + if (type.flags & 128) { context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } - if (type.flags & 128) { + if (type.flags & 256) { context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } - if (type.flags & 256) { + if (type.flags & 2048) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512) { context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 2048) { + if (type.flags & 8192) { if (!(context.flags & 1048576)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319); + return symbolToTypeNode(type.symbol, context, 67220415); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } context.approximateLength += 13; - return ts.createTypeOperatorNode(141, ts.createKeywordTypeNode(138)); - } - if (type.flags & 4096) { - context.approximateLength += 4; - return ts.createKeywordTypeNode(105); - } - if (type.flags & 8192) { - context.approximateLength += 9; - return ts.createKeywordTypeNode(140); + return ts.createTypeOperatorNode(142, ts.createKeywordTypeNode(139)); } if (type.flags & 16384) { context.approximateLength += 4; - return ts.createKeywordTypeNode(95); + return ts.createKeywordTypeNode(106); } if (type.flags & 32768) { + context.approximateLength += 9; + return ts.createKeywordTypeNode(141); + } + if (type.flags & 65536) { + context.approximateLength += 4; + return ts.createKeywordTypeNode(96); + } + if (type.flags & 131072) { context.approximateLength += 5; - return ts.createKeywordTypeNode(131); + return ts.createKeywordTypeNode(132); } - if (type.flags & 1024) { + if (type.flags & 4096) { context.approximateLength += 6; - return ts.createKeywordTypeNode(138); + return ts.createKeywordTypeNode(139); } - if (type.flags & 16777216) { + if (type.flags & 67108864) { context.approximateLength += 6; - return ts.createKeywordTypeNode(135); + return ts.createKeywordTypeNode(136); } - if (type.flags & 65536 && type.isThisType) { + if (type.flags & 262144 && type.isThisType) { if (context.flags & 4194304) { if (!context.encounteredError && !(context.flags & 32768)) { context.encounteredError = true; @@ -26471,16 +27733,16 @@ var ts; } var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4) { - ts.Debug.assert(!!(type.flags & 131072)); + ts.Debug.assert(!!(type.flags & 524288)); return typeReferenceToTypeNode(type); } - if (type.flags & 65536 || objectFlags & 3) { - if (type.flags & 65536 && ts.contains(context.inferTypeParameters, type)) { + if (type.flags & 262144 || objectFlags & 3) { + if (type.flags & 262144 && ts.contains(context.inferTypeParameters, type)) { context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, undefined)); } if (context.flags & 4 && - type.flags & 65536 && + type.flags & 262144 && ts.length(type.symbol.declarations) && ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && @@ -26490,20 +27752,23 @@ var ts; return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 | 8), undefined); } return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928) + ? symbolToTypeNode(type.symbol, context, 67897832) : ts.createTypeReferenceNode(ts.createIdentifier("?"), undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832, typeArgumentNodes); } - if (type.flags & (262144 | 524288)) { - var types = type.flags & 262144 ? formatUnionTypes(type.types) : type.types; + if (type.flags & (1048576 | 2097152)) { + var types = type.flags & 1048576 ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, true); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 ? 171 : 172, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 ? 173 : 174, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -26514,22 +27779,22 @@ var ts; } } if (objectFlags & (16 | 32)) { - ts.Debug.assert(!!(type.flags & 131072)); + ts.Debug.assert(!!(type.flags & 524288)); return createAnonymousTypeNode(type); } - if (type.flags & 1048576) { + if (type.flags & 4194304) { var indexedType = type.type; context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 2097152) { + if (type.flags & 8388608) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } - if (type.flags & 4194304) { + if (type.flags & 16777216) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); var saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; @@ -26540,12 +27805,12 @@ var ts; context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } - if (type.flags & 8388608) { + if (type.flags & 33554432) { return typeToTypeNodeHelper(type.typeVariable, context); } return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 131072)); + ts.Debug.assert(!!(type.flags & 524288)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; var appropriateConstraintTypeNode; @@ -26562,37 +27827,46 @@ var ts; return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { + var typeId = "" + type.id; var symbol = type.symbol; var id; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 : 67216319; + if (isJSConstructor(symbol.valueDeclaration)) { + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 : 67220415; return symbolToTypeNode(symbol, context, isInstanceType); } - else if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 && context.flags & 2048) || + else if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319); + return symbolToTypeNode(symbol, context, 67220415); } - else if (context.visitedSymbols && context.visitedSymbols.has(id)) { + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - return symbolToTypeNode(typeAlias, context, 67901928); + return symbolToTypeNode(typeAlias, context, 67897832); } else { - context.approximateLength += 3; - return ts.createKeywordTypeNode(119); + return createElidedInformationPlaceholder(context); } } else { - if (!context.visitedSymbols) { - context.visitedSymbols = ts.createMap(); + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); } - context.visitedSymbols.set(id, true); + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); var result = createTypeNodeFromObjectType(type); - context.visitedSymbols.delete(id); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); return result; } } @@ -26605,10 +27879,10 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 277 || declaration.parent.kind === 243; + return declaration.parent.kind === 279 || declaration.parent.kind === 245; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return (!!(context.flags & 4096) || (context.visitedSymbols && context.visitedSymbols.has(id))) && + return (!!(context.flags & 4096) || (context.visitedTypes && context.visitedTypes.has(typeId))) && (!(context.flags & 8) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); } } @@ -26625,12 +27899,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 163, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 164, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166, context); return signatureNode; } } @@ -26657,8 +27931,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -26694,7 +27968,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16; - var ref = symbolToTypeNode(parent, context, 67901928, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -26707,7 +27981,7 @@ var ts; } var flags = context.flags; context.flags |= 16; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -26755,17 +28029,22 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 158, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 159, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161, context)); } if (resolvedType.stringIndexInfo) { - var indexInfo = resolvedType.objectFlags & 2048 ? - createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : - resolvedType.stringIndexInfo; - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0, context)); + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context); + } + typeElements.push(indexSignature); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); @@ -26796,30 +28075,34 @@ var ts; return typeElements.length ? typeElements : undefined; } } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), undefined); + } + return ts.createKeywordTypeNode(120); + } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 && context.flags & 33554432 ? + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 | 1048576, undefined, undefined, true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319, true); + var propertyName = symbolToName(propertySymbol, context, 67220415, true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; + var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(56) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; if (propertySymbol.valueDeclaration) { @@ -26830,10 +28113,16 @@ var ts; } else { var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048) ? 33554432 : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + context.flags |= propertyIsReverseMapped ? 33554432 : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120); + } context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132)] : undefined; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133)] : undefined; if (modifiers) { context.approximateLength += 9; } @@ -26882,14 +28171,14 @@ var ts; } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 137 : 134); + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 138 : 135); var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); if (!indexInfo.type && !(context.flags & 2097152)) { context.encounteredError = true; } context.approximateLength += (name.length + 4); - return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(132)] : undefined, [indexingParameter], typeNode); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(133)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { var typeParameters; @@ -26900,7 +28189,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -26919,18 +28208,18 @@ var ts; returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } if (context.flags & 256) { - if (returnTypeNode && returnTypeNode.kind === 119) { + if (returnTypeNode && returnTypeNode.kind === 120) { returnTypeNode = undefined; } } else if (!returnTypeNode) { - returnTypeNode = ts.createKeywordTypeNode(119); + returnTypeNode = ts.createKeywordTypeNode(120); } context.approximateLength += 3; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928, undefined, type.symbol.escapedName, false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832, undefined, type.symbol.escapedName, false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -26941,7 +28230,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8) - : symbolToName(type.symbol, context, 67901928, true); + : symbolToName(type.symbol, context, 67897832, true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -26953,9 +28242,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -26964,36 +28253,48 @@ var ts; var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192; - var dotDotDotToken = isRest ? ts.createToken(24) : undefined; + var dotDotDotToken = isRest ? ts.createToken(25) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : - parameterDeclaration.name.kind === 146 ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216) : + parameterDeclaration.name.kind === 72 ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + parameterDeclaration.name.kind === 148 ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096; - var questionToken = isOptional ? ts.createToken(55) : undefined; + var questionToken = isOptional ? ts.createToken(56) : undefined; var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 184) { + if (clone.kind === 186) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 | 16777216); } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 | 1048576, undefined, undefined, true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64) && !(context.flags & 134217728)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, true)); ts.Debug.assert(chain && chain.length > 0); } @@ -27003,12 +28304,21 @@ var ts; return chain; function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128)); + var parentSpecifiers; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); - if (ts.length(parents)) { - for (var _i = 0, _a = parents; _i < _a.length; _i++) { - var parent = _a[_i]; + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); if (parentChain) { accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); @@ -27027,6 +28337,21 @@ var ts; } return [symbol]; } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + return -1; + } + return 1; + } + return 0; + } } } function typeParametersToTypeParameterDeclarations(symbol, context) { @@ -27061,7 +28386,7 @@ var ts; return top; } function getSpecifierForModuleSymbol(symbol, context) { - var file = ts.getDeclarationOfKind(symbol, 277); + var file = ts.getDeclarationOfKind(symbol, 279); if (file && file.moduleName !== undefined) { return file.moduleName; } @@ -27089,7 +28414,10 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -27097,11 +28425,17 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384)); - var isTypeOf = meaning === 67216319; + var isTypeOf = meaning === 67220415; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); @@ -27194,6 +28528,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216; } @@ -27234,7 +28571,7 @@ var ts; if (flags === void 0) { flags = 16384; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { - var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512)); + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 | 512)); var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4, predicate, sourceFile, writer); @@ -27247,12 +28584,12 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 24576)) { - if (t.flags & (256 | 512)) { - var baseType = t.flags & 256 ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 262144) { + if (!(t.flags & 98304)) { + if (t.flags & (512 | 1024)) { + var baseType = t.flags & 512 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -27262,9 +28599,9 @@ var ts; result.push(t); } } - if (flags & 16384) + if (flags & 65536) result.push(nullType); - if (flags & 8192) + if (flags & 32768) result.push(undefinedType); return result || types; } @@ -27279,8 +28616,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 175; }); - if (node.kind === 240) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177; }); + if (node.kind === 242) { return getSymbolOfNode(node); } } @@ -27288,11 +28625,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 243 && + node.parent.kind === 245 && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 277 || ts.isAmbientModule(location); + return location.kind === 279 || ts.isAmbientModule(location); } function getNameOfSymbolAsWritten(symbol, context) { if (context && symbol.escapedName === "default" && !(context.flags & 16384) && @@ -27305,27 +28642,30 @@ var ts; var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 235) { + if (declaration.parent && declaration.parent.kind === 237) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 207: - case 194: - case 195: + case 209: + case 196: + case 197: if (context && !context.encounteredError && !(context.flags & 131072)) { context.encounteredError = true; } - return declaration.kind === 207 ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 209 ? "(Anonymous class)" : "(Anonymous function)"; } } var nameType = symbol.nameType; if (nameType) { - if (nameType.flags & 64 && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + if (nameType.flags & 128 && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { return "\"" + ts.escapeString(nameType.value, 34) + "\""; } - if (nameType && nameType.flags & 2048) { + if (nameType && nameType.flags & 8192) { return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; } } @@ -27342,66 +28682,66 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 295: - case 302: + case 297: + case 304: return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 184: + case 186: return isDeclarationVisible(node.parent.parent); - case 235: + case 237: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } - case 242: - case 238: - case 239: + case 244: case 240: - case 237: case 241: - case 246: + case 242: + case 239: + case 243: + case 248: if (ts.isExternalModuleAugmentation(node)) { return true; } var parent = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 246 && parent.kind !== 277 && parent.flags & 4194304)) { + !(node.kind !== 248 && parent.kind !== 279 && parent.flags & 4194304)) { return isGlobalSourceFile(parent); } return isDeclarationVisible(parent); - case 152: - case 151: - case 156: - case 157: case 154: case 153: + case 158: + case 159: + case 156: + case 155: if (ts.hasModifier(node, 8 | 16)) { return false; } - case 155: - case 159: - case 158: + case 157: + case 161: case 160: - case 149: - case 243: - case 163: - case 164: - case 166: case 162: - case 167: - case 168: - case 171: - case 172: - case 175: - return isDeclarationVisible(node.parent); - case 248: - case 249: - case 251: - return false; - case 148: - case 277: + case 151: case 245: + case 165: + case 166: + case 168: + case 164: + case 169: + case 170: + case 173: + case 174: + case 177: + return isDeclarationVisible(node.parent); + case 250: + case 251: + case 253: + return false; + case 150: + case 279: + case 247: return true; - case 252: + case 254: return false; default: return false; @@ -27410,11 +28750,11 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 252) { - exportSymbol = resolveName(node, node.escapedText, 67216319 | 67901928 | 1920 | 2097152, undefined, node, false); + if (node.parent && node.parent.kind === 254) { + exportSymbol = resolveName(node, node.escapedText, 67220415 | 67897832 | 1920 | 2097152, undefined, node, false); } - else if (node.parent.kind === 255) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 | 67901928 | 1920 | 2097152); + else if (node.parent.kind === 257) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 | 67897832 | 1920 | 2097152); } var result; if (exportSymbol) { @@ -27434,7 +28774,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 | 67901928 | 1920, undefined, undefined, false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 | 67897832 | 1920, undefined, undefined, false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -27471,6 +28811,8 @@ var ts; switch (propertyName) { case 0: return !!getSymbolLinks(target).type; + case 5: + return !!(getNodeLinks(target).resolvedEnumType); case 2: return !!getSymbolLinks(target).declaredType; case 1: @@ -27479,6 +28821,8 @@ var ts; return !!target.resolvedReturnType; case 4: return !!target.immediateBaseConstraint; + case 6: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -27490,12 +28834,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 235: - case 236: + case 237: + case 238: + case 253: + case 252: case 251: case 250: - case 249: - case 248: return false; default: return true; @@ -27518,28 +28862,36 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } function isComputedNonLiteralName(name) { - return name.kind === 147 && !ts.isStringOrNumericLiteralLike(name.expression); + return name.kind === 149 && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 24576); }); - if (source.flags & 32768) { + source = filterType(source, function (t) { return !(t.flags & 98304); }); + if (source.flags & 131072) { return emptyObjectType; } - if (source.flags & 262144) { + if (source.flags & 1048576) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } - var members = ts.createSymbolTable(); - var names = ts.createUnderscoreEscapedMap(); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var name = properties_2[_i]; - names.set(ts.getTextOfPropertyName(name), true); + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - if (!names.has(prop.escapedName) + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576), omitKeyType) && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16)) && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getNonReadonlySymbol(prop)); + members.set(prop.escapedName, getSpreadSymbol(prop)); } } var stringIndexInfo = getIndexInfoOfType(source, 0); @@ -27558,8 +28910,11 @@ var ts; if (isTypeAny(parentType)) { return parentType; } + if (strictNullChecks && declaration.flags & 4194304 && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } var type; - if (pattern.kind === 182) { + if (pattern.kind === 184) { if (declaration.dotDotDotToken) { if (parentType.flags & 2 || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -27576,79 +28931,40 @@ var ts; } else { var name = declaration.propertyName || declaration.name; - var isLate = isLateBindableName(name); - var isWellKnown = ts.isComputedPropertyName(name) && ts.isWellKnownSymbolSyntactically(name.expression); - if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { - var exprType = checkExpression(name.expression); - if (isTypeAssignableToKind(exprType, 3072)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); - } - return anyType; - } - var indexerType = isTypeAssignableToKind(exprType, 168) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); - if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(parentType, 1)) { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType)); - } - } - return indexerType || anyType; - } - var nameType = isLate ? checkComputedPropertyName(name) : undefined; - var text = isLate ? getLateBoundNameFromType(nameType) : - isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : - ts.getTextOfPropertyName(name); - if (strictNullChecks && declaration.flags & 4194304 && ts.isParameterDeclaration(declaration)) { - parentType = getNonNullableType(parentType); - } - if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, 3072)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType)); - } - return anyType; - } - var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); - type = declaredType && getFlowTypeOfReference(declaration, declaredType) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || - getIndexTypeOfType(parentType, 0); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return errorType; - } + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); } } else { var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } } } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192)) { - type = getTypeWithFacts(type, 131072); + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768)) { + type = getTypeWithFacts(type, 524288); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -27660,22 +28976,22 @@ var ts; } function isNullOrUndefined(node) { var expr = ts.skipParentheses(node); - return expr.kind === 95 || expr.kind === 71 && getResolvedSymbol(expr) === undefinedSymbol; + return expr.kind === 96 || expr.kind === 72 && getResolvedSymbol(expr) === undefinedSymbol; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 185 && expr.elements.length === 0; + return expr.kind === 187 && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } return strictNullChecks && optional ? getOptionalType(type) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 224) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (65536 | 1048576) ? getExtractStringType(indexType) : stringType; + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 | 4194304) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 225) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227) { var forOfStatement = declaration.parent.parent; return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; } @@ -27688,8 +29004,8 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 235 && !ts.isBindingPattern(declaration.name) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1) && !(declaration.flags & 4194304)) { if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { return autoType; @@ -27698,10 +29014,10 @@ var ts; return autoArrayType; } } - if (declaration.kind === 149) { + if (declaration.kind === 151) { var func = declaration.parent; - if (func.kind === 157 && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 156); + if (func.kind === 159 && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -27712,15 +29028,21 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } var type = declaration.symbol.escapedName === "this" ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } if (declaration.initializer) { @@ -27735,15 +29057,15 @@ var ts; } return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -27751,14 +29073,14 @@ var ts; var types; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = ts.isBinaryExpression(declaration) ? declaration : + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -27766,35 +29088,35 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; if (!type) { var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; } } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(24576 | 134217728)); }) ? constructorTypes : types; + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 | 134217728)); }) ? constructorTypes : types; type = getUnionType(sourceTypes, 2); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~24576); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + if (filterType(widened, function (t) { return !!(t.flags & ~98304); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -27813,7 +29135,7 @@ var ts; type.objectFlags |= 16384; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -27826,10 +29148,35 @@ var ts; } return declaredType; } - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); - if (type.flags & 131072 && - special === 2 && + if (type.flags & 524288 && + kind === 2 && symbol.escapedName === "export=") { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -27853,18 +29200,16 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; } function isDeclarationInConstructor(expression) { var thisContainer = ts.getThisContainer(expression, false); - return thisContainer.kind === 155 || - thisContainer.kind === 237 || - (thisContainer.kind === 194 && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 157 || + thisContainer.kind === 239 || + (thisContainer.kind === 196 && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -27875,8 +29220,8 @@ var ts; return expression && isDeclarationInConstructor(expression); }); } - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, false).parent; return ts.isClassLike(parent) && parent; }); @@ -27884,7 +29229,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -27895,8 +29240,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -27932,7 +29277,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var hasRestElement = !!(lastElement && lastElement.kind === 184 && lastElement.dotDotDotToken); + var hasRestElement = !!(lastElement && lastElement.kind === 186 && lastElement.dotDotDotToken); if (elements.length === 0 || elements.length === 1 && hasRestElement) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } @@ -27948,7 +29293,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 182 + return pattern.kind === 184 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -27960,22 +29305,22 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - if (type.flags & 2048 && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 8192 && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } return getWidenedType(type); } type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 149 ? root.parent : root; + var memberDeclaration = root.kind === 151 ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -28007,18 +29352,25 @@ var ts; } if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } - if (declaration.kind === 252) { - return checkExpression(declaration.expression); + if (declaration.kind === 254) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } if (!pushTypeResolution(symbol, 0)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && - (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -28031,7 +29383,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -28053,6 +29405,12 @@ var ts; || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } @@ -28063,7 +29421,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 156) { + if (accessor.kind === 158) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -28090,9 +29448,9 @@ var ts; return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); } function getTypeOfAccessorsWorker(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 156); - var setter = ts.getDeclarationOfKind(symbol, 157); - if (getter && ts.isInJavaScriptFile(getter)) { + var getter = ts.getDeclarationOfKind(symbol, 158); + var setter = ts.getDeclarationOfKind(symbol, 159); + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -28116,14 +29474,12 @@ var ts; type = getReturnTypeFromBody(getter); } else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -28132,7 +29488,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156); + var getter_1 = ts.getDeclarationOfKind(symbol, 158); 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)); } } @@ -28140,13 +29496,13 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 2162688 ? baseConstructorType : undefined; + return baseConstructorType.flags & 8650752 ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -28171,9 +29527,9 @@ var ts; if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 202 || - declaration.kind === 187 && declaration.parent.kind === 202) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + else if (declaration.kind === 204 || + declaration.kind === 189 && declaration.parent.kind === 204) { + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -28182,11 +29538,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=")); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16, symbol); @@ -28206,7 +29562,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 67216319 + links.type = targetSymbol.flags & 67220415 ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -28215,22 +29571,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -28284,7 +29632,7 @@ var ts; var target = getTargetType(type); return target === checkBase || ts.some(getBaseTypes(target), check); } - else if (type.flags & 524288) { + else if (type.flags & 2097152) { return ts.some(type.types, check); } return false; @@ -28304,51 +29652,51 @@ var ts; return undefined; } switch (node.kind) { - case 238: - case 207: - case 239: - case 158: - case 159: - case 153: - case 163: - case 164: - case 287: - case 237: - case 154: - case 194: - case 195: case 240: - case 301: - case 302: - case 295: - case 179: - case 173: + case 209: + case 241: + case 160: + case 161: + case 155: + case 165: + case 166: + case 289: + case 239: + case 156: + case 196: + case 197: + case 242: + case 303: + case 304: + case 297: + case 181: + case 175: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 179) { + if (node.kind === 181) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 173) { + else if (node.kind === 175) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 238 || node.kind === 207 || node.kind === 239) && + (node.kind === 240 || node.kind === 209 || node.kind === 241) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 239); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241); return getOuterTypeParameters(declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 239 || - node.kind === 238 || - node.kind === 207 || + if (node.kind === 241 || + node.kind === 240 || + node.kind === 209 || ts.isTypeAlias(node)) { var declaration = node; result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); @@ -28371,27 +29719,24 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { return true; } - if (type.flags & 2162688) { + if (type.flags & 8650752) { var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -28409,7 +29754,7 @@ var ts; ts.Debug.assert(!extended.typeArguments); checkExpression(extended.expression); } - if (baseConstructorType.flags & (131072 | 524288)) { + if (baseConstructorType.flags & (524288 | 2097152)) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -28417,7 +29762,18 @@ var ts; return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & 1) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } return type.resolvedBaseConstructorType = errorType; } type.resolvedBaseConstructorType = baseConstructorType; @@ -28446,13 +29802,15 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (131072 | 524288 | 1))) { + if (!(baseConstructorType.flags & (524288 | 2097152 | 1))) { return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); @@ -28460,8 +29818,8 @@ var ts; else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); @@ -28475,7 +29833,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { @@ -28497,14 +29855,14 @@ var ts; return true; } function isValidBaseType(type) { - return !!(type.flags & (131072 | 16777216 | 1)) && !isGenericMappedType(type) || - !!(type.flags & 524288) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 | 67108864 | 1)) && !isGenericMappedType(type) || + !!(type.flags & 2097152) && ts.every(type.types, isValidBaseType); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 241 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -28523,7 +29881,7 @@ var ts; } } else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -28533,7 +29891,7 @@ var ts; function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239) { + if (declaration.kind === 241) { if (declaration.flags & 64) { return false; } @@ -28542,7 +29900,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928, true); + var baseSymbol = resolveEntityName(node.expression, 67897832, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -28569,7 +29927,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536); + type.thisType = createType(262144); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -28584,7 +29942,7 @@ var ts; return errorType; } var declaration = ts.find(symbol.declarations, function (d) { - return ts.isJSDocTypeAlias(d) || d.kind === 240; + return ts.isJSDocTypeAlias(d) || d.kind === 242; }); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; @@ -28605,10 +29963,10 @@ var ts; return links.declaredType; } function isStringConcatExpression(expr) { - if (expr.kind === 9) { + if (expr.kind === 10) { return true; } - else if (expr.kind === 202) { + else if (expr.kind === 204) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -28619,15 +29977,15 @@ var ts; return !(member.flags & 4194304); } switch (expr.kind) { - case 9: + case 10: case 8: return true; - case 200: - return expr.operator === 38 && - expr.operand.kind === 8; - case 71: - return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); case 202: + return expr.operator === 39 && + expr.operand.kind === 8; + case 72: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + case 204: return isStringConcatExpression(expr); default: return false; @@ -28641,10 +29999,10 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241) { + if (declaration.kind === 243) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (member.initializer && member.initializer.kind === 9) { + if (member.initializer && member.initializer.kind === 10) { return links.enumKind = 1; } if (!isLiteralEnumMember(member)) { @@ -28656,7 +30014,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 : 1; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 512 && !(type.flags & 262144) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 1024 && !(type.flags & 1048576) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -28668,19 +30026,19 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241) { + if (declaration.kind === 243) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, 1, symbol, undefined); - if (enumType_1.flags & 262144) { - enumType_1.flags |= 512; + if (enumType_1.flags & 1048576) { + enumType_1.flags |= 1024; enumType_1.symbol = symbol; } return links.declaredType = enumType_1; @@ -28703,7 +30061,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(65536); + var type = createType(262144); type.symbol = symbol; links.declaredType = type; } @@ -28742,22 +30100,23 @@ var ts; } function isThislessType(node) { switch (node.kind) { - case 119: - case 142: - case 137: - case 134: - case 122: + case 120: + case 143: case 138: case 135: - case 105: - case 140: - case 95: - case 131: - case 180: + case 146: + case 123: + case 139: + case 136: + case 106: + case 141: + case 96: + case 132: + case 182: return true; - case 167: + case 169: return isThislessType(node.elementType); - case 162: + case 164: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -28773,7 +30132,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 155 || (!!returnType && isThislessType(returnType))) && + return (node.kind === 157 || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -28782,12 +30141,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 152: - case 151: - return isThislessVariableLikeDeclaration(declaration); case 154: case 153: + return isThislessVariableLikeDeclaration(declaration); + case 156: case 155: + case 157: return isThislessFunctionLikeDeclaration(declaration); } } @@ -28825,7 +30184,7 @@ var ts; return type; } function isTypeUsableAsLateBoundName(type) { - return !!(type.flags & 2240); + return !!(type.flags & 8576); } function isLateBindableName(node) { return ts.isComputedPropertyName(node) @@ -28848,10 +30207,10 @@ var ts; return ts.isDynamicName(node) && !isLateBindableName(node); } function getLateBoundNameFromType(type) { - if (type.flags & 2048) { + if (type.flags & 8192) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192) { + if (type.flags & (128 | 256)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -28866,7 +30225,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319) { + if (symbolFlags & 67220415) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -28959,7 +30318,7 @@ var ts; return needApparentType ? getApparentType(ref) : ref; } } - else if (type.flags & 524288) { + else if (type.flags & 2097152) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } return needApparentType ? getApparentType(type) : type; @@ -29067,7 +30426,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, false, false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -29087,7 +30446,7 @@ var ts; function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { return s; } } @@ -29114,8 +30473,7 @@ var ts; } return result; } - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + function getUnionSignatures(signatureLists) { var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { @@ -29156,8 +30514,8 @@ var ts; return createIndexInfo(getUnionType(indexTypes, 2), isAnyReadonly); } function resolveUnionTypeMembers(type) { - var callSignatures = getUnionSignatures(type.types, 0); - var constructSignatures = getUnionSignatures(type.types, 1); + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0); var numberIndexInfo = getUnionIndexInfo(type.types, 1); setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -29190,7 +30548,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { var signatures = getSignaturesOfType(t, 1); @@ -29208,7 +30566,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -29242,7 +30600,7 @@ var ts; if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (131072 | 524288 | 2162688)) { + if (baseConstructorType.flags & (524288 | 2097152 | 8650752)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -29254,6 +30612,7 @@ var ts; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); if (symbol.flags & (16 | 8192)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); @@ -29270,7 +30629,7 @@ var ts; var modifiers = getMappedTypeModifiers(type.mappedType); var readonlyMask = modifiers & 1 ? false : true; var optionalMask = modifiers & 4 ? 0 : 16777216; - var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; @@ -29280,6 +30639,7 @@ var ts; inferredProp.nameType = prop.nameType; inferredProp.propertyType = getTypeOfSymbol(prop); inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -29294,11 +30654,11 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); var templateModifiers = getMappedTypeModifiers(type); - var include = keyofStringsOnly ? 64 : 2240; + var include = keyofStringsOnly ? 128 : 8576; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); } if (modifiersType.flags & 1 || getIndexInfoOfType(modifiersType, 0)) { addMemberForKeyType(stringType); @@ -29308,15 +30668,14 @@ var ts; } } else { - var keyType = constraintType.flags & 14745600 ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 1048576 ? getIndexType(getApparentType(keyType.type)) : keyType; + var iterationType = constraintType.flags & 4194304 ? getIndexType(getApparentType(constraintType.type)) : constraintType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); function addMemberForKeyType(t) { var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); var propType = instantiateType(templateType, templateMapper); - if (t.flags & 2240) { + if (t.flags & 8576) { var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 || @@ -29325,7 +30684,7 @@ var ts; !(templateModifiers & 2) && modifiersProp && isReadonlySymbol(modifiersProp)); var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName, isReadonly ? 8 : 0); prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 ? getTypeWithFacts(propType, 131072) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 ? getTypeWithFacts(propType, 524288) : propType; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; @@ -29348,7 +30707,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -29361,8 +30720,8 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); - return constraintDeclaration.kind === 177 && - constraintDeclaration.operator === 128; + return constraintDeclaration.kind === 179 && + constraintDeclaration.operator === 129; } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { @@ -29372,16 +30731,16 @@ var ts; else { var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 65536 ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 1048576 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 262144 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } function getMappedTypeModifiers(type) { var declaration = type.declaration; - return (declaration.readonlyToken ? declaration.readonlyToken.kind === 38 ? 2 : 1 : 0) | - (declaration.questionToken ? declaration.questionToken.kind === 38 ? 8 : 4 : 0); + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 ? 2 : 1 : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 ? 8 : 4 : 0); } function getMappedTypeOptionality(type) { var modifiers = getMappedTypeModifiers(type); @@ -29400,7 +30759,7 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072) { + if (type.flags & 524288) { if (type.objectFlags & 4) { resolveTypeReferenceMembers(type); } @@ -29417,23 +30776,23 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 262144) { + else if (type.flags & 1048576) { resolveUnionTypeMembers(type); } - else if (type.flags & 524288) { + else if (type.flags & 2097152) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 131072) { + if (type.flags & 524288) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 131072) { + if (type.flags & 524288) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -29455,7 +30814,7 @@ var ts; } } } - if (type.flags & 262144) { + if (type.flags & 1048576) { break; } } @@ -29465,12 +30824,13 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 786432 ? + return type.flags & 3145728 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { - return obj.properties.some(function (property) { + var list = obj.properties; + return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); @@ -29478,7 +30838,7 @@ var ts; } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 262144)) { + if (!(unionType.flags & 1048576)) { return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); @@ -29496,35 +30856,45 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 65536 ? getConstraintOfTypeParameter(type) : - type.flags & 2097152 ? getConstraintOfIndexedAccess(type) : - type.flags & 4194304 ? getConstraintOfConditionalType(type) : + return type.flags & 262144 ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { var rootTrueType = type.root.trueType; - var rootTrueConstraint = rootTrueType.flags & 8388608 ? rootTrueType.substitute : rootTrueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); } return type.resolvedDefaultConstraint; } function getConstraintOfDistributiveConditionalType(type) { if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); - if (!(instantiated.flags & 32768)) { + if (!(instantiated.flags & 131072)) { return instantiated; } } @@ -29539,19 +30909,19 @@ var ts; var hasDisjointDomainType = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 15794176) { + if (t.flags & 63176704) { var constraint = getConstraintOfType(t); - while (constraint && constraint.flags & (65536 | 1048576 | 4194304)) { + while (constraint && constraint.flags & (262144 | 4194304 | 16777216)) { constraint = getConstraintOfType(constraint); } if (constraint) { - if (!(constraint.flags & 262144)) { + if (!(constraint.flags & 1048576)) { return undefined; } constraints = ts.append(constraints, constraint); } } - else if (t.flags & 16809468) { + else if (t.flags & 67238908) { hasDisjointDomainType = true; } } @@ -29559,7 +30929,7 @@ var ts; if (hasDisjointDomainType) { for (var _b = 0, _c = type.types; _b < _c.length; _b++) { var t = _c[_b]; - if (t.flags & 16809468) { + if (t.flags & 67238908) { constraints = ts.append(constraints, t); } } @@ -29569,11 +30939,11 @@ var ts; return undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (14745600 | 786432)) { + if (type.flags & (58982400 | 3145728)) { var constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - return type.flags & 1048576 ? keyofConstraintType : undefined; + return type.flags & 4194304 ? keyofConstraintType : undefined; } function getBaseConstraintOrType(type) { return getBaseConstraintOfType(type) || type; @@ -29582,6 +30952,7 @@ var ts; return getResolvedBaseConstraint(type) !== circularConstraintType; } function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -29589,8 +30960,14 @@ var ts; if (!pushTypeResolution(t, 4)) { return circularConstraintType; } + if (constraintDepth === 50) { + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -29602,45 +30979,42 @@ var ts; return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { - if (t.flags & 65536) { + if (t.flags & 262144) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint); } - if (t.flags & 786432) { + if (t.flags & 3145728) { var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 262144 && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 524288 && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 1048576 && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 1048576) { + if (t.flags & 4194304) { return keyofConstraintType; } - if (t.flags & 2097152) { + if (t.flags & 8388608) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } - if (t.flags & 4194304) { + if (t.flags & 16777216) { var constraint = getConstraintOfConditionalType(t); return constraint && getBaseConstraint(constraint); } - if (t.flags & 8388608) { + if (t.flags & 33554432) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -29677,21 +31051,37 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } function getApparentType(type) { - var t = type.flags & 15794176 ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 ? globalStringType : - t.flags & 168 ? globalNumberType : - t.flags & 272 ? globalBooleanType : - t.flags & 3072 ? getGlobalESSymbolType(languageVersion >= 2) : - t.flags & 16777216 ? emptyObjectType : - t.flags & 1048576 ? keyofConstraintType : - t; + var t = type.flags & 63176704 ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 ? globalStringType : + t.flags & 296 ? globalNumberType : + t.flags & 2112 ? getGlobalBigIntType(languageVersion >= 6) : + t.flags & 528 ? globalBooleanType : + t.flags & 12288 ? getGlobalESSymbolType(languageVersion >= 2) : + t.flags & 67108864 ? emptyObjectType : + t.flags & 4194304 ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var indexTypes; - var isUnion = containingType.flags & 262144; + var isUnion = containingType.flags & 1048576; var excludeModifiers = isUnion ? 24 : 0; var commonFlags = isUnion ? 0 : 16777216; var syntheticFlag = 4; @@ -29715,10 +31105,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1)) || getIndexInfoOfType(type, 0)); - if (index) { - checkFlags |= index.isReadonly ? 8 : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1) || getIndexInfoOfType(type, 0)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16; @@ -29789,27 +31179,31 @@ var ts; } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 131072) { + if (type.flags & 524288) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 786432) { + if (type.flags & 3145728) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 917504) { + if (type.flags & 3670016) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -29819,7 +31213,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 917504) { + if (type.flags & 3670016) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -29867,10 +31261,10 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && (node.type && node.type.kind === 286 + return ts.isInJSFile(node) && (node.type && node.type.kind === 288 || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -29903,7 +31297,7 @@ var ts; return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288; } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -29924,27 +31318,29 @@ var ts; } function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { - if (!typeArguments) { - typeArguments = []; - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { - defaultType = anyType; - } - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - typeArguments.length = typeParameters.length; - } + if (!numTypeParameters) { + return []; } - return typeArguments; + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); @@ -29957,7 +31353,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -29966,7 +31362,7 @@ var ts; var paramSymbol = param.symbol; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319, undefined, undefined, false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415, undefined, undefined, false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -29976,7 +31372,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 180) { + if (type && type.kind === 182) { hasLiteralTypes = true; } var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -29988,20 +31384,20 @@ var ts; minArgumentCount = parameters.length; } } - if ((declaration.kind === 156 || declaration.kind === 157) && + if ((declaration.kind === 158 || declaration.kind === 159) && !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 156 ? 157 : 156; + var otherKind = declaration.kind === 158 ? 159 : 158; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 155 ? + var classType = declaration.kind === 157 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, undefined, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; @@ -30024,7 +31420,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -30047,13 +31443,13 @@ var ts; if (!node) return false; switch (node.kind) { - case 71: + case 72: return node.escapedText === "arguments" && ts.isExpressionNode(node); - case 152: case 154: case 156: - case 157: - return node.name.kind === 147 + case 158: + case 159: + return node.name.kind === 149 && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -30108,7 +31504,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -30125,7 +31521,7 @@ var ts; function createTypePredicateFromTypePredicateNode(node, func) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71) { + if (parameterName.kind === 72) { return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); } else { @@ -30135,7 +31531,7 @@ var ts; function getTypePredicateParameterIndex(parameterList, parameter) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 71 && param.name.escapedText === parameter.escapedText) { + if (param.name.kind === 72 && param.name.escapedText === parameter.escapedText) { return i; } } @@ -30149,6 +31545,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -30174,7 +31571,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 155) { + if (declaration.kind === 157) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -30184,12 +31581,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 156 && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (declaration.kind === 158 && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -30204,8 +31601,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -30239,7 +31640,7 @@ var ts; signature; } function createCanonicalSignature(signature) { - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -30252,7 +31653,7 @@ var ts; } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 155 || signature.declaration.kind === 159; + var isConstructor = signature.declaration.kind === 157 || signature.declaration.kind === 161; var type = createObjectType(16); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -30266,7 +31667,7 @@ var ts; return symbol.members.get("__index"); } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 134 : 137; + var syntaxKind = kind === 1 ? 135 : 138; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -30293,7 +31694,7 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148); + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150); return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { @@ -30301,9 +31702,9 @@ var ts; if (typeParameter.symbol) { for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.parent.kind === 174) { + if (declaration.parent.kind === 176) { var grandParent = declaration.parent.parent; - if (grandParent.kind === 162) { + if (grandParent.kind === 164) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -30320,7 +31721,7 @@ var ts; } } } - else if (grandParent.kind === 149 && grandParent.dotDotDotToken) { + else if (grandParent.kind === 151 && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } } @@ -30343,7 +31744,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -30409,10 +31810,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -30438,7 +31839,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -30460,9 +31861,9 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 162: + case 164: return node.typeName; - case 209: + case 211: var expr = node.expression; if (ts.isEntityNameExpression(expr)) { return expr; @@ -30485,32 +31886,50 @@ var ts; if (type) { return type; } + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 ? getConstrainedTypeVariable(res, node) : res : + res.flags & 262144 ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); if (jsdocType) { return jsdocType; } - resolveTypeReferenceName(getTypeReferenceName(node), 67901928); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832); return getTypeOfSymbol(symbol); } function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType || assignedType) { - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + if (referenceType || assignedType) { + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -30533,13 +31952,13 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { - var result = createType(8388608); + var result = createType(33554432); result.typeVariable = typeVariable; result.substitute = substitute; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 168 && node.elementTypes.length === 1; + return node.kind === 170 && node.elementTypes.length === 1; } function getImpliedConstraint(typeVariable, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : @@ -30548,9 +31967,9 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 289) { + while (node && !ts.isStatement(node) && node.kind !== 291) { var parent = node.parent; - if (parent.kind === 173 && node === parent.trueType) { + if (parent.kind === 175 && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -30561,7 +31980,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152) && (node.kind === 162 || node.kind === 181); + return !!(node.flags & 2097152) && (node.kind === 164 || node.kind === 183); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -30619,17 +32038,17 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getNullableType(type, 16384) : type; + return strictNullChecks ? getNullableType(type, 65536) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928; + var meaning = 67897832; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319; + meaning |= 67220415; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -30656,9 +32075,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 238: - case 239: + case 240: case 241: + case 243: return declaration; } } @@ -30667,7 +32086,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 131072)) { + if (!(type.flags & 524288)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } @@ -30678,10 +32097,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name, false); @@ -30708,6 +32127,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -30734,12 +32156,21 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928, undefined); + var symbol = getGlobalSymbol(name, 67897832, undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288, ts.Diagnostics.Cannot_find_global_type_0)); } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288, ts.Diagnostics.Cannot_find_global_type_0)); + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288, ts.Diagnostics.Cannot_find_global_type_0)); + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", 0, reportErrors)) || emptyObjectType; + } function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; } @@ -30778,7 +32209,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(65536); + var typeParameter = typeParameters[i] = createType(262144); if (i < maxLength) { var property = createSymbol(4 | (i >= minLength ? 16777216 : 0), "" + i); property.type = typeParameter; @@ -30800,7 +32231,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536); + type.thisType = createType(262144); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -30835,8 +32266,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var lastElement = ts.lastOrUndefined(node.elementTypes); - var restElement_1 = lastElement && lastElement.kind === 170 ? lastElement : undefined; - var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 169 && n !== restElement_1; }) + 1; + var restElement_1 = lastElement && lastElement.kind === 172 ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 && n !== restElement_1; }) + 1; var elementTypes = ts.map(node.elementTypes, function (n) { var type = getTypeFromTypeNode(n); return n === restElement_1 && getIndexTypeOfType(type, 1) || type; @@ -30845,6 +32276,13 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -30867,16 +32305,17 @@ var ts; var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 27072 && combined & 27072) { + if (t.flags & 109440 && combined & 109440) { return true; } combined |= t.flags; - if (combined & 24576 && combined & (131072 | 16777216) || - combined & 16777216 && combined & (16809468 & ~16777216) || - combined & 68 && combined & (16809468 & ~68) || - combined & 168 && combined & (16809468 & ~168) || - combined & 3072 && combined & (16809468 & ~3072) || - combined & 12288 && combined & (16809468 & ~12288)) { + if (combined & 98304 && combined & (524288 | 67108864) || + combined & 67108864 && combined & (67238908 & ~67108864) || + combined & 132 && combined & (67238908 & ~132) || + combined & 296 && combined & (67238908 & ~296) || + combined & 2112 && combined & (67238908 & ~2112) || + combined & 12288 && combined & (67238908 & ~12288) || + combined & 49152 && combined & (67238908 & ~49152)) { return true; } } @@ -30884,16 +32323,14 @@ var ts; } function addTypeToUnion(typeSet, includes, type) { var flags = type.flags; - if (flags & 262144) { + if (flags & 1048576) { return addTypesToUnion(typeSet, includes, type.types); } - if (!(flags & 32768 || flags & 524288 && isEmptyIntersectionType(type))) { + if (!(flags & 131072 || flags & 2097152 && isEmptyIntersectionType(type))) { includes |= flags & ~939524096; - if (flags & 3) { - if (type === wildcardType) - includes |= 268435456; - } - else if (!strictNullChecks && flags & 24576) { + if (type === wildcardType) + includes |= 268435456; + if (!strictNullChecks && flags & 98304) { if (!(flags & 134217728)) includes |= 134217728; } @@ -30901,10 +32338,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -30917,15 +32351,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - 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 isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -30939,11 +32364,11 @@ var ts; } function isSetOfLiteralsFromSameEnum(types) { var first = types[0]; - if (first.flags & 512) { + if (first.flags & 1024) { var firstEnum = getParentOfSymbol(first.symbol); for (var i = 1; i < types.length; i++) { var other = types[i]; - if (!(other.flags & 512) || (firstEnum !== getParentOfSymbol(other.symbol))) { + if (!(other.flags & 1024) || (firstEnum !== getParentOfSymbol(other.symbol))) { return false; } } @@ -30968,10 +32393,11 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 64 && includes & 4 || - t.flags & 128 && includes & 8 || - t.flags & 2048 && includes & 1024 || - t.flags & 192 && t.flags & 33554432 && containsType(types, t.regularType); + var remove = t.flags & 128 && includes & 4 || + t.flags & 256 && includes & 8 || + t.flags & 2048 && includes & 64 || + t.flags & 8192 && includes & 4096 || + isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -30987,25 +32413,27 @@ var ts; } var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); - if (includes & 3) { - return includes & 1 ? includes & 268435456 ? wildcardType : anyType : unknownType; + if (unionReduction !== 0) { + if (includes & 3) { + return includes & 1 ? includes & 268435456 ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1: + if (includes & 8576 | 512) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 ? includes & 134217728 ? nullType : nullWideningType : + includes & 32768 ? includes & 134217728 ? undefinedType : undefinedWideningType : + neverType; + } } - switch (unionReduction) { - case 1: - if (includes & 2240) { - removeRedundantLiteralTypes(typeSet, includes); - } - break; - case 2: - removeSubtypes(typeSet); - break; - } - if (typeSet.length === 0) { - return includes & 16384 ? includes & 134217728 ? nullType : nullWideningType : - includes & 8192 ? includes & 134217728 ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, includes & 16748579 ? 0 : 67108864, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211), aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -31039,7 +32467,7 @@ var ts; ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex : !ts.isIdentifierTypePredicate(b); } - function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -31049,10 +32477,11 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, 24576); - type = createType(262144 | propagatedFlags | unionOfUnitTypes); + var propagatedFlags = getPropagatingFlagsOfTypes(types, 98304); + type = createType(1048576 | propagatedFlags); unionTypes.set(id, type); type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } @@ -31068,11 +32497,14 @@ var ts; } function addTypeToIntersection(typeSet, includes, type) { var flags = type.flags; - if (flags & 524288) { + if (flags & 2097152) { return addTypesToIntersection(typeSet, includes, type.types); } - if (ts.getObjectFlags(type) & 16 && isEmptyObjectType(type)) { - includes |= 536870912; + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912)) { + includes |= 536870912; + typeSet.push(type); + } } else { includes |= flags & ~939524096; @@ -31080,18 +32512,15 @@ var ts; if (type === wildcardType) includes |= 268435456; } - else if ((strictNullChecks || !(flags & 24576)) && !ts.contains(typeSet, type) && - !(flags & 131072 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 98304)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } return includes; } function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -31101,9 +32530,10 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 4 && includes & 64 || - t.flags & 8 && includes & 128 || - t.flags & 1024 && includes & 2048; + var remove = t.flags & 4 && includes & 128 || + t.flags & 8 && includes & 256 || + t.flags & 64 && includes & 2048 || + t.flags & 4096 && includes & 8192; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -31113,10 +32543,11 @@ var ts; for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { var u = unionTypes_1[_i]; if (!containsType(u.types, type)) { - var primitive = type.flags & 64 ? stringType : - type.flags & 128 ? numberType : - type.flags & 2048 ? esSymbolType : - undefined; + var primitive = type.flags & 128 ? stringType : + type.flags & 256 ? numberType : + type.flags & 2048 ? bigintType : + type.flags & 8192 ? esSymbolType : + undefined; if (!primitive || !containsType(u.types, primitive)) { return false; } @@ -31126,11 +32557,14 @@ var ts; } function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return (t.flags & 67108864) !== 0; }); + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } var i = index + 1; while (i < types.length) { var t = types[i]; - if (t.flags & 67108864) { + if (t.flags & 1048576 && t.primitiveTypesOnly) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -31154,28 +32588,29 @@ var ts; } } } - types[index] = getUnionTypeFromSortedList(result, 67108864); + types[index] = getUnionTypeFromSortedList(result, true); return true; } function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); - if (includes & 32768) { + if (includes & 131072) { return neverType; } if (includes & 1) { return includes & 268435456 ? wildcardType : anyType; } - if (!strictNullChecks && includes & 24576) { - return includes & 8192 ? undefinedType : nullType; + if (!strictNullChecks && includes & 98304) { + return includes & 32768 ? undefinedType : nullType; } - if (includes & 4 && includes & 64 || - includes & 8 && includes & 128 || - includes & 1024 && includes & 2048) { + if (includes & 4 && includes & 128 || + includes & 8 && includes & 256 || + includes & 64 && includes & 2048 || + includes & 4096 && includes & 8192) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 536870912 && !(includes & 131072)) { - typeSet.push(emptyObjectType); + if (includes & 536870912 && includes & 524288) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { return unknownType; @@ -31183,19 +32618,19 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - if (includes & 262144) { - if (includes & 67108864 && intersectUnionsOfPrimitiveTypes(typeSet)) { + if (includes & 1048576) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); } - var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 262144) !== 0; }); + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576) !== 0; }); var unionType = typeSet[unionIndex_1]; return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 24576); - type = createType(524288 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 98304); + type = createType(2097152 | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; @@ -31212,7 +32647,7 @@ var ts; return links.resolvedType; } function createIndexType(type, stringsOnly) { - var result = createType(1048576); + var result = createType(4194304); result.type = type; result.stringsOnly = stringsOnly; return result; @@ -31222,14 +32657,22 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, false)); } - function getLiteralTypeFromPropertyName(prop, include) { + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) : - name && name.kind === 147 && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : - getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); } if (type && type.flags & include) { return type; @@ -31237,8 +32680,8 @@ var ts; } return neverType; } - function getLiteralTypeFromPropertyNames(type, include) { - return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromPropertyName(t, include); })); + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); } function getNonEnumNumberIndexInfo(type) { var numberIndexInfo = getIndexInfoOfType(type, 1); @@ -31246,16 +32689,16 @@ var ts; } function getIndexType(type, stringsOnly) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } - return type.flags & 262144 ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - type.flags & 524288 ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - maybeTypeOfKind(type, 14745600) ? getIndexTypeForGenericType(type, stringsOnly) : + return type.flags & 1048576 ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400) ? getIndexTypeForGenericType(type, stringsOnly) : ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : type === wildcardType ? wildcardType : type.flags & 1 ? keyofConstraintType : - stringsOnly ? getIndexInfoOfType(type, 0) ? stringType : getLiteralTypeFromPropertyNames(type, 64) : - getIndexInfoOfType(type, 0) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, 2048)]) : - getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, 64 | 2048)]) : - getLiteralTypeFromPropertyNames(type, 2240); + stringsOnly ? getIndexInfoOfType(type, 0) ? stringType : getLiteralTypeFromProperties(type, 128) : + getIndexInfoOfType(type, 0) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 | 8192)]) : + getLiteralTypeFromProperties(type, 8576); } function getExtractStringType(type) { if (keyofStringsOnly) { @@ -31266,17 +32709,17 @@ var ts; } function getIndexTypeOrString(type) { var indexType = getExtractStringType(getIndexType(type)); - return indexType.flags & 32768 ? stringType : indexType; + return indexType.flags & 131072 ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { switch (node.operator) { - case 128: + case 129: links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); break; - case 141: - links.resolvedType = node.type.kind === 138 + case 142: + links.resolvedType = node.type.kind === 139 ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) : errorType; break; @@ -31285,7 +32728,7 @@ var ts; return links.resolvedType; } function createIndexedAccessType(objectType, indexType) { - var type = createType(2097152); + var type = createType(8388608); type.objectType = objectType; type.indexType = indexType; return type; @@ -31297,56 +32740,62 @@ var ts; if (ts.getObjectFlags(type) & 16384) { return true; } - if (type.flags & 262144) { + if (type.flags & 1048576) { return ts.every(type.types, isJSLiteralType); } - if (type.flags & 524288) { + if (type.flags & 2097152) { return ts.some(type.types, isJSLiteralType); } - if (type.flags & 15794176) { + if (type.flags & 63176704) { return isJSLiteralType(getResolvedBaseConstraint(type)); } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 188 ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - undefined; + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 99); + markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 100); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } - if (!(indexType.flags & 24576) && isTypeAssignableToKind(indexType, 68 | 168 | 3072)) { - if (objectType.flags & (1 | 32768)) { + if (!(indexType.flags & 98304) && isTypeAssignableToKind(indexType, 132 | 296 | 12288)) { + if (objectType.flags & (1 | 131072)) { return objectType; } - var indexInfo = isTypeAssignableToKind(indexType, 168) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAssignableToKind(indexType, 296) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { if (accessNode && !isTypeAssignableToKind(indexType, 4 | 8)) { - var indexNode = accessNode.kind === 188 ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = getIndexNodeForAccessExpression(accessNode); error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { @@ -31354,7 +32803,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768) { + if (indexType.flags & 131072) { return neverType; } if (isJSLiteralType(objectType)) { @@ -31380,15 +32829,15 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { return anyType; } if (accessNode) { - var indexNode = accessNode.kind === 188 ? accessNode.argumentExpression : accessNode.indexType; - if (indexType.flags & (64 | 128)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 | 256)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (4 | 8)) { @@ -31398,28 +32847,36 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 + ? accessNode.argumentExpression + : accessNode.kind === 180 + ? accessNode.indexType + : accessNode.kind === 149 + ? accessNode.expression + : accessNode; } function isGenericObjectType(type) { - return maybeTypeOfKind(type, 14745600 | 134217728); + return maybeTypeOfKind(type, 58982400 | 134217728); } function isGenericIndexType(type) { - return maybeTypeOfKind(type, 14745600 | 1048576); - } - function isStringIndexOnlyType(type) { - if (type.flags & 131072 && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32) && getTemplateTypeFromMappedType(type) === neverType; + return maybeTypeOfKind(type, 58982400 | 4194304); } function getSimplifiedType(type) { - return type.flags & 2097152 ? getSimplifiedIndexedAccessType(type) : type; + return type.flags & 8388608 ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + if (objectType.flags & 1048576) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + if (objectType.flags & 2097152) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } } function getSimplifiedIndexedAccessType(type) { if (type.simplified) { @@ -31427,33 +32884,20 @@ var ts; } type.simplified = circularConstraintType; var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 && isGenericObjectType(objectType)) { - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); - } - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + var indexType = getSimplifiedType(type.indexType); + if (indexType.flags & 1048576) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + if (!(indexType.flags & 63176704)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; } } if (isGenericMappedType(objectType)) { return type.simplified = substituteIndexedMappedType(objectType, type); } - if (objectType.flags & 65536) { + if (objectType.flags & 262144) { var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); @@ -31466,11 +32910,12 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 188) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180) && isGenericObjectType(objectType)) { if (objectType.flags & 3) { return objectType; } @@ -31482,19 +32927,28 @@ var ts; return type; } var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 262144 && !(indexType.flags & 16)) { + if (indexType.flags & 1048576 && !(indexType.flags & 16)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false, missingType); + if (propType === missingType) { + if (!accessNode) { + return missingType; + } + else { + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -31502,7 +32956,7 @@ var ts; var objectType = getTypeFromTypeNode(node.objectType); var indexType = getTypeFromTypeNode(node.indexType); var resolved = getIndexedAccessType(objectType, indexType, node); - links.resolvedType = resolved.flags & 2097152 && + links.resolvedType = resolved.flags & 8388608 && resolved.objectType === objectType && resolved.indexType === indexType ? getConstrainedTypeVariable(resolved, node) : resolved; @@ -31522,7 +32976,7 @@ var ts; return links.resolvedType; } function getActualTypeVariable(type) { - return type.flags & 8388608 ? type.typeVariable : type; + return type.flags & 33554432 ? type.typeVariable : type; } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); @@ -31530,7 +32984,7 @@ var ts; if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 15794176); + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, undefined, 0); @@ -31555,7 +33009,7 @@ var ts; } } var erasedCheckType = getActualTypeVariable(checkType); - var result = createType(4194304); + var result = createType(16777216); result.root = root; result.checkType = erasedCheckType; result.extendsType = extendsType; @@ -31587,7 +33041,7 @@ var ts; return true; } while (node) { - if (node.kind === 173) { + if (node.kind === 175) { if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { return true; } @@ -31610,7 +33064,7 @@ var ts; extendsType: getTypeFromTypeNode(node.extendsType), trueType: getTypeFromTypeNode(node.trueType), falseType: getTypeFromTypeNode(node.falseType), - isDistributive: !!(checkType.flags & 65536), + isDistributive: !!(checkType.flags & 262144), inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, @@ -31653,7 +33107,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 : node.flags & 2097152 ? 67216319 | 67901928 : 67901928; + var targetMeaning = node.isTypeOf ? 67220415 : node.flags & 2097152 ? 67220415 | 67897832 : 67897832; var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; @@ -31682,7 +33136,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 + var errorMessage = targetMeaning === 67220415 ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -31696,7 +33150,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319) { + if (meaning === 67220415) { return links.resolvedType = getTypeOfSymbol(symbol); } else { @@ -31728,6 +33182,9 @@ var ts; function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288) && !isGenericMappedType(type); + } function getSpreadType(left, right, symbol, typeFlags, objectFlags) { if (left.flags & 1 || right.flags & 1) { return anyType; @@ -31735,21 +33192,34 @@ var ts; if (left.flags & 2 || right.flags & 2) { return unknownType; } - if (left.flags & 32768) { + if (left.flags & 131072) { return right; } - if (right.flags & 32768) { + if (right.flags & 131072) { return left; } - if (left.flags & 262144) { + if (left.flags & 1048576) { return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); } - if (right.flags & 262144) { + if (right.flags & 1048576) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); } - if (right.flags & (272 | 168 | 68 | 544 | 16777216 | 1048576)) { + if (right.flags & (528 | 296 | 2112 | 132 | 1056 | 67108864 | 4194304)) { return left; } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + if (left.flags & 2097152) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); var stringIndexInfo; @@ -31768,7 +33238,7 @@ var ts; skippedPrivateMembers.set(rightProp.escapedName, true); } else if (isSpreadableProperty(rightProp)) { - members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { @@ -31783,7 +33253,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 16777216); var result = createSymbol(flags, leftProp.escapedName); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -31792,26 +33262,27 @@ var ts; } } else { - members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= typeFlags | 268435456; - spread.objectFlags |= objectFlags | (128 | 1024); + spread.flags |= 268435456 | typeFlags; + spread.objectFlags |= 128 | 1024 | objectFlags; return spread; } function isSpreadableProperty(prop) { - return prop.flags & (8192 | 32768) - ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) - : !(prop.flags & 65536); + return !(prop.flags & (8192 | 32768 | 65536)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); + if (!isReadonly && !isSetonlyAccessor) { return prop; } var flags = 4 | (prop.flags & 16777216); var result = createSymbol(flags, prop.escapedName); - result.type = getTypeOfSymbol(prop); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); result.declarations = prop.declarations; result.nameType = prop.nameType; result.syntheticOrigin = prop; @@ -31830,10 +33301,11 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 && !(type.flags & 33554432)) { + if (type.flags & 2944) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 33554432, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; + freshType.freshType = freshType; type.freshType = freshType; } return type.freshType; @@ -31841,17 +33313,23 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 && type.flags & 33554432 ? type.regularType : - type.flags & 262144 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + return type.flags & 2944 ? type.regularType : + type.flags & 1048576 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } + function isFreshLiteralType(type) { + return !!(type.flags & 2944) && type.freshType === type; + } function getLiteralType(value, enumId, symbol) { - var qualifier = typeof value === "number" ? "#" : "@"; - var key = enumId ? enumId + qualifier + value : qualifier + value; + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); var type = literalTypes.get(key); if (!type) { - var flags = (typeof value === "number" ? 128 : 64) | (enumId ? 512 : 0); + var flags = (typeof value === "number" ? 256 : + typeof value === "string" ? 128 : 2048) | + (enumId ? 1024 : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; } return type; } @@ -31863,7 +33341,7 @@ var ts; return links.resolvedType; } function createUniqueESSymbolType(symbol) { - var type = createType(2048); + var type = createType(8192); type.symbol = symbol; return type; } @@ -31878,9 +33356,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 239)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 241)) { if (!ts.hasModifier(container, 32) && - (container.kind !== 155 || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 157 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -31896,85 +33374,87 @@ var ts; } function getTypeFromTypeNode(node) { switch (node.kind) { - case 119: - case 282: - case 283: - return anyType; - case 142: - return unknownType; - case 137: - return stringType; - case 134: - return numberType; - case 122: - return booleanType; - case 138: - return esSymbolType; - case 105: - return voidType; - case 140: - return undefinedType; - case 95: - return nullType; - case 131: - return neverType; - case 135: - return node.flags & 65536 ? anyType : nonPrimitiveType; - case 176: - case 99: - return getTypeFromThisTypeNode(node); - case 180: - return getTypeFromLiteralTypeNode(node); - case 162: - return getTypeFromTypeReference(node); - case 161: - return booleanType; - case 209: - return getTypeFromTypeReference(node); - case 165: - return getTypeFromTypeQueryNode(node); - case 167: - return getTypeFromArrayTypeNode(node); - case 168: - return getTypeFromTupleTypeNode(node); - case 169: - return getTypeFromOptionalTypeNode(node); - case 171: - return getTypeFromUnionTypeNode(node); - case 172: - return getTypeFromIntersectionTypeNode(node); + case 120: case 284: - return getTypeFromJSDocNullableTypeNode(node); - case 286: - return addOptionality(getTypeFromTypeNode(node.type)); - case 175: - case 170: case 285: - case 281: - return getTypeFromTypeNode(node.type); - case 288: - return getTypeFromJSDocVariadicType(node); - case 163: - case 164: - case 166: - case 290: - case 287: - case 291: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 177: - return getTypeFromTypeOperatorNode(node); - case 178: - return getTypeFromIndexedAccessTypeNode(node); - case 179: - return getTypeFromMappedTypeNode(node); - case 173: - return getTypeFromConditionalTypeNode(node); - case 174: - return getTypeFromInferTypeNode(node); - case 181: - return getTypeFromImportTypeNode(node); - case 71: + return anyType; + case 143: + return unknownType; + case 138: + return stringType; + case 135: + return numberType; case 146: + return bigintType; + case 123: + return booleanType; + case 139: + return esSymbolType; + case 106: + return voidType; + case 141: + return undefinedType; + case 96: + return nullType; + case 132: + return neverType; + case 136: + return node.flags & 65536 ? anyType : nonPrimitiveType; + case 178: + case 100: + return getTypeFromThisTypeNode(node); + case 182: + return getTypeFromLiteralTypeNode(node); + case 164: + return getTypeFromTypeReference(node); + case 163: + return booleanType; + case 211: + return getTypeFromTypeReference(node); + case 167: + return getTypeFromTypeQueryNode(node); + case 169: + return getTypeFromArrayTypeNode(node); + case 170: + return getTypeFromTupleTypeNode(node); + case 171: + return getTypeFromOptionalTypeNode(node); + case 173: + return getTypeFromUnionTypeNode(node); + case 174: + return getTypeFromIntersectionTypeNode(node); + case 286: + return getTypeFromJSDocNullableTypeNode(node); + case 288: + return addOptionality(getTypeFromTypeNode(node.type)); + case 177: + case 172: + case 287: + case 283: + return getTypeFromTypeNode(node.type); + case 290: + return getTypeFromJSDocVariadicType(node); + case 165: + case 166: + case 168: + case 292: + case 289: + case 293: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 179: + return getTypeFromTypeOperatorNode(node); + case 180: + return getTypeFromIndexedAccessTypeNode(node); + case 181: + return getTypeFromMappedTypeNode(node); + case 175: + return getTypeFromConditionalTypeNode(node); + case 176: + return getTypeFromInferTypeNode(node); + case 183: + return getTypeFromImportTypeNode(node); + case 72: + case 148: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -32037,7 +33517,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -32051,10 +33531,10 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function wildcardMapper(type) { - return type.flags & 65536 ? wildcardType : type; + return type.flags & 262144 ? wildcardType : type; } function cloneTypeParameter(typeParameter) { - var result = createType(65536); + var result = createType(262144); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -32092,7 +33572,7 @@ var ts; } function instantiateSymbol(symbol, mapper) { var links = getSymbolLinks(symbol); - if (links.type && !maybeTypeOfKind(links.type, 131072 | 15794176)) { + if (links.type && !maybeTypeOfKind(links.type, 524288 | 63176704)) { return symbol; } if (ts.getCheckFlags(symbol) & 1) { @@ -32119,7 +33599,7 @@ var ts; var typeParameters = links.outerTypeParameters; if (!typeParameters) { var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -32129,7 +33609,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -32158,55 +33638,65 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 146 || - node.parent.kind === 162 && node.parent.typeArguments && node === node.parent.typeName); + return !(node.kind === 148 || + node.parent.kind === 164 && node.parent.typeArguments && node === node.parent.typeName); } function isTypeParameterPossiblyReferenced(tp, node) { if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 216 ? "quit" : n === container_3; })) { + if (ts.findAncestor(node, function (n) { return n.kind === 218 ? "quit" : n === container_3; })) { return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { - case 176: + case 178: return !!tp.isThisType; - case 71: + case 72: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; - case 165: + case 167: return true; } return !!ts.forEachChild(node, containsReference); } } - function instantiateMappedType(type, mapper) { + function getHomomorphicTypeVariable(type) { var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + if (constraintType.flags & 4194304) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144) { + return typeVariable; + } + } + return undefined; + } + function instantiateMappedType(type, mapper) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 | 58982400 | 524288 | 2097152) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 | 14745600 | 131072 | 524288); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -32223,13 +33713,18 @@ var ts; var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); var modifiers = getMappedTypeModifiers(type); return strictNullChecks && modifiers & 4 && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && modifiers & 8 && isOptional ? getTypeWithFacts(propType, 131072) : + strictNullChecks && modifiers & 8 && isOptional ? getTypeWithFacts(propType, 524288) : propType; } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64, type.symbol); if (type.objectFlags & 32) { result.declaration = type.declaration; + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -32256,91 +33751,104 @@ var ts; if (root.isDistributive) { var checkType_1 = root.checkType; var instantiatedType = mapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & (262144 | 32768)) { + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 | 131072)) { return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144) { + return mapper(type); + } + if (flags & 524288) { + var objectFlags = type.objectFlags; + if (objectFlags & 16) { + return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072) { - if (type.objectFlags & 16) { - return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 && !(type.flags & 32764)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 1048576 && !(flags & 131068)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432) { + return instantiateType(type.typeVariable, mapper); } return type; } function getWildcardInstantiation(type) { - return type.flags & (32764 | 3 | 32768) ? type : + return type.flags & (131068 | 3 | 131072) ? type : type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 154 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 194: - case 195: - case 154: + case 196: + case 197: + case 156: return isContextSensitiveFunctionLikeDeclaration(node); - case 186: + case 188: return ts.some(node.properties, isContextSensitive); - case 185: + case 187: return ts.some(node.elements, isContextSensitive); - case 203: + case 205: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 202: - return node.operatorToken.kind === 54 && + case 204: + return node.operatorToken.kind === 55 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 273: + case 275: return isContextSensitive(node.initializer); - case 193: + case 195: return isContextSensitive(node.expression); - case 266: - return ts.some(node.properties, isContextSensitive); - case 265: { + case 268: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267: { var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 268: { + case 270: { var expression = node.expression; return !!expression && isContextSensitive(expression); } @@ -32354,7 +33862,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 195) { + if (node.kind !== 197) { var parameter = ts.firstOrUndefined(node.parameters); if (!(parameter && ts.parameterIsThisKeyword(parameter))) { return true; @@ -32364,14 +33872,14 @@ var ts; } function hasContextSensitiveReturnExpression(node) { var body = node.body; - return body.kind === 216 ? false : isContextSensitive(body); + return body.kind === 218 ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 131072) { + if (type.flags & 524288) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16, type.symbol); @@ -32382,7 +33890,7 @@ var ts; return result; } } - else if (type.flags & 524288) { + else if (type.flags & 2097152) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -32396,6 +33904,9 @@ var ts; function compareTypesAssignable(source, target) { return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 : 0; + } function isTypeSubtypeOf(source, target) { return isTypeRelatedTo(source, target, subtypeRelation); } @@ -32403,11 +33914,12 @@ var ts; return isTypeRelatedTo(source, target, assignableRelation); } function isTypeDerivedFrom(source, target) { - return source.flags & 262144 ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : - target.flags & 262144 ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : - source.flags & 14745600 ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + return source.flags & 1048576 ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 | 67108864)) : + target === globalFunctionType ? !!(source.flags & 524288) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } function isTypeComparableTo(source, target) { return isTypeRelatedTo(source, target, comparableRelation); @@ -32419,53 +33931,118 @@ var ts; return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); } function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 || (type.flags & 2097152 && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { - case 268: - case 193: - return elaborateError(node.expression, source, target); - case 202: + case 270: + case 195: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204: switch (node.operatorToken.kind) { - case 58: - case 26: - return elaborateError(node.right, source, target); + case 59: + case 27: + return elaborateError(node.right, source, target, relation, headMessage); } break; - case 186: - return elaborateObjectLiteral(node, source, target); - case 185: - return elaborateArrayLiteral(node, source, target); - case 266: - return elaborateJsxAttributes(node, source, target); + case 188: + return elaborateObjectLiteral(node, source, target, relation); + case 187: + return elaborateArrayLiteral(node, source, target, relation); + case 268: + return elaborateJsxAttributes(node, source, target, relation); + case 197: + return elaborateArrowFunction(node, source, target, relation); } return false; } - function elaborateElementwise(iterator, source, target) { + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0); + var constructSignatures = getSignaturesOfType(source, 1); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 | 131072)) && checkTypeRelatedTo(returnType, target, relation, undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + if (ts.isBlock(node.body)) { + return false; + } + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, undefined, undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } + } + return false; + } + function elaborateElementwise(iterator, source, target, relation) { var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var targetPropType = getIndexedAccessType(target, nameType, undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608) + continue; + var sourcePropType = getIndexedAccessType(source, nameType, undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, undefined); if (elaborated) { reportedError = true; } else { var resultObj = {}; var specificSource = next ? checkExpressionForMutableLocation(next, 0, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, undefined, resultObj); if (result && specificSource !== sourcePropType) { - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -32473,16 +34050,19 @@ var ts; var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; var issuedElaboration = false; if (!targetProp) { - var indexInfo = isTypeAssignableToKind(nameType, 168) && getIndexInfoOfType(target, 1) || + var indexInfo = isTypeAssignableToKind(nameType, 296) && getIndexInfoOfType(target, 1) || getIndexInfoOfType(target, 0) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -32516,8 +34096,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -32548,9 +34128,13 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + var tupleizedType = checkArrayLiteral(node, 3, true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -32568,17 +34152,17 @@ var ts; prop = _a[_i]; if (ts.isSpreadAssignment(prop)) return [3, 7]; - type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), 2240); - if (!type || (type.flags & 32768)) { + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576); + if (!type || (type.flags & 131072)) { return [3, 7]; } _b = prop.kind; switch (_b) { - case 157: return [3, 2]; + case 159: return [3, 2]; + case 158: return [3, 2]; case 156: return [3, 2]; - case 154: return [3, 2]; - case 274: return [3, 2]; - case 273: return [3, 4]; + case 276: return [3, 2]; + case 275: return [3, 4]; } return [3, 6]; case 2: return [4, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -32599,8 +34183,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); @@ -32621,14 +34205,14 @@ var ts; source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { return 0; } var kind = target.declaration ? target.declaration.kind : 0; - var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 154 && - kind !== 153 && kind !== 155; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 && + kind !== 155 && kind !== 157; var result = -1; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -32645,15 +34229,15 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && - (getFalsyFlags(sourceType) & 24576) === (getFalsyFlags(targetType) & 24576); + (getFalsyFlags(sourceType) & 98304) === (getFalsyFlags(targetType) & 98304); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 : 1, false, reportErrors, errorReporter, compareTypes) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); @@ -32666,13 +34250,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); @@ -32739,12 +34323,15 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 131072 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 ? true : - type.flags & 262144 ? ts.some(type.types, isEmptyObjectType) : - type.flags & 524288 ? ts.every(type.types, isEmptyObjectType) : + return type.flags & 524288 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 ? true : + type.flags & 1048576 ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 ? ts.every(type.types, isEmptyObjectType) : false; } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16) && isEmptyObjectType(type); + } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { if (sourceSymbol === targetSymbol) { return true; @@ -32781,71 +34368,73 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 3 || s & 32768 || source === wildcardType) + if (t & 3 || s & 131072 || source === wildcardType) return true; - if (t & 32768) + if (t & 131072) return false; - if (s & 68 && t & 4) + if (s & 132 && t & 4) return true; - if (s & 64 && s & 512 && - t & 64 && !(t & 512) && + if (s & 128 && s & 1024 && + t & 128 && !(t & 1024) && source.value === target.value) return true; - if (s & 168 && t & 8) + if (s & 296 && t & 8) return true; - if (s & 128 && s & 512 && - t & 128 && !(t & 512) && + if (s & 256 && s & 1024 && + t & 256 && !(t & 1024) && source.value === target.value) return true; - if (s & 272 && t & 16) + if (s & 2112 && t & 64) return true; - if (s & 3072 && t & 1024) + if (s & 528 && t & 16) + return true; + if (s & 12288 && t & 4096) return true; if (s & 32 && t & 32 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 512 && t & 512) { - if (s & 262144 && t & 262144 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 1024 && t & 1024) { + if (s & 1048576 && t & 1048576 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 448 && t & 448 && + if (s & 2944 && t & 2944 && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 8192 && (!strictNullChecks || t & (8192 | 4096))) + if (s & 32768 && (!strictNullChecks || t & (32768 | 16384))) return true; - if (s & 16384 && (!strictNullChecks || t & 16384)) + if (s & 65536 && (!strictNullChecks || t & 65536)) return true; - if (s & 131072 && t & 16777216) + if (s & 524288 && t & 67108864) return true; - if (s & 2048 || t & 2048) + if (s & 8192 || t & 8192) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { if (s & 1) return true; - if (s & (8 | 128) && !(s & 512) && (t & 32 || t & 128 && t & 512)) + if (s & (8 | 256) && !(s & 1024) && (t & 32 || t & 256 && t & 1024)) return true; } return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 && source.flags & 33554432) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 && target.flags & 33554432) { + if (isFreshLiteralType(target)) { target = target.regularType; } if (source === target || - relation === comparableRelation && !(target.flags & 32768) && isSimpleTypeRelatedTo(target, source, relation) || + relation === comparableRelation && !(target.flags & 131072) && isSimpleTypeRelatedTo(target, source, relation) || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 131072 && target.flags & 131072) { + if (source.flags & 524288 && target.flags & 524288) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1; } } - if (source.flags & 16711680 || target.flags & 16711680) { + if (source.flags & 66846720 || target.flags & 66846720) { return checkTypeRelatedTo(source, target, relation, undefined); } return false; @@ -32855,6 +34444,7 @@ var ts; } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -32862,7 +34452,7 @@ var ts; var depth = 0; var expandingFlags = 0; var overflow = false; - var isIntersectionConstituent = false; + var suppressNextError = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, !!errorNode, headMessage); if (overflow) { @@ -32887,15 +34477,27 @@ var ts; } } var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } if (errorOutputContainer) { errorOutputContainer.error = diag; } diagnostics.add(diag); } return result !== 0; - function reportError(message, arg0, arg1, arg2) { + function reportError(message, arg0, arg1, arg2, arg3) { ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } } function reportRelationError(message, source, target) { var sourceType = typeToString(source); @@ -32928,13 +34530,13 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 786432)) { + if (!(type.flags & 3145728)) { return false; } var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 24576) { + if (t.flags & 98304) { continue; } if (seenNonNullable) { @@ -32944,30 +34546,30 @@ var ts; } return false; } - function isRelatedTo(source, target, reportErrors, headMessage) { + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 && source.flags & 33554432) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 && target.flags & 33554432) { + if (isFreshLiteralType(target)) { target = target.regularType; } - if (source.flags & 8388608) { + if (source.flags & 33554432) { source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } - if (target.flags & 8388608) { + if (target.flags & 33554432) { target = target.typeVariable; } - if (source.flags & 2097152) { + if (source.flags & 8388608) { source = getSimplifiedType(source); } - if (target.flags & 2097152) { + if (target.flags & 8388608) { target = getSimplifiedType(target); } - if (target.flags & 262144 && source.flags & 131072 && - target.types.length <= 3 && maybeTypeOfKind(target, 24576)) { - var nullStrippedTarget = extractTypesOfKind(target, ~24576); - if (!(nullStrippedTarget.flags & (262144 | 32768))) { + if (target.flags & 1048576 && source.flags & 524288 && + target.types.length <= 3 && maybeTypeOfKind(target, 98304)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304); + if (!(nullStrippedTarget.flags & (1048576 | 131072))) { target = nullStrippedTarget; } } @@ -32976,11 +34578,12 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (relation === comparableRelation && !(target.flags & 32768) && isSimpleTypeRelatedTo(target, source, relation) || + if (relation === comparableRelation && !(target.flags & 131072) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1; - if (isObjectLiteralType(source) && source.flags & 33554432) { - var discriminantType = target.flags & 262144 ? findMatchingDiscriminantType(source, target) : undefined; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768) { + var discriminantType = target.flags & 1048576 ? findMatchingDiscriminantType(source, target) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -32991,14 +34594,11 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432) && - !(target.flags & 262144) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 | 524288 | 2097152) && source !== globalObjectType && + target.flags & (524288 | 2097152) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && - !hasCommonProperties(source, target)) { + !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0); var constructs = getSignaturesOfType(source, 1); @@ -33014,47 +34614,47 @@ var ts; } var result = 0; var saveErrorInfo = errorInfo; - var saveIsIntersectionConstituent = isIntersectionConstituent; - isIntersectionConstituent = false; - if (source.flags & 262144) { + var isIntersectionConstituent = !!isApparentIntersectionConstituent; + if (source.flags & 1048576) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068)); } else { - if (target.flags & 262144) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 32764) && !(target.flags & 32764)); + if (target.flags & 1048576) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068) && !(target.flags & 131068)); } - else if (target.flags & 524288) { + else if (target.flags & 2097152) { isIntersectionConstituent = true; result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 524288) { + else if (source.flags & 2097152) { result = someTypeRelatedToType(source, target, false); } - if (!result && (source.flags & 16711680 || target.flags & 16711680)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + if (!result && (source.flags & 66846720 || target.flags & 66846720)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - if (!result && source.flags & 524288) { - var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 262144)); + if (!result && source.flags & 2097152) { + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576)); if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { + if (result = isRelatedTo(constraint, target, reportErrors, undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 131072 && target.flags & 32764) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 && target.flags & 131068) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 131072 && globalObjectType === source) { + else if (source.symbol && source.flags & 524288 && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } - else if (ts.getObjectFlags(source) & 4096 && target.flags & 524288) { + else if (isComparingJsxAttributes && target.flags & 2097152) { var targetTypes = target.types; var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); @@ -33063,6 +34663,9 @@ var ts; return result; } } + if (!headMessage && maybeSuppress) { + return result; + } reportRelationError(headMessage, source, target); } return result; @@ -33070,49 +34673,23 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072) { - return recursiveTypeRelatedTo(source, target, false); + if (flags & 524288 || flags & 8388608 || flags & 16777216 || flags & 4194304 || flags & 33554432) { + return recursiveTypeRelatedTo(source, target, false, false); } - if (flags & (262144 | 524288)) { + if (flags & (1048576 | 2097152)) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } } - if (flags & 1048576) { - return isRelatedTo(source.type, target.type, false); - } - if (flags & 2097152) { - if (result = isRelatedTo(source.objectType, target.objectType, false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, false)) { - return result; - } - } - } - if (flags & 4194304) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608) { - return isRelatedTo(source.substitute, target.substitute, false); - } return 0; } function hasExcessProperties(source, target, discriminant, reportErrors) { if (!noImplicitAny && ts.getObjectFlags(target) & 16384) { return false; } - if (maybeTypeOfKind(target, 131072) && !(ts.getObjectFlags(target) & 512)) { + if (maybeTypeOfKind(target, 524288) && !(ts.getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { @@ -33121,12 +34698,12 @@ var ts; if (discriminant) { return hasExcessProperties(source, discriminant, undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { if (!errorNode) return { value: ts.Debug.fail() }; - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { @@ -33154,13 +34731,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1; var sourceTypes = source.types; @@ -33176,7 +34756,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 262144 && containsType(targetTypes, source)) { + if (target.flags & 1048576 && containsType(targetTypes, source)) { return -1; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -33189,16 +34769,17 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], true); } return 0; } function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { var sourceObjectFlags = ts.getObjectFlags(source); - if (sourceObjectFlags & (4 | 16) && unionTarget.flags & 262144) { + if (sourceObjectFlags & (4 | 16) && unionTarget.flags & 1048576) { return ts.find(unionTarget.types, function (target) { - if (target.flags & 131072) { + if (target.flags & 524288) { var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); if (overlapObjFlags & 4) { return source.target === target.target; @@ -33216,38 +34797,32 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } function findMatchingDiscriminantType(source, target) { - var match; - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); - if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; - if (match) { - return undefined; - } - match = type; - } - } + if (target.flags & 1048576) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1; var targetTypes = target.types; for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); + var related = isRelatedTo(source, targetType, reportErrors, undefined, true); if (!related) { return 0; } @@ -33257,7 +34832,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 262144 && containsType(sourceTypes, target)) { + if (source.flags & 1048576 && containsType(sourceTypes, target)) { return -1; } var len = sourceTypes.length; @@ -33282,9 +34857,10 @@ var ts; } return result; } - function typeArgumentsRelatedTo(source, target, variances, reportErrors) { - var sources = source.typeArguments || ts.emptyArray; - var targets = target.typeArguments || ts.emptyArray; + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } if (sources.length !== targets.length && relation === identityRelation) { return 0; } @@ -33322,7 +34898,7 @@ var ts; } return result; } - function recursiveTypeRelatedTo(source, target, reportErrors) { + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { if (overflow) { return 0; } @@ -33362,7 +34938,7 @@ var ts; expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) expandingFlags |= 2; - var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1; + var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -33382,12 +34958,53 @@ var ts; function getConstraintForRelation(type) { return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } - function structuredTypeRelatedTo(source, target, reportErrors) { + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288)) { + if (flags & 4194304) { + return isRelatedTo(source.type, target.type, false); + } + var result_2 = 0; + if (flags & 8388608) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, false)) { + return result_2; + } + } + } + if (flags & 16777216) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432) { + return isRelatedTo(source.substitute, target.substitute, false); + } + return 0; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 65536) { - if (ts.getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (source.flags & (524288 | 16777216) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144) { + if (ts.getObjectFlags(source) & 32 && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { if (!(getMappedTypeModifiers(source) & 4)) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -33397,8 +35014,8 @@ var ts; } } } - else if (target.flags & 1048576) { - if (source.flags & 1048576) { + else if (target.flags & 4194304) { + if (source.flags & 4194304) { if (result = isRelatedTo(target.type, source.type, false)) { return result; } @@ -33407,18 +35024,19 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1) { + return -1; } } } } - else if (target.flags & 2097152) { - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (target.flags & 8388608) { + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -33426,22 +35044,23 @@ var ts; var template = getTemplateTypeFromMappedType(target); var modifiers = getMappedTypeModifiers(target); if (!(modifiers & 8)) { - if (template.flags & 2097152 && template.objectType === source && + if (template.flags & 8388608 && template.objectType === source && template.indexType === getTypeParameterFromMappedType(target)) { return -1; } - if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } } - if (source.flags & 2162688) { - if (source.flags & 2097152 && target.flags & 2097152) { + if (source.flags & 8650752) { + if (source.flags & 8388608 && target.flags & 8388608) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { result &= isRelatedTo(source.indexType, target.indexType, reportErrors); } @@ -33451,28 +35070,29 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 65536 && constraint.flags & 3)) { - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~16777216))) { + if (!constraint || (source.flags & 262144 && constraint.flags & 3)) { + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864))) { errorInfo = saveErrorInfo; return result; } } - else { - var instantiated = getTypeWithThisArgument(constraint, source); - if (result = isRelatedTo(instantiated, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } + else if (result = isRelatedTo(constraint, target, false, undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; } - } - else if (source.flags & 1048576) { - if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; return result; } } else if (source.flags & 4194304) { - if (target.flags & 4194304) { + if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 16777216) { + if (target.flags & 16777216) { if (isTypeIdenticalTo(source.extendsType, target.extendsType) && (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { @@ -33502,10 +35122,29 @@ var ts; } } else { + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0; + } + var sourceIsPrimitive = !!(source.flags & 131068); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target && !(ts.getObjectFlags(source) & 8192 || ts.getObjectFlags(target) & 8192)) { var variances = getVariances(source.target); - if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { return result; } if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { @@ -33516,29 +35155,20 @@ var ts; errorInfo = saveErrorInfo; } } - var sourceIsPrimitive = !!(source.flags & 32764); - if (relation !== identityRelation) { - source = getApparentType(source); + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1) || anyType, getIndexTypeOfType(target, 1) || anyType, reportErrors); } - if (source.flags & (131072 | 524288) && target.flags & 131072) { + if (source.flags & (524288 | 2097152) && target.flags & 524288) { var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); } } } @@ -33558,10 +35188,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0; @@ -33574,7 +35204,24 @@ var ts; var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } } return 0; } @@ -33621,8 +35268,8 @@ var ts; } } var properties = getPropertiesOfObjectType(target); - for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { - var targetProp = properties_3[_b]; + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; if (!(targetProp.flags & 4194304)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { @@ -33684,31 +35331,8 @@ var ts; } return result; } - function isWeakType(type) { - if (type.flags & 131072) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); - } - if (type.flags & 524288) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 131072 && target.flags & 131072)) { + if (!(source.flags & 524288 && target.flags & 524288)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -33738,8 +35362,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1) ? 0 : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1) ? @@ -33818,7 +35442,7 @@ var ts; if (isIgnoredJsxProperty(source, prop, undefined)) { continue; } - if (prop.nameType && prop.nameType.flags & 2048) { + if (prop.nameType && prop.nameType.flags & 8192) { continue; } if (kind === 0 || isNumericLiteralName(prop.escapedName)) { @@ -33907,50 +35531,100 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + function isWeakType(type) { + if (type.flags & 524288) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); + } + if (type.flags & 2097152) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); result.objectFlags |= 8192; return result; } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 : 0); + if (variance === 3 && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } function getVariances(type) { if (!strictFunctionTypes) { return ts.emptyArray; } - var typeParameters = type.typeParameters || ts.emptyArray; - var variances = type.variances; - if (!variances) { - if (type === globalArrayType || type === globalReadonlyArrayType) { - variances = [1]; - } - else { - type.variances = ts.emptyArray; - variances = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); - var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); - var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 : 0) | - (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 : 0); - if (variance === 3 && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { - variance = 4; - } - variances.push(variance); - } - } - type.variances = variances; + if (type === globalArrayType || type === globalReadonlyArrayType) { + return ts.emptyArray; } - return variances; + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } function hasCovariantVoidArgument(type, variances) { for (var i = 0; i < variances.length; i++) { - if (variances[i] === 1 && type.typeArguments[i].flags & 4096) { + if (variances[i] === 1 && type.typeArguments[i].flags & 16384) { return true; } } return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 && !getConstraintOfTypeParameter(type); + return type.flags & 262144 && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -34021,13 +35695,13 @@ var ts; !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5 && type.flags & 131072) { + if (depth >= 5 && type.flags & 524288) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 131072 && t.symbol === symbol) { + if (t.flags & 524288 && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -34076,10 +35750,7 @@ var ts; sourceHasRestParameter === targetHasRestParameter) { return true; } - var sourceRestCount = sourceHasRestParameter ? 1 : 0; - var targetRestCount = targetHasRestParameter ? 1 : 0; - if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) { + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { return true; } return false; @@ -34114,7 +35785,7 @@ var ts; for (var i = 0; i < targetLen; i++) { var s = getTypeAtPosition(source, i); var t = getTypeAtPosition(target, i); - var related = compareTypes(s, t); + var related = compareTypes(t, s); if (!related) { return 0; } @@ -34134,8 +35805,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -34155,9 +35826,9 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 24576); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 24576) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304) : getUnionType(types, 2); } function getCommonSubtype(types) { @@ -34169,9 +35840,12 @@ var ts; function isReadonlyArrayType(type) { return !!(ts.getObjectFlags(type) & 4) && type.target === globalReadonlyArrayType; } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } function isArrayLikeType(type) { return ts.getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 24576) && isTypeAssignableTo(type, anyReadonlyArrayType); + !(type.flags & 98304) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isEmptyArrayLiteralType(type) { var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; @@ -34181,40 +35855,47 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { - return !(type.flags & (27072 | 32768)); + return !(type.flags & (109440 | 131072)); } function isUnitType(type) { - return !!(type.flags & 27072); + return !!(type.flags & 109440); } function isLiteralType(type) { return type.flags & 16 ? true : - type.flags & 262144 ? type.flags & 512 ? true : ts.every(type.types, isUnitType) : + type.flags & 1048576 ? type.flags & 1024 ? true : ts.every(type.types, isUnitType) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 512 ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 ? stringType : - type.flags & 128 ? numberType : - type.flags & 256 ? booleanType : - type.flags & 262144 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : - type; + return type.flags & 1024 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 ? stringType : + type.flags & 256 ? numberType : + type.flags & 2048 ? bigintType : + type.flags & 512 ? booleanType : + type.flags & 1048576 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; } function getWidenedLiteralType(type) { - return type.flags & 512 ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 && type.flags & 33554432 ? stringType : - type.flags & 128 && type.flags & 33554432 ? numberType : - type.flags & 256 ? booleanType : - type.flags & 262144 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : - type; + return type.flags & 1024 && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 && isFreshLiteralType(type) ? stringType : + type.flags & 256 && isFreshLiteralType(type) ? numberType : + type.flags & 2048 && isFreshLiteralType(type) ? bigintType : + type.flags & 512 && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; } function getWidenedUniqueESSymbolType(type) { - return type.flags & 2048 ? esSymbolType : - type.flags & 262144 ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + return type.flags & 8192 ? esSymbolType : + type.flags & 1048576 ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : type; } function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { @@ -34229,27 +35910,36 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; } function getFalsyFlags(type) { - return type.flags & 262144 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 64 ? type.value === "" ? 64 : 0 : - type.flags & 128 ? type.value === 0 ? 128 : 0 : - type.flags & 256 ? type === falseType ? 256 : 0 : - type.flags & 29148; + return type.flags & 1048576 ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 ? type.value === "" ? 128 : 0 : + type.flags & 256 ? type.value === 0 ? 256 : 0 : + type.flags & 2048 ? isZeroBigInt(type) ? 2048 : 0 : + type.flags & 512 ? (type === falseType || type === regularFalseType) ? 512 : 0 : + type.flags & 117724; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 29120 ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 29120); }) : + return getFalsyFlags(type) & 117632 ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632); }) : type; } function extractDefinitelyFalsyTypes(type) { @@ -34258,22 +35948,25 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 ? emptyStringType : type.flags & 8 ? zeroType : - type.flags & 16 || type === falseType ? falseType : - type.flags & (4096 | 8192 | 16384) || - type.flags & 64 && type.value === "" || - type.flags & 128 && type.value === 0 ? type : + type.flags & 64 ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 | 32768 | 65536) || + type.flags & 128 && type.value === "" || + type.flags & 256 && type.value === 0 || + type.flags & 2048 && isZeroBigInt(type) ? type : neverType; } function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (8192 | 16384); + var missing = (flags & ~type.flags) & (32768 | 65536); return missing === 0 ? type : - missing === 8192 ? getUnionType([type, undefinedType]) : - missing === 16384 ? getUnionType([type, nullType]) : + missing === 32768 ? getUnionType([type, undefinedType]) : + missing === 65536 ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } function getOptionalType(type) { ts.Debug.assert(strictNullChecks); - return type.flags & 8192 ? type : getUnionType([type, undefinedType]); + return type.flags & 32768 ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { if (!deferredGlobalNonNullableTypeAlias) { @@ -34282,7 +35975,7 @@ var ts; if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); } - return getTypeWithFacts(type, 524288); + return getTypeWithFacts(type, 2097152); } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -34316,7 +36009,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && type.flags & 33554432)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768)) { return type; } var regularType = type.regularType; @@ -34326,7 +36019,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~33554432; + regularNew.flags = resolved.flags; regularNew.objectFlags |= 128 | (ts.getObjectFlags(resolved) & 16384); type.regularType = regularNew; return regularNew; @@ -34412,15 +36105,15 @@ var ts; } function getWidenedTypeWithContext(type, context) { if (type.flags & 402653184) { - if (type.flags & 24576) { + if (type.flags & 98304) { return anyType; } if (isObjectLiteralType(type)) { return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 262144) { + if (type.flags & 1048576) { var unionContext_1 = context || createWideningContext(undefined, undefined, type.types); - var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 24576 ? t : getWidenedTypeWithContext(t, unionContext_1); }); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 ? t : getWidenedTypeWithContext(t, unionContext_1); }); return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 : 1); } if (isArrayType(type) || isTupleType(type)) { @@ -34432,7 +36125,7 @@ var ts; function reportWideningErrorsInType(type) { var errorReported = false; if (type.flags & 134217728) { - if (type.flags & 262144) { + if (type.flags & 1048576) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } @@ -34468,67 +36161,88 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + return; + } var diagnostic; switch (declaration.kind) { - case 202: - case 152: - case 151: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; - break; - case 149: - diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; - break; - case 184: - diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; - break; - case 237: + case 204: case 154: case 153: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 151: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832, undefined, param.name.escapedText, true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } + diagnostic = declaration.dotDotDotToken ? + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 186: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 289: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239: case 156: - case 157: - case 194: - case 195: - if (!declaration.name) { + case 155: + case 158: + case 159: + case 196: + case 197: + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; break; - case 179: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + case 181: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728) { if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -34574,11 +36288,11 @@ var ts; } function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - return !!(type.flags & 15794176 || + return !!(type.flags & 63176704 || objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || objectFlags & 32 || - type.flags & 786432 && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 3145728 && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -34587,12 +36301,12 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || !!(type.flags & 786432) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 3145728) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { - if (!(t.flags & 64)) { + if (!(t.flags & 128)) { return; } var name = ts.escapeLeadingUnderscores(t.value); @@ -34607,35 +36321,35 @@ var ts; var indexInfo = type.flags & 4 ? createIndexInfo(emptyObjectType, false) : undefined; return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); } - function inferTypeForHomomorphicMappedType(source, target) { - var key = source.id + "," + target.id; + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } reverseMappedCache.set(key, undefined); - var type = createReverseMappedType(source, target); + var type = createReverseMappedType(source, target, constraint); reverseMappedCache.set(key, type); return type; } - function createReverseMappedType(source, target) { + function createReverseMappedType(source, target, constraint) { var properties = getPropertiesOfType(source); if (properties.length === 0 && !getIndexInfoOfType(source, 0)) { return undefined; } - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var prop = properties_4[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; if (getTypeOfSymbol(prop).flags & 536870912) { return undefined; } } if (isArrayType(source)) { - return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isReadonlyArrayType(source)) { - return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isTupleType(source)) { - var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); var minLength = getMappedTypeModifiers(target) & 4 ? getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); @@ -34643,30 +36357,46 @@ var ts; var reversed = createObjectType(2048 | 16, undefined); reversed.source = source; reversed.mappedType = target; + reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); } - function inferReverseMappedType(sourceType, target) { - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = target.flags & 524288 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; - if (requireOptionalProperties || !(targetProp.flags & 16777216)) { - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (!sourceProp) { - return targetProp; - } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216))) return [3, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3, 3]; + return [4, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3, 1]; + case 4: return [2]; } - } - return undefined; + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -34686,7 +36416,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -34707,8 +36439,8 @@ var ts; } return; } - if (source.flags & 262144 && target.flags & 262144 && !(source.flags & 512 && target.flags & 512) || - source.flags & 524288 && target.flags & 524288) { + if (source.flags & 1048576 && target.flags & 1048576 && !(source.flags & 1024 && target.flags & 1024) || + source.flags & 2097152 && target.flags & 2097152) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -34723,7 +36455,7 @@ var ts; (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } - else if (t.flags & (128 | 64)) { + else if (t.flags & (256 | 128)) { var b = getBaseTypeOfLiteralType(t); if (typeIdenticalToSomeType(b, target.types)) { (matchingTypes || (matchingTypes = [])).push(t, b); @@ -34735,8 +36467,8 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 2162688) { - if (source.flags & 536870912 || source === silentNeverType) { + if (target.flags & 8650752) { + if (source.flags & 536870912 || source === silentNeverType || (priority & 8 && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -34749,19 +36481,34 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } - if (!(priority & 8) && target.flags & 65536 && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8) && target.flags & 262144 && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } + else { + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608) { + var indexType = getSimplifiedType(target.indexType); + if (indexType.flags & 63176704) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } } if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target) { var sourceTypes = source.typeArguments || ts.emptyArray; @@ -34777,12 +36524,12 @@ var ts; } } } - else if (source.flags & 1048576 && target.flags & 1048576) { + else if (source.flags & 4194304 && target.flags & 4194304) { contravariant = !contravariant; inferFromTypes(source.type, target.type); contravariant = !contravariant; } - else if ((isLiteralType(source) || source.flags & 4) && target.flags & 1048576) { + else if ((isLiteralType(source) || source.flags & 4) && target.flags & 4194304) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; var savePriority = priority; @@ -34791,17 +36538,20 @@ var ts; priority = savePriority; contravariant = !contravariant; } - else if (source.flags & 2097152 && target.flags & 2097152) { + else if (source.flags & 8388608 && target.flags & 8388608) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (source.flags & 4194304 && target.flags & 4194304) { + else if (source.flags & 16777216 && target.flags & 16777216) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } - else if (target.flags & 786432) { + else if (target.flags & 16777216) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -34822,7 +36572,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 262144) { + else if (source.flags & 1048576) { var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { var sourceType = sourceTypes_3[_e]; @@ -34830,16 +36580,21 @@ var ts; } } else { - if (!(priority & 32 && source.flags & (524288 | 15794176))) { - source = getApparentType(source); + if (!(priority & 32 && source.flags & (2097152 | 63176704))) { + var apparentSource = getApparentType(source); + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 | 2097152))) { + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } - if (source.flags & (131072 | 524288)) { + if (source.flags & (524288 | 2097152)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; } (visited || (visited = ts.createMap())).set(key, true); - var isNonConstructorObject = target.flags & 131072 && + var isNonConstructorObject = target.flags & 524288 && !(ts.getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { @@ -34855,6 +36610,13 @@ var ts; } } } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes || priority & 64) { @@ -34867,7 +36629,7 @@ var ts; } } function getInferenceInfoForType(type) { - if (type.flags & 2162688) { + if (type.flags & 8650752) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -34877,6 +36639,38 @@ var ts; } return undefined; } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304) { + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144) { + var savePriority = priority; + priority |= 4; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } function inferFromObjectTypes(source, target) { if (isGenericMappedType(source) && isGenericMappedType(target)) { inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); @@ -34884,25 +36678,7 @@ var ts; } if (ts.getObjectFlags(target) & 32) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 1048576) { - var inference = getInferenceInfoForType(constraintType.type); - if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - var savePriority = priority; - priority |= 2; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; - } - } - return; - } - if (constraintType.flags & 65536) { - var savePriority = priority; - priority |= 4; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { return; } } @@ -34914,33 +36690,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -34950,12 +36731,19 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0; + bivariant = bivariant || kind === 156 || kind === 155 || kind === 157; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -34986,8 +36774,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -35002,11 +36790,11 @@ var ts; reducedTypes.push(t); } } - return type.flags & 262144 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 1048576 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 | 1048576); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 | 4194304); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128); @@ -35024,7 +36812,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { var candidates = widenObjectLiteralCandidates(inference.candidates); var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); var widenLiteralTypes = !primitiveConstraint && inference.topLevel && @@ -35032,7 +36820,7 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = context.flags & 1 || inference.priority & 28 ? + var unwidenedType = inference.priority & 28 ? getUnionType(baseCandidates, 2) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -35043,14 +36831,17 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2) { + else if (context.flags & 1) { inferredType = silentNeverType; } else { @@ -35059,7 +36850,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2)); } } } @@ -35087,32 +36878,61 @@ var ts; } return result; } + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 67220415 | 1048576, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } function isInTypeQuery(node) { - return !!ts.findAncestor(node, function (n) { return n.kind === 165 ? true : n.kind === 71 || n.kind === 146 ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 167 ? true : n.kind === 72 || n.kind === 148 ? false : "quit"; }); } function getFlowCacheKey(node) { - if (node.kind === 71) { + if (node.kind === 72) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } - if (node.kind === 99) { + if (node.kind === 100) { return "0"; } - if (node.kind === 187) { + if (node.kind === 189) { var key = getFlowCacheKey(node.expression); return key && key + "." + ts.idText(node.name); } - if (node.kind === 184) { + if (node.kind === 186) { var container = node.parent.parent; - var key = container.kind === 184 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 186 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -35121,14 +36941,14 @@ var ts; } function getBindingElementNameText(element) { var parent = element.parent; - if (parent.kind === 182) { + if (parent.kind === 184) { var name = element.propertyName || element.name; switch (name.kind) { - case 71: + case 72: return ts.idText(name); - case 147: + case 149: return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 9: + case 10: case 8: return name.text; default: @@ -35141,29 +36961,29 @@ var ts; } function isMatchingReference(source, target) { switch (source.kind) { - case 71: - return target.kind === 71 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 235 || target.kind === 184) && + case 72: + return target.kind === 72 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 || target.kind === 186) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99: - return target.kind === 99; - case 97: - return target.kind === 97; - case 187: - case 188: + case 100: + return target.kind === 100; + case 98: + return target.kind === 98; + case 189: + case 190: return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 184: - if (target.kind !== 187) + case 186: + if (target.kind !== 189) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 184 && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 186 && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 235) { + if (source.parent.parent.kind === 237) { var maybeId = source.parent.parent.initializer; return !!maybeId && isMatchingReference(maybeId, t.expression); } @@ -35176,7 +36996,7 @@ var ts; undefined; } function containsMatchingReference(source, target) { - while (source.kind === 187) { + while (source.kind === 189) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -35185,32 +37005,52 @@ var ts; return false; } function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 187 && + return target.kind === 189 && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71) { + if (expr.kind === 72) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 187) { + if (expr.kind === 189) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 262144) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32) && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; + function isDiscriminantType(type) { + if (type.flags & 1048576) { + if (type.flags & (16 | 1024)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 && !(combined & 63176704)) { + return true; } } return false; } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576); + } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -35237,7 +37077,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 && + if (callExpression.expression.kind === 189 && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -35250,13 +37090,28 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 32768) { + if (assignedType.flags & 131072) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); + } + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -35264,8 +37119,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -35278,55 +37133,66 @@ var ts; function getTypeFacts(type) { var flags = type.flags; if (flags & 4) { - return strictNullChecks ? 4079361 : 4194049; - } - if (flags & 64) { - var isEmpty = type.value === ""; - return strictNullChecks ? - isEmpty ? 3030785 : 1982209 : - isEmpty ? 3145473 : 4194049; - } - if (flags & (8 | 32)) { - return strictNullChecks ? 4079234 : 4193922; + return strictNullChecks ? 16317953 : 16776705; } if (flags & 128) { + var isEmpty = type.value === ""; + return strictNullChecks ? + isEmpty ? 12123649 : 7929345 : + isEmpty ? 12582401 : 16776705; + } + if (flags & (8 | 32)) { + return strictNullChecks ? 16317698 : 16776450; + } + if (flags & 256) { var isZero = type.value === 0; return strictNullChecks ? - isZero ? 3030658 : 1982082 : - isZero ? 3145346 : 4193922; + isZero ? 12123394 : 7929090 : + isZero ? 12582146 : 16776450; + } + if (flags & 64) { + return strictNullChecks ? 16317188 : 16775940; + } + if (flags & 2048) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 : 7928580 : + isZero ? 12581636 : 16775940; } if (flags & 16) { - return strictNullChecks ? 4078980 : 4193668; + return strictNullChecks ? 16316168 : 16774920; } - if (flags & 272) { + if (flags & 528) { return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; + (type === falseType || type === regularFalseType) ? 12121864 : 7927560 : + (type === falseType || type === regularFalseType) ? 12580616 : 16774920; } - if (flags & 131072) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 : 4181984 : - strictNullChecks ? 1972176 : 4184016; + if (flags & 524288) { + return ts.getObjectFlags(type) & 16 && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 : 16777215 : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 : 16728000 : + strictNullChecks ? 7888800 : 16736160; } - if (flags & (4096 | 8192)) { - return 2457472; + if (flags & (16384 | 32768)) { + return 9830144; } - if (flags & 16384) { - return 2340752; + if (flags & 65536) { + return 9363232; } - if (flags & 3072) { - return strictNullChecks ? 1981320 : 4193160; + if (flags & 12288) { + return strictNullChecks ? 7925520 : 16772880; } - if (flags & 16777216) { - return strictNullChecks ? 1972176 : 4184016; + if (flags & 67108864) { + return strictNullChecks ? 7888800 : 16736160; } - if (flags & 15794176) { + if (flags & 63176704) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 786432) { + if (flags & 3145728) { return getTypeFactsOfTypes(type.types); } - return 4194303; + return 16777215; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -35334,7 +37200,7 @@ var ts; function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072), defaultType]); + return getUnionType([getTypeWithFacts(type, 524288), defaultType]); } return type; } @@ -35346,7 +37212,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, undefined, false, false) || errorType; } @@ -35354,15 +37220,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 185 && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 273 && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 187 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 202 && parent.parent.left === parent || - parent.parent.kind === 225 && parent.parent.initializer === parent; + return parent.parent.kind === 204 && parent.parent.left === parent || + parent.parent.kind === 227 && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -35379,21 +37245,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 224: + case 226: return stringType; - case 225: + case 227: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; - case 202: + case 204: return getAssignedTypeOfBinaryExpression(parent); - case 196: + case 198: return undefinedType; - case 185: + case 187: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 206: + case 208: return getAssignedTypeOfSpreadExpression(parent); - case 273: + case 275: return getAssignedTypeOfPropertyAssignment(parent); - case 274: + case 276: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -35401,7 +37267,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 182 ? + var type = pattern.kind === 184 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -35416,39 +37282,39 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 224) { + if (node.parent.parent.kind === 226) { return stringType; } - if (node.parent.parent.kind === 225) { + if (node.parent.parent.kind === 227) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 235 ? + return node.kind === 237 ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 || node.kind === 184 ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 || node.kind === 186 ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { - return node.kind === 235 && node.initializer && + return node.kind === 237 && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 184 && node.parent.kind === 202 && + node.kind !== 186 && node.parent.kind === 204 && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 193: + case 195: return getReferenceCandidate(node.expression); - case 202: + case 204: switch (node.operatorToken.kind) { - case 58: + case 59: return getReferenceCandidate(node.left); - case 26: + case 27: return getReferenceCandidate(node.right); } } @@ -35456,13 +37322,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 193 || - parent.kind === 202 && parent.operatorToken.kind === 58 && parent.left === node || - parent.kind === 202 && parent.operatorToken.kind === 26 && parent.right === node ? + return parent.kind === 195 || + parent.kind === 204 && parent.operatorToken.kind === 59 && parent.left === node || + parent.kind === 204 && parent.operatorToken.kind === 27 && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 269) { + if (clause.kind === 271) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -35478,14 +37344,29 @@ var ts; } return links.switchTypes; } + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271) { + if (clause.expression.kind === 10) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { - return source.flags & 262144 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 1048576 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 262144 && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 1048576 && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 262144) { + if (source.flags & 1048576) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -35494,34 +37375,37 @@ var ts; } return true; } - if (source.flags & 512 && getBaseTypeOfEnumLiteralType(source) === target) { + if (source.flags & 1024 && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 262144 ? ts.forEach(type.types, f) : f(type); + return type.flags & 1048576 ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 ? ts.every(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 262144) { + if (type.flags & 1048576) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); } return f(type) ? type : neverType; } function mapType(type, mapper, noReductions) { - if (type.flags & 32768) { + if (type.flags & 131072) { return type; } - if (!(type.flags & 262144)) { + if (!(type.flags & 1048576)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35541,12 +37425,14 @@ var ts; return filterType(type, function (t) { return (t.flags & kind) !== 0; }); } function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128)) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048)) { return mapType(typeWithPrimitives, function (t) { - return t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : - t.flags & 8 ? extractTypesOfKind(typeWithLiterals, 8 | 128) : - t; + return t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 128) : + t.flags & 8 ? extractTypesOfKind(typeWithLiterals, 8 | 256) : + t.flags & 64 ? extractTypesOfKind(typeWithLiterals, 64 | 2048) : + t; }); } return typeWithPrimitives; @@ -35573,9 +37459,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 32768 ? + return elementType.flags & 131072 ? autoArrayType : - createArrayType(elementType.flags & 262144 ? + createArrayType(elementType.flags & 1048576 ? getUnionType(elementType.types, 2) : elementType); } @@ -35590,9 +37476,9 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - if (!(t.flags & 32768)) { + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072)) { if (!(ts.getObjectFlags(t) & 256)) { return false; } @@ -35609,15 +37495,15 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 187 && (parent.name.escapedText === "length" || - parent.parent.kind === 189 && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 188 && + var isLengthPushOrUnshift = parent.kind === 189 && (parent.name.escapedText === "length" || + parent.parent.kind === 191 && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 && parent.expression === root && - parent.parent.kind === 202 && - parent.parent.operatorToken.kind === 58 && + parent.parent.kind === 204 && + parent.parent.operatorToken.kind === 59 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 168); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -35628,7 +37514,7 @@ var ts; return links.maybeTypePredicate; } function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97) { + if (node.expression.kind !== 98) { var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); @@ -35650,19 +37536,19 @@ var ts; if (flowAnalysisDisabled) { return errorType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 33492479)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943)) { return declaredType; } var sharedFlowStart = sharedFlowCount; var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); sharedFlowCount = sharedFlowStart; - var resultType = ts.getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent && reference.parent.kind === 211 && getTypeWithFacts(resultType, 524288).flags & 32768) { + var resultType = ts.getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 && getTypeWithFacts(resultType, 2097152).flags & 131072) { return declaredType; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { + if (flowDepth === 2000) { flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -35720,9 +37606,9 @@ var ts; else if (flags & 2) { var container = flow.container; if (container && container !== flowContainer && - reference.kind !== 187 && - reference.kind !== 188 && - reference.kind !== 99) { + reference.kind !== 189 && + reference.kind !== 190 && + reference.kind !== 100) { flow = container.flowNode; continue; } @@ -35751,23 +37637,32 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 262144) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + if (declaredType.flags & 1048576) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } if (containsMatchingReference(reference, node)) { + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 || init.kind === 197)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } return undefined; } function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 189 ? + var expr = node.kind === 191 ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -35775,15 +37670,15 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256) { var evolvedType_1 = type; - if (node.kind === 189) { + if (node.kind === 191) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 168)) { + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -35797,7 +37692,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 32768) { + if (type.flags & 131072) { return flowType; } var assumeTrue = (flow.flags & 32) !== 0; @@ -35807,19 +37702,25 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 32768 ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 131072 ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 199 && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -35899,8 +37800,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 262144) || - expr.kind !== 187 && expr.kind !== 188) { + if (!(computedType.flags & 1048576) || + expr.kind !== 189 && expr.kind !== 190) { return false; } var access = expr; @@ -35921,10 +37822,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); + return getTypeWithFacts(type, assumeTrue ? 4194304 : 8388608); } if (isMatchingReferenceDiscriminant(expr, declaredType)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 : 8388608); }); } if (containsMatchingReferenceDiscriminant(reference, expr)) { return declaredType; @@ -35942,7 +37843,7 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if ((type.flags & (262144 | 131072)) || (type.flags & 65536 && type.isThisType)) { + if ((type.flags & (1048576 | 524288)) || (type.flags & 262144 && type.isThisType)) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); } @@ -35950,19 +37851,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 58: + case 59: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32: case 33: case 34: case 35: + case 36: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 197 && ts.isStringLiteralLike(right_1)) { + if (left_1.kind === 199 && ts.isStringLiteralLike(right_1)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 197 && ts.isStringLiteralLike(left_1)) { + if (right_1.kind === 199 && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -35981,15 +37882,15 @@ var ts; return declaredType; } break; - case 93: + case 94: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 92: + case 93: var target = getReferenceCandidate(expr.right); if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; - case 26: + case 27: return narrowType(type, expr.right, assumeTrue); } return type; @@ -35998,28 +37899,28 @@ var ts; if (type.flags & 1) { return type; } - if (operator === 33 || operator === 35) { + if (operator === 34 || operator === 36) { assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 24576) { + if (valueType.flags & 98304) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 32 || operator === 33; + var doubleEquals = operator === 33 || operator === 34; var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - valueType.flags & 16384 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; + assumeTrue ? 262144 : 2097152 : + valueType.flags & 65536 ? + assumeTrue ? 131072 : 1048576 : + assumeTrue ? 65536 : 524288; return getTypeWithFacts(type, facts); } - if (type.flags & 16909315) { + if (type.flags & 67637251) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 32768 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 131072 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -36030,35 +37931,42 @@ var ts; function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { - if (containsMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { return declaredType; } return type; } - if (operator === 33 || operator === 35) { + if (operator === 34 || operator === 36) { assumeTrue = !assumeTrue; } if (type.flags & 1 && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 : + typeofNEFacts.get(literal.text) || 32768; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 15794176) { + if (type.flags & 63176704) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 : - typeofNEFacts.get(literal.text) || 8192; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { var switchTypes = getSwitchClauseTypes(switchStatement); @@ -36068,24 +37976,77 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 32768 ? neverType : + var caseType = discriminantType.flags & 131072 ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 32768 ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 131072 ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 ? type : globalFunctionType; + case "object": + return type.flags & 2 ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { - if (containsMatchingReference(reference, left)) { + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { return declaredType; } return type; } var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -36100,29 +38061,20 @@ var ts; return type; } if (!targetType) { - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16) { - constructSignatures = getSignaturesOfType(rightType, 1); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - if (type.flags & 262144) { + if (type.flags & 1048576) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 32768)) { + if (!(assignableType.flags & 131072)) { return assignableType; } } @@ -36156,7 +38108,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 188 || invokedExpression.kind === 187) { + if (invokedExpression.kind === 190 || invokedExpression.kind === 189) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -36171,20 +38123,20 @@ var ts; } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 71: - case 99: - case 97: - case 187: - case 188: - return narrowTypeByTruthiness(type, expr, assumeTrue); + case 72: + case 100: + case 98: case 189: + case 190: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 191: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 193: + case 195: return narrowType(type, expr.expression, assumeTrue); - case 202: + case 204: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 200: - if (expr.operator === 51) { + case 202: + if (expr.operator === 52) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -36194,7 +38146,7 @@ var ts; } function getTypeOfSymbolAtLocation(symbol, location) { symbol = symbol.exportSymbol || symbol; - if (location.kind === 71) { + if (location.kind === 72) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } @@ -36210,16 +38162,16 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 243 || - node.kind === 277 || - node.kind === 152; + node.kind === 245 || + node.kind === 279 || + node.kind === 154; }); } function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304)) { - links.flags |= 4194304; + if (!(links.flags & 8388608)) { + links.flags |= 8388608; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -36227,13 +38179,13 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608); }); } function markParameterAssignments(node) { - if (node.kind === 71) { + if (node.kind === 72) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 149) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151) { symbol.isAssigned = true; } } @@ -36247,21 +38199,21 @@ var ts; } function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 149 && + declaration.kind === 151 && declaration.initializer && - getFalsyFlags(declaredType) & 8192 && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 8192); - return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; + getFalsyFlags(declaredType) & 32768 && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288) : declaredType; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 187 || - parent.kind === 189 && parent.expression === node || - parent.kind === 188 && parent.expression === node || - parent.kind === 184 && parent.name === node && !!parent.initializer; + return parent.kind === 189 || + parent.kind === 191 && parent.expression === node || + parent.kind === 190 && parent.expression === node || + parent.kind === 186 && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { - return type.flags & 14745600 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 24576); + return type.flags & 58982400 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304); } function getConstraintForLocation(type, node) { if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { @@ -36270,7 +38222,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, 67216319) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, 67220415) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -36282,7 +38234,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2) { - if (container.kind === 195) { + if (container.kind === 197) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256)) { @@ -36298,25 +38250,25 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var declaration = localOrExportSymbol.valueDeclaration; if (localOrExportSymbol.flags & 32) { - if (declaration.kind === 238 + if (declaration.kind === 240 && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; + getNodeLinks(declaration).flags |= 16777216; + getNodeLinks(node).flags |= 33554432; break; } container = ts.getContainingClass(container); } } - else if (declaration.kind === 207) { + else if (declaration.kind === 209) { var container = ts.getThisContainer(node, false); - while (container.kind !== 277) { + while (container.kind !== 279) { if (container.parent === declaration) { - if (container.kind === 152 && ts.hasModifier(container, 32)) { - getNodeLinks(declaration).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; + if (container.kind === 154 && ts.hasModifier(container, 32)) { + getNodeLinks(declaration).flags |= 16777216; + getNodeLinks(node).flags |= 33554432; } break; } @@ -36329,12 +38281,17 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + if (localOrExportSymbol.flags & 3) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } return errorType; } } @@ -36353,28 +38310,28 @@ var ts; if (!declaration) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 149; + var isParameter = ts.getRootDeclaration(declaration).kind === 151; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); var isModuleExports = symbol.flags & 134217728; - while (flowContainer !== declarationContainer && (flowContainer.kind === 194 || - flowContainer.kind === 195 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 || + flowContainer.kind === 197 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3) !== 0 || - isInTypeQuery(node) || node.parent.kind === 255) || - node.parent.kind === 211 || - declaration.kind === 235 && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 257) || + node.parent.kind === 213 || + declaration.kind === 237 && declaration.exclamationToken || declaration.flags & 4194304; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : getOptionalType(type); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); - if (type === autoType || type === autoArrayType) { + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); @@ -36383,7 +38340,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 8192) && getFalsyFlags(flowType) & 8192) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768) && getFalsyFlags(flowType) & 32768) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -36392,10 +38349,13 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 272) { + symbol.valueDeclaration.parent.kind === 274) { return; } var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -36411,31 +38371,51 @@ var ts; } if (containedInIterationStatement) { if (usedInFunction) { - getNodeLinks(current).flags |= 65536; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536; + } } - if (container.kind === 223 && - ts.getAncestor(symbol.valueDeclaration, 236).parent === container && + if (container.kind === 225 && + ts.getAncestor(symbol.valueDeclaration, 238).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304; } - getNodeLinks(symbol.valueDeclaration).flags |= 262144; + getNodeLinks(symbol.valueDeclaration).flags |= 524288; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072; + getNodeLinks(symbol.valueDeclaration).flags |= 262144; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { var current = node; - while (current.parent.kind === 193) { + while (current.parent.kind === 195) { current = current.parent; } var isAssigned = false; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 200 || current.parent.kind === 201)) { + else if ((current.parent.kind === 202 || current.parent.kind === 203)) { var expr = current.parent; - isAssigned = expr.operator === 43 || expr.operator === 44; + isAssigned = expr.operator === 44 || expr.operator === 45; } if (!isAssigned) { return false; @@ -36444,7 +38424,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2; - if (container.kind === 152 || container.kind === 155) { + if (container.kind === 154 || container.kind === 157) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } @@ -36488,32 +38468,32 @@ var ts; function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var capturedByArrowFunction = false; - if (container.kind === 155) { + if (container.kind === 157) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } - if (container.kind === 195) { + if (container.kind === 197) { container = ts.getThisContainer(container, false); capturedByArrowFunction = true; } switch (container.kind) { - case 242: + case 244: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 241: + case 243: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 155: + case 157: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 152: - case 151: + case 154: + case 153: if (ts.hasModifier(container, 32)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 147: + case 149: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -36522,31 +38502,37 @@ var ts; } var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { - error(node, capturedByArrowFunction && container.kind === 277 ? + var diag = error(node, capturedByArrowFunction && container.kind === 279 ? ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } } return type || anyType; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - if (container.kind === 194 && - container.parent.kind === 202 && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { - var className = container.parent - .left - .expression - .expression; + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } - else if ((container.kind === 194 || container.kind === 237) && + else if (isInJS && + (container.kind === 196 || container.kind === 239) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -36561,16 +38547,58 @@ var ts; var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + if (container.kind === 196 && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3) { + return container.parent + .left + .expression + .expression; + } + else if (container.kind === 156 && + container.parent.kind === 188 && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6) { + return container.parent.parent.left.expression; + } + else if (container.kind === 196 && + container.parent.kind === 275 && + container.parent.parent.kind === 188 && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6) { + return container.parent.parent.parent.left.expression; + } + else if (container.kind === 196 && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9) { + return container.parent.parent.parent.arguments[0].expression; + } + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9) { + return container.parent.parent.arguments[0].expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 287) { + if (jsdocType && jsdocType.kind === 289) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -36584,14 +38612,14 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 149; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 189 && node.parent.expression === node; + var isCallExpression = node.parent.kind === 191 && node.parent.expression === node; var container = ts.getSuperContainer(node, true); var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 195) { + while (container && container.kind === 197) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } @@ -36599,14 +38627,14 @@ var ts; var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; if (!canUseSuperExpression) { - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 147; }); - if (current && current.kind === 147) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149; }); + if (current && current.kind === 149) { 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 === 186)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -36614,7 +38642,7 @@ var ts; } return errorType; } - if (!isCallExpression && container.kind === 155) { + if (!isCallExpression && container.kind === 157) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasModifier(container, 32) || isCallExpression) { @@ -36624,7 +38652,7 @@ var ts; nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 154 && ts.hasModifier(container, 256)) { + if (container.kind === 156 && ts.hasModifier(container, 256)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -36635,7 +38663,7 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node.parent, container); } - if (container.parent.kind === 186) { + if (container.parent.kind === 188) { 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 errorType; @@ -36654,7 +38682,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 155 && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 157 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return errorType; } @@ -36666,24 +38694,24 @@ var ts; return false; } if (isCallExpression) { - return container.kind === 155; + return container.kind === 157; } else { - if (ts.isClassLike(container.parent) || container.parent.kind === 186) { + if (ts.isClassLike(container.parent) || container.parent.kind === 188) { if (ts.hasModifier(container, 32)) { - return container.kind === 154 || - container.kind === 153 || - container.kind === 156 || - container.kind === 157; + return container.kind === 156 || + container.kind === 155 || + container.kind === 158 || + container.kind === 159; } else { - return container.kind === 154 || + return container.kind === 156 || + container.kind === 155 || + container.kind === 158 || + container.kind === 159 || + container.kind === 154 || container.kind === 153 || - container.kind === 156 || - container.kind === 157 || - container.kind === 152 || - container.kind === 151 || - container.kind === 155; + container.kind === 157; } } } @@ -36691,10 +38719,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 154 || - func.kind === 156 || - func.kind === 157) && func.parent.kind === 186 ? func.parent : - func.kind === 194 && func.parent.kind === 273 ? func.parent.parent : + return (func.kind === 156 || + func.kind === 158 || + func.kind === 159) && func.parent.kind === 188 ? func.parent : + func.kind === 196 && func.parent.kind === 275 ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -36702,11 +38730,11 @@ var ts; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 524288 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 2097152 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 195) { + if (func.kind === 197) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -36718,7 +38746,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -36730,7 +38758,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 273) { + if (literal.parent.kind !== 275) { break; } literal = literal.parent.parent; @@ -36739,9 +38767,9 @@ var ts; return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); } var parent = func.parent; - if (parent.kind === 202 && parent.operatorToken.kind === 58) { + if (parent.kind === 204 && parent.operatorToken.kind === 59) { var target = parent.left; - if (target.kind === 187 || target.kind === 188) { + if (target.kind === 189 || target.kind === 190) { var expression = target.expression; if (inJs && ts.isIdentifier(expression)) { var sourceFile = ts.getSourceFileOfNode(parent); @@ -36765,7 +38793,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -36791,7 +38819,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 149) { + if (declaration.kind === 151) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -36803,7 +38831,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 184) { + if (parentDeclaration.kind !== 186) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -36824,9 +38852,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) - : contextualReturnType; + if (contextualReturnType) { + if (functionFlags & 2) { + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -36874,10 +38914,13 @@ var ts; } function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 191) { + if (template.parent.kind === 193) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -36886,21 +38929,28 @@ var ts; var binaryExpression = node.parent; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { - case 58: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; - case 54: + case 59: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55: var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; - case 53: - case 26: + case 54: + case 27: return node === right ? getContextualType(binaryExpression) : undefined; default: return undefined; } } - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0: return true; @@ -36916,26 +38966,57 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319, undefined, id.escapedText, true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415, undefined, id.escapedText, true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4: case 2: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7: + case 8: + case 9: + return ts.Debug.fail("Does not apply"); default: return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - if (t.flags & 917504) { + if (t.flags & 3670016) { var prop = getPropertyOfType(t, name); if (prop) { return getTypeOfSymbol(prop); @@ -36946,6 +39027,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1) || + getIndexTypeOfContextualType(t, 0); } return undefined; }, true); @@ -36953,9 +39036,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, true); } - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); if (node.flags & 8388608) { @@ -36968,8 +39048,8 @@ var ts; var type = getApparentTypeOfContextualType(objectLiteral); if (type) { if (!hasNonBindableDynamicName(element)) { - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -36981,7 +39061,6 @@ var ts; } function getContextualTypeForElementExpression(arrayContextualType, index) { return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) - || getIndexTypeOfContextualType(arrayContextualType, 1) || getIteratedTypeOrElementType(arrayContextualType, undefined, false, false, false)); } function getContextualTypeForConditionalOperand(node) { @@ -37015,51 +39094,42 @@ var ts; } function isPossiblyDiscriminantValue(node) { switch (node.kind) { - case 9: + case 10: case 8: - case 13: - case 101: - case 86: - case 95: - case 71: + case 9: + case 14: + case 102: + case 87: + case 96: + case 72: + case 141: return true; - case 187: - case 193: + case 189: + case 195: return isPossiblyDiscriminantValue(node.expression); + case 270: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 1048576) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } function getContextualType(node) { if (node.flags & 8388608) { @@ -37070,51 +39140,53 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 235: - case 149: - case 152: + case 237: case 151: - case 184: + case 154: + case 153: + case 186: return getContextualTypeForInitializerExpression(node); - case 195: - case 228: + case 197: + case 230: return getContextualTypeForReturnExpression(node); - case 205: + case 207: return getContextualTypeForYieldOperand(parent); - case 189: - case 190: - return getContextualTypeForArgument(parent, node); + case 201: + return getContextualTypeForAwaitOperand(parent); + case 191: case 192: - case 210: + return getContextualTypeForArgument(parent, node); + case 194: + case 212: return getTypeFromTypeNode(parent.type); - case 202: + case 204: return getContextualTypeForBinaryOperand(node); - case 273: - case 274: - return getContextualTypeForObjectLiteralElement(parent); case 275: + case 276: + return getContextualTypeForObjectLiteralElement(parent); + case 277: return getApparentTypeOfContextualType(parent.parent); - case 185: { + case 187: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 203: + case 205: return getContextualTypeForConditionalOperand(node); - case 214: - ts.Debug.assert(parent.parent.kind === 204); + case 216: + ts.Debug.assert(parent.parent.kind === 206); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 193: { - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + case 195: { + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 268: + case 270: return getContextualTypeForJsxExpression(parent); - case 265: case 267: + case 269: return getContextualTypeForJsxAttribute(parent); - case 260: - case 259: + case 262: + case 261: return getContextualJsxElementAttributesType(parent); } return undefined; @@ -37124,58 +39196,13 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + return node.parent.contextualType; } - var valueType = checkExpression(node.tagName); - if (isTypeAny(valueType)) { - return anyType; - } - var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); + return getContextualTypeForArgumentAtIndex(node, 0); } - function getJsxSignaturesParameterTypes(valueType, isJs, context) { - if (valueType.flags & 4) { - return anyType; - } - else if (valueType.flags & 64) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = valueType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); - if (indexSignatureType) { - return indexSignatureType; - } - } - return anyType; - } - var signatures = getSignaturesOfType(valueType, 1); - var ctor = true; - if (signatures.length === 0) { - signatures = getSignaturesOfType(valueType, 0); - ctor = false; - if (signatures.length === 0) { - return errorType; - } - } - var links = getNodeLinks(context); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(valueType); - var cachedResolved = links.resolvedSignatures.get(cacheKey); - if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { - signatures = cachedResolved; - } - else if (!cachedResolved) { - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); - } - return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0); + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); @@ -37190,22 +39217,40 @@ var ts; var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } return attributesType; } - function getJsxPropsTypeFromClassType(sig, isJs, context, reportErrors) { + function getJsxPropsTypeFromClassType(sig, context) { var ns = getJsxNamespaceAt(context); var forcedLookupLocation = getJsxElementPropertiesName(ns); var attributesType = forcedLookupLocation === undefined @@ -37214,7 +39259,7 @@ var ts; ? getReturnTypeOfSignature(sig) : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); if (!attributesType) { - if (reportErrors && !!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); } return emptyObjectType; @@ -37230,7 +39275,7 @@ var ts; var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); var hostClassType = getReturnTypeOfSignature(sig); apparentAttributesType = intersectTypes(typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) : intrinsicClassAttribs, apparentAttributesType); } var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); @@ -37263,7 +39308,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 194 || node.kind === 195; + return node.kind === 196 || node.kind === 197; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -37276,7 +39321,7 @@ var ts; getApparentTypeOfContextualType(node); } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 154 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -37285,13 +39330,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 262144)) { + if (!(type.flags & 1048576)) { return getContextualCallSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -37320,10 +39365,10 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); } function hasDefaultValue(node) { - return (node.kind === 184 && !!node.initializer) || - (node.kind === 202 && node.operatorToken.kind === 58); + return (node.kind === 186 && !!node.initializer) || + (node.kind === 204 && node.operatorToken.kind === 59); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -37332,8 +39377,8 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elementCount; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 206) { - var restArrayType = checkExpression(e.expression, checkMode); + if (inDestructuringPattern && e.kind === 208) { + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1) || getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); if (restElementType) { @@ -37342,43 +39387,54 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } - if (index < elementCount - 1 && e.kind === 206) { + if (index < elementCount - 1 && e.kind === 208) { hasNonEndingSpreadElement = true; } } if (!hasNonEndingSpreadElement) { - var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206; + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208; var minLength = elementCount - (hasRestElement ? 1 : 0); + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - if (!hasRestElement && pattern && (pattern.kind === 183 || pattern.kind === 185)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 && e.dotDotDotToken || e.kind === 206)) { - if (e.kind !== 208) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + if (!hasRestElement && pattern && (pattern.kind === 185 || pattern.kind === 187)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 && e.dotDotDotToken || e.kind === 208)) { + if (e.kind !== 210) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1; } return createArrayType(elementTypes.length ? @@ -37387,19 +39443,19 @@ var ts; } function isNumericName(name) { switch (name.kind) { - case 147: + case 149: return isNumericComputedName(name); - case 71: + case 72: return isNumericLiteralName(name.escapedText); case 8: - case 9: + case 10: return isNumericLiteralName(name.text); default: return false; } } function isNumericComputedName(name) { - return isTypeAssignableToKind(checkComputedPropertyName(name), 168); + return isTypeAssignableToKind(checkComputedPropertyName(name), 296); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -37411,8 +39467,8 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (links.resolvedType.flags & 24576 || - !isTypeAssignableToKind(links.resolvedType, 68 | 168 | 3072) && + if (links.resolvedType.flags & 98304 || + !isTypeAssignableToKind(links.resolvedType, 132 | 296 | 12288) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -37432,19 +39488,30 @@ var ts; var unionType = propTypes.length ? getUnionType(propTypes, 2) : undefinedType; return createIndexInfo(unionType, false); } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, true); + } + return links.immediateTarget; + } function checkObjectLiteral(node, checkMode) { var inDestructuringPattern = ts.isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 33554432; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 182 || contextualType.pattern.kind === 186); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + (contextualType.pattern.kind === 184 || contextualType.pattern.kind === 188); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -37454,15 +39521,15 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 147 && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 273 || - memberDecl.kind === 274 || + if (memberDecl.kind === 275 || + memberDecl.kind === 276 || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 273 ? checkPropertyAssignment(memberDecl, checkMode) : - memberDecl.kind === 274 ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + var type = memberDecl.kind === 275 ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -37473,7 +39540,7 @@ var ts; } } typeFlags |= type.flags; - var nameType = computedNameType && computedNameType.flags & 2240 ? + var nameType = computedNameType && computedNameType.flags & 8576 ? computedNameType : undefined; var prop = nameType ? createSymbol(4 | member.flags, getLateBoundNameFromType(nameType), 1024) : @@ -37482,8 +39549,8 @@ var ts; prop.nameType = nameType; } if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 273 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 274 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 275 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216; } @@ -37506,12 +39573,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 275) { + else if (memberDecl.kind === 277) { if (languageVersion < 2) { checkExternalEmitHelpers(memberDecl, 2); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -37523,15 +39590,15 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 0); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768); offset = i + 1; continue; } else { - ts.Debug.assert(memberDecl.kind === 156 || memberDecl.kind === 157); + ts.Debug.assert(memberDecl.kind === 158 || memberDecl.kind === 159); checkNodeDeferred(memberDecl); } - if (computedNameType && !(computedNameType.flags & 2240)) { + if (computedNameType && !(computedNameType.flags & 8576)) { if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { if (isTypeAssignableTo(computedNameType, numberType)) { hasComputedNumberProperty = true; @@ -37563,7 +39630,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768); } return spread; } @@ -37572,9 +39639,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432; - result.flags |= 268435456 | freshObjectLiteralFlag | (typeFlags & 939524096); - result.objectFlags |= 128; + result.flags |= 268435456 | typeFlags & 939524096; + result.objectFlags |= 128 | freshObjectLiteralFlag; if (isJSObjectLiteral) { result.objectFlags |= 16384; } @@ -37584,52 +39650,51 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 24576)) { - propagatedFlags |= (result.flags & 939524096); - } + propagatedFlags |= result.flags & 939524096; return result; } } function isValidSpreadType(type) { - return !!(type.flags & (3 | 16777216) || - getFalsyFlags(type) & 29120 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 131072 && !isGenericMappedType(type) || - type.flags & 786432 && ts.every(type.types, isValidSpreadType)); + return !!(type.flags & (3 | 67108864 | 524288 | 58982400) || + getFalsyFlags(type) & 117632 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 && ts.every(type.types, isValidSpreadType)); } function checkJsxSelfClosingElementDeferred(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node, 0); + checkJsxOpeningLikeElementOrOpeningFragment(node); } function checkJsxSelfClosingElement(node, _checkMode) { checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } function checkJsxElementDeferred(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, 0); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); } else { checkExpression(node.closingElement.tagName); } + checkJsxChildren(node); } function checkJsxElement(node, _checkMode) { checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } - function checkJsxFragment(node, checkMode) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); if (compilerOptions.jsx === 2 && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { error(node, compilerOptions.jsxFactory ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } + checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } function isUnhyphenatedJsxName(name) { return !ts.stringContains(name, "-"); } function isJsxIntrinsicIdentifier(tagName) { - return tagName.kind === 71 && ts.isIntrinsicJsxName(tagName.escapedText); + return tagName.kind === 72 && ts.isIntrinsicJsxName(tagName.escapedText); } function checkJsxAttribute(node, checkMode) { return node.initializer @@ -37639,16 +39704,19 @@ var ts; function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); - var spread = emptyObjectType; + var spread = emptyJsxObjectType; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096; var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -37663,9 +39731,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 267); + ts.Debug.assert(attributeDecl.kind === 269); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -37673,7 +39741,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 0, 4096); + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -37682,36 +39750,39 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); } } - var parent = openingLikeElement.parent.kind === 258 ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 260 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); var childrenPropSymbol = createSymbol(4 | 33554432, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, typeFlags, objectFlags); } } if (hasSpreadAnyType) { return anyType; } - if (typeToIntersect && spread !== emptyObjectType) { + if (typeToIntersect && spread !== emptyJsxObjectType) { return getIntersectionType([typeToIntersect, spread]); } - return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); - result.flags |= 268435456; - result.objectFlags |= 128 | 4096; + result.flags |= 268435456 | typeFlags; + result.objectFlags |= 128 | objectFlags; return result; } } @@ -37719,7 +39790,7 @@ var ts; var childrenTypes = []; for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; - if (child.kind === 10) { + if (child.kind === 11) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); } @@ -37736,7 +39807,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928); + var typeSymbol = exports && getSymbol(exports, name, 67897832); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } function getIntrinsicTagSymbol(node) { @@ -37768,56 +39839,6 @@ var ts; } return links.resolvedSymbol; } - function instantiateJsxSignatures(node, signatures) { - var instantiatedSignatures = []; - var candidateForTypeArgumentError; - var hasTypeArgumentError = !!node.typeArguments; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, false); - if (typeArgumentInstantiated) { - hasTypeArgumentError = false; - instantiatedSignatures.push(typeArgumentInstantiated); - } - else { - if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - candidateForTypeArgumentError = signature; - } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 4 : 0); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - } - else { - instantiatedSignatures.push(signature); - } - } - if (node.typeArguments && hasTypeArgumentError) { - if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true); - } - else if (node.typeArguments.length !== 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); - } - } - return instantiatedSignatures; - } - function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { - if (reportErrors === void 0) { reportErrors = false; } - if (!node.typeArguments) { - return; - } - if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - return; - } - var args = checkTypeArguments(signature, node.typeArguments, reportErrors); - if (!args) { - return; - } - return getSignatureInstantiation(signature, args, isJavascript); - } function getJsxNamespaceAt(location) { var links = location && getNodeLinks(location); if (links && links.jsxNamespace) { @@ -37842,7 +39863,7 @@ var ts; return getGlobalSymbol(JsxNames.JSX, 1920, undefined); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832); var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); if (propertiesOfJsxElementAttribPropInterface) { @@ -37859,7 +39880,7 @@ var ts; return undefined; } function getJsxLibraryManagedAttributes(jsxNamespace) { - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832); } function getJsxElementPropertiesName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); @@ -37867,157 +39888,69 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4) { + return [anySignature]; + } + else if (elementType.flags & 128) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; + } + } + var apparentElemType = getApparentType(elementType); + var signatures = getSignaturesOfType(apparentElemType, 1); + if (signatures.length === 0) { + signatures = getSignaturesOfType(apparentElemType, 0); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576) { + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + return indexSignatureType; + } return undefined; } - if (propsType.flags & 524288) { - var propsApparentType = []; - for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { - var t = _a[_i]; - propsApparentType.push(getApparentType(t)); - } - return getIntersectionType(propsApparentType); - } - return getApparentType(propsType); + return anyType; } - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined, false); - if (callSignature !== unknownSignature) { - var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); - var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } } - return undefined; - } - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, false); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - var candidate = candidatesOutArray_1[_i]; - var callReturnType = getReturnTypeOfSignature(candidate); - var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - var shouldBeCandidate = true; - for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - if (!result) { - result = allMatchingAttributesType; - } - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; + else if (refKind === 0) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } } - return undefined; - } - function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { - var links = getNodeLinks(openingLikeElement); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(elementType); - if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { - return; - } - else if (links.resolvedSignatures.get(cacheKey)) { - return links.resolvedSignatures.get(cacheKey); - } - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - var signatures = getSignaturesOfType(elementType, 1); - if (signatures.length === 0) { - signatures = getSignaturesOfType(elementType, 0); - if (signatures.length === 0) { - if (reportErrors) { - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - } + else { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { return; } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var results = instantiateJsxSignatures(openingLikeElement, signatures); - links.resolvedSignatures.set(cacheKey, results); - return results; - } - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType.flags & 262144) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), 2); - } - if (isTypeAny(elementType)) { - return elementType; - } - else if (elementType.flags & 4) { - return anyType; - } - else if (elementType.flags & 64) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - return anyType; - } - var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, true); - if (!ts.length(instantiatedSignatures)) { - return errorType; - } - var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2); - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, true); })); } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); @@ -38036,30 +39969,6 @@ var ts; } return links.resolvedJsxElementAttributesType; } - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); - } - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, true); - } - } - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, false); - } - } - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.escapedText); - return prop || unknownSymbol; - } function getJsxElementClassTypeAt(location) { var type = getJsxType(JsxNames.ElementClass, location); if (type === errorType) @@ -38089,7 +39998,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -38098,7 +40007,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319, reactRefErr, reactNamespace, true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = 67108863; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { @@ -38106,14 +40015,12 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 131072) { + if (targetType.flags & 524288) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -38122,7 +40029,7 @@ var ts; return true; } } - else if (targetType.flags & 786432) { + else if (targetType.flags & 3145728) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -38130,36 +40037,12 @@ var ts; } } } - else if (targetType.flags & 4194304) { + else if (targetType.flags & 16777216) { return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); } return false; } - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, false); - var sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); - var isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { - var attribute = _a[_i]; - if (!ts.isJsxAttribute(attribute)) { - continue; - } - var attrName = attribute.name; - var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); - break; - } - } - } - else if (!isSourceAttributeTypeAssignableToTarget) { - checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); - } - } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -38179,15 +40062,15 @@ var ts; if (symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3; + ts.getAssignmentDeclarationKind(parent) === 3; } } function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 146 ? node.right : node.kind === 181 ? node : node.name; + var errorNode = node.kind === 148 ? node.right : node.kind === 183 ? node : node.name; if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; @@ -38206,7 +40089,7 @@ var ts; } if ((flags & 128) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); return false; } @@ -38236,12 +40119,12 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536) ? getConstraintOfTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 262144) ? getConstraintOfTypeParameter(thisType) : thisType); } if (flags & 32) { return true; } - if (type.flags & 65536) { + if (type.flags & 262144) { type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); } if (!type || !hasBaseType(type, enclosingClass)) { @@ -38260,19 +40143,26 @@ var ts; function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304; + if (kind) { + return getNonNullableType(type); + } + return type; + } function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { if (type.flags & 2) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 24576; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304; if (kind) { - error(node, kind & 8192 ? kind & 16384 ? + error(node, kind & 32768 ? kind & 65536 ? (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); - return t.flags & (24576 | 32768) ? errorType : t; + return t.flags & (98304 | 131072) ? errorType : t; } return type; } @@ -38305,7 +40195,7 @@ var ts; return anyType; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, leftType.flags & 65536 && leftType.isThisType ? apparentType : leftType); + reportNonexistentProperty(right, leftType.flags & 262144 && leftType.isThisType ? apparentType : leftType); } return errorType; } @@ -38316,34 +40206,40 @@ var ts; } else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 99); + markPropertyAsReferenced(prop, node, left.kind === 100); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 97, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 98, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - if (node.kind !== 187 || + if (node.kind !== 189 || assignmentKind === 1 || - prop && !(prop.flags & (3 | 4 | 98304)) && !(prop.flags & 8192 && propType.flags & 262144)) { + prop && !(prop.flags & (3 | 4 | 98304)) && !(prop.flags & 8192 && propType.flags & 1048576)) { return propType; } var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && left.kind === 99) { + if (strictNullChecks && strictPropertyInitialization && left.kind === 100) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 155 && flowContainer.parent === declaration.parent) { + if (flowContainer.kind === 157 && flowContainer.parent === declaration.parent) { assumeUninitialized = true; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 8192) && getFalsyFlags(flowType) & 8192) { + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768) && getFalsyFlags(flowType) & 32768) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); return propType; } @@ -38361,8 +40257,8 @@ var ts; && !isPropertyDeclaredInAncestorClass(prop)) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 238 && - node.parent.kind !== 162 && + else if (valueDeclaration.kind === 240 && + node.parent.kind !== 164 && !(valueDeclaration.flags & 4194304) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -38374,9 +40270,9 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 152: + case 154: return true; - case 273: + case 275: return false; default: return ts.isExpressionNode(node) ? false : "quit"; @@ -38409,7 +40305,7 @@ var ts; function reportNonexistentProperty(propNode, containingType) { var errorInfo; var relatedInfo; - if (containingType.flags & 262144 && !(containingType.flags & 32764)) { + if (containingType.flags & 1048576 && !(containingType.flags & 131068)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -38449,7 +40345,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -38483,7 +40379,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (!prop || !(prop.flags & 106500) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8)) { + if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 && !(prop.flags & 32768))) { @@ -38499,16 +40395,16 @@ var ts; } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 187: - return isValidPropertyAccessWithType(node, node.expression.kind === 97, propertyName, getWidenedType(checkExpression(node.expression))); - case 146: + case 189: + return isValidPropertyAccessWithType(node, node.expression.kind === 98, propertyName, getWidenedType(checkExpression(node.expression))); + case 148: return isValidPropertyAccessWithType(node, false, propertyName, getWidenedType(checkExpression(node.left))); - case 181: + case 183: return isValidPropertyAccessWithType(node, false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 181 && node.expression.kind === 97, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 183 && node.expression.kind === 98, property.escapedName, type) && (!(property.flags & 8192) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -38534,17 +40430,17 @@ var ts; } var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) - : ts.isInJavaScriptFile(node) && (type.flags & 262144) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 1048576) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 236) { + if (initializer.kind === 238) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 71) { + else if (initializer.kind === 72) { return getResolvedSymbol(initializer); } return undefined; @@ -38554,13 +40450,13 @@ var ts; } function isForInVariableForNumericPropertyNames(expr) { var e = ts.skipParentheses(expr); - if (e.kind === 71) { + if (e.kind === 72) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 224 && + if (node.kind === 226 && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -38578,7 +40474,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 190 && node.parent.expression === node) { + if (node.parent.kind === 192 && 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); @@ -38590,15 +40486,15 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10) { error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -38607,7 +40503,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 3072) === 0) { + if ((expressionType.flags & 12288) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -38631,16 +40527,19 @@ var ts; return true; } function callLikeExpressionMayHaveTypeArguments(node) { - return ts.isCallOrNewExpression(node); + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); } function resolveUntypedCall(node) { if (callLikeExpressionMayHaveTypeArguments(node)) { ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 191) { + if (node.kind === 193) { checkExpression(node.template); } - else if (node.kind !== 150) { + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -38659,8 +40558,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -38689,51 +40588,69 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 206 || arg.kind === 213 && arg.isSpread); + return !!arg && (arg.kind === 208 || arg.kind === 215 && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); } + function acceptsVoid(t) { + return !!(t.flags & 16384); + } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; var callIsIncomplete = false; - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - return true; - } - if (node.kind === 191) { + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193) { argCount = args.length; - if (node.template.kind === 204) { + if (node.template.kind === 206) { var lastSpan = ts.last(node.template.templateSpans); callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } else { var templateLiteral = node.template; - ts.Debug.assert(templateLiteral.kind === 13); + ts.Debug.assert(templateLiteral.kind === 14); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 150) { - argCount = getEffectiveArgumentCount(node, undefined, signature); + else if (node.kind === 152) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); } else { if (!node.arguments) { - ts.Debug.assert(node.kind === 190); + ts.Debug.assert(node.kind === 192); return getMinArgumentCount(signature) === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); - } - if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { return false; } - var hasEnoughArguments = argCount >= getMinArgumentCount(signature); - return callIsIncomplete || hasEnoughArguments; + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072) { + return false; + } + } + return true; } function hasCorrectTypeArgumentArity(signature, typeArguments) { var numTypeParameters = ts.length(signature.typeParameters); @@ -38742,7 +40659,7 @@ var ts; (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); } function getSingleCallSignature(type) { - if (type.flags & 131072) { + if (type.flags & 524288) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -38752,7 +40669,7 @@ var ts; return undefined; } function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { inferTypes(context.inferences, source, target); @@ -38760,14 +40677,11 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, node, context) { - var skipContextParamType = getTypeAtPosition(signature, 0); - var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); - inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); - var paramType = getTypeAtPosition(signature, 0); - var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } @@ -38778,7 +40692,10 @@ var ts; inference.inferredType = undefined; } } - if (node.kind !== 150) { + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } + if (node.kind !== 152) { var contextualType = getContextualType(node); if (contextualType) { var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); @@ -38796,56 +40713,46 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 208) { + var arg = args[i]; + if (arg.kind !== 210) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - if (argType === undefined) { - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 | 63176704) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { - return arg.kind === 213 ? + return arg.kind === 215 ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1) || anyType; - var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 32764 | 1048576); + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 | 4194304); var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -38854,50 +40761,51 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; } - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - var callIsIncomplete = node.attributes.end === node.end; - if (callIsIncomplete) { - return true; + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2; } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { - return false; - } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1))) { + return 0; } - return checkTypeRelatedTo(attributesType, paramType, relation, undefined, headMessage); + if (ts.length(getSignaturesOfType(tagType, 0))) { + return 1; + } + return 2; + } + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 190) { + if (thisType && thisType !== voidType && node.kind !== 192) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; @@ -38907,221 +40815,116 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 208) { - if (i === restIndex && (restType.flags & 65536 || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 210) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } function getThisArgumentOfCall(node) { - if (node.kind === 189) { + if (node.kind === 191) { var callee = ts.skipOuterExpressions(node.expression); - if (callee.kind === 187 || callee.kind === 188) { + if (callee.kind === 189 || callee.kind === 190) { return callee.expression; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } function getEffectiveCallArguments(node) { - if (node.kind === 191) { + if (node.kind === 193) { var template = node.template; - var args_4 = [undefined]; - if (template.kind === 204) { + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 150) { - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; - } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150) { - switch (node.parent.kind) { - case 238: - case 207: - return 1; - case 152: - return 2; - case 154: - case 156: - case 157: - if (languageVersion === 0) { - return 2; - } - return signature.parameters.length >= 3 ? 3 : 2; - case 149: - return 3; - default: - return ts.Debug.fail(); - } - } - else { - return args.length; - } - } - function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 238) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 149) { - node = node.parent; - if (node.kind === 155) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 || - node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 238) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149) { - node = node.parent; - if (node.kind === 155) { - return anyType; - } - } - if (node.kind === 152 || - node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - var element = node; - var name = element.name; - switch (name.kind) { - case 71: - return getLiteralType(ts.idText(name)); - case 8: - case 9: - return getLiteralType(name.text); - case 147: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 238) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149) { - return numberType; - } if (node.kind === 152) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; + return getEffectiveDecoratorArguments(node); } - if (node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); + } + } + return args; } - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240: + case 209: + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151: + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154: + case 156: + case 158: + case 159: + var hasPropDesc = parent.kind !== 154 && languageVersion !== 0; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; + return ts.Debug.fail(); } - function getEffectiveArgumentType(node, argIndex) { - if (node.kind === 150) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191) { - return getGlobalTemplateStringsArrayType(); - } - return undefined; - } - function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 150 || - (argIndex === 0 && node.kind === 191)) { - return undefined; - } - return args[argIndex]; - } - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150) { - return node.expression; - } - else if (argIndex === 0 && node.kind === 191) { - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240: + case 209: + return 1; + case 154: + return 2; + case 156: + case 158: + case 159: + return languageVersion === 0 || signature.parameters.length <= 2 ? 2 : 3; + case 151: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -39130,15 +40933,19 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; var minCount = getMinArgumentCount(sig); var maxCount = getParameterCount(sig); if (minCount < argCount && minCount > belowArgCount) belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -39149,22 +40956,31 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -39172,42 +40988,33 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { - var isTaggedTemplate = node.kind === 191; - var isDecorator = node.kind === 150; + var isTaggedTemplate = node.kind === 193; + var isDecorator = node.kind === 152; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; var typeArguments; if (!isDecorator) { typeArguments = node.typeArguments; - if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98) { ts.forEach(typeArguments, checkSourceElement); } } var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; var candidateForArgumentError; var candidateForArgumentArityError; var candidateForTypeArgumentError; var result; - var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } @@ -39217,26 +41024,28 @@ var ts; if (result) { return result; } - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - return candidateForArgumentError; + if (reportErrors) { + if (candidateForArgumentError) { + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); - } - else if (candidateForArgumentArityError) { - diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); - } - else if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); - } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -39256,58 +41065,71 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) { + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) { + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { ts.Debug.assert(candidates.length > 0); return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) @@ -39322,7 +41144,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -39333,7 +41155,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -39360,17 +41182,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -39389,7 +41221,7 @@ var ts; return maxParamsIndex; } function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { - if (node.expression.kind === 97) { + if (node.expression.kind === 98) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { @@ -39416,31 +41248,38 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { if (funcType !== errorType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); } if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0); + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0, relatedInformation); } return resolveErrorCall(node); } - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 | 32768)) && isTypeAssignableTo(funcType, globalFunctionType); + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 | 131072)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1) { @@ -39478,11 +41317,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -39495,7 +41336,7 @@ var ts; return false; } var firstBase = baseTypes[0]; - if (firstBase.flags & 524288) { + if (firstBase.flags & 2097152) { var types = firstBase.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); var i = 0; @@ -39549,10 +41390,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -39573,8 +41415,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -39585,16 +41427,16 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 238: - case 207: + case 240: + case 209: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 149: + case 151: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 152: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 154: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 156: - case 157: + case 158: + case 159: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -39607,8 +41449,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -39627,45 +41469,58 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832, node); + var declaration = ts.createFunctionTypeNode(undefined, [ts.createParameter(undefined, undefined, undefined, "props", undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, undefined) : ts.createKeywordTypeNode(120)); + var parameterSymbol = createSymbol(1, "props"); + parameterSymbol.type = result; + return createSignature(declaration, undefined, undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, undefined, 1, false, false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { - ts.Debug.assert(!(elementType.flags & 262144)); - var callSignatures = elementType && getSignaturesOfType(elementType, 0); - if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); - } - return undefined; - } function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { - case 189: - return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); - case 190: - return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); case 191: + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); + case 192: + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); + case 193: return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); - case 150: + case 152: return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); - case 260: - case 259: - var exprTypes = checkExpression(node.tagName); - return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); - if (sfcResult && sfcResult !== unknownSignature) { - return sfcResult; - } - var sigs = getInstantiatedJsxSignatures(node, exprType); - if (candidatesOutArray && ts.length(sigs)) { - candidatesOutArray.push.apply(candidatesOutArray, sigs); - } - return ts.length(sigs) ? sigs[0] : unknownSignature; - }) || unknownSignature; + case 262: + case 261: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -39681,32 +41536,36 @@ var ts; links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { if (ts.getJSDocClassTag(node)) return true; - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { - if (type.flags & 131072) { + function isJSConstructorType(type) { + if (type.flags & 524288) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -39719,22 +41578,19 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } var parent = node.parent; - while (parent && parent.kind === 187) { + while (parent && parent.kind === 189) { parent = parent.parent; } - if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 58) { + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59) { var right = ts.getInitializerOfBinaryExpression(parent); return ts.isObjectLiteralExpression(right) && right; } @@ -39755,21 +41611,21 @@ var ts; if (!checkGrammarTypeArguments(node, node.typeArguments)) checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 97) { + if (node.expression.kind === 98) { return voidType; } - if (node.kind === 190) { + if (node.kind === 192) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 155 && - declaration.kind !== 159 && - declaration.kind !== 164 && + declaration.kind !== 157 && + declaration.kind !== 161 && + declaration.kind !== 166 && !ts.isJSDocConstructSignature(declaration)) { var funcSymbol = checkExpression(node.expression).symbol; - if (!funcSymbol && node.expression.kind === 71) { + if (!funcSymbol && node.expression.kind === 72) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -39779,16 +41635,16 @@ var ts; return anyType; } } - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); - if (returnType.flags & 3072 && isSymbolOrSymbolForCall(node)) { + if (returnType.flags & 12288 && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -39813,7 +41669,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319, undefined, undefined, false); + return globalESSymbol === resolveName(left, "Symbol", 67220415, undefined, undefined, false); } function checkImportCallExpression(node) { if (!checkGrammarArguments(node.arguments)) @@ -39826,7 +41682,7 @@ var ts; for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 8192 || specifierType.flags & 16384 || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 32768 || specifierType.flags & 65536 || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } var moduleSymbol = resolveExternalModuleName(node, specifier); @@ -39868,7 +41724,7 @@ var ts; } if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319, undefined, undefined, true); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415, undefined, undefined, true); if (resolvedRequire === requireSymbol) { return true; } @@ -39876,9 +41732,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 - ? 237 + ? 239 : resolvedRequire.flags & 3 - ? 235 + ? 237 : 0; if (targetDeclarationKind !== 0) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -39913,10 +41769,10 @@ var ts; } function checkMetaProperty(node) { checkGrammarMetaProperty(node); - if (node.keywordToken === 94) { + if (node.keywordToken === 95) { return checkNewTargetMetaProperty(node); } - if (node.keywordToken === 91) { + if (node.keywordToken === 92) { return checkImportMetaProperty(node); } return ts.Debug.assertNever(node.keywordToken); @@ -39927,7 +41783,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 155) { + else if (container.kind === 157) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -39991,14 +41847,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -40007,17 +41860,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -40041,15 +41884,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -40057,6 +41891,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -40106,7 +41951,7 @@ var ts; for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71) { + if (element.name.kind === 72) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } else { @@ -40120,7 +41965,7 @@ var ts; if (!links.type) { links.type = contextualType; var decl = parameter.valueDeclaration; - if (decl.name.kind !== 71) { + if (decl.name.kind !== 72) { if (links.type === emptyObjectType) { links.type = getTypeFromBindingPattern(decl.name); } @@ -40136,6 +41981,14 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + var globalPromiseLikeType = getGlobalPromiseLikeType(true); + if (globalPromiseLikeType !== emptyGenericType) { + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -40157,7 +42010,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 216) { + if (func.body.kind !== 218) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2) { type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -40242,10 +42095,40 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0; + if (hasDefault) { + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768; + } + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768; + } + } + else { + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128; + } + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 199) { + var operandType = getTypeOfExpression(node.expression.expression); + var witnesses = getSwitchClauseTypeOfWitnesses(node); + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -40260,7 +42143,7 @@ var ts; if (!(func.flags & 128)) { return false; } - if (ts.some(func.body.statements, function (statement) { return statement.kind === 230 && isExhaustiveSwitchStatement(statement); })) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -40277,7 +42160,7 @@ var ts; if (functionFlags & 2) { type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 32768) { + if (type.flags & 131072) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -40290,18 +42173,18 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; } function mayReturnNever(func) { switch (func.kind) { - case 194: - case 195: + case 196: + case 197: return true; - case 154: - return func.parent.kind === 186; + case 156: + return func.parent.kind === 188; default: return false; } @@ -40310,14 +42193,14 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 1 | 4096)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 16384)) { return; } - if (func.kind === 153 || ts.nodeIsMissing(func.body) || func.body.kind !== 216 || !functionHasImplicitReturn(func)) { + if (func.kind === 155 || ts.nodeIsMissing(func.body) || func.body.kind !== 218 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256; - if (returnType && returnType.flags & 32768) { + if (returnType && returnType.flags & 131072) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -40340,7 +42223,8 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 154 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); if (checkMode === 1 && isContextSensitive(node)) { if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { var links_1 = getNodeLinks(node); @@ -40348,13 +42232,15 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 194) { + if (!hasGrammarError && node.kind === 196) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -40385,7 +42271,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -40396,7 +42281,7 @@ var ts; getAwaitedType(type) || errorType : type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 154 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1) === 0) { @@ -40406,7 +42291,7 @@ var ts; if (!ts.getEffectiveReturnTypeNode(node)) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 216) { + if (node.body.kind === 218) { checkSourceElement(node.body); } else { @@ -40424,26 +42309,54 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAssignableToKind(type, 168)) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { error(operand, diagnostic); return false; } return true; } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } function isReadonlySymbol(symbol) { return !!(ts.getCheckFlags(symbol) & 8 || symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || - symbol.flags & 8); + symbol.flags & 8 || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); } function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { if (symbol.flags & 4 && - (expr.kind === 187 || expr.kind === 188) && - expr.expression.kind === 99) { + (expr.kind === 189 || expr.kind === 190) && + expr.expression.kind === 100) { var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 155)) { + if (!(func && func.kind === 157)) { return true; } return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); @@ -40453,13 +42366,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 187 || expr.kind === 188) { + if (expr.kind === 189 || expr.kind === 190) { var node = ts.skipParentheses(expr.expression); - if (node.kind === 71) { + if (node.kind === 72) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152) { var declaration = getDeclarationOfAliasSymbol(symbol); - return !!declaration && declaration.kind === 249; + return !!declaration && declaration.kind === 251; } } } @@ -40467,7 +42380,7 @@ var ts; } function checkReferenceExpression(expr, invalidReferenceMessage) { var node = ts.skipOuterExpressions(expr, 2 | 1); - if (node.kind !== 71 && node.kind !== 187 && node.kind !== 188) { + if (node.kind !== 72 && node.kind !== 189 && node.kind !== 190) { error(expr, invalidReferenceMessage); return false; } @@ -40476,7 +42389,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 187 && expr.kind !== 188) { + if (expr.kind !== 189 && expr.kind !== 190) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -40512,36 +42425,51 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operand.kind === 8) { - if (node.operator === 38) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - else if (node.operator === 37) { - return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); - } + switch (node.operand.kind) { + case 8: + switch (node.operator) { + case 39: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9: + if (node.operator === 39) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } } switch (node.operator) { - case 37: case 38: - case 52: + case 39: + case 53: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 3072)) { + if (maybeTypeOfKind(operandType, 12288)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } - return numberType; - case 51: + if (node.operator === 38) { + if (maybeTypeOfKind(operandType, 2112)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52: checkTruthinessExpression(node.operand); - var facts = getTypeFacts(operandType) & (1048576 | 2097152); - return facts === 1048576 ? falseType : - facts === 2097152 ? trueType : + var facts = getTypeFacts(operandType) & (4194304 | 8388608); + return facts === 4194304 ? falseType : + facts === 8388608 ? trueType : booleanType; - case 43: case 44: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + case 45: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } - return numberType; + return getUnaryResultType(operandType); } return errorType; } @@ -40550,20 +42478,28 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112)) { + return isTypeAssignableToKind(operandType, 3) || maybeTypeOfKind(operandType, 296) + ? numberOrBigIntType + : bigintType; + } return numberType; } function maybeTypeOfKind(type, kind) { if (type.flags & kind & ~134217728 || kind & 134217728 && isGenericMappedType(type)) { return true; } - if (type.flags & 786432) { + if (type.flags & 3145728) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40575,21 +42511,22 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (3 | 4096 | 8192 | 16384)) { + if (strict && source.flags & (3 | 16384 | 32768 | 65536)) { return false; } - return !!(kind & 168) && isTypeAssignableTo(source, numberType) || - !!(kind & 68) && isTypeAssignableTo(source, stringType) || - !!(kind & 272) && isTypeAssignableTo(source, booleanType) || - !!(kind & 4096) && isTypeAssignableTo(source, voidType) || - !!(kind & 32768) && isTypeAssignableTo(source, neverType) || - !!(kind & 16384) && isTypeAssignableTo(source, nullType) || - !!(kind & 8192) && isTypeAssignableTo(source, undefinedType) || - !!(kind & 1024) && isTypeAssignableTo(source, esSymbolType) || - !!(kind & 16777216) && isTypeAssignableTo(source, nonPrimitiveType); + return !!(kind & 296) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132) && isTypeAssignableTo(source, stringType) || + !!(kind & 528) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { - return source.flags & 262144 ? + return source.flags & 1048576 ? ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : isTypeAssignableToKind(source, kind, strict); } @@ -40604,7 +42541,7 @@ var ts; return silentNeverType; } if (!isTypeAny(leftType) && - allTypesAssignableToKind(leftType, 32764)) { + allTypesAssignableToKind(leftType, 131068)) { 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) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -40618,10 +42555,10 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 168 | 3072))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 | 12288))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 | 14745600)) { + if (!isTypeAssignableToKind(rightType, 67108864 | 58982400)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -40631,17 +42568,17 @@ var ts; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { if (rightIsThis === void 0) { rightIsThis = false; } - if (property.kind === 273 || property.kind === 274) { + if (property.kind === 275 || property.kind === 276) { var name = property.name; - if (name.kind === 147) { + if (name.kind === 149) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -40649,13 +42586,13 @@ var ts; } var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { - return checkDestructuringAssignment(property.kind === 274 ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 276 ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 275) { + else if (property.kind === 277) { if (languageVersion < 6) { checkExternalEmitHelpers(property, 4); } @@ -40704,11 +42641,11 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 208) { - if (element.kind !== 206) { + if (element.kind !== 210) { + if (element.kind !== 208) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -40727,13 +42664,13 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 202 && restExpression.operatorToken.kind === 58) { + if (restExpression.kind === 204 && restExpression.operatorToken.kind === 59) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -40744,12 +42681,12 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 274) { + if (exprOrAssignment.kind === 276) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 8192)) { - sourceType = getTypeWithFacts(sourceType, 131072); + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768)) { + sourceType = getTypeWithFacts(sourceType, 524288); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); } @@ -40758,21 +42695,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 202 && target.operatorToken.kind === 58) { + if (target.kind === 204 && target.operatorToken.kind === 59) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 186) { + if (target.kind === 188) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 185) { + if (target.kind === 187) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 275 ? + var error = target.parent.kind === 277 ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { @@ -40783,69 +42720,70 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 71: - case 9: - case 12: - case 191: - case 204: + case 72: + case 10: case 13: + case 193: + case 206: + case 14: case 8: - case 101: - case 86: - case 95: - case 140: - case 194: - case 207: - case 195: - case 185: - case 186: + case 9: + case 102: + case 87: + case 96: + case 141: + case 196: + case 209: case 197: - case 211: - case 259: - case 258: + case 187: + case 188: + case 199: + case 213: + case 261: + case 260: return true; - case 203: + case 205: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 202: + case 204: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 200: - case 201: + case 202: + case 203: switch (node.operator) { - case 51: - case 37: - case 38: case 52: + case 38: + case 39: + case 53: return true; } return false; - case 198: - case 192: - case 210: + case 200: + case 194: + case 212: default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 24576) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 98304) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 && (left.kind === 186 || left.kind === 185)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99); + if (operator === 59 && (left.kind === 188 || left.kind === 187)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100); } var leftType; - if (operator === 53 || operator === 54) { + if (operator === 54 || operator === 55) { leftType = checkTruthinessExpression(left, checkMode); } else { @@ -40853,61 +42791,82 @@ var ts; } var rightType = checkExpression(right, checkMode); switch (operator) { - case 39: case 40: - case 61: - case 62: case 41: + case 62: case 63: case 42: case 64: - case 38: - case 60: - case 45: + case 43: case 65: + case 39: + case 61: case 46: case 66: case 47: case 67: - case 49: - case 69: - case 50: - case 70: case 48: case 68: + case 50: + case 70: + case 51: + case 71: + case 49: + case 69: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); var suggestedOperator = void 0; - if ((leftType.flags & 272) && - (rightType.flags & 272) && + if ((leftType.flags & 528) && + (rightType.flags & 528) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; } else { - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + if ((isTypeAssignableToKind(leftType, 3) && isTypeAssignableToKind(rightType, 3)) || + !(maybeTypeOfKind(leftType, 2112) || maybeTypeOfKind(rightType, 2112))) { + resultType_1 = numberType; } + else if (isTypeAssignableToKind(leftType, 2112) && isTypeAssignableToKind(rightType, 2112)) { + switch (operator) { + case 48: + case 68: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; } - return numberType; - case 37: - case 59: + case 38: + case 60: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 68) && !isTypeAssignableToKind(rightType, 68)) { + if (!isTypeAssignableToKind(leftType, 132) && !isTypeAssignableToKind(rightType, 132)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeAssignableToKind(leftType, 168, true) && isTypeAssignableToKind(rightType, 168, true)) { + if (isTypeAssignableToKind(leftType, 296, true) && isTypeAssignableToKind(rightType, 296, true)) { resultType = numberType; } - else if (isTypeAssignableToKind(leftType, 68, true) || isTypeAssignableToKind(rightType, 68, true)) { + else if (isTypeAssignableToKind(leftType, 2112, true) && isTypeAssignableToKind(rightType, 2112, true)) { + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132, true) || isTypeAssignableToKind(rightType, 132, true)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -40920,26 +42879,27 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 59) { + if (operator === 60) { checkAssignmentOperator(resultType); } return resultType; - case 27: - case 29: + case 28: case 30: case 31: + case 32: if (checkForDisallowedESSymbolOperand(operator)) { leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { reportOperatorError(); } } return booleanType; - case 32: case 33: case 34: case 35: + case 36: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -40950,29 +42910,37 @@ var ts; reportOperatorError(); } return booleanType; - case 93: + case 94: return checkInstanceOfExpression(left, right, leftType, rightType); - case 92: + case 93: return checkInExpression(left, right, leftType, rightType); - case 53: - return getTypeFacts(leftType) & 1048576 ? + case 54: + return getTypeFacts(leftType) & 4194304 ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; - case 54: - return getTypeFacts(leftType) & 2097152 ? + case 55: + return getTypeFacts(leftType) & 8388608 ? getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2) : leftType; - case 58: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + case 59: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288) || + declKind !== 2 && + declKind !== 6 && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1)) { + checkAssignmentOperator(rightType); + } return leftType; } else { checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); } - case 26: + case 27: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -40980,15 +42948,14 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2) { - var rightType_1 = checkExpression(right, checkMode); - for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928, undefined, name, false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832, undefined, name, false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -40998,11 +42965,11 @@ var ts; } } function isEvalNode(node) { - return node.kind === 71 && node.escapedText === "eval"; + return node.kind === 72 && node.escapedText === "eval"; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 3072) ? left : - maybeTypeOfKind(rightType, 3072) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288) ? left : + maybeTypeOfKind(rightType, 12288) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -41012,15 +42979,15 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { + case 50: + case 70: + return 55; + case 51: + case 71: + return 36; case 49: case 69: return 54; - case 50: - case 70: - return 35; - case 48: - case 68: - return 53; default: return undefined; } @@ -41033,8 +43000,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2: return true; case 1: @@ -41043,7 +43010,7 @@ var ts; case 3: case 4: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -41060,11 +43027,11 @@ var ts; } function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { switch (operatorToken.kind) { - case 34: - case 32: - return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); case 35: case 33: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); + case 36: + case 34: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); } return undefined; @@ -41128,14 +43095,14 @@ var ts; } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { - if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072)) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288)) { error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; } function getContextNode(node) { - if (node.kind === 266) { + if (node.kind === 268 && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; } return node; @@ -41168,25 +43135,21 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 192 || node.kind === 210; + return node.kind === 194 || node.kind === 212; } function checkDeclarationInitializer(declaration) { var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, true); var widened = ts.getCombinedNodeFlags(declaration) & 2 || - (ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { - if (widened.flags & 24576) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304) { + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -41194,41 +43157,43 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 786432) { + if (contextualType.flags & 3145728) { var types = contextualType.types; return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } - if (contextualType.flags & 14745600) { + if (contextualType.flags & 58982400) { var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 64) || - maybeTypeOfKind(constraint, 8) && maybeTypeOfKind(candidateType, 128) || - maybeTypeOfKind(constraint, 1024) && maybeTypeOfKind(candidateType, 2048) || + return maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 128) || + maybeTypeOfKind(constraint, 8) && maybeTypeOfKind(candidateType, 256) || + maybeTypeOfKind(constraint, 64) && maybeTypeOfKind(candidateType, 2048) || + maybeTypeOfKind(constraint, 4096) && maybeTypeOfKind(candidateType, 8192) || isLiteralOfContextualType(candidateType, constraint); } - return !!(contextualType.flags & (64 | 1048576) && maybeTypeOfKind(candidateType, 64) || - contextualType.flags & 128 && maybeTypeOfKind(candidateType, 128) || + return !!(contextualType.flags & (128 | 4194304) && maybeTypeOfKind(candidateType, 128) || contextualType.flags & 256 && maybeTypeOfKind(candidateType, 256) || - contextualType.flags & 2048 && maybeTypeOfKind(candidateType, 2048)); + contextualType.flags & 2048 && maybeTypeOfKind(candidateType, 2048) || + contextualType.flags & 512 && maybeTypeOfKind(candidateType, 512) || + contextualType.flags & 8192 && maybeTypeOfKind(candidateType, 8192)); } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } function checkPropertyAssignment(node, checkMode) { - if (node.name.kind === 147) { + if (node.name.kind === 149) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); } function checkObjectLiteralMethod(node, checkMode) { checkGrammarMethod(node); - if (node.name.kind === 147) { + if (node.name.kind === 149) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -41250,36 +43215,44 @@ var ts; return type; } function getTypeOfExpression(node, cache) { - if (node.kind === 189 && node.expression.kind !== 97 && !ts.isRequireCall(node, true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + var expr = ts.skipParentheses(node); + if (expr.kind === 191 && expr.expression.kind !== 98 && !ts.isRequireCall(expr, true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 194 || expr.kind === 212) { + return getTypeFromTypeNode(expr.type); + } return cache ? checkExpressionCached(node) : checkExpression(node); } function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1); node.contextualType = saveContextualType; return type; } - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; - if (node.kind === 146) { + if (node.kind === 148) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 187 && node.parent.expression === node) || - (node.parent.kind === 188 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 146) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 165 && node.parent.exprName === node)); + var ok = (node.parent.kind === 189 && node.parent.expression === node) || + (node.parent.kind === 190 && node.parent.expression === node) || + ((node.kind === 72 || node.kind === 148) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 && node.parent.exprName === 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_or_type_query); } @@ -41287,101 +43260,104 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { - case 71: + case 72: return checkIdentifier(node); - case 99: + case 100: return checkThisExpression(node); - case 97: + case 98: return checkSuperExpression(node); - case 95: + case 96: return nullWideningType; - case 13: - case 9: + case 14: + case 10: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101: + case 9: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102: return trueType; - case 86: + case 87: return falseType; - case 204: + case 206: return checkTemplateExpression(node); - case 12: + case 13: return globalRegExpType; - case 185: - return checkArrayLiteral(node, checkMode); - case 186: - return checkObjectLiteral(node, checkMode); case 187: - return checkPropertyAccessExpression(node); + return checkArrayLiteral(node, checkMode, forceTuple); case 188: - return checkIndexedAccess(node); + return checkObjectLiteral(node, checkMode); case 189: - if (node.expression.kind === 91) { + return checkPropertyAccessExpression(node); + case 190: + return checkIndexedAccess(node); + case 191: + if (node.expression.kind === 92) { return checkImportCallExpression(node); } - case 190: - return checkCallExpression(node); - case 191: - return checkTaggedTemplateExpression(node); - case 193: - return checkParenthesizedExpression(node, checkMode); - case 207: - return checkClassExpression(node); - case 194: - case 195: - return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 197: - return checkTypeOfExpression(node); case 192: - case 210: - return checkAssertion(node); - case 211: - return checkNonNullAssertion(node); - case 212: - return checkMetaProperty(node); + return checkCallExpression(node); + case 193: + return checkTaggedTemplateExpression(node); + case 195: + return checkParenthesizedExpression(node, checkMode); + case 209: + return checkClassExpression(node); case 196: - return checkDeleteExpression(node); - case 198: - return checkVoidExpression(node); + case 197: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); case 199: - return checkAwaitExpression(node); - case 200: - return checkPrefixUnaryExpression(node); - case 201: - return checkPostfixUnaryExpression(node); - case 202: - return checkBinaryExpression(node, checkMode); - case 203: - return checkConditionalExpression(node, checkMode); - case 206: - return checkSpreadExpression(node, checkMode); - case 208: - return undefinedWideningType; - case 205: - return checkYieldExpression(node); + return checkTypeOfExpression(node); + case 194: + case 212: + return checkAssertion(node); case 213: + return checkNonNullAssertion(node); + case 214: + return checkMetaProperty(node); + case 198: + return checkDeleteExpression(node); + case 200: + return checkVoidExpression(node); + case 201: + return checkAwaitExpression(node); + case 202: + return checkPrefixUnaryExpression(node); + case 203: + return checkPostfixUnaryExpression(node); + case 204: + return checkBinaryExpression(node, checkMode); + case 205: + return checkConditionalExpression(node, checkMode); + case 208: + return checkSpreadExpression(node, checkMode); + case 210: + return undefinedWideningType; + case 207: + return checkYieldExpression(node); + case 215: return node.type; - case 268: + case 270: return checkJsxExpression(node, checkMode); - case 258: - return checkJsxElement(node, checkMode); - case 259: - return checkJsxSelfClosingElement(node, checkMode); - case 262: - return checkJsxFragment(node, checkMode); - case 266: - return checkJsxAttributes(node, checkMode); case 260: + return checkJsxElement(node, checkMode); + case 261: + return checkJsxSelfClosingElement(node, checkMode); + case 264: + return checkJsxFragment(node); + case 268: + return checkJsxAttributes(node, checkMode); + case 262: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -41408,15 +43384,12 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92)) { - if (!(func.kind === 155 && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 157 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -41427,14 +43400,14 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 155 || func.kind === 159 || func.kind === 164) { + if (func.kind === 157 || func.kind === 161 || func.kind === 166) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 195) { + if (func.kind === 197) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } } - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -41481,13 +43454,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 195: - case 158: - case 237: - case 194: - case 163: - case 154: - case 153: + case 197: + case 160: + case 239: + case 196: + case 165: + case 156: + case 155: var parent = node.parent; if (node === parent.type) { return parent; @@ -41501,11 +43474,11 @@ var ts; continue; } var name = element.name; - if (name.kind === 71 && name.escapedText === predicateVariableName) { + if (name.kind === 72 && name.escapedText === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 183 || name.kind === 182) { + else if (name.kind === 185 || name.kind === 184) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -41513,12 +43486,12 @@ var ts; } } function checkSignatureDeclaration(node) { - if (node.kind === 160) { + if (node.kind === 162) { checkGrammarIndexSignature(node); } - else if (node.kind === 163 || node.kind === 237 || node.kind === 164 || - node.kind === 158 || node.kind === 155 || - node.kind === 159) { + else if (node.kind === 165 || node.kind === 239 || node.kind === 166 || + node.kind === 160 || node.kind === 157 || + node.kind === 161) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -41543,10 +43516,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 159: + case 161: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 158: + case 160: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -41570,7 +43543,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 160 && node.kind !== 287) { + if (node.kind !== 162 && node.kind !== 289) { registerForUnusedIdentifiersCheck(node); } } @@ -41580,7 +43553,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 155) { + if (member.kind === 157) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -41595,16 +43568,16 @@ var ts; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (name && memberName) { switch (member.kind) { - case 156: + case 158: addName(names, name, memberName, 1); break; - case 157: + case 159: addName(names, name, memberName, 2); break; - case 152: + case 154: addName(names, name, memberName, 3); break; - case 154: + case 156: addName(names, name, memberName, 4); break; } @@ -41656,15 +43629,15 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151) { + if (member.kind === 153) { var memberName = void 0; var name = member.name; switch (name.kind) { - case 9: + case 10: case 8: memberName = name.text; break; - case 71: + case 72: memberName = ts.idText(name); break; default: @@ -41681,7 +43654,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 239) { + if (node.kind === 241) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -41696,7 +43669,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 137: + case 138: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -41704,7 +43677,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134: + case 135: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -41726,7 +43699,7 @@ var ts; if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); checkFunctionOrMethodDeclaration(node); - if (ts.hasModifier(node, 128) && node.kind === 154 && node.body) { + if (ts.hasModifier(node, 128) && node.kind === 156 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -41747,7 +43720,7 @@ var ts; return; } function isInstancePropertyWithInitializer(n) { - return n.kind === 152 && + return n.kind === 154 && !ts.hasModifier(n, 32) && !!n.initializer; } @@ -41767,7 +43740,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 219 && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -41791,18 +43764,18 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 156) { + if (node.kind === 158) { if (!(node.flags & 4194304) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { if (!(node.flags & 256)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } } - if (node.name.kind === 147) { + if (node.name.kind === 149) { checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(node)) { - var otherKind = node.kind === 156 ? 157 : 156; + var otherKind = node.kind === 158 ? 159 : 158; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); @@ -41818,7 +43791,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156) { + if (node.kind === 158) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -41835,7 +43808,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -41866,7 +43839,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 164 && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -41913,7 +43886,7 @@ var ts; var seenOptionalElement = false; for (var i = 0; i < elementTypes.length; i++) { var e = elementTypes[i]; - if (e.kind === 170) { + if (e.kind === 172) { if (i !== elementTypes.length - 1) { grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); break; @@ -41922,7 +43895,7 @@ var ts; error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); } } - else if (e.kind === 169) { + else if (e.kind === 171) { seenOptionalElement = true; } else if (seenOptionalElement) { @@ -41937,19 +43910,19 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 2097152)) { + if (!(type.flags & 8388608)) { return type; } var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, false))) { - if (accessNode.kind === 188 && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 190 && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 && getMappedTypeModifiers(objectType) & 1) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } return type; } - if (getIndexInfoOfType(getApparentType(objectType), 1) && isTypeAssignableToKind(indexType, 168)) { + if (getIndexInfoOfType(getApparentType(objectType), 1) && isTypeAssignableToKind(indexType, 296)) { return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -41963,8 +43936,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -41981,7 +43954,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 173 && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -41996,9 +43969,9 @@ var ts; } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 239 && - n.parent.kind !== 238 && - n.parent.kind !== 207 && + if (n.parent.kind !== 241 && + n.parent.kind !== 240 && + n.parent.kind !== 209 && n.flags & 4194304) { if (!(flags & 2) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { flags |= 1; @@ -42078,7 +44051,7 @@ var ts; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 154 || node.kind === 153) && + var reportError = (node.kind === 156 || node.kind === 155) && ts.hasModifier(node, 32) !== ts.hasModifier(subsequentNode, 32); if (reportError) { var diagnostic = ts.hasModifier(node, 32) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; @@ -42111,11 +44084,11 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = node.flags & 4194304; - var inAmbientContextOrInterface = node.parent.kind === 239 || node.parent.kind === 166 || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 241 || node.parent.kind === 168 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 237 || node.kind === 154 || node.kind === 153 || node.kind === 155) { + if (node.kind === 239 || node.kind === 156 || node.kind === 155 || node.kind === 157) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -42166,8 +44139,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var signature = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -42228,36 +44201,36 @@ var ts; function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 239: - case 240: - case 302: - case 295: - return 2; + case 241: case 242: + case 304: + case 297: + return 2; + case 244: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 ? 4 | 1 : 4; - case 238: - case 241: + case 240: + case 243: return 2 | 1; - case 277: + case 279: return 2 | 1 | 4; - case 252: + case 254: if (!ts.isEntityNameExpression(d.expression)) { return 1; } d = d.expression; - case 246: - case 249: case 248: - var result_3 = 0; - var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 235: - case 184: - case 237: case 251: + case 250: + var result_4 = 0; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237: + case 186: + case 239: + case 253: return 1; default: return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); @@ -42290,7 +44263,7 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -42314,7 +44287,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 262144) { + if (type.flags & 1048576) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -42374,10 +44347,10 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319, true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415, true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { - if (promiseConstructorName.kind === 71 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { + if (promiseConstructorName.kind === 72 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { @@ -42394,7 +44367,7 @@ var ts; return; } var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -42412,22 +44385,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 238: + case 240: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 149: + case 151: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 152: + case 154: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 154: case 156: - case 157: + case 158: + case 159: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -42444,7 +44417,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 ? 67901928 : 1920) | 2097152; + var meaning = (typeName.kind === 72 ? 67897832 : 1920) | 2097152; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol && rootSymbol.flags & 2097152 @@ -42462,43 +44435,48 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 172: - case 171: - var commonEntityName = void 0; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175) { - typeNode = typeNode.type; - } - if (typeNode.kind === 131) { - continue; - } - if (!strictNullChecks && (typeNode.kind === 95 || typeNode.kind === 140)) { - continue; - } - var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); - if (!individualEntityName) { - return undefined; - } - if (commonEntityName) { - if (!ts.isIdentifier(commonEntityName) || - !ts.isIdentifier(individualEntityName) || - commonEntityName.escapedText !== individualEntityName.escapedText) { - return undefined; - } - } - else { - commonEntityName = individualEntityName; - } - } - return commonEntityName; + case 174: + case 173: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); case 175: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177: return getEntityNameForDecoratorMetadata(node.type); - case 162: + case 164: return node.typeName; } } } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177) { + typeNode = typeNode.type; + } + if (typeNode.kind === 132) { + continue; + } + if (!strictNullChecks && (typeNode.kind === 96 || typeNode.kind === 141)) { + continue; + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } function getParameterTypeNodeForDecoratorCheck(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; @@ -42515,13 +44493,13 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8); - if (node.kind === 149) { + if (node.kind === 151) { checkExternalEmitHelpers(firstDecorator, 32); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16); switch (node.kind) { - case 238: + case 240: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -42530,23 +44508,23 @@ var ts; } } break; - case 156: - case 157: - var otherKind = node.kind === 156 ? 157 : 156; + case 158: + case 159: + var otherKind = node.kind === 158 ? 159 : 158; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 154: + case 156: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 152: + case 154: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 149: + case 151: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -42595,16 +44573,22 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 146 ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 ? node.name.right : node.name)); } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 146 ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 ? node.name.right : node.name)); } } } } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } function checkJSDocAugmentsTag(node) { var classLike = ts.getJSDocHost(node); if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { @@ -42627,9 +44611,9 @@ var ts; } function getIdentifierFromEntityNameExpression(node) { switch (node.kind) { - case 71: + case 72: return node; - case 187: + case 189: return node.name; default: return undefined; @@ -42639,7 +44623,7 @@ var ts; checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); - if (node.name && node.name.kind === 147) { + if (node.name && node.name.kind === 149) { checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(node)) { @@ -42655,21 +44639,21 @@ var ts; } } } - var body = node.kind === 153 ? undefined : node.body; + var body = node.kind === 155 ? undefined : node.body; checkSourceElement(body); if ((functionFlags & 1) === 0) { var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 && ts.nodeIsPresent(body)) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -42677,7 +44661,7 @@ var ts; } } function registerForUnusedIdentifiersCheck(node) { - if (produceDiagnostics) { + if (produceDiagnostics && !(node.flags & 4194304)) { var sourceFile = ts.getSourceFileOfNode(node); var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); if (!potentiallyUnusedIdentifiers) { @@ -42691,44 +44675,44 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 238: - case 207: + case 240: + case 209: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 239: - checkUnusedTypeParameters(node, addDiagnostic); - break; - case 277: - case 242: - case 216: + case 279: case 244: - case 223: - case 224: + case 218: + case 246: case 225: + case 226: + case 227: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 155: - case 194: - case 237: - case 195: - case 154: - case 156: case 157: + case 196: + case 239: + case 197: + case 156: + case 158: + case 159: if (node.body) { checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 153: - case 158: - case 159: - case 163: - case 164: - case 240: - case 174: + case 155: + case 160: + case 161: + case 165: + case 166: + case 242: + case 241: checkUnusedTypeParameters(node, addDiagnostic); break; + case 176: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; default: ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); } @@ -42743,72 +44727,68 @@ var ts; return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95; } function checkUnusedClassMembers(node, addDiagnostic) { - if (!(node.flags & 4194304)) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 154: - case 152: - case 156: - case 157: - if (member.kind === 157 && member.symbol.flags & 32768) { - break; - } - var symbol = getSymbolOfNode(member); - if (!symbol.isReferenced && ts.hasModifier(member, 8)) { - addDiagnostic(member, 0, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156: + case 154: + case 158: + case 159: + if (member.kind === 159 && member.symbol.flags & 32768) { break; - case 155: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { - addDiagnostic(parameter, 0, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8)) { + addDiagnostic(member, 0, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { + addDiagnostic(parameter, 0, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } - break; - case 160: - case 215: - break; - default: - ts.Debug.fail(); - } + } + break; + case 162: + case 217: + break; + default: + ts.Debug.fail(); } } } - function checkUnusedTypeParameters(node, addDiagnostic) { - if (node.flags & 4194304 || node.kind !== 174 && ts.last(getSymbolOfNode(node).declarations) !== node) - return; - if (node.kind === 174) { - var typeParameter = node.typeParameter; - if (isTypeParameterUnused(typeParameter)) { - addDiagnostic(node, 1, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); - } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); } - else { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - var seenParentsWithEveryUnused = new ts.NodeSet(); - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var typeParameter = typeParameters_2[_i]; - if (!isTypeParameterUnused(typeParameter)) - continue; - var name = ts.idText(typeParameter.name); - var parent = typeParameter.parent; - if (parent.kind !== 174 && parent.typeParameters.every(isTypeParameterUnused)) { - if (seenParentsWithEveryUnused.tryAdd(parent)) { - var range = ts.isJSDocTemplateTag(parent) - ? ts.rangeOfNode(parent) - : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; - var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; - var arg0 = only ? name : undefined; - addDiagnostic(typeParameter, 1, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); - } - } - else { - addDiagnostic(typeParameter, 1, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); + } + function checkUnusedTypeParameters(node, addDiagnostic) { + if (ts.last(getSymbolOfNode(node).declarations) !== node) + return; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + ? ts.rangeOfNode(parent) + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); } } + else { + addDiagnostic(typeParameter, 1, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); + } } } function isTypeParameterUnused(typeParameter) { @@ -42874,7 +44854,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 249 ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 251 ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0, unuseds.length === 1 @@ -42892,7 +44872,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 : 0; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 235 && bindingPattern.parent.parent.kind === 236) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 && bindingPattern.parent.parent.kind === 238) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -42913,7 +44893,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 217 ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -42925,23 +44905,23 @@ var ts; } function bindingNameText(name) { switch (name.kind) { - case 71: + case 72: return ts.idText(name); - case 183: - case 182: + case 185: + case 184: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 248 || node.kind === 251 || node.kind === 249; + return node.kind === 250 || node.kind === 253 || node.kind === 251; } function importClauseFromImported(decl) { - return decl.kind === 248 ? decl : decl.kind === 249 ? decl.parent : decl.parent.parent; + return decl.kind === 250 ? decl : decl.kind === 251 ? decl.parent : decl.parent.parent; } function checkBlock(node) { - if (node.kind === 216) { + if (node.kind === 218) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -42970,19 +44950,19 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 152 || - node.kind === 151 || - node.kind === 154 || + if (node.kind === 154 || node.kind === 153 || node.kind === 156 || - node.kind === 157) { + node.kind === 155 || + node.kind === 158 || + node.kind === 159) { return false; } if (node.flags & 4194304) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 149 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 151 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -42990,7 +44970,7 @@ var ts; function checkIfThisIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 4) { - var isDeclaration_1 = node.kind !== 71; + var isDeclaration_1 = node.kind !== 72; if (isDeclaration_1) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -43005,7 +44985,7 @@ var ts; function checkIfNewTargetIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 8) { - var isDeclaration_2 = node.kind !== 71; + var isDeclaration_2 = node.kind !== 72; if (isDeclaration_2) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } @@ -43028,7 +45008,7 @@ var ts; return; } var parent = getDeclarationContainer(node); - if (parent.kind === 277 && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 279 && 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)); } } @@ -43040,7 +45020,7 @@ var ts; return; } var parent = getDeclarationContainer(node); - if (parent.kind === 277 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { + if (parent.kind === 279 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -43048,7 +45028,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 235 && !node.initializer) { + if (node.kind === 237 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -43060,15 +45040,15 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 236); - var container = varDeclList.parent.kind === 217 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238); + var container = varDeclList.parent.kind === 219 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 216 && ts.isFunctionLike(container.parent) || - container.kind === 243 || - container.kind === 242 || - container.kind === 277); + (container.kind === 218 && ts.isFunctionLike(container.parent) || + container.kind === 245 || + container.kind === 244 || + container.kind === 279); if (!namesShareScope) { var name = symbolToString(localDeclarationSymbol); error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); @@ -43078,7 +45058,7 @@ var ts; } } function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 149) { + if (ts.getRootDeclaration(node).kind !== 151) { return; } var func = ts.getContainingFunction(node); @@ -43087,11 +45067,11 @@ var ts; if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { return; } - if (n.kind === 187) { + if (n.kind === 189) { return visit(n.expression); } - else if (n.kind === 71) { - var symbol = resolveName(n, n.escapedText, 67216319 | 2097152, undefined, undefined, false); + else if (n.kind === 72) { + var symbol = resolveName(n, n.escapedText, 67220415 | 2097152, undefined, undefined, false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -43101,8 +45081,8 @@ var ts; } var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 149 || - symbol.valueDeclaration.kind === 184) { + if (symbol.valueDeclaration.kind === 151 || + symbol.valueDeclaration.kind === 186) { if (symbol.valueDeclaration.pos < node.pos) { return; } @@ -43111,7 +45091,7 @@ var ts; return "quit"; } return ts.isFunctionLike(current.parent) || - (current.parent.kind === 152 && + (current.parent.kind === 154 && !(ts.hasModifier(current.parent, 32)) && ts.isClassLike(current.parent.parent)); })) { @@ -43137,17 +45117,17 @@ var ts; if (!node.name) { return; } - if (node.name.kind === 147) { + if (node.name.kind === 149) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 184) { - if (node.parent.kind === 182 && languageVersion < 6) { + if (node.kind === 186) { + if (node.parent.kind === 184 && languageVersion < 6) { checkExternalEmitHelpers(node, 4); } - if (node.propertyName && node.propertyName.kind === 147) { + if (node.propertyName && node.propertyName.kind === 149) { checkComputedPropertyName(node.propertyName); } var parent = node.parent.parent; @@ -43157,25 +45137,25 @@ var ts; var nameText = ts.getTextOfPropertyName(name); if (nameText) { var property = getPropertyOfType(parentType, nameText); - markPropertyAsReferenced(property, undefined, false); - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { - checkPropertyAccessibility(parent, parent.initializer.kind === 97, parentType, property); + if (property) { + markPropertyAsReferenced(property, undefined, false); + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98, parentType, property); } } } } if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 183 && languageVersion < 2 && compilerOptions.downlevelIteration) { + if (node.name.kind === 185 && languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512); } ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 149 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 151 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } if (ts.isBindingPattern(node.name)) { - if (node.initializer && node.parent.parent.kind !== 224) { + if (node.initializer && node.parent.parent.kind !== 226) { var initializerType = checkExpressionCached(node.initializer); if (strictNullChecks && node.name.elements.length === 0) { checkNonNullType(initializerType, node); @@ -43192,15 +45172,20 @@ var ts; if (node === symbol.valueDeclaration) { var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 224) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, undefined); checkParameterInitializer(node); } } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } } else { var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); @@ -43213,13 +45198,12 @@ var ts; checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 152 && node.kind !== 151) { + if (node.kind !== 154 && node.kind !== 153) { checkExportsOnMergedDeclarations(node); - if (node.kind === 235 || node.kind === 184) { + if (node.kind === 237 || node.kind === 186) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -43228,14 +45212,14 @@ var ts; } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 152 || nextDeclaration.kind === 151 + var message = nextDeclaration.kind === 154 || nextDeclaration.kind === 153 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 149 && right.kind === 235) || - (left.kind === 235 && right.kind === 149)) { + if ((left.kind === 151 && right.kind === 237) || + (left.kind === 237 && right.kind === 151)) { return true; } if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { @@ -43270,7 +45254,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 218) { + if (node.thenStatement.kind === 220) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -43287,19 +45271,19 @@ var ts; } function checkTruthinessExpression(node, checkMode) { var type = checkExpression(node, checkMode); - if (type.flags & 4096) { + if (type.flags & 16384) { error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); } return type; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 236) { + if (node.initializer && node.initializer.kind === 238) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 236) { + if (node.initializer.kind === 238) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -43326,13 +45310,13 @@ var ts; else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } - if (node.initializer.kind === 236) { + if (node.initializer.kind === 238) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); - if (varExpr.kind === 185 || varExpr.kind === 186) { + if (varExpr.kind === 187 || varExpr.kind === 188) { checkDestructuringAssignment(varExpr, iteratedType || errorType); } else { @@ -43350,8 +45334,8 @@ var ts; } function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); - if (node.initializer.kind === 236) { + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); + if (node.initializer.kind === 238) { 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); @@ -43361,7 +45345,7 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 185 || varExpr.kind === 186) { + if (varExpr.kind === 187 || varExpr.kind === 188) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -43371,7 +45355,7 @@ var ts; checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - if (rightType === neverType || !isTypeAssignableToKind(rightType, 16777216 | 14745600)) { + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 | 58982400)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -43413,14 +45397,14 @@ var ts; var reportedError = false; var hasStringConstituent = false; if (allowStringInput) { - if (arrayType.flags & 262144) { + if (arrayType.flags & 1048576) { var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 68); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, 2); } } - else if (arrayType.flags & 68) { + else if (arrayType.flags & 132) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -43431,7 +45415,7 @@ var ts; reportedError = true; } } - if (arrayType.flags & 32768) { + if (arrayType.flags & 131072) { return stringType; } } @@ -43456,7 +45440,7 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1); if (hasStringConstituent && arrayElementType) { - if (arrayElementType.flags & 68) { + if (arrayElementType.flags & 132) { return stringType; } return getUnionType([arrayElementType, stringType], 2); @@ -43481,11 +45465,15 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } if (isReferenceToType(type, getGlobalIterableType(false)) || isReferenceToType(type, getGlobalIterableIteratorType(false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -43508,9 +45496,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -43583,7 +45573,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 ? getPromisedTypeOfPromise(returnType) : returnType; - return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 4096 | 3); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 | 3); } function checkReturnStatement(node) { if (checkGrammarStatementInAmbientContext(node)) { @@ -43598,17 +45588,17 @@ var ts; var returnType = getReturnTypeOfSignature(signature); var functionFlags = ts.getFunctionFlags(func); var isGenerator = functionFlags & 1; - if (strictNullChecks || node.expression || returnType.flags & 32768) { + if (strictNullChecks || node.expression || returnType.flags & 131072) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (isGenerator) { return; } - else if (func.kind === 157) { + else if (func.kind === 159) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 155) { + else if (func.kind === 157) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -43626,7 +45616,7 @@ var ts; } } } - else if (func.kind !== 155 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + else if (func.kind !== 157 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } @@ -43651,7 +45641,7 @@ var ts; var expressionType = checkExpression(node.expression); var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 270 && !hasDuplicateDefaultClause) { + if (clause.kind === 272 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -43663,7 +45653,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 269) { + if (produceDiagnostics && clause.kind === 271) { var caseType = checkExpression(clause.expression); var caseIsLiteral = isLiteralType(caseType); var comparedExpressionType = expressionType; @@ -43687,7 +45677,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 231 && current.label.escapedText === node.label.escapedText) { + if (current.kind === 233 && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -43782,8 +45772,8 @@ var ts; } var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 202 || - name.kind === 147 || + (propDeclaration.kind === 204 || + name.kind === 149 || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -43807,6 +45797,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -43965,13 +45956,15 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 2162688 && !isMixinConstructorType(staticType)) { + else { + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 2162688)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 8650752)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -43999,7 +45992,7 @@ var ts; } } else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -44013,7 +46006,7 @@ var ts; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -44031,7 +46024,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -44054,7 +46047,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 238 || d.kind === 239; + return d.kind === 240 || d.kind === 241; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -44072,7 +46065,7 @@ var ts; if (derived === base) { var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128))) { - if (derivedClassDecl.kind === 207) { + if (derivedClassDecl.kind === 209) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -44119,8 +46112,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -44151,7 +46144,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 || getFalsyFlags(type) & 8192)) { + if (!(type.flags & 3 || getFalsyFlags(type) & 32768)) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -44161,16 +46154,18 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 152 && + return node.kind === 154 && !ts.hasModifier(node, 32 | 128) && !node.exclamationToken && !node.initializer; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 8192); + return !(getFalsyFlags(flowType) & 32768); } function checkInterfaceDeclaration(node) { if (!checkGrammarDecoratorsAndModifiers(node)) @@ -44181,7 +46176,7 @@ var ts; checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 239); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -44277,60 +46272,60 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 200: + case 202: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { - case 37: return value_2; - case 38: return -value_2; - case 52: return ~value_2; + case 38: return value_2; + case 39: return -value_2; + case 53: return ~value_2; } } break; - case 202: + case 204: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { switch (expr.operatorToken.kind) { - case 49: return left | right; - case 48: return left & right; - case 46: return left >> right; - case 47: return left >>> right; - case 45: return left << right; - case 50: return left ^ right; - case 39: return left * right; - case 41: return left / right; - case 37: return left + right; - case 38: return left - right; - case 42: return left % right; - case 40: return Math.pow(left, right); + case 50: return left | right; + case 49: return left & right; + case 47: return left >> right; + case 48: return left >>> right; + case 46: return left << right; + case 51: return left ^ right; + case 40: return left * right; + case 42: return left / right; + case 38: return left + right; + case 39: return left - right; + case 43: return left % right; + case 41: return Math.pow(left, right); } } - else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 37) { + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38) { return left + right; } break; - case 9: + case 10: return expr.text; case 8: checkGrammarNumericLiteral(expr); return +expr.text; - case 193: + case 195: return evaluate(expr.expression); - case 71: + case 72: var identifier = expr; if (isInfinityOrNaNString(identifier.escapedText)) { return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 188: - case 187: + case 190: + case 189: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384) { var name = void 0; - if (ex.kind === 187) { + if (ex.kind === 189) { name = ex.name.escapedText; } else { @@ -44361,10 +46356,10 @@ var ts; } } function isConstantMemberAccess(node) { - return node.kind === 71 || - node.kind === 187 && isConstantMemberAccess(node.expression) || - node.kind === 188 && isConstantMemberAccess(node.expression) && - node.argumentExpression.kind === 9; + return node.kind === 72 || + node.kind === 189 && isConstantMemberAccess(node.expression) || + node.kind === 190 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10; } function checkEnumDeclaration(node) { if (!produceDiagnostics) { @@ -44392,7 +46387,7 @@ var ts; } var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 241) { + if (declaration.kind !== 243) { return false; } var enumDeclaration = declaration; @@ -44415,8 +46410,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { var declaration = declarations_8[_i]; - if ((declaration.kind === 238 || - (declaration.kind === 237 && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 240 || + (declaration.kind === 239 && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304)) { return declaration; } @@ -44451,7 +46446,7 @@ var ts; return; } if (!checkGrammarDecoratorsAndModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9) { + if (!inAmbientContext && node.name.kind === 10) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } @@ -44474,7 +46469,7 @@ 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, 238); + var mergedClass = ts.getDeclarationOfKind(symbol, 240); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; @@ -44517,22 +46512,22 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 217: + case 219: for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 252: - case 253: + case 254: + case 255: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 246: - case 247: + case 248: + case 249: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 184: - case 235: + case 186: + case 237: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -44541,12 +46536,12 @@ var ts; } break; } - case 238: - case 241: - case 237: - case 239: - case 242: case 240: + case 243: + case 239: + case 241: + case 244: + case 242: if (isGlobalAugmentation) { return; } @@ -44554,7 +46549,7 @@ var ts; if (symbol) { var reportError = !(symbol.flags & 33554432); if (!reportError) { - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -44562,17 +46557,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 71: + case 72: return node; - case 146: + case 148: do { node = node.left; - } while (node.kind !== 71); + } while (node.kind !== 72); return node; - case 187: + case 189: do { node = node.expression; - } while (node.kind !== 71); + } while (node.kind !== 72); return node; } } @@ -44585,9 +46580,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 243 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 277 && !inAmbientExternalModule) { - error(moduleName, node.kind === 253 ? + var inAmbientExternalModule = node.parent.kind === 245 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -44604,18 +46599,18 @@ var ts; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { - var excludedMeanings = (symbol.flags & (67216319 | 1048576) ? 67216319 : 0) | - (symbol.flags & 67901928 ? 67901928 : 0) | + var excludedMeanings = (symbol.flags & (67220415 | 1048576) ? 67220415 : 0) | + (symbol.flags & 67897832 ? 67897832 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 255 ? + var message = node.kind === 257 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } if (compilerOptions.isolatedModules - && node.kind === 255 - && !(target.flags & 67216319) + && node.kind === 257 + && !(target.flags & 67220415) && !(node.flags & 4194304)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -44640,7 +46635,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249) { + if (importClause.namedBindings.kind === 251) { checkImportBinding(importClause.namedBindings); } else { @@ -44663,16 +46658,16 @@ var ts; if (ts.hasModifier(node, 1)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 257) { + if (node.moduleReference.kind !== 259) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319) { + if (target.flags & 67220415) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 | 1920).flags & 1920)) { + if (!(resolveEntityName(moduleName, 67220415 | 1920).flags & 1920)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928) { + if (target.flags & 67897832) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -44694,10 +46689,10 @@ var ts; if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause) { ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 243 && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 243 && + var inAmbientExternalModule = node.parent.kind === 245 && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 && !node.moduleSpecifier && node.flags & 4194304; - if (node.parent.kind !== 277 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 279 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -44713,7 +46708,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 277 || node.parent.kind === 243 || node.parent.kind === 242; + var isInAppropriateContext = node.parent.kind === 279 || node.parent.kind === 245 || node.parent.kind === 244; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -44721,12 +46716,12 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 | 67901928 | 1920 | 2097152, undefined, undefined, true); + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 | 67897832 | 1920 | 2097152, undefined, undefined, true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } @@ -44739,8 +46734,8 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { return; } - var container = node.parent.kind === 277 ? node.parent : node.parent.parent; - if (container.kind === 242 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 279 ? node.parent : node.parent.parent; + if (container.kind === 244 && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -44752,9 +46747,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 71) { + if (node.expression.kind === 72) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, true); } } @@ -44784,7 +46779,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -44819,14 +46814,14 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 237 && declaration.kind !== 154) || + return (declaration.kind !== 239 && declaration.kind !== 156) || !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -44835,162 +46830,162 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { - case 242: - case 238: + case 244: + case 240: + case 241: case 239: - case 237: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 148: + case 150: return checkTypeParameter(node); - case 149: - return checkParameter(node); - case 152: case 151: - return checkPropertyDeclaration(node); - case 163: - case 164: - case 158: - case 159: - case 160: - return checkSignatureDeclaration(node); + return checkParameter(node); case 154: case 153: - return checkMethodDeclaration(node); - case 155: - return checkConstructorDeclaration(node); - case 156: - case 157: - return checkAccessorDeclaration(node); - case 162: - return checkTypeReferenceNode(node); - case 161: - return checkTypePredicate(node); + return checkPropertyDeclaration(node); case 165: - return checkTypeQuery(node); case 166: - return checkTypeLiteral(node); + case 160: + case 161: + case 162: + return checkSignatureDeclaration(node); + case 156: + case 155: + return checkMethodDeclaration(node); + case 157: + return checkConstructorDeclaration(node); + case 158: + case 159: + return checkAccessorDeclaration(node); + case 164: + return checkTypeReferenceNode(node); + case 163: + return checkTypePredicate(node); case 167: - return checkArrayType(node); + return checkTypeQuery(node); case 168: + return checkTypeLiteral(node); + case 169: + return checkArrayType(node); + case 170: return checkTupleType(node); + case 173: + case 174: + return checkUnionOrIntersectionType(node); + case 177: case 171: case 172: - return checkUnionOrIntersectionType(node); - case 175: - case 169: - case 170: return checkSourceElement(node.type); - case 176: + case 178: return checkThisType(node); - case 177: + case 179: return checkTypeOperator(node); - case 173: + case 175: return checkConditionalType(node); - case 174: + case 176: return checkInferType(node); - case 181: + case 183: return checkImportType(node); - case 293: - return checkJSDocAugmentsTag(node); - case 302: case 295: - return checkJSDocTypeAliasTag(node); - case 301: - return checkJSDocTemplateTag(node); - case 300: - return checkJSDocTypeTag(node); + return checkJSDocAugmentsTag(node); + case 304: case 297: + return checkJSDocTypeAliasTag(node); + case 303: + return checkJSDocTemplateTag(node); + case 302: + return checkJSDocTypeTag(node); + case 299: return checkJSDocParameterTag(node); + case 289: + checkJSDocFunctionType(node); case 287: - checkSignatureDeclaration(node); - case 285: + case 286: case 284: - case 282: - case 283: - case 290: + case 285: + case 292: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 288: + case 290: checkJSDocVariadicType(node); return; - case 281: + case 283: return checkSourceElement(node.type); - case 178: + case 180: return checkIndexedAccessType(node); - case 179: + case 181: return checkMappedType(node); - case 237: - return checkFunctionDeclaration(node); - case 216: - case 243: - return checkBlock(node); - case 217: - return checkVariableStatement(node); - case 219: - return checkExpressionStatement(node); - case 220: - return checkIfStatement(node); - case 221: - return checkDoStatement(node); - case 222: - return checkWhileStatement(node); - case 223: - return checkForStatement(node); - case 224: - return checkForInStatement(node); - case 225: - return checkForOfStatement(node); - case 226: - case 227: - return checkBreakOrContinueStatement(node); - case 228: - return checkReturnStatement(node); - case 229: - return checkWithStatement(node); - case 230: - return checkSwitchStatement(node); - case 231: - return checkLabeledStatement(node); - case 232: - return checkThrowStatement(node); - case 233: - return checkTryStatement(node); - case 235: - return checkVariableDeclaration(node); - case 184: - return checkBindingElement(node); - case 238: - return checkClassDeclaration(node); case 239: - return checkInterfaceDeclaration(node); - case 240: - return checkTypeAliasDeclaration(node); - case 241: - return checkEnumDeclaration(node); - case 242: - return checkModuleDeclaration(node); - case 247: - return checkImportDeclaration(node); - case 246: - return checkImportEqualsDeclaration(node); - case 253: - return checkExportDeclaration(node); - case 252: - return checkExportAssignment(node); + return checkFunctionDeclaration(node); case 218: + case 245: + return checkBlock(node); + case 219: + return checkVariableStatement(node); + case 221: + return checkExpressionStatement(node); + case 222: + return checkIfStatement(node); + case 223: + return checkDoStatement(node); + case 224: + return checkWhileStatement(node); + case 225: + return checkForStatement(node); + case 226: + return checkForInStatement(node); + case 227: + return checkForOfStatement(node); + case 228: + case 229: + return checkBreakOrContinueStatement(node); + case 230: + return checkReturnStatement(node); + case 231: + return checkWithStatement(node); + case 232: + return checkSwitchStatement(node); + case 233: + return checkLabeledStatement(node); case 234: + return checkThrowStatement(node); + case 235: + return checkTryStatement(node); + case 237: + return checkVariableDeclaration(node); + case 186: + return checkBindingElement(node); + case 240: + return checkClassDeclaration(node); + case 241: + return checkInterfaceDeclaration(node); + case 242: + return checkTypeAliasDeclaration(node); + case 243: + return checkEnumDeclaration(node); + case 244: + return checkModuleDeclaration(node); + case 249: + return checkImportDeclaration(node); + case 248: + return checkImportEqualsDeclaration(node); + case 255: + return checkExportDeclaration(node); + case 254: + return checkExportAssignment(node); + case 220: + case 236: checkGrammarStatementInAmbientContext(node); return; - case 256: + case 258: return checkMissingDeclaration(node); } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -45042,31 +47037,38 @@ var ts; return addOptionality(type); } function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { - case 194: - case 195: - case 154: - case 153: + case 196: + case 197: + case 156: + case 155: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 156: - case 157: + case 158: + case 159: checkAccessorDeclaration(node); break; - case 207: + case 209: checkClassExpressionDeferred(node); break; - case 259: + case 261: checkJsxSelfClosingElementDeferred(node); break; - case 258: + case 260: checkJsxElementDeferred(node); break; } @@ -45100,9 +47102,9 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -45113,7 +47115,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -45181,24 +47182,27 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 242: + case 279: + if (!ts.isExternalOrCommonJsModule(location)) + break; + case 244: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475); break; - case 241: + case 243: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 207: + case 209: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 238: - case 239: + case 240: + case 241: if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832); } break; - case 194: + case 196: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -45230,33 +47234,33 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 71 && + return name.kind === 72 && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 148: - case 238: - case 239: + case 150: case 240: case 241: + case 242: + case 243: return true; default: return false; } } function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 146) { + while (node.parent.kind === 148) { node = node.parent; } - return node.parent.kind === 162; + return node.parent.kind === 164; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 187) { + while (node.parent.kind === 189) { node = node.parent; } - return node.parent.kind === 209; + return node.parent.kind === 211; } function forEachEnclosingClass(node, callback) { var result; @@ -45269,12 +47273,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -45284,13 +47288,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 146) { + while (nodeOnRightSide.parent.kind === 148) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 246) { + if (nodeOnRightSide.parent.kind === 248) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 252) { + if (nodeOnRightSide.parent.kind === 254) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -45299,7 +47303,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1: case 3: @@ -45316,7 +47320,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 181 && parent.qualifier === node) { + if (parent && parent.kind === 183 && parent.qualifier === node) { return parent; } return undefined; @@ -45325,22 +47329,22 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 187 && + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 && entityName.parent === entityName.parent.parent.left) { var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); if (specialPropertyAssignmentSymbol) { return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 252 && ts.isEntityNameExpression(entityName)) { - var success = resolveEntityName(entityName, 67216319 | 67901928 | 1920 | 2097152, true); + if (entityName.parent.kind === 254 && ts.isEntityNameExpression(entityName)) { + var success = resolveEntityName(entityName, 67220415 | 67897832 | 1920 | 2097152, true); if (success && success !== unknownSymbol) { return success; } } else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 246); + var importEqualsDeclaration = ts.getAncestor(entityName, 248); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); } @@ -45357,10 +47361,10 @@ var ts; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; - if (entityName.parent.kind === 209) { - meaning = 67901928; + if (entityName.parent.kind === 211) { + meaning = 67897832; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319; + meaning |= 67220415; } } else { @@ -45372,11 +47376,11 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 297) { + if (entityName.parent.kind === 299) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 && entityName.parent.parent.kind === 301) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); + if (entityName.parent.kind === 150 && entityName.parent.parent.kind === 303) { + ts.Debug.assert(!ts.isInJSFile(entityName)); var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -45384,19 +47388,19 @@ var ts; if (ts.nodeIsMissing(entityName)) { return undefined; } - if (entityName.kind === 71) { + if (entityName.kind === 72) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319, false, true); + return resolveEntityName(entityName, 67220415, false, true); } - else if (entityName.kind === 187 || entityName.kind === 146) { + else if (entityName.kind === 189 || entityName.kind === 148) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 187) { + if (entityName.kind === 189) { checkPropertyAccessExpression(entityName); } else { @@ -45406,19 +47410,16 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 ? 67901928 : 1920; + var meaning = entityName.parent.kind === 164 ? 67897832 : 1920; return resolveEntityName(entityName, meaning, false, true); } - else if (entityName.parent.kind === 265) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 161) { + if (entityName.parent.kind === 163) { return resolveEntityName(entityName, 1); } return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 277) { + if (node.kind === 279) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -45427,17 +47428,20 @@ var ts; return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { - return getSymbolOfNode(parent); + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(parent.parent); } - if (node.kind === 71) { + if (node.kind === 72) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (parent.kind === 184 && - grandParent.kind === 182 && + else if (parent.kind === 186 && + grandParent.kind === 184 && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -45447,11 +47451,11 @@ var ts; } } switch (node.kind) { - case 71: - case 187: - case 146: + case 72: + case 189: + case 148: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99: + case 100: var container = ts.getThisContainer(node, false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -45462,24 +47466,27 @@ var ts; if (ts.isInExpressionContext(node)) { return checkExpression(node).symbol; } - case 176: + case 178: return getTypeFromThisTypeNode(node).symbol; - case 97: + case 98: return checkExpression(node).symbol; - case 123: + case 124: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 155) { + if (constructorDeclaration && constructorDeclaration.kind === 157) { return constructorDeclaration.parent.symbol; } return undefined; - case 9: - case 13: + case 10: + case 14: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 247 || node.parent.kind === 253) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent)) || + ((node.parent.kind === 249 || node.parent.kind === 255) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } case 8: var objectType = ts.isElementAccessExpression(parent) ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined @@ -45487,46 +47494,44 @@ var ts; ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); - case 79: - case 89: - case 36: + case 80: + case 90: + case 37: + case 76: return getSymbolOfNode(node.parent); - case 181: + case 183: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 274) { - return resolveEntityName(location.name, 67216319 | 2097152); + if (location && location.kind === 276) { + return resolveEntityName(location.name, 67220415 | 2097152); } return undefined; } function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 | 67901928 | 1920 | 2097152); + resolveEntityName(node.propertyName || node.name, 67220415 | 67897832 | 1920 | 2097152); } function getTypeOfNode(node) { if (node.flags & 8388608) { return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + if (classType && !classDecl.isImplements) { var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -45559,20 +47564,20 @@ var ts; return errorType; } function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 186 || expr.kind === 185); - if (expr.parent.kind === 225) { + ts.Debug.assert(expr.kind === 188 || expr.kind === 187); + if (expr.parent.kind === 227) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || errorType); } - if (expr.parent.kind === 202) { + if (expr.parent.kind === 204) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } - if (expr.parent.kind === 273) { + if (expr.parent.kind === 275) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); } - ts.Debug.assert(expr.parent.kind === 185); + ts.Debug.assert(expr.parent.kind === 187); var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, false, false) || errorType; return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); @@ -45593,11 +47598,30 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72: + return getLiteralType(ts.idText(name)); + case 8: + case 10: + return getLiteralType(name.text); + case 149: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -45636,7 +47660,7 @@ var ts; if (!ts.isGeneratedIdentifier(nodeIn)) { var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 187 && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 189 && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -45652,13 +47676,13 @@ var ts; var symbolLinks = getSymbolLinks(moduleSymbol); if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319) + ? !!(moduleSymbol.flags & 67220415) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319); + return s && !!(s.flags & 67220415); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -45678,7 +47702,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 277) { + if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 279) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); var symbolIsUmdExport = symbolFile !== referenceFile; @@ -45693,7 +47717,7 @@ var ts; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); - if (isNonLocalAlias(symbol, 67216319)) { + if (isNonLocalAlias(symbol, 67220415)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -45706,13 +47730,13 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319, undefined, undefined, false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415, undefined, undefined, false)) { links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072) { - var isDeclaredInLoop = nodeLinks_1.flags & 262144; + else if (nodeLinks_1.flags & 262144) { + var isDeclaredInLoop = nodeLinks_1.flags & 524288; var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 216 && ts.isIterationStatement(container.parent, false); + var inLoopBodyBlock = container.kind === 218 && ts.isIterationStatement(container.parent, false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -45748,18 +47772,18 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 246: case 248: - case 249: + case 250: case 251: - case 255: - return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 253: + case 257: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 255: var exportClause = node.exportClause; return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); - case 252: + case 254: return node.expression - && node.expression.kind === 71 + && node.expression.kind === 72 ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -45767,7 +47791,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 277 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 279 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -45778,7 +47802,7 @@ var ts; if (target === unknownSymbol) { return true; } - return !!(target.flags & 67216319) && + return !!(target.flags & 67220415) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -45791,7 +47815,8 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; - if (target && ts.getModifierFlags(node) & 1 && target.flags & 67216319) { + if (target && ts.getModifierFlags(node) & 1 && + target.flags & 67220415 && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { return true; } } @@ -45824,6 +47849,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -45833,15 +47877,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 276: - case 187: - case 188: + case 278: + case 189: + case 190: return true; } return false; } function getConstantValue(node) { - if (node.kind === 276) { + if (node.kind === 278) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -45854,7 +47898,7 @@ var ts; return undefined; } function isFunctionType(type) { - return !!(type.flags & 131072) && getSignaturesOfType(type, 0).length > 0; + return !!(type.flags & 524288) && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeNameIn, location) { var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); @@ -45865,8 +47909,8 @@ var ts; if (!location) return ts.TypeReferenceSerializationKind.Unknown; } - var valueSymbol = resolveEntityName(typeName, 67216319, true, false, location); - var typeSymbol = resolveEntityName(typeName, 67901928, true, false, location); + var valueSymbol = resolveEntityName(typeName, 67220415, true, false, location); + var typeSymbol = resolveEntityName(typeName, 67897832, true, false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -45887,22 +47931,25 @@ var ts; else if (type.flags & 3) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 4096 | 24576 | 32768)) { + else if (isTypeAssignableToKind(type, 16384 | 98304 | 131072)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeAssignableToKind(type, 272)) { + else if (isTypeAssignableToKind(type, 528)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeAssignableToKind(type, 168)) { + else if (isTypeAssignableToKind(type, 296)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 68)) { + else if (isTypeAssignableToKind(type, 2112)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 3072)) { + else if (isTypeAssignableToKind(type, 12288)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -45918,13 +47965,13 @@ var ts; function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { - return ts.createToken(119); + return ts.createToken(120); } var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 | 131072)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; - if (type.flags & 2048 && + if (type.flags & 8192 && type.symbol === symbol) { flags |= 1048576; } @@ -45936,7 +47983,7 @@ var ts; function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { - return ts.createToken(119); + return ts.createToken(120); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, tracker); @@ -45944,7 +47991,7 @@ var ts; function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { - return ts.createToken(119); + return ts.createToken(120); } var type = getWidenedType(getRegularTypeOfExpression(expr)); return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024, tracker); @@ -45964,7 +48011,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 | 1048576 | 2097152, undefined, undefined, true); + return resolveName(location, reference.escapedText, 67220415 | 1048576 | 2097152, undefined, undefined, true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -45979,18 +48026,19 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 && type.flags & 33554432); + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 ? nodeBuilder.symbolToExpression(type.symbol, 67220415, enclosing, undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } - function createLiteralConstValue(node) { + function createLiteralConstValue(node, tracker) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node, tracker); } function createResolver() { var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); @@ -46028,6 +48076,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -46056,12 +48106,12 @@ var ts; getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); - var otherKind = accessor.kind === 157 ? 156 : 157; + var otherKind = accessor.kind === 159 ? 158 : 159; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 157 ? accessor : otherAccessor; - var getAccessor = accessor.kind === 156 ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -46069,18 +48119,23 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { - return node.parent && node.parent.kind === 209 && node.parent.parent && node.parent.parent.kind === 271; + return node.parent && node.parent.kind === 211 && node.parent.parent && node.parent.parent.kind === 273; } function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { return undefined; } - var meaning = 67901928 | 1920; - if ((node.kind === 71 && isInTypeQuery(node)) || (node.kind === 187 && !isInHeritageClause(node))) { - meaning = 67216319 | 1048576; + var meaning = 67897832 | 1920; + if ((node.kind === 72 && isInTypeQuery(node)) || (node.kind === 189 && !isInHeritageClause(node))) { + meaning = 67220415 | 1048576; } var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -46122,7 +48177,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 277 && current.flags & 512) { + if (current.valueDeclaration && current.valueDeclaration.kind === 279 && current.flags & 512) { return false; } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -46136,12 +48191,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 242 ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 244 ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 277); + return ts.getDeclarationOfKind(moduleSymbol, 279); } function initializeTypeChecker() { for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { @@ -46158,6 +48213,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -46191,6 +48249,8 @@ var ts; globalArrayType = getGlobalType("Array", 1, true); globalObjectType = getGlobalType("Object", 0, true); globalFunctionType = getGlobalType("Function", 0, true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", 0, true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", 0, true) || globalFunctionType; globalStringType = getGlobalType("String", 0, true); globalNumberType = getGlobalType("Number", 0, true); globalBooleanType = getGlobalType("Boolean", 0, true); @@ -46215,29 +48275,28 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -46249,7 +48308,7 @@ var ts; for (var helper = 1; helper <= 65536; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -46296,14 +48355,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 154 && !ts.nodeIsPresent(node.body)) { + if (node.kind === 156 && !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 === 156 || node.kind === 157) { + else if (node.kind === 158 || node.kind === 159) { 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); @@ -46320,23 +48379,23 @@ var ts; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 132) { - if (node.kind === 151 || node.kind === 153) { + if (modifier.kind !== 133) { + if (node.kind === 153 || node.kind === 155) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 160) { + if (node.kind === 162) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 76: - if (node.kind !== 241) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76)); + case 77: + if (node.kind !== 243) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77)); } break; + case 115: case 114: case 113: - case 112: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); if (flags & 28) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); @@ -46350,11 +48409,11 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 243 || node.parent.kind === 277) { + else if (node.parent.kind === 245 || node.parent.kind === 279) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128) { - if (modifier.kind === 112) { + if (modifier.kind === 113) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -46363,7 +48422,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 115: + case 116: if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -46373,10 +48432,10 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 243 || node.parent.kind === 277) { + else if (node.parent.kind === 245 || node.parent.kind === 279) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 149) { + else if (node.kind === 151) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128) { @@ -46385,17 +48444,17 @@ var ts; flags |= 32; lastStatic = modifier; break; - case 132: + case 133: if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 152 && node.kind !== 151 && node.kind !== 160 && node.kind !== 149) { + else if (node.kind !== 154 && node.kind !== 153 && node.kind !== 162 && 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 84: + case 85: if (flags & 1) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -46408,52 +48467,52 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 238) { + else if (node.parent.kind === 240) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 149) { + else if (node.kind === 151) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1; break; - case 79: - var container = node.parent.kind === 277 ? node.parent : node.parent.parent; - if (container.kind === 242 && !ts.isAmbientModule(container)) { + case 80: + var container = node.parent.kind === 279 ? node.parent : node.parent.parent; + if (container.kind === 244 && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512; break; - case 124: + case 125: 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 === 238) { + else if (node.parent.kind === 240) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 149) { + else if (node.kind === 151) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 4194304) && node.parent.kind === 243) { + else if ((node.parent.flags & 4194304) && node.parent.kind === 245) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2; lastDeclare = modifier; break; - case 117: + case 118: if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 238) { - if (node.kind !== 154 && - node.kind !== 152 && - node.kind !== 156 && - node.kind !== 157) { + if (node.kind !== 240) { + if (node.kind !== 156 && + node.kind !== 154 && + node.kind !== 158 && + node.kind !== 159) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 238 && ts.hasModifier(node.parent, 128))) { + if (!(node.parent.kind === 240 && ts.hasModifier(node.parent, 128))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -46465,14 +48524,14 @@ var ts; } flags |= 128; break; - case 120: + case 121: if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 || node.parent.flags & 4194304) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 149) { + else if (node.kind === 151) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256; @@ -46480,7 +48539,7 @@ var ts; break; } } - if (node.kind === 155) { + if (node.kind === 157) { if (flags & 32) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -46495,13 +48554,13 @@ var ts; } return false; } - else if ((node.kind === 247 || node.kind === 246) && flags & 2) { + else if ((node.kind === 249 || node.kind === 248) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 149 && (flags & 92) && ts.isBindingPattern(node.name)) { + else if (node.kind === 151 && (flags & 92) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 149 && (flags & 92) && node.dotDotDotToken) { + else if (node.kind === 151 && (flags & 92) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { @@ -46518,38 +48577,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 156: + case 158: + case 159: case 157: - case 155: - case 152: - case 151: case 154: case 153: - case 160: - case 242: - case 247: - case 246: - case 253: - case 252: - case 194: - case 195: - case 149: + case 156: + case 155: + case 162: + case 244: + case 249: + case 248: + case 255: + case 254: + case 196: + case 197: + case 151: return false; default: - if (node.parent.kind === 243 || node.parent.kind === 277) { + if (node.parent.kind === 245 || node.parent.kind === 279) { return false; } switch (node.kind) { - case 237: - return nodeHasAnyModifiersExcept(node, 120); - case 238: - return nodeHasAnyModifiersExcept(node, 117); case 239: - case 217: + return nodeHasAnyModifiersExcept(node, 121); case 240: - return true; + return nodeHasAnyModifiersExcept(node, 118); case 241: - return nodeHasAnyModifiersExcept(node, 76); + case 219: + case 242: + return true; + case 243: + return nodeHasAnyModifiersExcept(node, 77); default: ts.Debug.fail(); return false; @@ -46561,10 +48620,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 154: - case 237: - case 194: - case 195: + case 156: + case 239: + case 196: + case 197: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -46617,10 +48676,31 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -46660,12 +48740,12 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 137 && parameter.type.kind !== 134) { + if (parameter.type.kind !== 138 && parameter.type.kind !== 135) { var type = getTypeFromTypeNode(parameter.type); if (type.flags & 4 || type.flags & 8) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); } - if (type.flags & 262144 && allTypesAssignableToKind(type, 64, true)) { + if (type.flags & 1048576 && allTypesAssignableToKind(type, 128, true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); @@ -46695,7 +48775,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 208) { + if (arg.kind === 210) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -46725,7 +48805,7 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85) { + if (heritageClause.token === 86) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -46738,7 +48818,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108); + ts.Debug.assert(heritageClause.token === 109); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -46753,14 +48833,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85) { + if (heritageClause.token === 86) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108); + ts.Debug.assert(heritageClause.token === 109); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } checkGrammarHeritageClause(heritageClause); @@ -46769,20 +48849,20 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 147) { + if (node.kind !== 149) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 202 && computedPropertyName.expression.operatorToken.kind === 26) { + if (computedPropertyName.expression.kind === 204 && computedPropertyName.expression.operatorToken.kind === 27) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 237 || - node.kind === 194 || - node.kind === 154); + ts.Debug.assert(node.kind === 239 || + node.kind === 196 || + node.kind === 156); if (node.flags & 4194304) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -46794,43 +48874,47 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275) { + if (prop.kind === 277) { continue; } var name = prop.name; - if (name.kind === 147) { + if (name.kind === 149) { checkGrammarComputedPropertyName(name); } - if (prop.kind === 274 && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 276 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 120 || prop.kind !== 154) { + if (mod.kind !== 121 || prop.kind !== 156) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } var currentKind = void 0; switch (prop.kind) { - case 273: - case 274: + case 276: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + case 275: checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8) { checkGrammarNumericLiteral(name); } - case 154: + case 156: currentKind = 1; break; - case 156: + case 158: currentKind = 2; break; - case 157: + case 159: currentKind = 4; break; default: @@ -46867,7 +48951,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 267) { + if (attr.kind === 269) { continue; } var name = attr.name, initializer = attr.initializer; @@ -46877,7 +48961,7 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 268 && !initializer.expression) { + if (initializer && initializer.kind === 270 && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -46886,12 +48970,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 225 && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 227 && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384) === 0) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 236) { + if (forInOrOfStatement.initializer.kind === 238) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -46899,20 +48983,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 224 + var diagnostic = forInOrOfStatement.kind === 226 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 224 + var diagnostic = forInOrOfStatement.kind === 226 ? 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 === 224 + var diagnostic = forInOrOfStatement.kind === 226 ? 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); @@ -46939,11 +49023,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 156 ? + return grammarErrorOnNode(accessor.name, kind === 158 ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 157) { + else if (kind === 159) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -46963,23 +49047,23 @@ var ts; return false; } function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 156 ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 156 ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 158 ? 1 : 2)) { return ts.getThisParameter(accessor); } } function checkGrammarTypeOperatorNode(node) { - if (node.operator === 141) { - if (node.type.kind !== 138) { - return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(138)); + if (node.operator === 142) { + if (node.type.kind !== 139) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139)); } var parent = ts.walkUpParenthesizedTypes(node.parent); switch (parent.kind) { - case 235: + case 237: var decl = parent; - if (decl.name.kind !== 71) { + if (decl.name.kind !== 72) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); } if (!ts.isVariableDeclarationInVariableStatement(decl)) { @@ -46989,13 +49073,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 152: + case 154: if (!ts.hasModifier(parent, 32) || !ts.hasModifier(parent, 64)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 151: + case 153: if (!ts.hasModifier(parent, 64)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -47014,14 +49098,17 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 154) { - if (node.parent.kind === 186) { - if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 120)) { + if (node.kind === 156) { + if (node.parent.kind === 188) { + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -47034,14 +49121,14 @@ var ts; if (node.flags & 4194304) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 154 && !node.body) { + else if (node.kind === 156 && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 239) { + else if (node.parent.kind === 241) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 166) { + else if (node.parent.kind === 168) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -47052,9 +49139,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 231: + case 233: if (node.label && current.label.escapedText === node.label.escapedText) { - var isMisplacedContinueLabel = node.kind === 226 + var isMisplacedContinueLabel = node.kind === 228 && !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); @@ -47062,8 +49149,8 @@ var ts; return false; } break; - case 230: - if (node.kind === 227 && !node.label) { + case 232: + if (node.kind === 229 && !node.label) { return false; } break; @@ -47076,13 +49163,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 227 + var message = node.kind === 229 ? 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 === 227 + var message = node.kind === 229 ? 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); @@ -47104,28 +49191,45 @@ var ts; } } function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 || expr.kind === 8 || - expr.kind === 200 && expr.operator === 38 && + return expr.kind === 10 || expr.kind === 8 || + expr.kind === 202 && expr.operator === 39 && expr.operand.kind === 8; } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 || + expr.kind === 202 && expr.operator === 39 && + expr.operand.kind === 9; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 || initializer.kind === 87 || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 224 && node.parent.parent.kind !== 225) { + if (node.parent.parent.kind !== 226 && node.parent.parent.kind !== 227) { if (node.flags & 4194304) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -47136,7 +49240,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 217 || !node.type || node.initializer || node.flags & 4194304)) { + if (node.exclamationToken && (node.parent.parent.kind !== 219 || !node.type || node.initializer || node.flags & 4194304)) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && @@ -47147,7 +49251,7 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkESModuleMarker(name) { - if (name.kind === 71) { + if (name.kind === 72) { if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } @@ -47164,8 +49268,8 @@ var ts; return false; } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71) { - if (name.originalKeywordKind === 110) { + if (name.kind === 72) { + if (name.originalKeywordKind === 111) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -47192,15 +49296,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 220: - case 221: case 222: - case 229: case 223: case 224: - case 225: - return false; case 231: + case 225: + case 226: + case 227: + return false; + case 233: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -47218,12 +49322,12 @@ var ts; function checkGrammarMetaProperty(node) { var escapedText = node.name.escapedText; switch (node.keywordToken) { - case 94: + case 95: if (escapedText !== "target") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); } break; - case 91: + case 92: if (escapedText !== "meta") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); } @@ -47259,10 +49363,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -47277,7 +49382,7 @@ var ts; return true; } } - else if (node.parent.kind === 239) { + else if (node.parent.kind === 241) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -47285,7 +49390,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 166) { + else if (node.parent.kind === 168) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -47293,8 +49398,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 || ts.hasModifier(node, 32 | 128))) { @@ -47302,13 +49407,13 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 239 || - node.kind === 240 || + if (node.kind === 241 || + node.kind === 242 || + node.kind === 249 || + node.kind === 248 || + node.kind === 255 || + node.kind === 254 || node.kind === 247 || - node.kind === 246 || - node.kind === 253 || - node.kind === 252 || - node.kind === 245 || ts.hasModifier(node, 2 | 1 | 512)) { return false; } @@ -47317,7 +49422,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 === 217) { + if (ts.isDeclaration(decl) || decl.kind === 219) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -47337,7 +49442,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 === 216 || node.parent.kind === 243 || node.parent.kind === 277) { + if (node.parent.kind === 218 || node.parent.kind === 245 || node.parent.kind === 279) { var links_2 = getNodeLinks(node.parent); if (!links_2.hasReportedStatementInAmbientContext) { return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -47354,20 +49459,32 @@ var ts; if (languageVersion >= 1) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 180)) { + else if (ts.isChildOfNodeWithKind(node, 182)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 276)) { + else if (ts.isChildOfNodeWithKind(node, 278)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38; + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39; var literal = (withMinus ? "-" : "") + "0o" + node.text; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } return false; } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { @@ -47408,8 +49525,8 @@ var ts; ts.createTypeChecker = createTypeChecker; function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 251: - case 255: + case 253: + case 257: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); @@ -47417,13 +49534,13 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { + case 250: case 248: - case 246: - case 249: case 251: + case 253: return true; - case 71: - return decl.parent.kind === 251; + case 72: + return decl.parent.kind === 253; default: return false; } @@ -47441,7 +49558,7 @@ var ts; JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; })(JsxNames || (JsxNames = {})); function typeIsLiteralType(type) { - return !!(type.flags & 448); + return !!(type.flags & 2944); } })(ts || (ts = {})); var ts; @@ -47494,6 +49611,9 @@ var ts; if (typeof value === "number") { return createNumericLiteral(value + ""); } + if (typeof value === "object" && "base10Value" in value) { + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } @@ -47513,14 +49633,20 @@ var ts; return node; } ts.createNumericLiteral = createNumericLiteral; - function createStringLiteral(text) { + function createBigIntLiteral(value) { var node = createSynthesizedNode(9); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; + function createStringLiteral(text) { + var node = createSynthesizedNode(10); node.text = text; return node; } ts.createStringLiteral = createStringLiteral; function createRegularExpressionLiteral(text) { - var node = createSynthesizedNode(12); + var node = createSynthesizedNode(13); node.text = text; return node; } @@ -47531,7 +49657,7 @@ var ts; return node; } function createIdentifier(text, typeArguments) { - var node = createSynthesizedNode(71); + var node = createSynthesizedNode(72); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateFlags = 0; @@ -47607,23 +49733,23 @@ var ts; } ts.createToken = createToken; function createSuper() { - return createSynthesizedNode(97); + return createSynthesizedNode(98); } ts.createSuper = createSuper; function createThis() { - return createSynthesizedNode(99); + return createSynthesizedNode(100); } ts.createThis = createThis; function createNull() { - return createSynthesizedNode(95); + return createSynthesizedNode(96); } ts.createNull = createNull; function createTrue() { - return createSynthesizedNode(101); + return createSynthesizedNode(102); } ts.createTrue = createTrue; function createFalse() { - return createSynthesizedNode(86); + return createSynthesizedNode(87); } ts.createFalse = createFalse; function createModifier(kind) { @@ -47633,43 +49759,43 @@ var ts; function createModifiersFromModifierFlags(flags) { var result = []; if (flags & 1) { - result.push(createModifier(84)); + result.push(createModifier(85)); } if (flags & 2) { - result.push(createModifier(124)); + result.push(createModifier(125)); } if (flags & 512) { - result.push(createModifier(79)); + result.push(createModifier(80)); } if (flags & 2048) { - result.push(createModifier(76)); + result.push(createModifier(77)); } if (flags & 4) { - result.push(createModifier(114)); - } - if (flags & 8) { - result.push(createModifier(112)); - } - if (flags & 16) { - result.push(createModifier(113)); - } - if (flags & 128) { - result.push(createModifier(117)); - } - if (flags & 32) { result.push(createModifier(115)); } + if (flags & 8) { + result.push(createModifier(113)); + } + if (flags & 16) { + result.push(createModifier(114)); + } + if (flags & 128) { + result.push(createModifier(118)); + } + if (flags & 32) { + result.push(createModifier(116)); + } if (flags & 64) { - result.push(createModifier(132)); + result.push(createModifier(133)); } if (flags & 256) { - result.push(createModifier(120)); + result.push(createModifier(121)); } return result; } ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; function createQualifiedName(left, right) { - var node = createSynthesizedNode(146); + var node = createSynthesizedNode(148); node.left = left; node.right = asName(right); return node; @@ -47688,7 +49814,7 @@ var ts; : expression; } function createComputedPropertyName(expression) { - var node = createSynthesizedNode(147); + var node = createSynthesizedNode(149); node.expression = parenthesizeForComputedName(expression); return node; } @@ -47700,7 +49826,7 @@ var ts; } ts.updateComputedPropertyName = updateComputedPropertyName; function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(148); + var node = createSynthesizedNode(150); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -47716,7 +49842,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149); + var node = createSynthesizedNode(151); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -47740,7 +49866,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(150); + var node = createSynthesizedNode(152); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -47752,7 +49878,7 @@ var ts; } ts.updateDecorator = updateDecorator; function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(151); + var node = createSynthesizedNode(153); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -47772,12 +49898,12 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createSynthesizedNode(152); + var node = createSynthesizedNode(154); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); - node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 ? questionOrExclamationToken : undefined; - node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 ? questionOrExclamationToken : undefined; + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 ? questionOrExclamationToken : undefined; node.type = type; node.initializer = initializer; return node; @@ -47787,8 +49913,8 @@ var ts; return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name - || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 ? questionOrExclamationToken : undefined) - || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 ? questionOrExclamationToken : undefined) + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) @@ -47796,7 +49922,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(153, typeParameters, parameters, type); + var node = createSignatureDeclaration(155, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -47813,7 +49939,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(154); + var node = createSynthesizedNode(156); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -47841,7 +49967,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(155); + var node = createSynthesizedNode(157); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -47861,7 +49987,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(156); + var node = createSynthesizedNode(158); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47884,7 +50010,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(157); + var node = createSynthesizedNode(159); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47905,7 +50031,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(158, typeParameters, parameters, type); + return createSignatureDeclaration(160, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -47913,7 +50039,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(159, typeParameters, parameters, type); + return createSignatureDeclaration(161, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -47921,7 +50047,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(160); + var node = createSynthesizedNode(162); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -47959,7 +50085,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(161); + var node = createSynthesizedNode(163); node.parameterName = asName(parameterName); node.type = type; return node; @@ -47973,7 +50099,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(162); + var node = createSynthesizedNode(164); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -47987,7 +50113,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(163, typeParameters, parameters, type); + return createSignatureDeclaration(165, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -47995,7 +50121,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(164, typeParameters, parameters, type); + return createSignatureDeclaration(166, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -48003,7 +50129,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(165); + var node = createSynthesizedNode(167); node.exprName = exprName; return node; } @@ -48015,7 +50141,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(166); + var node = createSynthesizedNode(168); node.members = createNodeArray(members); return node; } @@ -48027,7 +50153,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(167); + var node = createSynthesizedNode(169); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -48039,7 +50165,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(168); + var node = createSynthesizedNode(170); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -48051,7 +50177,7 @@ var ts; } ts.updateTupleTypeNode = updateTupleTypeNode; function createOptionalTypeNode(type) { - var node = createSynthesizedNode(169); + var node = createSynthesizedNode(171); node.type = ts.parenthesizeArrayTypeMember(type); return node; } @@ -48063,7 +50189,7 @@ var ts; } ts.updateOptionalTypeNode = updateOptionalTypeNode; function createRestTypeNode(type) { - var node = createSynthesizedNode(170); + var node = createSynthesizedNode(172); node.type = type; return node; } @@ -48075,7 +50201,7 @@ var ts; } ts.updateRestTypeNode = updateRestTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(171, types); + return createUnionOrIntersectionTypeNode(173, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -48083,7 +50209,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(172, types); + return createUnionOrIntersectionTypeNode(174, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -48102,7 +50228,7 @@ var ts; : node; } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createSynthesizedNode(173); + var node = createSynthesizedNode(175); node.checkType = ts.parenthesizeConditionalTypeMember(checkType); node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); node.trueType = trueType; @@ -48120,7 +50246,7 @@ var ts; } ts.updateConditionalTypeNode = updateConditionalTypeNode; function createInferTypeNode(typeParameter) { - var node = createSynthesizedNode(174); + var node = createSynthesizedNode(176); node.typeParameter = typeParameter; return node; } @@ -48132,7 +50258,7 @@ var ts; } ts.updateInferTypeNode = updateInferTypeNode; function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { - var node = createSynthesizedNode(181); + var node = createSynthesizedNode(183); node.argument = argument; node.qualifier = qualifier; node.typeArguments = asNodeArray(typeArguments); @@ -48150,7 +50276,7 @@ var ts; } ts.updateImportTypeNode = updateImportTypeNode; function createParenthesizedType(type) { - var node = createSynthesizedNode(175); + var node = createSynthesizedNode(177); node.type = type; return node; } @@ -48162,12 +50288,12 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(176); + return createSynthesizedNode(178); } ts.createThisTypeNode = createThisTypeNode; function createTypeOperatorNode(operatorOrType, type) { - var node = createSynthesizedNode(177); - node.operator = typeof operatorOrType === "number" ? operatorOrType : 128; + var node = createSynthesizedNode(179); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129; node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } @@ -48177,7 +50303,7 @@ var ts; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(178); + var node = createSynthesizedNode(180); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -48191,7 +50317,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(179); + var node = createSynthesizedNode(181); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -48209,7 +50335,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(180); + var node = createSynthesizedNode(182); node.literal = literal; return node; } @@ -48221,7 +50347,7 @@ var ts; } ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(182); + var node = createSynthesizedNode(184); node.elements = createNodeArray(elements); return node; } @@ -48233,7 +50359,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(183); + var node = createSynthesizedNode(185); node.elements = createNodeArray(elements); return node; } @@ -48245,7 +50371,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(184); + var node = createSynthesizedNode(186); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -48263,7 +50389,7 @@ var ts; } ts.updateBindingElement = updateBindingElement; function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(185); + var node = createSynthesizedNode(187); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -48277,7 +50403,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(186); + var node = createSynthesizedNode(188); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -48291,7 +50417,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(187); + var node = createSynthesizedNode(189); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); setEmitFlags(node, 131072); @@ -48306,7 +50432,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(188); + var node = createSynthesizedNode(190); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -48320,7 +50446,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(189); + var node = createSynthesizedNode(191); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -48336,7 +50462,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(190); + var node = createSynthesizedNode(192); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -48352,7 +50478,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { - var node = createSynthesizedNode(191); + var node = createSynthesizedNode(193); node.tag = ts.parenthesizeForAccess(tag); if (template) { node.typeArguments = asNodeArray(typeArgumentsOrTemplate); @@ -48375,7 +50501,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(192); + var node = createSynthesizedNode(194); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -48389,7 +50515,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(193); + var node = createSynthesizedNode(195); node.expression = expression; return node; } @@ -48401,7 +50527,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(194); + var node = createSynthesizedNode(196); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -48425,12 +50551,12 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(195); + var node = createSynthesizedNode(197); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(36); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37); node.body = ts.parenthesizeConciseBody(body); return node; } @@ -48447,7 +50573,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(196); + var node = createSynthesizedNode(198); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -48459,7 +50585,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(197); + var node = createSynthesizedNode(199); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -48471,7 +50597,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(198); + var node = createSynthesizedNode(200); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -48483,7 +50609,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(199); + var node = createSynthesizedNode(201); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -48495,7 +50621,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(200); + var node = createSynthesizedNode(202); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -48508,7 +50634,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(201); + var node = createSynthesizedNode(203); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -48521,7 +50647,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(202); + var node = createSynthesizedNode(204); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, true, undefined); @@ -48538,11 +50664,11 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(203); + var node = createSynthesizedNode(205); node.condition = ts.parenthesizeForConditionalHead(condition); - node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); - node.colonToken = whenFalse ? colonToken : createToken(56); + node.colonToken = whenFalse ? colonToken : createToken(57); node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); return node; } @@ -48558,7 +50684,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(204); + var node = createSynthesizedNode(206); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -48572,33 +50698,33 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createTemplateHead(text) { - var node = createSynthesizedNode(14); + var node = createSynthesizedNode(15); node.text = text; return node; } ts.createTemplateHead = createTemplateHead; function createTemplateMiddle(text) { - var node = createSynthesizedNode(15); + var node = createSynthesizedNode(16); node.text = text; return node; } ts.createTemplateMiddle = createTemplateMiddle; function createTemplateTail(text) { - var node = createSynthesizedNode(16); + var node = createSynthesizedNode(17); node.text = text; return node; } ts.createTemplateTail = createTemplateTail; function createNoSubstitutionTemplateLiteral(text) { - var node = createSynthesizedNode(13); + var node = createSynthesizedNode(14); node.text = text; return node; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(205); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 ? asteriskTokenOrExpression : expression; + var node = createSynthesizedNode(207); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 ? asteriskTokenOrExpression : expression; return node; } ts.createYield = createYield; @@ -48610,7 +50736,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(206); + var node = createSynthesizedNode(208); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -48622,7 +50748,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(207); + var node = createSynthesizedNode(209); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -48643,11 +50769,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(208); + return createSynthesizedNode(210); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(209); + var node = createSynthesizedNode(211); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -48661,7 +50787,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(210); + var node = createSynthesizedNode(212); node.expression = expression; node.type = type; return node; @@ -48675,7 +50801,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(211); + var node = createSynthesizedNode(213); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -48687,7 +50813,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(212); + var node = createSynthesizedNode(214); node.keywordToken = keywordToken; node.name = name; return node; @@ -48700,7 +50826,7 @@ var ts; } ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(214); + var node = createSynthesizedNode(216); node.expression = expression; node.literal = literal; return node; @@ -48714,11 +50840,11 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(215); + return createSynthesizedNode(217); } ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { - var block = createSynthesizedNode(216); + var block = createSynthesizedNode(218); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -48732,7 +50858,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(217); + var node = createSynthesizedNode(219); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -48747,11 +50873,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(218); + return createSynthesizedNode(220); } ts.createEmptyStatement = createEmptyStatement; function createExpressionStatement(expression) { - var node = createSynthesizedNode(219); + var node = createSynthesizedNode(221); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -48765,7 +50891,7 @@ var ts; ts.createStatement = createExpressionStatement; ts.updateStatement = updateExpressionStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(220); + var node = createSynthesizedNode(222); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -48781,7 +50907,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(221); + var node = createSynthesizedNode(223); node.statement = statement; node.expression = expression; return node; @@ -48795,7 +50921,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(222); + var node = createSynthesizedNode(224); node.expression = expression; node.statement = statement; return node; @@ -48809,7 +50935,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(223); + var node = createSynthesizedNode(225); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -48827,7 +50953,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(224); + var node = createSynthesizedNode(226); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -48843,7 +50969,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(225); + var node = createSynthesizedNode(227); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -48861,7 +50987,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(226); + var node = createSynthesizedNode(228); node.label = asName(label); return node; } @@ -48873,7 +50999,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(227); + var node = createSynthesizedNode(229); node.label = asName(label); return node; } @@ -48885,7 +51011,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(228); + var node = createSynthesizedNode(230); node.expression = expression; return node; } @@ -48897,7 +51023,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(229); + var node = createSynthesizedNode(231); node.expression = expression; node.statement = statement; return node; @@ -48911,7 +51037,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(230); + var node = createSynthesizedNode(232); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -48925,7 +51051,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(231); + var node = createSynthesizedNode(233); node.label = asName(label); node.statement = statement; return node; @@ -48939,7 +51065,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(232); + var node = createSynthesizedNode(234); node.expression = expression; return node; } @@ -48951,7 +51077,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(233); + var node = createSynthesizedNode(235); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -48967,11 +51093,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(234); + return createSynthesizedNode(236); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(235); + var node = createSynthesizedNode(237); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -48988,7 +51114,7 @@ var ts; ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0; } - var node = createSynthesizedNode(236); + var node = createSynthesizedNode(238); node.flags |= flags & 3; node.declarations = createNodeArray(declarations); return node; @@ -49001,7 +51127,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(237); + var node = createSynthesizedNode(239); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -49027,7 +51153,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(238); + var node = createSynthesizedNode(240); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -49049,7 +51175,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(239); + var node = createSynthesizedNode(241); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -49071,7 +51197,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(240); + var node = createSynthesizedNode(242); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -49091,7 +51217,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(241); + var node = createSynthesizedNode(243); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -49110,7 +51236,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0; } - var node = createSynthesizedNode(242); + var node = createSynthesizedNode(244); node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -49129,7 +51255,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(243); + var node = createSynthesizedNode(245); node.statements = createNodeArray(statements); return node; } @@ -49141,7 +51267,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(244); + var node = createSynthesizedNode(246); node.clauses = createNodeArray(clauses); return node; } @@ -49153,7 +51279,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(245); + var node = createSynthesizedNode(247); node.name = asName(name); return node; } @@ -49165,7 +51291,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(246); + var node = createSynthesizedNode(248); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -49183,7 +51309,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(247); + var node = createSynthesizedNode(249); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -49201,7 +51327,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(248); + var node = createSynthesizedNode(250); node.name = name; node.namedBindings = namedBindings; return node; @@ -49215,7 +51341,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(249); + var node = createSynthesizedNode(251); node.name = name; return node; } @@ -49227,7 +51353,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(250); + var node = createSynthesizedNode(252); node.elements = createNodeArray(elements); return node; } @@ -49239,7 +51365,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(251); + var node = createSynthesizedNode(253); node.propertyName = propertyName; node.name = name; return node; @@ -49253,11 +51379,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(252); + var node = createSynthesizedNode(254); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58, expression, false, undefined) : ts.parenthesizeDefaultExpression(expression); + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59, expression, false, undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -49270,7 +51396,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(253); + var node = createSynthesizedNode(255); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -49288,7 +51414,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(254); + var node = createSynthesizedNode(256); node.elements = createNodeArray(elements); return node; } @@ -49300,7 +51426,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(255); + var node = createSynthesizedNode(257); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -49314,7 +51440,7 @@ var ts; } ts.updateExportSpecifier = updateExportSpecifier; function createExternalModuleReference(expression) { - var node = createSynthesizedNode(257); + var node = createSynthesizedNode(259); node.expression = expression; return node; } @@ -49325,8 +51451,49 @@ var ts; : node; } ts.updateExternalModuleReference = updateExternalModuleReference; + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(258); + var node = createSynthesizedNode(260); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -49342,7 +51509,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(259); + var node = createSynthesizedNode(261); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -49358,7 +51525,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(260); + var node = createSynthesizedNode(262); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -49374,7 +51541,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(261); + var node = createSynthesizedNode(263); node.tagName = tagName; return node; } @@ -49386,7 +51553,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxFragment(openingFragment, children, closingFragment) { - var node = createSynthesizedNode(262); + var node = createSynthesizedNode(264); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -49402,7 +51569,7 @@ var ts; } ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(265); + var node = createSynthesizedNode(267); node.name = name; node.initializer = initializer; return node; @@ -49416,7 +51583,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(266); + var node = createSynthesizedNode(268); node.properties = createNodeArray(properties); return node; } @@ -49428,7 +51595,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(267); + var node = createSynthesizedNode(269); node.expression = expression; return node; } @@ -49440,7 +51607,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(268); + var node = createSynthesizedNode(270); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -49453,7 +51620,7 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; function createCaseClause(expression, statements) { - var node = createSynthesizedNode(269); + var node = createSynthesizedNode(271); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -49467,7 +51634,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(270); + var node = createSynthesizedNode(272); node.statements = createNodeArray(statements); return node; } @@ -49479,7 +51646,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(271); + var node = createSynthesizedNode(273); node.token = token; node.types = createNodeArray(types); return node; @@ -49492,7 +51659,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(272); + var node = createSynthesizedNode(274); node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -49506,7 +51673,7 @@ var ts; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(273); + var node = createSynthesizedNode(275); node.name = asName(name); node.questionToken = undefined; node.initializer = ts.parenthesizeExpressionForList(initializer); @@ -49521,7 +51688,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(274); + var node = createSynthesizedNode(276); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -49535,7 +51702,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(275); + var node = createSynthesizedNode(277); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; return node; } @@ -49547,7 +51714,7 @@ var ts; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { - var node = createSynthesizedNode(276); + var node = createSynthesizedNode(278); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -49567,7 +51734,7 @@ var ts; (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { - var updated = createSynthesizedNode(277); + var updated = createSynthesizedNode(279); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -49641,28 +51808,28 @@ var ts; } ts.getMutableClone = getMutableClone; function createNotEmittedStatement(original) { - var node = createSynthesizedNode(305); + var node = createSynthesizedNode(307); node.original = original; setTextRange(node, original); return node; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(309); + var node = createSynthesizedNode(311); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(308); + var node = createSynthesizedNode(310); node.emitNode = {}; node.original = original; return node; } ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(306); + var node = createSynthesizedNode(308); node.expression = expression; node.original = original; setTextRange(node, original); @@ -49678,17 +51845,17 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 307) { + if (node.kind === 309) { return node.elements; } - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27) { return [node.left, node.right]; } } return node; } function createCommaList(elements) { - var node = createSynthesizedNode(307); + var node = createSynthesizedNode(309); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -49701,14 +51868,14 @@ var ts; ts.updateCommaList = updateCommaList; function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = ts.createNode(278); + var node = ts.createNode(280); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; function createUnparsedSourceFile(text, mapPath, map) { - var node = ts.createNode(279); + var node = ts.createNode(281); node.text = text; node.sourceMapPath = mapPath; node.sourceMapText = map; @@ -49716,7 +51883,7 @@ var ts; } ts.createUnparsedSourceFile = createUnparsedSourceFile; function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { - var node = ts.createNode(280); + var node = ts.createNode(282); node.javascriptText = javascript; node.javascriptMapPath = javascriptMapPath; node.javascriptMapText = javascriptMapText; @@ -49743,47 +51910,47 @@ var ts; } ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { - return createBinary(left, 26, right); + return createBinary(left, 27, right); } ts.createComma = createComma; function createLessThan(left, right) { - return createBinary(left, 27, right); + return createBinary(left, 28, right); } ts.createLessThan = createLessThan; function createAssignment(left, right) { - return createBinary(left, 58, right); + return createBinary(left, 59, right); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 34, right); + return createBinary(left, 35, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 35, right); + return createBinary(left, 36, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 37, right); + return createBinary(left, 38, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 38, right); + return createBinary(left, 39, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand) { - return createPostfix(operand, 43); + return createPostfix(operand, 44); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 53, right); + return createBinary(left, 54, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 54, right); + return createBinary(left, 55, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(51, operand); + return createPrefix(52, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { @@ -49825,7 +51992,7 @@ var ts; function getOrCreateEmitNode(node) { if (!node.emitNode) { if (ts.isParseTreeNode(node)) { - if (node.kind === 277) { + if (node.kind === 279) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -50256,7 +52423,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 231 + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -50268,19 +52435,20 @@ var ts; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = ts.skipParentheses(node); switch (target.kind) { - case 71: + case 72: return cacheIdentifiers; - case 99: + case 100: case 8: case 9: + case 10: return false; - case 185: + case 187: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 186: + case 188: return target.properties.length > 0; default: return true; @@ -50295,7 +52463,7 @@ var ts; thisArg = ts.createThis(); target = callee; } - else if (callee.kind === 97) { + else if (callee.kind === 98) { thisArg = ts.createThis(); target = languageVersion < 2 ? ts.setTextRange(ts.createIdentifier("_super"), callee) @@ -50307,7 +52475,7 @@ var ts; } else { switch (callee.kind) { - case 187: { + case 189: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = ts.createTempVariable(recordTempVariable); target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name); @@ -50319,7 +52487,7 @@ var ts; } break; } - case 188: { + case 190: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = ts.createTempVariable(recordTempVariable); target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); @@ -50372,14 +52540,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 156: - case 157: + case 158: + case 159: return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); - case 273: + case 275: return createExpressionForPropertyAssignment(property, receiver); - case 274: + case 276: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 154: + case 156: return createExpressionForMethodDeclaration(property, receiver); } } @@ -50387,27 +52555,27 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_9 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_9.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_9.push(setter); + properties_8.push(setter); } - properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_9, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), firstAccessor); return ts.aggregateTransformFlags(expression); } @@ -50550,6 +52718,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -50558,19 +52741,7 @@ var ts; } ts.startsWithUseStrict = startsWithUseStrict; function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -50581,7 +52752,7 @@ var ts; ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); - if (skipped.kind === 193) { + if (skipped.kind === 195) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -50590,10 +52761,10 @@ var ts; } ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var binaryOperatorPrecedence = ts.getOperatorPrecedence(202, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(202, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 195 && binaryOperatorPrecedence > 4) { + if (!isLeftSideOfBinary && operand.kind === 197 && binaryOperatorPrecedence > 4) { return true; } var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); @@ -50601,7 +52772,7 @@ var ts; case -1: if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 - && operand.kind === 205) { + && operand.kind === 207) { return false; } return true; @@ -50617,7 +52788,7 @@ var ts; if (operatorHasAssociativeProperty(binaryOperator)) { return false; } - if (binaryOperator === 37) { + if (binaryOperator === 38) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -50630,17 +52801,17 @@ var ts; } } function operatorHasAssociativeProperty(binaryOperator) { - return binaryOperator === 39 + return binaryOperator === 40 + || binaryOperator === 50 || binaryOperator === 49 - || binaryOperator === 48 - || binaryOperator === 50; + || binaryOperator === 51; } function getLiteralKindOfBinaryPlusOperand(node) { node = ts.skipPartiallyEmittedExpressions(node); if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 202 && node.operatorToken.kind === 37) { + if (node.kind === 204 && node.operatorToken.kind === 38) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -50655,7 +52826,7 @@ var ts; return 0; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(203, 55); + var conditionalPrecedence = ts.getOperatorPrecedence(205, 56); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { @@ -50676,8 +52847,8 @@ var ts; var needsParens = isCommaSequence(check); if (!needsParens) { switch (getLeftmostExpression(check, false).kind) { - case 207: - case 194: + case 209: + case 196: needsParens = true; } } @@ -50687,9 +52858,9 @@ var ts; function parenthesizeForNew(expression) { var leftmostExpr = getLeftmostExpression(expression, true); switch (leftmostExpr.kind) { - case 189: + case 191: return ts.createParen(expression); - case 190: + case 192: return !leftmostExpr.arguments ? ts.createParen(expression) : expression; @@ -50700,7 +52871,7 @@ var ts; function parenthesizeForAccess(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 190 || emittedExpression.arguments)) { + && (emittedExpression.kind !== 192 || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -50738,7 +52909,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(202, 26); + var commaPrecedence = ts.getOperatorPrecedence(204, 27); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -50749,29 +52920,29 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 194 || kind === 195) { + if (kind === 196 || kind === 197) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4); } } var leftmostExpressionKind = getLeftmostExpression(emittedExpression, false).kind; - if (leftmostExpressionKind === 186 || leftmostExpressionKind === 194) { + if (leftmostExpressionKind === 188 || leftmostExpressionKind === 196) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeConditionalTypeMember(member) { - return member.kind === 173 ? ts.createParenthesizedType(member) : member; + return member.kind === 175 ? ts.createParenthesizedType(member) : member; } ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 171: - case 172: - case 163: - case 164: + case 173: + case 174: + case 165: + case 166: return ts.createParenthesizedType(member); } return parenthesizeConditionalTypeMember(member); @@ -50779,9 +52950,9 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 165: - case 177: - case 174: + case 167: + case 179: + case 176: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -50807,27 +52978,27 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 201: + case 203: node = node.operand; continue; - case 202: + case 204: node = node.left; continue; - case 203: + case 205: node = node.condition; continue; - case 191: + case 193: node = node.tag; continue; - case 189: + case 191: if (stopAtCallExpressions) { return node; } - case 210: - case 188: - case 187: - case 211: - case 306: + case 212: + case 190: + case 189: + case 213: + case 308: node = node.expression; continue; } @@ -50835,27 +53006,27 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, false).kind === 186)) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, false).kind === 188)) { return ts.setTextRange(ts.createParen(body), body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { - return node.kind === 202 && node.operatorToken.kind === 26 || - node.kind === 307; + return node.kind === 204 && node.operatorToken.kind === 27 || + node.kind === 309; } ts.isCommaSequence = isCommaSequence; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7; } switch (node.kind) { - case 193: + case 195: return (kinds & 1) !== 0; - case 192: - case 210: - case 211: + case 194: + case 212: + case 213: return (kinds & 2) !== 0; - case 306: + case 308: return (kinds & 4) !== 0; } return false; @@ -50880,7 +53051,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 211) { + while (ts.isAssertionExpression(node) || node.kind === 213) { node = node.expression; } return node; @@ -50888,15 +53059,15 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 193: return ts.updateParen(outerExpression, expression); - case 192: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 210: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 211: return ts.updateNonNullExpression(outerExpression, expression); - case 306: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 195: return ts.updateParen(outerExpression, expression); + case 194: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213: return ts.updateNonNullExpression(outerExpression, expression); + case 308: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } function isIgnorableParen(node) { - return node.kind === 193 + return node.kind === 195 && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -50958,10 +53129,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 247 && node.importClause) { + if (node.kind === 249 && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 253 && node.moduleSpecifier) { + if (node.kind === 255 && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -50969,7 +53140,7 @@ var ts; ts.getLocalNameForExternalImport = getLocalNameForExternalImport; function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); - if (moduleName.kind === 9) { + if (moduleName.kind === 10) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) || ts.getSynthesizedClone(moduleName); @@ -51024,11 +53195,11 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 273: - return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 274: - return bindingElement.name; case 275: + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 276: + return bindingElement.name; + case 277: return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } return undefined; @@ -51044,11 +53215,11 @@ var ts; ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 149: - case 184: + case 151: + case 186: return bindingElement.dotDotDotToken; - case 206: - case 275: + case 208: + case 277: return bindingElement; } return undefined; @@ -51056,7 +53227,7 @@ var ts; ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 184: + case 186: if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) @@ -51064,7 +53235,7 @@ var ts; : propertyName; } break; - case 273: + case 275: if (bindingElement.name) { var propertyName = bindingElement.name; return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) @@ -51072,7 +53243,7 @@ var ts; : propertyName; } break; - case 275: + case 277: return bindingElement.name; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); @@ -51086,16 +53257,16 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; - return kind === 9 + return kind === 10 || kind === 8; } function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 182: - case 183: + case 184: case 185: + case 187: return name.elements; - case 186: + case 188: return name.properties; } } @@ -51134,11 +53305,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 183: case 185: + case 187: return convertToArrayAssignmentPattern(node); - case 182: - case 186: + case 184: + case 188: return convertToObjectAssignmentPattern(node); } } @@ -51275,261 +53446,261 @@ var ts; return undefined; } var kind = node.kind; - if ((kind > 0 && kind <= 145) || kind === 176) { + if ((kind > 0 && kind <= 147) || kind === 178) { return node; } switch (kind) { - case 71: + case 72: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 146: - return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 147: - return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); case 148: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); + return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 149: - return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); case 150: - return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 151: - return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 152: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); case 153: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 154: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 155: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); case 156: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 157: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 158: - return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 159: - return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 160: - return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 161: - return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 163: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); case 164: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 165: - return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 166: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 167: - return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); + return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 168: - return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 169: - return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 170: - return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 171: - return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); case 172: - return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); case 173: - return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 174: - return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 181: - return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 175: - return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 177: - return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 178: - return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 179: - return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 180: - return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 182: - return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); + return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); + case 176: + return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); case 183: - return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + case 177: + return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 179: + return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 180: + return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); + case 181: + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 182: + return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); case 184: - return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 185: - return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); case 186: - return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); case 187: - return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); case 188: - return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); case 189: - return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); case 190: - return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); case 191: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 192: - return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 193: - return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 194: - return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 195: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 196: - return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 197: - return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); case 198: - return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 199: - return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); case 200: - return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 201: - return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); case 202: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 203: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); case 204: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 205: - return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); case 206: - return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); case 207: - return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); + case 208: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); case 209: - return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 210: - return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 211: - return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 212: - return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); + case 213: + return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); case 214: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); case 216: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + case 218: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 217: - return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); case 219: - return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 220: - return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); case 221: - return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 222: - return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); case 223: - return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); case 224: - return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 225: - return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 226: - return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 227: - return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 228: - return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 229: - return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); case 230: - return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); case 231: - return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 232: - return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); case 233: - return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + case 234: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); case 235: - return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 236: - return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); case 237: - return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 238: - return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 239: - return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 240: - return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 241: - return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 242: - return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 243: - return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 244: - return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); case 245: - return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 246: - return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); + return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); case 247: - return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 248: - return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); + return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 249: - return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); case 250: - return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); case 251: - return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); case 252: - return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); case 253: - return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); case 254: - return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); case 255: - return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 256: + return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); case 257: - return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); - case 258: - return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); case 259: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 260: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 261: - return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 262: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 263: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 264: return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 265: - return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 266: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 267: - return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); case 268: - return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 269: - return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 270: - return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); case 271: - return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); case 272: - return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 273: - return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); case 274: - return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); case 275: - return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); case 276: - return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); case 277: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + case 278: + return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 279: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 306: + case 308: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 307: + case 309: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; @@ -51555,48 +53726,41 @@ var ts; var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; - if ((kind > 0 && kind <= 145)) { + if ((kind > 0 && kind <= 147)) { return initial; } - if ((kind >= 161 && kind <= 180)) { + if ((kind >= 163 && kind <= 182)) { return initial; } var result = initial; switch (node.kind) { - case 215: - case 218: - case 208: - case 234: - case 305: + case 217: + case 220: + case 210: + case 236: + case 307: break; - case 146: + case 148: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 147: - result = reduceNode(node.expression, cbNode, result); - break; case 149: - result = reduceNodes(node.decorators, cbNodes, result); - result = reduceNodes(node.modifiers, cbNodes, result); - result = reduceNode(node.name, cbNode, result); - result = reduceNode(node.type, cbNode, result); - result = reduceNode(node.initializer, cbNode, result); - break; - case 150: result = reduceNode(node.expression, cbNode, result); break; case 151: + result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); - result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; case 152: - result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 153: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; @@ -51604,73 +53768,81 @@ var ts; result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); - result = reduceNodes(node.typeParameters, cbNodes, result); - result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); - result = reduceNode(node.body, cbNode, result); - break; - case 155: - result = reduceNodes(node.modifiers, cbNodes, result); - result = reduceNodes(node.parameters, cbNodes, result); - result = reduceNode(node.body, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 156: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; case 157: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); + break; + case 158: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 159: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 182: - case 183: - result = reduceNodes(node.elements, cbNodes, result); - break; case 184: - result = reduceNode(node.propertyName, cbNode, result); - result = reduceNode(node.name, cbNode, result); - result = reduceNode(node.initializer, cbNode, result); - break; case 185: result = reduceNodes(node.elements, cbNodes, result); break; case 186: - result = reduceNodes(node.properties, cbNodes, result); + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 187: - result = reduceNode(node.expression, cbNode, result); - result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.elements, cbNodes, result); break; case 188: - result = reduceNode(node.expression, cbNode, result); - result = reduceNode(node.argumentExpression, cbNode, result); + result = reduceNodes(node.properties, cbNodes, result); break; case 189: result = reduceNode(node.expression, cbNode, result); - result = reduceNodes(node.typeArguments, cbNodes, result); - result = reduceNodes(node.arguments, cbNodes, result); + result = reduceNode(node.name, cbNode, result); break; case 190: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); + break; + case 191: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 191: + case 192: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 193: result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNode(node.template, cbNode, result); break; - case 192: + case 194: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 194: + case 196: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -51678,121 +53850,121 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; + case 197: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; case 195: - result = reduceNodes(node.modifiers, cbNodes, result); - result = reduceNodes(node.typeParameters, cbNodes, result); - result = reduceNodes(node.parameters, cbNodes, result); - result = reduceNode(node.type, cbNode, result); - result = reduceNode(node.body, cbNode, result); - break; - case 193: - case 196: - case 197: case 198: case 199: - case 205: - case 206: - case 211: - result = reduceNode(node.expression, cbNode, result); - break; case 200: case 201: - result = reduceNode(node.operand, cbNode, result); + case 207: + case 208: + case 213: + result = reduceNode(node.expression, cbNode, result); break; case 202: + case 203: + result = reduceNode(node.operand, cbNode, result); + break; + case 204: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 203: + case 205: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 204: + case 206: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 207: + case 209: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 209: + case 211: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 210: + case 212: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; - case 214: + case 216: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; - case 216: + case 218: result = reduceNodes(node.statements, cbNodes, result); break; - case 217: + case 219: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 219: + case 221: result = reduceNode(node.expression, cbNode, result); break; - case 220: + case 222: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 221: - result = reduceNode(node.statement, cbNode, result); - result = reduceNode(node.expression, cbNode, result); - break; - case 222: - case 229: - result = reduceNode(node.expression, cbNode, result); - result = reduceNode(node.statement, cbNode, result); - break; case 223: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 224: + case 231: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); + break; + case 225: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224: - case 225: + case 226: + case 227: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 228: - case 232: + case 230: + case 234: result = reduceNode(node.expression, cbNode, result); break; - case 230: + case 232: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 231: + case 233: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 233: + case 235: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 235: + case 237: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 236: + case 238: result = reduceNodes(node.declarations, cbNodes, result); break; - case 237: + case 239: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -51801,7 +53973,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 238: + case 240: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -51809,131 +53981,132 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 241: + case 243: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 242: + case 244: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 243: + case 245: result = reduceNodes(node.statements, cbNodes, result); break; - case 244: + case 246: result = reduceNodes(node.clauses, cbNodes, result); break; - case 246: + case 248: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 247: + case 249: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 248: + case 250: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 249: - result = reduceNode(node.name, cbNode, result); - break; - case 250: - case 254: - result = reduceNodes(node.elements, cbNodes, result); - break; case 251: - case 255: - result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; case 252: + case 256: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 253: + case 257: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 254: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 253: + case 255: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 257: + case 259: result = reduceNode(node.expression, cbNode, result); break; - case 258: + case 260: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 262: + case 264: result = reduceNode(node.openingFragment, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingFragment, cbNode, result); break; - case 259: - case 260: + case 261: + case 262: result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 266: + case 268: result = reduceNodes(node.properties, cbNodes, result); break; - case 261: + case 263: result = reduceNode(node.tagName, cbNode, result); break; - case 265: + case 267: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 267: - result = reduceNode(node.expression, cbNode, result); - break; - case 268: - result = reduceNode(node.expression, cbNode, result); - break; case 269: result = reduceNode(node.expression, cbNode, result); + break; case 270: - result = reduceNodes(node.statements, cbNodes, result); + result = reduceNode(node.expression, cbNode, result); break; case 271: + result = reduceNode(node.expression, cbNode, result); + case 272: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 273: result = reduceNodes(node.types, cbNodes, result); break; - case 272: + case 274: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; - case 273: + case 275: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 274: - result = reduceNode(node.name, cbNode, result); - result = reduceNode(node.objectAssignmentInitializer, cbNode, result); - break; - case 275: - result = reduceNode(node.expression, cbNode, result); - break; case 276: result = reduceNode(node.name, cbNode, result); - result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; case 277: - result = reduceNodes(node.statements, cbNodes, result); - break; - case 306: result = reduceNode(node.expression, cbNode, result); break; - case 307: + case 278: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 279: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 308: + result = reduceNode(node.expression, cbNode, result); + break; + case 309: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -51986,7 +54159,7 @@ var ts; return subtreeFlags; } function aggregateTransformFlagsForSubtree(node) { - if (ts.hasModifier(node, 2) || (ts.isTypeNode(node) && node.kind !== 209)) { + if (ts.hasModifier(node, 2) || (ts.isTypeNode(node) && node.kind !== 211)) { return 0; } return reduceEachChild(node, 0, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); @@ -52027,7 +54200,7 @@ var ts; }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, - __debugObjectFlags: { get: function () { return this.flags & 131072 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ @@ -52063,251 +54236,580 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + sourcesContent.push(null); } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - var text = host.readFile(path); - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } } - }; - cached.set(path, file); - return file; + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + if (lastGeneratedLine < pendingGeneratedLine) { + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + if (hasLast) { + mappings += ","; + } + } + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(true, true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59) { + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44) { + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); } }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 || + mappings.charCodeAt(pos) === 59); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + moreDigits = (currentByte & 32) !== 0; + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + if ((value & 1) === 0) { + value = value >> 1; + } + else { + value = value >> 1; + value = -value; + } + return value; + } } - ts.createSourceFileLikeCache = createSourceFileLikeCache; -})(ts || (ts = {})); -(function (ts) { - var sourcemaps; - (function (sourcemaps) { - sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; - function decode(host, mapPath, map, program, fallbackCache) { - if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } - var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; - var decodedMappings; - var generatedOrderedMappings; - var sourceOrderedMappings; - return { - getOriginalPosition: getOriginalPosition, - getGeneratedPosition: getGeneratedPosition - }; - function getGeneratedPosition(loc) { - var maps = getSourceOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); - if (targetIndex < 0 && maps.length > 0) { - targetIndex = ~targetIndex; - } - if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { - return loc; - } - return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; - } - function getOriginalPosition(loc) { - var maps = getGeneratedOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); - if (targetIndex < 0 && maps.length > 0) { - targetIndex = ~targetIndex; - } - return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; - } - function getSourceFileLike(fileName, location) { - var path = ts.toPath(fileName, location, host.getCanonicalFileName); - var file = program && program.getSourceFile(path); - if (!file || file.resolvedPath !== path) { - return fallbackCache.get(path); - } - return file; - } - function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { - var file = getSourceFileLike(fileName, directory); - if (!file) { - return -1; - } - return ts.getPositionOfLineAndCharacter(file, line, character); - } - function getDecodedMappings() { - return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host)); - } - function getSourceOrderedMappings() { - return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); - } - function getGeneratedOrderedMappings() { - return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); - } - function compareProcessedPositionSourcePositions(a, b) { - return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || - ts.compareValues(a.sourcePosition, b.sourcePosition); - } - function compareProcessedPositionEmittedPositions(a, b) { - return ts.compareValues(a.emittedPosition, b.emittedPosition); - } - function processPosition(position) { - var sourcePath = map.sources[position.sourceIndex]; - return { - emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), - sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), - sourcePath: sourcePath, - }; - } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 + value : + value >= 26 && value < 52 ? 97 + value - 26 : + value >= 52 && value < 62 ? 48 + value - 52 : + value === 62 ? 43 : + value === 63 ? 47 : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 && ch <= 90 ? ch - 65 : + ch >= 97 && ch <= 122 ? ch - 97 + 26 : + ch >= 48 && ch <= 57 ? ch - 48 + 52 : + ch === 43 ? 62 : + ch === 47 ? 63 : + -1; + } + function base64VLQFormatEncode(inValue) { + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; } - sourcemaps.decode = decode; - function decodeMappings(map) { - var state = { - encodedText: map.mappings, - currentNameIndex: undefined, - sourceMapNamesLength: map.names ? map.names.length : undefined, - currentEmittedColumn: 0, - currentEmittedLine: 0, - currentSourceColumn: 0, - currentSourceLine: 0, - currentSourceIndex: 0, - decodingIndex: 0 - }; - function captureSpan() { - return { - emittedColumn: state.currentEmittedColumn, - emittedLine: state.currentEmittedLine, - sourceColumn: state.currentSourceColumn, - sourceIndex: state.currentSourceIndex, - sourceLine: state.currentSourceLine, - nameIndex: state.currentNameIndex - }; + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; } return { - get decodingIndex() { return state.decodingIndex; }, - get error() { return state.error; }, - get lastSpan() { return captureSpan(); }, - next: function () { - if (hasCompletedDecoding(state) || state.error) - return { done: true, value: undefined }; - if (!decodeSinglePosition(state)) - return { done: true, value: undefined }; - return { done: false, value: captureSpan() }; - } + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex }; } - sourcemaps.decodeMappings = decodeMappings; - function calculateDecodedMappings(map, processPosition, host) { - var decoder = decodeMappings(map); - var positions = ts.arrayFrom(decoder, processPosition); - if (decoder.error) { - if (host && host.log) { - host.log("Encountered error while decoding sourcemap: " + decoder.error); - } - return []; - } - return positions; - } - function hasCompletedDecoding(state) { - return state.decodingIndex === state.encodedText.length; - } - function decodeSinglePosition(state) { - while (state.decodingIndex < state.encodedText.length) { - var char = state.encodedText.charCodeAt(state.decodingIndex); - if (char === 59) { - state.currentEmittedLine++; - state.currentEmittedColumn = 0; - state.decodingIndex++; - continue; - } - if (char === 44) { - state.decodingIndex++; - continue; - } - state.currentEmittedColumn += base64VLQFormatDecode(); - if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { - return false; - } - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { - return false; - } - state.currentSourceIndex += base64VLQFormatDecode(); - if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { - return false; - } - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { - return false; - } - state.currentSourceLine += base64VLQFormatDecode(); - if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { - return false; - } - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { - return false; - } - state.currentSourceColumn += base64VLQFormatDecode(); - if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { - return false; - } - if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { - if (state.currentNameIndex === undefined) { - state.currentNameIndex = 0; + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); } - state.currentNameIndex += base64VLQFormatDecode(); - } - if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { - return false; - } - return true; - } - createErrorIfCondition(true, "No encoded entry found"); - return false; - function createErrorIfCondition(condition, errormsg) { - if (state.error) { - return true; - } - if (condition) { - state.error = errormsg; - } - return condition; - } - function base64VLQFormatDecode() { - var moreDigits = true; - var shiftCount = 0; - var value = 0; - for (; moreDigits; state.decodingIndex++) { - if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return undefined; - } - var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); - moreDigits = (currentByte & 32) !== 0; - value = value | ((currentByte & 31) << shiftCount); - shiftCount += 5; - } - if ((value & 1) === 0) { - value = value >> 1; + decodedMappings = ts.emptyArray; } else { - value = value >> 1; - value = -value; + decodedMappings = mappings; } - return value; } + return decodedMappings; } - function base64FormatDecode(char) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; } - function isSourceMappingSegmentEnd(encodedText, pos) { - return (pos === encodedText.length || - encodedText.charCodeAt(pos) === 44 || - encodedText.charCodeAt(pos) === 59); + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; } - })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; })(ts || (ts = {})); var ts; (function (ts) { @@ -52329,7 +54831,7 @@ var ts; function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 277 ? transformSourceFile(node) : transformBundle(node); + return node.kind === 279 ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -52373,16 +54875,16 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 247: + case 249: externalImports.push(node); hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; - case 246: - if (node.moduleReference.kind === 257) { + case 248: + if (node.moduleReference.kind === 259) { externalImports.push(node); } break; - case 253: + case 255: if (node.moduleSpecifier) { if (!node.exportClause) { externalImports.push(node); @@ -52409,12 +54911,12 @@ var ts; } } break; - case 252: + case 254: if (node.isExportEquals && !exportEquals) { exportEquals = node; } break; - case 217: + case 219: if (ts.hasModifier(node, 1)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -52422,7 +54924,7 @@ var ts; } } break; - case 237: + case 239: if (ts.hasModifier(node, 1)) { if (ts.hasModifier(node, 512)) { if (!hasExportDefault) { @@ -52440,7 +54942,7 @@ var ts; } } break; - case 238: + case 240: if (ts.hasModifier(node, 1)) { if (ts.hasModifier(node, 512)) { if (!hasExportDefault) { @@ -52706,8 +55208,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 - && !(element.transformFlags & (524288 | 1048576)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 | 1048576)) + && !(element.transformFlags & (131072 | 262144)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 | 262144)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -52754,7 +55256,7 @@ var ts; for (var i = 0; i < numElements; i++) { var element = elements[i]; if (flattenContext.level >= 1) { - if (element.transformFlags & 1048576) { + if (element.transformFlags & 262144) { var temp = ts.createTempVariable(undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -52885,8 +55387,8 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(187); - context.enableSubstitution(188); + context.enableSubstitution(189); + context.enableSubstitution(190); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; @@ -52899,14 +55401,14 @@ var ts; var pendingExpressions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 278) { + if (node.kind === 280) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280) { + if (prepend.kind === 282) { return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); } return prepend; @@ -52937,16 +55439,16 @@ var ts; } function onBeforeVisitNode(node) { switch (node.kind) { - case 277: - case 244: - case 243: - case 216: + case 279: + case 246: + case 245: + case 218: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 238: - case 237: + case 240: + case 239: if (ts.hasModifier(node, 2)) { break; } @@ -52954,7 +55456,7 @@ var ts; recordEmittedDeclarationInScope(node); } else { - ts.Debug.assert(node.kind === 238 || ts.hasModifier(node, 512)); + ts.Debug.assert(node.kind === 240 || ts.hasModifier(node, 512)); } if (ts.isClassDeclaration(node)) { currentNameScope = node; @@ -52979,10 +55481,10 @@ var ts; } function sourceElementVisitorWorker(node) { switch (node.kind) { - case 247: - case 246: - case 252: - case 253: + case 249: + case 248: + case 254: + case 255: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -52997,13 +55499,13 @@ var ts; return node; } switch (node.kind) { - case 247: + case 249: return visitImportDeclaration(node); - case 246: + case 248: return visitImportEqualsDeclaration(node); - case 252: + case 254: return visitExportAssignment(node); - case 253: + case 255: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -53013,11 +55515,11 @@ var ts; return saveStateAndInvoke(node, namespaceElementVisitorWorker); } function namespaceElementVisitorWorker(node) { - if (node.kind === 253 || - node.kind === 247 || - node.kind === 248 || - (node.kind === 246 && - node.moduleReference.kind === 257)) { + if (node.kind === 255 || + node.kind === 249 || + node.kind === 250 || + (node.kind === 248 && + node.moduleReference.kind === 259)) { return undefined; } else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { @@ -53033,15 +55535,15 @@ var ts; } function classElementVisitorWorker(node) { switch (node.kind) { - case 155: - return undefined; - case 152: - case 160: - case 156: case 157: + return undefined; case 154: + case 162: + case 158: + case 159: + case 156: return visitorWorker(node); - case 215: + case 217: return node; default: return ts.Debug.failBadSyntaxKind(node); @@ -53051,7 +55553,7 @@ var ts; if (ts.modifierToFlag(node.kind) & 2270) { return undefined; } - else if (currentNamespace && node.kind === 84) { + else if (currentNamespace && node.kind === 85) { return undefined; } return node; @@ -53061,100 +55563,100 @@ var ts; return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 84: - case 79: + case 85: + case 80: return currentNamespace ? undefined : node; - case 114: - case 112: + case 115: case 113: - case 117: - case 76: - case 124: - case 132: - case 167: - case 168: + case 114: + case 118: + case 77: + case 125: + case 133: case 169: case 170: - case 166: - case 161: - case 148: - case 119: - case 142: - case 122: - case 137: - case 134: - case 131: - case 105: - case 138: - case 164: - case 163: - case 165: - case 162: case 171: case 172: + case 168: + case 163: + case 150: + case 120: + case 143: + case 123: + case 138: + case 135: + case 132: + case 106: + case 139: + case 166: + case 165: + case 167: + case 164: case 173: + case 174: case 175: - case 176: case 177: case 178: case 179: case 180: - case 160: - case 150: - case 240: - return undefined; + case 181: + case 182: + case 162: case 152: - return visitPropertyDeclaration(node); - case 245: - return undefined; - case 155: - return visitConstructor(node); - case 239: - return ts.createNotEmittedStatement(node); - case 238: - return visitClassDeclaration(node); - case 207: - return visitClassExpression(node); - case 271: - return visitHeritageClause(node); - case 209: - return visitExpressionWithTypeArguments(node); - case 154: - return visitMethodDeclaration(node); - case 156: - return visitGetAccessor(node); - case 157: - return visitSetAccessor(node); - case 237: - return visitFunctionDeclaration(node); - case 194: - return visitFunctionExpression(node); - case 195: - return visitArrowFunction(node); - case 149: - return visitParameter(node); - case 193: - return visitParenthesizedExpression(node); - case 192: - case 210: - return visitAssertionExpression(node); - case 189: - return visitCallExpression(node); - case 190: - return visitNewExpression(node); - case 191: - return visitTaggedTemplateExpression(node); - case 211: - return visitNonNullExpression(node); - case 241: - return visitEnumDeclaration(node); - case 217: - return visitVariableStatement(node); - case 235: - return visitVariableDeclaration(node); case 242: + return undefined; + case 154: + return visitPropertyDeclaration(node); + case 247: + return undefined; + case 157: + return visitConstructor(node); + case 241: + return ts.createNotEmittedStatement(node); + case 240: + return visitClassDeclaration(node); + case 209: + return visitClassExpression(node); + case 273: + return visitHeritageClause(node); + case 211: + return visitExpressionWithTypeArguments(node); + case 156: + return visitMethodDeclaration(node); + case 158: + return visitGetAccessor(node); + case 159: + return visitSetAccessor(node); + case 239: + return visitFunctionDeclaration(node); + case 196: + return visitFunctionExpression(node); + case 197: + return visitArrowFunction(node); + case 151: + return visitParameter(node); + case 195: + return visitParenthesizedExpression(node); + case 194: + case 212: + return visitAssertionExpression(node); + case 191: + return visitCallExpression(node); + case 192: + return visitNewExpression(node); + case 193: + return visitTaggedTemplateExpression(node); + case 213: + return visitNonNullExpression(node); + case 243: + return visitEnumDeclaration(node); + case 219: + return visitVariableStatement(node); + case 237: + return visitVariableDeclaration(node); + case 244: return visitModuleDeclaration(node); - case 246: + case 248: return visitImportEqualsDeclaration(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -53184,7 +55686,7 @@ var ts; if (ts.some(staticProperties)) facts |= 1; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); - if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95) + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96) facts |= 64; if (shouldEmitDecorateCallForClass(node)) facts |= 2; @@ -53224,7 +55726,7 @@ var ts; addClassElementDecorationStatements(statements, node, true); addConstructorDecorationStatement(statements, node); if (facts & 128) { - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19); var localName = ts.getInternalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; @@ -53298,13 +55800,13 @@ var ts; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85; })); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86; })); var classExpression = ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); @@ -53333,9 +55835,11 @@ var ts; return ts.setTextRange(ts.createNodeArray(members), node.members); } function transformConstructor(node, isDerivedClass) { - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { return ts.visitEachChild(constructor, visitor, context); } @@ -53375,7 +55879,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 219 && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -53409,13 +55913,13 @@ var ts; return isInitializedProperty(member, false); } function isInitializedProperty(member, isStatic) { - return member.kind === 152 + return member.kind === 154 && isStatic === ts.hasModifier(member, 32) && member.initializer !== undefined; } function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -53425,8 +55929,8 @@ var ts; } function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { - var property = properties_11[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var expression = transformInitializedProperty(property, receiver); ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -53486,12 +55990,12 @@ var ts; } function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 156: - case 157: + case 158: + case 159: return getAllDecoratorsOfAccessors(node, member); - case 154: + case 156: return getAllDecoratorsOfMethod(member); - case 152: + case 154: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -53570,7 +56074,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, true); var descriptor = languageVersion > 0 - ? member.kind === 152 + ? member.kind === 154 ? ts.createVoidZero() : ts.createNull() : undefined; @@ -53639,13 +56143,13 @@ var ts; if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(36), serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(37), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(36), serializeParameterTypesOfNode(node, container)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(37), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(36), serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(37), serializeReturnTypeOfNode(node)))); } if (properties) { decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, true))); @@ -53654,22 +56158,22 @@ var ts; } function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 154 - || kind === 156 - || kind === 157 - || kind === 152; + return kind === 156 + || kind === 158 + || kind === 159 + || kind === 154; } function shouldAddReturnTypeMetadata(node) { - return node.kind === 154; + return node.kind === 156; } function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 238: - case 207: + case 240: + case 209: return ts.getFirstConstructorWithBody(node) !== undefined; - case 154: case 156: - case 157: + case 158: + case 159: return true; } return false; @@ -53681,15 +56185,15 @@ var ts; } function serializeTypeOfNode(node) { switch (node.kind) { - case 152: - case 149: - return serializeTypeNode(node.type); - case 157: - case 156: - return serializeTypeNode(getAccessorTypeNode(node)); - case 238: - case 207: case 154: + case 151: + return serializeTypeNode(node.type); + case 159: + case 158: + return serializeTypeNode(getAccessorTypeNode(node)); + case 240: + case 209: + case 156: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -53721,7 +56225,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 156) { + if (container && node.kind === 158) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -53743,75 +56247,81 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 105: - case 140: - case 95: - case 131: + case 106: + case 141: + case 96: + case 132: return ts.createVoidZero(); - case 175: + case 177: return serializeTypeNode(node.type); - case 163: - case 164: + case 165: + case 166: return ts.createIdentifier("Function"); - case 167: - case 168: + case 169: + case 170: return ts.createIdentifier("Array"); - case 161: - case 122: + case 163: + case 123: return ts.createIdentifier("Boolean"); - case 137: + case 138: return ts.createIdentifier("String"); - case 135: + case 136: return ts.createIdentifier("Object"); - case 180: + case 182: switch (node.literal.kind) { - case 9: + case 10: return ts.createIdentifier("String"); case 8: return ts.createIdentifier("Number"); - case 101: - case 86: + case 9: + return getGlobalBigIntNameWithFallback(); + case 102: + case 87: return ts.createIdentifier("Boolean"); default: return ts.Debug.failBadSyntaxKind(node.literal); } - case 134: + case 135: return ts.createIdentifier("Number"); - case 138: + case 146: + return getGlobalBigIntNameWithFallback(); + case 139: return languageVersion < 2 ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 162: + case 164: return serializeTypeReferenceNode(node); - case 172: - case 171: - return serializeUnionOrIntersectionType(node); - case 165: - case 177: - case 178: + case 174: + case 173: + return serializeTypeList(node.types); + case 175: + return serializeTypeList([node.trueType, node.falseType]); + case 167: case 179: - case 166: - case 119: - case 142: - case 176: + case 180: case 181: + case 168: + case 120: + case 143: + case 178: + case 183: break; default: return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } - function serializeUnionOrIntersectionType(node) { + function serializeTypeList(types) { var serializedUnion; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175) { + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177) { typeNode = typeNode.type; } - if (typeNode.kind === 131) { + if (typeNode.kind === 132) { continue; } - if (!strictNullChecks && (typeNode.kind === 95 || typeNode.kind === 140)) { + if (!strictNullChecks && (typeNode.kind === 96 || typeNode.kind === 141)) { continue; } var serializedIndividual = serializeTypeNode(typeNode); @@ -53835,6 +56345,9 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); @@ -53842,6 +56355,8 @@ var ts; return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); case ts.TypeReferenceSerializationKind.BooleanType: return ts.createIdentifier("Boolean"); case ts.TypeReferenceSerializationKind.NumberLikeType: @@ -53868,11 +56383,11 @@ var ts; return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); } function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 71) { + if (node.kind === 72) { var copied = serializeEntityNameAsExpression(node); return createCheckedValue(copied, copied); } - if (node.left.kind === 71) { + if (node.left.kind === 72) { return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); } var left = serializeEntityNameAsExpressionFallback(node.left); @@ -53881,13 +56396,13 @@ var ts; } function serializeEntityNameAsExpression(node) { switch (node.kind) { - case 71: + case 72: var name = ts.getMutableClone(node); name.flags &= ~8; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); return name; - case 146: + case 148: return serializeQualifiedNameAsExpression(node); } } @@ -53897,6 +56412,11 @@ var ts; function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } function isSimpleInlineableExpression(expression) { return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || ts.isWellKnownSymbolSyntactically(expression); @@ -53943,9 +56463,9 @@ var ts; } } function visitHeritageClause(node) { - if (node.token === 85) { + if (node.token === 86) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(85, types), node); + return ts.setTextRange(ts.createHeritageClause(86, types), node); } return undefined; } @@ -54145,7 +56665,7 @@ var ts; var name = getExpressionForPropertyName(member, false); var valueExpression = transformEnumMemberDeclarationValue(member); var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); - var outerAssignment = valueExpression.kind === 9 ? + var outerAssignment = valueExpression.kind === 10 ? innerAssignment : ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); @@ -54198,11 +56718,11 @@ var ts; function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ], currentLexicalScope.kind === 277 ? 0 : 1)); + ], currentLexicalScope.kind === 279 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { - if (node.kind === 241) { + if (node.kind === 243) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -54268,7 +56788,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 243) { + if (body.kind === 245) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -54292,13 +56812,13 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true); ts.setTextRange(block, blockLocation); - if (body.kind !== 243) { + if (body.kind !== 245) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 242) { + if (moduleDeclaration.body.kind === 244) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -54318,7 +56838,7 @@ var ts; return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; } function visitNamedImportBindings(node) { - if (node.kind === 249) { + if (node.kind === 251) { return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } else { @@ -54420,7 +56940,7 @@ var ts; return ts.getGeneratedNameForNode(node); } function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608) { + if (resolver.getNodeCheckFlags(node) & 16777216) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -54439,29 +56959,29 @@ var ts; function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8) === 0) { enabledSubstitutions |= 8; - context.enableSubstitution(71); + context.enableSubstitution(72); } } function enableSubstitutionForClassAliases() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(71); + context.enableSubstitution(72); classAliases = []; } } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; - context.enableSubstitution(71); - context.enableSubstitution(274); - context.enableEmitNotification(242); + context.enableSubstitution(72); + context.enableSubstitution(276); + context.enableEmitNotification(244); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 242; + return ts.getOriginalNode(node).kind === 244; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 241; + return ts.getOriginalNode(node).kind === 243; } function onEmitNode(hint, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; @@ -54505,11 +57025,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 71: + case 72: return substituteExpressionIdentifier(node); - case 187: + case 189: return substitutePropertyAccessExpression(node); - case 188: + case 190: return substituteElementAccessExpression(node); } return node; @@ -54521,7 +57041,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1) { - if (resolver.getNodeCheckFlags(node) & 16777216) { + if (resolver.getNodeCheckFlags(node) & 33554432) { var declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { var classAlias = classAliases[declaration.id]; @@ -54539,9 +57059,9 @@ var ts; function trySubstituteNamespaceExportedName(node) { if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var container = resolver.getReferencedExportContainer(node, false); - if (container && container.kind !== 277) { - var substitute = (applicableSubstitutions & 2 && container.kind === 242) || - (applicableSubstitutions & 8 && container.kind === 241); + if (container && container.kind !== 279) { + var substitute = (applicableSubstitutions & 2 && container.kind === 244) || + (applicableSubstitutions & 8 && container.kind === 243); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), node); } @@ -54634,6 +57154,9 @@ var ts; var enabledSubstitutions; var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + var capturedSuperProperties; + var hasSuperElementAccess; + var substitutedSuperAccessors = []; var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; @@ -54652,18 +57175,28 @@ var ts; return node; } switch (node.kind) { - case 120: + case 121: return undefined; - case 199: + case 201: return visitAwaitExpression(node); - case 154: + case 156: return visitMethodDeclaration(node); - case 237: + case 239: return visitFunctionDeclaration(node); - case 194: + case 196: return visitFunctionExpression(node); - case 195: + case 197: return visitArrowFunction(node); + case 189: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190: + if (capturedSuperProperties && node.expression.kind === 98) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -54671,27 +57204,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 217: + case 219: return visitVariableStatementInAsyncBody(node); - case 223: - return visitForStatementInAsyncBody(node); - case 224: - return visitForInStatementInAsyncBody(node); case 225: + return visitForStatementInAsyncBody(node); + case 226: + return visitForInStatementInAsyncBody(node); + case 227: return visitForOfStatementInAsyncBody(node); - case 272: + case 274: return visitCatchClauseInAsyncBody(node); - case 216: - case 230: - case 244: - case 269: - case 270: - case 233: - case 221: + case 218: + case 232: + case 246: + case 271: + case 272: + case 235: + case 223: + case 224: case 222: - case 220: - case 229: case 231: + case 233: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -54840,7 +57373,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 195; + var isArrowFunction = node.kind === 197; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); @@ -54848,21 +57381,30 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); - if (languageVersion >= 2) { + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -54880,6 +57422,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -54904,14 +57448,15 @@ var ts; function enableSubstitutionForAsyncMethodsWithSuper() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; + context.enableSubstitution(191); context.enableSubstitution(189); - context.enableSubstitution(187); - context.enableSubstitution(188); - context.enableEmitNotification(238); - context.enableEmitNotification(154); + context.enableSubstitution(190); + context.enableEmitNotification(240); context.enableEmitNotification(156); + context.enableEmitNotification(158); + context.enableEmitNotification(159); context.enableEmitNotification(157); - context.enableEmitNotification(155); + context.enableEmitNotification(219); } } function onEmitNode(hint, node, emitCallback) { @@ -54925,6 +57470,13 @@ var ts; return; } } + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } function onSubstituteNode(hint, node) { @@ -54936,24 +57488,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187: - return substitutePropertyAccessExpression(node); - case 188: - return substituteElementAccessExpression(node); case 189: + return substitutePropertyAccessExpression(node); + case 190: + return substituteElementAccessExpression(node); + case 191: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -54971,22 +57523,44 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 - || kind === 155 - || kind === 154 + return kind === 240 + || kind === 157 || kind === 156 - || kind === 157; + || kind === 158 + || kind === 159; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), undefined, [argumentExpression]), "value"), location); + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), undefined, [argumentExpression]), location); + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + function createSuperAccessVariableStatement(resolver, node, names) { + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "v", undefined, undefined, undefined) + ], undefined, undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, true) + ])) + ], 2)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -54995,7 +57569,7 @@ var ts; }; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); - var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(39), undefined, undefined, [], undefined, body); + var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(40), undefined, undefined, [], undefined, body); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 | 524288; return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ ts.createThis(), @@ -55007,12 +57581,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_superIndex") }; })(ts || (ts = {})); var ts; @@ -55029,6 +57603,9 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + var capturedSuperProperties; + var hasSuperElementAccess; + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -55045,7 +57622,7 @@ var ts; return visitorWorker(node, true); } function visitorNoAsyncModifier(node) { - if (node.kind === 120) { + if (node.kind === 121) { return undefined; } return node; @@ -55055,48 +57632,58 @@ var ts; return node; } switch (node.kind) { - case 199: + case 201: return visitAwaitExpression(node); - case 205: + case 207: return visitYieldExpression(node); - case 228: + case 230: return visitReturnStatement(node); - case 231: + case 233: return visitLabeledStatement(node); - case 186: + case 188: return visitObjectLiteralExpression(node); - case 202: + case 204: return visitBinaryExpression(node, noDestructuringValue); - case 235: - return visitVariableDeclaration(node); - case 225: - return visitForOfStatement(node, undefined); - case 223: - return visitForStatement(node); - case 198: - return visitVoidExpression(node); - case 155: - return visitConstructorDeclaration(node); - case 154: - return visitMethodDeclaration(node); - case 156: - return visitGetAccessorDeclaration(node); - case 157: - return visitSetAccessorDeclaration(node); case 237: + return visitVariableDeclaration(node); + case 227: + return visitForOfStatement(node, undefined); + case 225: + return visitForStatement(node); + case 200: + return visitVoidExpression(node); + case 157: + return visitConstructorDeclaration(node); + case 156: + return visitMethodDeclaration(node); + case 158: + return visitGetAccessorDeclaration(node); + case 159: + return visitSetAccessorDeclaration(node); + case 239: return visitFunctionDeclaration(node); - case 194: + case 196: return visitFunctionExpression(node); - case 195: + case 197: return visitArrowFunction(node); - case 149: + case 151: return visitParameter(node); - case 219: + case 221: return visitExpressionStatement(node); - case 193: + case 195: return visitParenthesizedExpression(node, noDestructuringValue); - case 272: + case 274: return visitCatchClause(node); + case 189: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190: + if (capturedSuperProperties && node.expression.kind === 98) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -55128,7 +57715,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 225 && statement.awaitModifier) { + if (statement.kind === 227 && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); @@ -55140,7 +57727,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 275) { + if (e.kind === 277) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -55149,7 +57736,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 273 + chunkObject = ts.append(chunkObject, e.kind === 275 ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -55160,9 +57747,9 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576) { + if (node.transformFlags & 262144) { var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 186) { + if (objects.length && objects[0].kind !== 188) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -55182,16 +57769,16 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144) { return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); } - else if (node.operatorToken.kind === 26) { + else if (node.operatorToken.kind === 27) { return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); } function visitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144) { return ts.flattenDestructuringBinding(node, visitor, context, 1); } return ts.visitEachChild(node, visitor, context); @@ -55203,7 +57790,7 @@ var ts; return ts.visitEachChild(node, visitorNoDestructuringValue, context); } function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576) { + if (node.initializer.transformFlags & 262144) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -55290,7 +57877,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576) { + if (node.transformFlags & 262144) { return ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); @@ -55367,19 +57954,31 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(40), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); + var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); - if (languageVersion >= 2) { + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -55403,7 +58002,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576) { + if (parameter.transformFlags & 262144) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); if (ts.some(declarations)) { @@ -55418,14 +58017,15 @@ var ts; function enableSubstitutionForAsyncMethodsWithSuper() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; + context.enableSubstitution(191); context.enableSubstitution(189); - context.enableSubstitution(187); - context.enableSubstitution(188); - context.enableEmitNotification(238); - context.enableEmitNotification(154); + context.enableSubstitution(190); + context.enableEmitNotification(240); context.enableEmitNotification(156); + context.enableEmitNotification(158); + context.enableEmitNotification(159); context.enableEmitNotification(157); - context.enableEmitNotification(155); + context.enableEmitNotification(219); } } function onEmitNode(hint, node, emitCallback) { @@ -55439,6 +58039,13 @@ var ts; return; } } + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } function onSubstituteNode(hint, node) { @@ -55450,24 +58057,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187: - return substitutePropertyAccessExpression(node); - case 188: - return substituteElementAccessExpression(node); case 189: + return substitutePropertyAccessExpression(node); + case 190: + return substituteElementAccessExpression(node); + case 191: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -55485,18 +58092,18 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 - || kind === 155 - || kind === 154 + return kind === 240 + || kind === 157 || kind === 156 - || kind === 157; + || kind === 158 + || kind === 159; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value"), location); + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), location); + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), undefined, [argumentExpression]), location); } } } @@ -55584,13 +58191,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 258: + case 260: return visitJsxElement(node, false); - case 259: + case 261: return visitJsxSelfClosingElement(node, false); - case 262: + case 264: return visitJsxFragment(node, false); - case 268: + case 270: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -55598,15 +58205,15 @@ var ts; } function transformJsxChildToExpression(node) { switch (node.kind) { - case 10: + case 11: return visitJsxText(node); - case 268: + case 270: return visitJsxExpression(node); - case 258: + case 260: return visitJsxElement(node, true); - case 259: + case 261: return visitJsxSelfClosingElement(node, true); - case 262: + case 264: return visitJsxFragment(node, true); default: return ts.Debug.failBadSyntaxKind(node); @@ -55665,12 +58272,12 @@ var ts; if (node === undefined) { return ts.createTrue(); } - else if (node.kind === 9) { + else if (node.kind === 10) { var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); return ts.setTextRange(literal, node); } - else if (node.kind === 268) { + else if (node.kind === 270) { if (node.expression === undefined) { return ts.createTrue(); } @@ -55730,7 +58337,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 258) { + if (node.kind === 260) { return getTagName(node.openingElement); } else { @@ -56030,7 +58637,7 @@ var ts; return node; } switch (node.kind) { - case 202: + case 204: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -56038,9 +58645,9 @@ var ts; } function visitBinaryExpression(node) { switch (node.operatorToken.kind) { - case 62: + case 63: return visitExponentiationAssignmentExpression(node); - case 40: + case 41: return visitExponentiationExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -56120,14 +58727,14 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096) !== 0 - && node.kind === 228 + && node.kind === 230 && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 216))) - || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) + || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 218))) + || (ts.isIterationStatement(node, false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432) !== 0; } function visitor(node) { @@ -56145,104 +58752,104 @@ var ts; return node; } function callExpressionVisitor(node) { - if (node.kind === 97) { + if (node.kind === 98) { return visitSuperKeyword(true); } return visitor(node); } function visitJavaScript(node) { switch (node.kind) { - case 115: + case 116: return undefined; - case 238: + case 240: return visitClassDeclaration(node); - case 207: + case 209: return visitClassExpression(node); - case 149: + case 151: return visitParameter(node); - case 237: + case 239: return visitFunctionDeclaration(node); - case 195: + case 197: return visitArrowFunction(node); - case 194: + case 196: return visitFunctionExpression(node); - case 235: + case 237: return visitVariableDeclaration(node); - case 71: + case 72: return visitIdentifier(node); - case 236: + case 238: return visitVariableDeclarationList(node); - case 230: + case 232: return visitSwitchStatement(node); - case 244: + case 246: return visitCaseBlock(node); - case 216: + case 218: return visitBlock(node, false); - case 227: - case 226: + case 229: + case 228: return visitBreakOrContinueStatement(node); - case 231: + case 233: return visitLabeledStatement(node); - case 221: - case 222: - return visitDoOrWhileStatement(node, undefined); case 223: - return visitForStatement(node, undefined); case 224: - return visitForInStatement(node, undefined); + return visitDoOrWhileStatement(node, undefined); case 225: + return visitForStatement(node, undefined); + case 226: + return visitForInStatement(node, undefined); + case 227: return visitForOfStatement(node, undefined); - case 219: + case 221: return visitExpressionStatement(node); - case 186: + case 188: return visitObjectLiteralExpression(node); - case 272: - return visitCatchClause(node); case 274: + return visitCatchClause(node); + case 276: return visitShorthandPropertyAssignment(node); - case 147: + case 149: return visitComputedPropertyName(node); - case 185: + case 187: return visitArrayLiteralExpression(node); - case 189: + case 191: return visitCallExpression(node); - case 190: + case 192: return visitNewExpression(node); - case 193: + case 195: return visitParenthesizedExpression(node, true); - case 202: + case 204: return visitBinaryExpression(node, true); - case 13: case 14: case 15: case 16: + case 17: return visitTemplateLiteral(node); - case 9: + case 10: return visitStringLiteral(node); case 8: return visitNumericLiteral(node); - case 191: + case 193: return visitTaggedTemplateExpression(node); - case 204: - return visitTemplateExpression(node); - case 205: - return visitYieldExpression(node); case 206: + return visitTemplateExpression(node); + case 207: + return visitYieldExpression(node); + case 208: return visitSpreadElement(node); - case 97: + case 98: return visitSuperKeyword(false); - case 99: + case 100: return visitThisKeyword(node); - case 212: + case 214: return visitMetaProperty(node); - case 154: - return visitMethodDeclaration(node); case 156: - case 157: + return visitMethodDeclaration(node); + case 158: + case 159: return visitAccessorDeclaration(node); - case 217: + case 219: return visitVariableStatement(node); - case 228: + case 230: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -56323,14 +58930,14 @@ var ts; } function visitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 227 ? 2 : 4; + var jump = node.kind === 229 ? 2 : 4; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 227) { + if (node.kind === 229) { convertedLoopState.nonLocalJumps |= 2; labelMarker = "break"; } @@ -56340,7 +58947,7 @@ var ts; } } else { - if (node.kind === 227) { + if (node.kind === 229) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, true, ts.idText(label), labelMarker); } @@ -56359,10 +58966,10 @@ var ts; expr = copyExpr; } else { - expr = ts.createBinary(expr, 26, copyExpr); + expr = ts.createBinary(expr, 27, copyExpr); } } - returnExpression = ts.createBinary(expr, 26, returnExpression); + returnExpression = ts.createBinary(expr, 27, returnExpression); } return ts.createReturn(returnExpression); } @@ -56420,7 +59027,7 @@ var ts; addExtendsHelperIfNeeded(statements, node, extendsClauseElement); addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19); var localName = ts.getInternalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; @@ -56476,7 +59083,7 @@ var ts; } ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); } - var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); if (superCaptureStatus === 1 || superCaptureStatus === 2) { statementOffset++; @@ -56504,17 +59111,17 @@ var ts; return block; } function isSufficientlyCoveredByReturnStatements(statement) { - if (statement.kind === 228) { + if (statement.kind === 230) { return true; } - else if (statement.kind === 220) { + else if (statement.kind === 222) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); } } - else if (statement.kind === 216) { + else if (statement.kind === 218) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -56543,16 +59150,16 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 219 && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 221 && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 | 32768))) { + && !(ctor.transformFlags & (8192 | 16384))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 202 - || superCallExpression.left.kind !== 189) { + if (superCallExpression.kind !== 204 + || superCallExpression.left.kind !== 191) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536))); @@ -56586,7 +59193,7 @@ var ts; } } function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072) !== 0; + return (node.transformFlags & 65536) !== 0; } function addDefaultValueAssignmentsIfNeeded(statements, node) { if (!shouldAddDefaultValueAssignments(node)) { @@ -56626,7 +59233,7 @@ var ts; statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 71 && !inConstructorWithSynthesizedSuper; + return node && node.dotDotDotToken && node.name.kind === 72 && !inConstructorWithSynthesizedSuper; } function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { var parameter = ts.lastOrUndefined(node.parameters); @@ -56653,7 +59260,7 @@ var ts; statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 && node.kind !== 195) { + if (node.transformFlags & 16384 && node.kind !== 197) { captureThisForNode(statements, node, ts.createThis()); } } @@ -56670,19 +59277,19 @@ var ts; if (hierarchyFacts & 16384) { var newTarget = void 0; switch (node.kind) { - case 195: + case 197: return statements; - case 154: case 156: - case 157: + case 158: + case 159: newTarget = ts.createVoidZero(); break; - case 155: + case 157: newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"); break; - case 237: - case 194: - newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4), 93, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"), ts.createVoidZero()); + case 239: + case 196: + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4), 94, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"), ts.createVoidZero()); break; default: return ts.Debug.failBadSyntaxKind(node); @@ -56701,20 +59308,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 215: + case 217: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 154: + case 156: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 156: - case 157: + case 158: + case 159: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 155: + case 157: break; default: ts.Debug.failBadSyntaxKind(node); @@ -56785,7 +59392,7 @@ var ts; return call; } function visitArrowFunction(node) { - if (node.transformFlags & 16384) { + if (node.transformFlags & 8192) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -56839,7 +59446,7 @@ var ts; : enterSubtree(16286, 65); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 && !name && (node.kind === 237 || node.kind === 194)) { + if (hierarchyFacts & 16384 && !name && (node.kind === 239 || node.kind === 196)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152, 0); @@ -56871,7 +59478,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 195); + ts.Debug.assert(node.kind === 197); statementsLocation = ts.moveRangeEnd(body, -1); var equalsGreaterThanToken = node.equalsGreaterThanToken; if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { @@ -56902,7 +59509,7 @@ var ts; ts.setEmitFlags(block, 1); } if (closeBraceLocation) { - ts.setTokenSourceMapRange(block, 18, closeBraceLocation); + ts.setTokenSourceMapRange(block, 19, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -56924,9 +59531,9 @@ var ts; } function visitExpressionStatement(node) { switch (node.expression.kind) { - case 193: + case 195: return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, false)); - case 202: + case 204: return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, false)); } return ts.visitEachChild(node, visitor, context); @@ -56934,9 +59541,9 @@ var ts; function visitParenthesizedExpression(node, needsDestructuringValue) { if (!needsDestructuringValue) { switch (node.expression.kind) { - case 193: + case 195: return ts.updateParen(node, visitParenthesizedExpression(node.expression, false)); - case 202: + case 204: return ts.updateParen(node, visitBinaryExpression(node.expression, false)); } } @@ -56962,7 +59569,7 @@ var ts; assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0); } else { - assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + assignment = ts.createBinary(decl.name, 59, ts.visitNode(decl.initializer, visitor, ts.isExpression)); ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); @@ -56993,21 +59600,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 + if (node.transformFlags & 2097152 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } function shouldEmitExplicitInitializerForLetDeclaration(node) { var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072; - var isDeclaredInLoop = flags & 262144; + var isCapturedInFunction = flags & 262144; + var isDeclaredInLoop = flags & 524288; var emittedAsTopLevel = (hierarchyFacts & 64) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -57061,14 +59674,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 221: - case 222: - return visitDoOrWhileStatement(node, outermostLabeledStatement); case 223: - return visitForStatement(node, outermostLabeledStatement); case 224: - return visitForInStatement(node, outermostLabeledStatement); + return visitDoOrWhileStatement(node, outermostLabeledStatement); case 225: + return visitForStatement(node, outermostLabeledStatement); + case 226: + return visitForInStatement(node, outermostLabeledStatement); + case 227: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -57188,11 +59801,11 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 && hierarchyFacts & 4) + if ((property.transformFlags & 4194304 && hierarchyFacts & 4) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 147) { + if (property.name.kind === 149) { numInitialProperties = i; break; } @@ -57214,7 +59827,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536) !== 0; } function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { @@ -57223,7 +59852,7 @@ var ts; } visit(node.name); function visit(node) { - if (node.kind === 71) { + if (node.kind === 72) { state.hoistedLocalVariables.push(node); } else { @@ -57237,7 +59866,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; @@ -57251,14 +59880,75 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226: return convertForInStatement(node, convertedLoopBody); + case 227: return convertForOfStatement(node, convertedLoopBody); + case 223: return convertDoStatement(node, convertedLoopBody); + case 224: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 223: - case 224: case 225: + case 226: + case 227: var initializer = node.initializer; - if (initializer && initializer.kind === 236) { + if (initializer && initializer.kind === 238) { loopInitializer = initializer; } break; @@ -57266,164 +59956,189 @@ var ts; var loopParameters = []; var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { - if (outerConvertedLoopState.argumentsName) { - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { + if (convertedLoopState.argumentsName) { + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { - convertedLoopState.thisName = outerConvertedLoopState.thisName; + if (convertedLoopState.thisName) { + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + if (convertedLoopState.hoistedLocalVariables) { + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], true); - } - var containsYield = (node.statement.transformFlags & 16777216) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144; - } - var convertedLoopVariable = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) - ]), 2097152)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; - if (currentState.argumentsName) { - if (outerConvertedLoopState) { - outerConvertedLoopState.argumentsName = currentState.argumentsName; + if (state.argumentsName) { + if (outerState) { + outerState.argumentsName = state.argumentsName; } else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, undefined, ts.createIdentifier("arguments"))); + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { - if (outerConvertedLoopState) { - outerConvertedLoopState.thisName = currentState.thisName; + if (state.thisName) { + if (outerState) { + outerState.thisName = state.thisName; } else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, undefined, ts.createIdentifier("this"))); + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { - if (outerConvertedLoopState) { - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + if (state.hoistedLocalVariables) { + if (outerState) { + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, undefined, ts.createFalse())); + } if (extraVariableDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, undefined, p.outParamName); + } + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8; + if (containsYield && hierarchyFacts & 4) + emitFlags |= 262144; + var statements = []; + statements.push(ts.createVariableStatement(undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2, 1, statements); + var functionDeclaration = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(40) : undefined, undefined, undefined, undefined, undefined, ts.visitNode(ts.createBlock(statements, true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - clone_3.statement = undefined; - clone_3 = ts.visitEachChild(clone_3, visitor, context); - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, true); - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1, 1, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8; + if (containsYield && (hierarchyFacts & 4) !== 0) + emitFlags |= 262144; + var functionDeclaration = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(40) : undefined, undefined, undefined, currentState.loopParameters, undefined, loopBody), emitFlags)) + ]), 2097152)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 58, source); + return ts.createBinary(target, 59, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40), ts.setEmitFlags(call, 8388608)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; var isSimpleLoop = !(state.nonLocalJumps & ~4) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 8388608)) + var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40), ts.setEmitFlags(call, 8388608)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0, statements); + copyOutParameters(state.loopOutParameters, 1, 0, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0, statements); + copyOutParameters(state.loopOutParameters, 1, 0, statements); if (state.nonLocalJumps & 8) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8; + if (outerState) { + outerState.nonLocalJumps |= 8; returnStatement = ts.createReturn(loopResultName); } else { returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 34, ts.createLiteral("object")), returnStatement)); + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35, ts.createLiteral("object")), returnStatement)); } if (state.nonLocalJumps & 2) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 34, ts.createLiteral("break")), ts.createBreak())); + statements.push(ts.createIf(ts.createBinary(loopResultName, 35, ts.createLiteral("break")), ts.createBreak())); } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -57460,21 +60175,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304) { + flags |= 1; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -57484,20 +60207,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 156: - case 157: + case 158: + case 159: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 154: + case 156: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 273: + case 275: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 274: + case 276: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -57569,10 +60292,10 @@ var ts; var ancestorFacts = enterSubtree(16286, 65); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 | 128) + var body = node.transformFlags & (16384 | 128) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); - if (node.kind === 156) { + if (node.kind === 158) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -57650,21 +60373,21 @@ var ts; return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { - if (node.transformFlags & 524288 || - node.expression.kind === 97 || + if (node.transformFlags & 131072 || + node.expression.kind === 98 || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97) { + if (node.expression.kind === 98) { ts.setEmitFlags(thisArg, 4); } var resultingCall = void 0; - if (node.transformFlags & 524288) { + if (node.transformFlags & 131072) { resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); } - if (node.expression.kind === 97) { + if (node.expression.kind === 98) { var actualThis = ts.createThis(); ts.setEmitFlags(actualThis, 4); var initializer = ts.createLogicalOr(resultingCall, actualThis); @@ -57677,7 +60400,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitNewExpression(node) { - if (node.transformFlags & 524288) { + if (node.transformFlags & 131072) { var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); } @@ -57703,7 +60426,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 185 + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -57775,7 +60498,7 @@ var ts; } function getRawLiteral(node) { var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - var isLast = node.kind === 13 || node.kind === 16; + var isLast = node.kind === 14 || node.kind === 17; text = text.substring(1, text.length - (isLast ? 1 : 2)); text = text.replace(/\r\n?/g, "\n"); return ts.setTextRange(ts.createLiteral(text), node); @@ -57817,7 +60540,7 @@ var ts; : ts.createFileLevelUniqueName("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 && node.name.escapedText === "target") { + if (node.keywordToken === 95 && node.name.escapedText === "target") { if (hierarchyFacts & 8192) { hierarchyFacts |= 32768; } @@ -57842,20 +60565,20 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; - context.enableSubstitution(71); + context.enableSubstitution(72); } } function enableSubstitutionsForCapturedThis() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(99); - context.enableEmitNotification(155); - context.enableEmitNotification(154); - context.enableEmitNotification(156); + context.enableSubstitution(100); context.enableEmitNotification(157); - context.enableEmitNotification(195); - context.enableEmitNotification(194); - context.enableEmitNotification(237); + context.enableEmitNotification(156); + context.enableEmitNotification(158); + context.enableEmitNotification(159); + context.enableEmitNotification(197); + context.enableEmitNotification(196); + context.enableEmitNotification(239); } } function onSubstituteNode(hint, node) { @@ -57879,10 +60602,10 @@ var ts; } function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 184: - case 238: - case 241: - case 235: + case 186: + case 240: + case 243: + case 237: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -57890,9 +60613,9 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 71: + case 72: return substituteExpressionIdentifier(node); - case 99: + case 100: return substituteThisKeyword(node); } return node; @@ -57943,19 +60666,19 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 219) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 189) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191) { return false; } var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 97) { + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98) { return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 206) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208) { return false; } var expression = callArgument.expression; @@ -57981,7 +60704,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -57999,24 +60722,24 @@ var ts; if (compilerOptions.jsx === 1 || compilerOptions.jsx === 3) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(260); + context.enableEmitNotification(262); + context.enableEmitNotification(263); context.enableEmitNotification(261); - context.enableEmitNotification(259); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(187); - context.enableSubstitution(273); + context.enableSubstitution(189); + context.enableSubstitution(275); return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { return node; } function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 260: + case 262: + case 263: case 261: - case 259: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -58052,7 +60775,7 @@ var ts; } function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token !== undefined && token >= 72 && token <= 107) { + if (token !== undefined && token >= 73 && token <= 108) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -58133,13 +60856,13 @@ var ts; } function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 221: + case 223: return visitDoStatement(node); - case 222: + case 224: return visitWhileStatement(node); - case 230: + case 232: return visitSwitchStatement(node); - case 231: + case 233: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -58147,30 +60870,30 @@ var ts; } function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 237: + case 239: return visitFunctionDeclaration(node); - case 194: + case 196: return visitFunctionExpression(node); - case 156: - case 157: + case 158: + case 159: return visitAccessorDeclaration(node); - case 217: + case 219: return visitVariableStatement(node); - case 223: + case 225: return visitForStatement(node); - case 224: - return visitForInStatement(node); - case 227: - return visitBreakStatement(node); case 226: - return visitContinueStatement(node); + return visitForInStatement(node); + case 229: + return visitBreakStatement(node); case 228: + return visitContinueStatement(node); + case 230: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216) { + if (node.transformFlags & 4194304) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 | 33554432)) { + else if (node.transformFlags & (512 | 8388608)) { return ts.visitEachChild(node, visitor, context); } else { @@ -58180,21 +60903,21 @@ var ts; } function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 202: + case 204: return visitBinaryExpression(node); - case 203: - return visitConditionalExpression(node); case 205: + return visitConditionalExpression(node); + case 207: return visitYieldExpression(node); - case 185: + case 187: return visitArrayLiteralExpression(node); - case 186: - return visitObjectLiteralExpression(node); case 188: - return visitElementAccessExpression(node); - case 189: - return visitCallExpression(node); + return visitObjectLiteralExpression(node); case 190: + return visitElementAccessExpression(node); + case 191: + return visitCallExpression(node); + case 192: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -58202,9 +60925,9 @@ var ts; } function visitGenerator(node) { switch (node.kind) { - case 237: + case 239: return visitFunctionDeclaration(node); - case 194: + case 196: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -58306,7 +61029,7 @@ var ts; return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); } function visitVariableStatement(node) { - if (node.transformFlags & 16777216) { + if (node.transformFlags & 4194304) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -58337,23 +61060,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 59 - && kind <= 70; + return kind >= 60 + && kind <= 71; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 59: return 37; case 60: return 38; case 61: return 39; case 62: return 40; case 63: return 41; case 64: return 42; - case 65: return 45; + case 65: return 43; case 66: return 46; case 67: return 47; case 68: return 48; case 69: return 49; case 70: return 50; + case 71: return 51; } } function visitRightAssociativeBinaryExpression(node) { @@ -58361,10 +61084,10 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 187: + case 189: target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 188: + case 190: target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); break; default: @@ -58386,13 +61109,13 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 26) { + else if (node.operatorToken.kind === 27) { return visitCommaExpression(node); } - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -58400,7 +61123,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), node.left); - if (node.operatorToken.kind === 53) { + if (node.operatorToken.kind === 54) { emitBreakWhenFalse(resultLabel, resultLocal, node.left); } else { @@ -58416,7 +61139,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27) { visit(node.left); visit(node.right); } @@ -58519,10 +61242,10 @@ var ts; } function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -58565,35 +61288,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 216: + case 218: return transformAndEmitBlock(node); - case 219: - return transformAndEmitExpressionStatement(node); - case 220: - return transformAndEmitIfStatement(node); case 221: - return transformAndEmitDoStatement(node); + return transformAndEmitExpressionStatement(node); case 222: - return transformAndEmitWhileStatement(node); + return transformAndEmitIfStatement(node); case 223: - return transformAndEmitForStatement(node); + return transformAndEmitDoStatement(node); case 224: - return transformAndEmitForInStatement(node); + return transformAndEmitWhileStatement(node); + case 225: + return transformAndEmitForStatement(node); case 226: - return transformAndEmitContinueStatement(node); - case 227: - return transformAndEmitBreakStatement(node); + return transformAndEmitForInStatement(node); case 228: - return transformAndEmitReturnStatement(node); + return transformAndEmitContinueStatement(node); case 229: - return transformAndEmitWithStatement(node); + return transformAndEmitBreakStatement(node); case 230: - return transformAndEmitSwitchStatement(node); + return transformAndEmitReturnStatement(node); case 231: - return transformAndEmitLabeledStatement(node); + return transformAndEmitWithStatement(node); case 232: - return transformAndEmitThrowStatement(node); + return transformAndEmitSwitchStatement(node); case 233: + return transformAndEmitLabeledStatement(node); + case 234: + return transformAndEmitThrowStatement(node); + case 235: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -58887,7 +61610,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 270 && defaultClauseIndex === -1) { + if (clause.kind === 272 && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -58897,7 +61620,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 269) { + if (clause.kind === 271) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -58987,7 +61710,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216) !== 0; + return !!node && (node.transformFlags & 4194304) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -59019,10 +61742,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -59132,7 +61855,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = []; - context.enableSubstitution(71); + context.enableSubstitution(72); } renamedCatchVariables.set(text, true); renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -59712,12 +62435,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71); + context.enableSubstitution(72); + context.enableSubstitution(204); context.enableSubstitution(202); - context.enableSubstitution(200); - context.enableSubstitution(201); - context.enableSubstitution(274); - context.enableEmitNotification(277); + context.enableSubstitution(203); + context.enableSubstitution(276); + context.enableEmitNotification(279); var moduleInfoMap = []; var deferredExports = []; var currentSourceFile; @@ -59726,7 +62449,10 @@ var ts; var needUMDDynamicImportHelper; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -59767,17 +62493,20 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; var _a = collectAsynchronousDependencies(node, true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createExpressionStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), - ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ - ts.createParameter(undefined, undefined, undefined, "require"), - ts.createParameter(undefined, undefined, undefined, "exports") - ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "require"), + ts.createParameter(undefined, undefined, undefined, "exports") + ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ]))) ]), node.statements)); ts.addEmitHelpers(updated, context.readEmitHelpers()); @@ -59902,30 +62631,30 @@ var ts; } function sourceElementVisitor(node) { switch (node.kind) { - case 247: + case 249: return visitImportDeclaration(node); - case 246: + case 248: return visitImportEqualsDeclaration(node); - case 253: + case 255: return visitExportDeclaration(node); - case 252: + case 254: return visitExportAssignment(node); - case 217: + case 219: return visitVariableStatement(node); - case 237: + case 239: return visitFunctionDeclaration(node); - case 238: + case 240: return visitClassDeclaration(node); - case 308: + case 310: return visitMergeDeclarationMarker(node); - case 309: + case 311: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } function moduleExpressionElementVisitor(node) { - if (!(node.transformFlags & 67108864) && !(node.transformFlags & 2048)) { + if (!(node.transformFlags & 16777216) && !(node.transformFlags & 2048)) { return node; } if (ts.isImportCall(node)) { @@ -59943,24 +62672,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 273: + case 275: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 274: + case 276: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 275: + case 277: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 154: case 156: - case 157: + case 158: + case 159: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -59992,7 +62721,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384); + var containsLexicalThis = !!(node.transformFlags & 8192); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -60275,7 +63004,7 @@ var ts; } } function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -60307,10 +63036,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249: + case 251: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250: + case 252: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -60411,14 +63140,14 @@ var ts; } function modifierVisitor(node) { switch (node.kind) { - case 84: - case 79: + case 85: + case 80: return undefined; } return node; } function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277) { + if (node.kind === 279) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -60458,12 +63187,12 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 71: + case 72: return substituteExpressionIdentifier(node); - case 202: + case 204: return substituteBinaryExpression(node); - case 201: - case 200: + case 203: + case 202: return substituteUnaryExpression(node); } return node; @@ -60478,7 +63207,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 277) { + if (exportContainer && exportContainer.kind === 279) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); @@ -60514,15 +63243,15 @@ var ts; return node; } function substituteUnaryExpression(node) { - if ((node.operator === 43 || node.operator === 44) + if ((node.operator === 44 || node.operator === 45) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 - ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 ? 59 : 60), ts.createLiteral(1)), node) + var expression = node.kind === 203 + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 ? 60 : 61), ts.createLiteral(1)), node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { var exportName = exportedNames_3[_i]; @@ -60584,12 +63313,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71); - context.enableSubstitution(274); + context.enableSubstitution(72); + context.enableSubstitution(276); + context.enableSubstitution(204); context.enableSubstitution(202); - context.enableSubstitution(200); - context.enableSubstitution(201); - context.enableEmitNotification(277); + context.enableSubstitution(203); + context.enableEmitNotification(279); var moduleInfoMap = []; var deferredExports = []; var exportFunctionsMap = []; @@ -60603,7 +63332,7 @@ var ts; var noSubstitution; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216)) { return node; } var id = ts.getOriginalNodeId(node); @@ -60693,7 +63422,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 253 && externalImport.exportClause) { + if (externalImport.kind === 255 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -60716,7 +63445,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 253) { + if (externalImport.kind !== 255) { continue; } if (!externalImport.exportClause) { @@ -60767,15 +63496,15 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { - case 247: + case 249: if (!entry.importClause) { break; } - case 246: + case 248: ts.Debug.assert(importVariableName !== undefined); statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 253: + case 255: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { var properties = []; @@ -60797,13 +63526,13 @@ var ts; } function sourceElementVisitor(node) { switch (node.kind) { - case 247: + case 249: return visitImportDeclaration(node); - case 246: + case 248: return visitImportEqualsDeclaration(node); - case 253: + case 255: return undefined; - case 252: + case 254: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -60924,7 +63653,7 @@ var ts; } function shouldHoistVariableDeclarationList(node) { return (ts.getEmitFlags(node) & 2097152) === 0 - && (enclosingBlockScopedContainer.kind === 277 + && (enclosingBlockScopedContainer.kind === 279 || (ts.getOriginalNode(node).flags & 3) === 0); } function transformInitializedVariable(node, isExportedDeclaration) { @@ -60946,7 +63675,7 @@ var ts; : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)); } function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -60985,10 +63714,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249: + case 251: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250: + case 252: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -61088,43 +63817,43 @@ var ts; } function nestedElementVisitor(node) { switch (node.kind) { - case 217: + case 219: return visitVariableStatement(node); - case 237: + case 239: return visitFunctionDeclaration(node); - case 238: + case 240: return visitClassDeclaration(node); - case 223: - return visitForStatement(node); - case 224: - return visitForInStatement(node); case 225: + return visitForStatement(node); + case 226: + return visitForInStatement(node); + case 227: return visitForOfStatement(node); - case 221: + case 223: return visitDoStatement(node); - case 222: + case 224: return visitWhileStatement(node); - case 231: - return visitLabeledStatement(node); - case 229: - return visitWithStatement(node); - case 230: - return visitSwitchStatement(node); - case 244: - return visitCaseBlock(node); - case 269: - return visitCaseClause(node); - case 270: - return visitDefaultClause(node); case 233: - return visitTryStatement(node); + return visitLabeledStatement(node); + case 231: + return visitWithStatement(node); + case 232: + return visitSwitchStatement(node); + case 246: + return visitCaseBlock(node); + case 271: + return visitCaseClause(node); case 272: + return visitDefaultClause(node); + case 235: + return visitTryStatement(node); + case 274: return visitCatchClause(node); - case 216: + case 218: return visitBlock(node); - case 308: + case 310: return visitMergeDeclarationMarker(node); - case 309: + case 311: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -61218,13 +63947,13 @@ var ts; } function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 - && node.kind === 202) { + && node.kind === 204) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048) || (node.transformFlags & 67108864)) { + else if ((node.transformFlags & 2048) || (node.transformFlags & 16777216)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -61261,7 +63990,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 277; + return container !== undefined && container.kind === 279; } else { return false; @@ -61269,14 +63998,14 @@ var ts; } function modifierVisitor(node) { switch (node.kind) { - case 84: - case 79: + case 85: + case 80: return undefined; } return node; } function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277) { + if (node.kind === 279) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -61310,7 +64039,7 @@ var ts; } function substituteUnspecified(node) { switch (node.kind) { - case 274: + case 276: return substituteShorthandPropertyAssignment(node); } return node; @@ -61332,12 +64061,12 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 71: + case 72: return substituteExpressionIdentifier(node); - case 202: + case 204: return substituteBinaryExpression(node); - case 200: - case 201: + case 202: + case 203: return substituteUnaryExpression(node); } return node; @@ -61382,22 +64111,22 @@ var ts; return node; } function substituteUnaryExpression(node) { - if ((node.operator === 43 || node.operator === 44) + if ((node.operator === 44 || node.operator === 45) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 + var expression = node.kind === 203 ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 201) { - expression = node.operator === 43 + if (node.kind === 203) { + expression = node.operator === 44 ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); } @@ -61413,7 +64142,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, false); - if (exportContainer && exportContainer.kind === 277) { + if (exportContainer && exportContainer.kind === 279) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -61441,8 +64170,8 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(277); - context.enableSubstitution(71); + context.enableEmitNotification(279); + context.enableSubstitution(72); var currentSourceFile; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { @@ -61468,9 +64197,9 @@ var ts; } function visitor(node) { switch (node.kind) { - case 246: + case 248: return undefined; - case 252: + case 254: return visitExportAssignment(node); } return node; @@ -61556,7 +64285,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238) { + else if (node.parent.kind === 240) { 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 : @@ -61585,7 +64314,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238) { + else if (node.parent.kind === 240) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -61632,15 +64361,15 @@ var ts; return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 235 || node.kind === 184) { + if (node.kind === 237 || node.kind === 186) { 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 === 152 || node.kind === 151 || - (node.kind === 149 && ts.hasModifier(node.parent, 8))) { + else if (node.kind === 154 || node.kind === 153 || + (node.kind === 151 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -61648,7 +64377,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 || node.kind === 149) { + else if (node.parent.kind === 240 || node.kind === 151) { 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 : @@ -61672,7 +64401,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 157) { + if (node.kind === 159) { if (ts.hasModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : @@ -61709,23 +64438,23 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 159: + case 161: 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 158: + case 160: 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 160: + case 162: 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 154: - case 153: + case 156: + case 155: if (ts.hasModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -61733,7 +64462,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 238) { + else if (node.parent.kind === 240) { 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 : @@ -61746,7 +64475,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 237: + case 239: 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 : @@ -61771,27 +64500,27 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 155: + case 157: 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 159: - case 164: + case 161: + case 166: 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 158: + case 160: 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 160: + case 162: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 154: - case 153: + case 156: + case 155: if (ts.hasModifier(node.parent, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -61799,7 +64528,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 238) { + else if (node.parent.parent.kind === 240) { 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 : @@ -61811,8 +64540,8 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 237: - case 163: + case 239: + case 165: 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 : @@ -61825,34 +64554,34 @@ var ts; function getTypeParameterConstraintVisibilityError() { var diagnosticMessage; switch (node.parent.kind) { - case 238: + case 240: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 239: + case 241: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 159: + case 161: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 158: + case 160: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 154: - case 153: + case 156: + case 155: if (ts.hasModifier(node.parent, 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 === 238) { + else if (node.parent.parent.kind === 240) { 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 237: + case 239: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 240: + case 242: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -61866,8 +64595,8 @@ var ts; } function getHeritageClauseVisibilityError() { var diagnosticMessage; - if (node.parent.parent.kind === 238) { - diagnosticMessage = node.parent.token === 108 ? + if (node.parent.parent.kind === 240) { + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 ? 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; } @@ -61900,11 +64629,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -61924,7 +64653,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -61935,6 +64664,7 @@ var ts; reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode @@ -61942,6 +64672,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -61951,10 +64682,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -62017,16 +64748,22 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } function transformRoot(node) { - if (node.kind === 277 && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 279 && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } - if (node.kind === 278) { + if (node.kind === 280) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -62038,23 +64775,25 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], true, [], [], false, []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], true, [], [], false, []); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), true, [], [], false, []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280) { + if (prepend.kind === 282) { return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -62072,8 +64811,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -62084,11 +64824,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([]), undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { if (emittedImports) { @@ -62117,20 +64860,23 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; var paths = ts.getOutputPathsFor(file, host, true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -62140,12 +64886,21 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { - if (name.kind === 71) { + if (name.kind === 72) { return name; } else { - if (name.kind === 183) { + if (name.kind === 185) { return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -62153,7 +64908,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 208) { + if (elem.kind === 210) { return elem; } return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -62165,7 +64920,7 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } - var newParam = ts.updateParameter(p, undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55)) : undefined, ensureType(p, p.type, true), ensureNoInitializer(p)); + var newParam = ts.updateParameter(p, undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56)) : undefined, ensureType(p, p.type, true), ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } @@ -62176,7 +64931,7 @@ var ts; } function ensureNoInitializer(node) { if (shouldPrintWithInitializer(node)) { - return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); } return undefined; } @@ -62187,17 +64942,17 @@ var ts; if (shouldPrintWithInitializer(node)) { return; } - var shouldUseResolverType = node.kind === 149 && + var shouldUseResolverType = node.kind === 151 && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { return ts.visitNode(type, visitDeclarationSubtree); } if (!ts.getParseTreeNode(node)) { - return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119); + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120); } - if (node.kind === 157) { - return ts.createKeywordTypeNode(119); + if (node.kind === 159) { + return ts.createKeywordTypeNode(120); } errorNameNode = node.name; var oldDiag; @@ -62205,12 +64960,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 235 || node.kind === 184) { + if (node.kind === 237 || node.kind === 186) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 149 - || node.kind === 152 - || node.kind === 151) { + if (node.kind === 151 + || node.kind === 154 + || node.kind === 153) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -62221,25 +64976,25 @@ var ts; if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } - return returnValue || ts.createKeywordTypeNode(119); + return returnValue || ts.createKeywordTypeNode(120); } } function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 237: - case 242: case 239: - case 238: - case 240: + case 244: case 241: + case 240: + case 242: + case 243: return !resolver.isDeclarationVisible(node); - case 235: + case 237: return !getBindingNameVisible(node); - case 246: - case 247: - case 253: - case 252: + case 248: + case 249: + case 255: + case 254: return false; } return false; @@ -62292,7 +65047,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 && parent.kind !== 181); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 && parent.kind !== 183); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -62312,7 +65067,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 257) { + if (decl.moduleReference.kind === 259) { var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return ts.updateImportEqualsDeclaration(decl, undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } @@ -62332,7 +65087,7 @@ var ts; if (!decl.importClause.namedBindings) { return visibleDefaultBinding && ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 249) { + if (decl.importClause.namedBindings.kind === 251) { var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : undefined; return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; } @@ -62412,61 +65167,61 @@ var ts; checkEntityNameVisibility(input.exprName, enclosingDeclaration); } var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 || input.kind === 179) && input.parent.kind !== 240); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 || input.kind === 181) && input.parent.kind !== 242); if (shouldEnterSuppressNewDiagnosticsContextContext) { suppressNewDiagnosticContexts = true; } if (isProcessedComponent(input)) { switch (input.kind) { - case 209: { + case 211: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); } - case 162: { + case 164: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); } - case 159: + case 161: return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 155: { + case 157: { var isPrivate = ts.hasModifier(input, 8); - var ctor = ts.createSignatureDeclaration(155, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0), undefined); + var ctor = ts.createSignatureDeclaration(157, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0), undefined); ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); return cleanup(ctor); } - case 154: { - var sig = ts.createSignatureDeclaration(153, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + case 156: { + var sig = ts.createSignatureDeclaration(155, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); sig.name = input.name; sig.modifiers = ts.createNodeArray(ensureModifiers(input)); sig.questionToken = input.questionToken; return cleanup(sig); } - case 156: { + case 158: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 157: { + case 159: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 152: + case 154: return cleanup(ts.updateProperty(input, undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 151: + case 153: return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 153: { + case 155: { return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); } - case 158: { + case 160: { return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 160: { - return cleanup(ts.updateIndexSignature(input, undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119))); + case 162: { + return cleanup(ts.updateIndexSignature(input, undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120))); } - case 235: { + case 237: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -62474,13 +65229,13 @@ var ts; suppressNewDiagnosticContexts = true; return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); } - case 148: { + case 150: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(ts.updateTypeParameterDeclaration(input, input.name, undefined, undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 173: { + case 175: { var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); var oldEnclosingDecl = enclosingDeclaration; @@ -62490,13 +65245,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 163: { + case 165: { return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 164: { + case 166: { return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 181: { + case 183: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -62525,7 +65280,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 154 && ts.hasModifier(node.parent, 8); + return node.parent.kind === 156 && ts.hasModifier(node.parent, 8); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -62534,19 +65289,19 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 253: { + case 255: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; } return ts.updateExportDeclaration(input, undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 252: { + case 254: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; } - if (input.expression.kind === 71) { + if (input.expression.kind === 72) { return input; } else { @@ -62556,7 +65311,7 @@ var ts; errorNode: input }); }; var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124)] : [], ts.createVariableDeclarationList([varDecl], 2)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125)] : [], ts.createVariableDeclarationList([varDecl], 2)); return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } @@ -62569,10 +65324,10 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 246: { + case 248: { return transformImportEqualsDeclaration(input); } - case 247: { + case 249: { return transformImportDeclaration(input); } } @@ -62592,18 +65347,33 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 240: + case 242: return cleanup(ts.updateTypeAliasDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 239: { + case 241: { return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 237: { - return cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + case 239: { + var clean = cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, undefined); + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16); + return [clean, namespaceDecl]; + } + else { + return clean; + } } - case 242: { + case 244: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 243) { + if (inner && inner.kind === 245) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; @@ -62621,7 +65391,7 @@ var ts; return cleanup(ts.updateModuleDeclaration(input, undefined, mods, input.name, body)); } } - case 238: { + case 240: { var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -62632,7 +65402,7 @@ var ts; if (!ts.hasModifier(param, 92)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); - if (param.name.kind === 71) { + if (param.name.kind === 72) { return preserveJsDoc(ts.createProperty(undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } else { @@ -62657,7 +65427,7 @@ var ts; } var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); - if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95) { + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96) { var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, @@ -62665,16 +65435,16 @@ var ts; typeName: input.name }); }; var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124)] : [], ts.createVariableDeclarationList([varDecl], 2)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125)] : [], ts.createVariableDeclarationList([varDecl], 2)); var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { - if (clause.token === 85) { + if (clause.token === 86) { var oldDiag_2 = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); getSymbolAccessibilityDiagnostic = oldDiag_2; return newClause; } - return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95; })), visitDeclarationSubtree)); + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96; })), visitDeclarationSubtree)); })); return [statement, cleanup(ts.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; } @@ -62683,10 +65453,10 @@ var ts; return cleanup(ts.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 217: { + case 219: { return cleanup(transformVariableStatement(input, isPrivate)); } - case 241: { + case 243: { return cleanup(ts.updateEnumDeclaration(input, undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -62703,7 +65473,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242) { + if (input.kind === 244) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -62724,7 +65494,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 208) { + if (e.kind === 210) { return; } if (e.name) { @@ -62787,7 +65557,7 @@ var ts; function ensureModifierFlags(node, privateDeclaration) { var mask = 3071 ^ (4 | 256); var additions = (needsDeclare && !isAlwaysType(node)) ? 2 : 0; - var parentIsFile = node.parent.kind === 277; + var parentIsFile = node.parent.kind === 279; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1) | 2); additions = 0; @@ -62807,7 +65577,7 @@ var ts; var prop = ts.createProperty(undefined, maskModifiers(node, undefined, (!accessors.setAccessor) ? 64 : 0), node.name, node.questionToken, ensureType(node, accessorType), undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -62821,20 +65591,20 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; } function transformHeritageClauses(nodes) { return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { - return ts.isEntityNameExpression(t.expression) || (clause.token === 85 && t.expression.kind === 95); + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 && t.expression.kind === 96); })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); } } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 239) { + if (node.kind === 241) { return true; } return false; @@ -62856,7 +65626,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 156 + return accessor.kind === 158 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type @@ -62865,51 +65635,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235: - case 152: + case 154: + case 153: + return !ts.hasModifier(node, 8); case 151: - case 149: + case 237: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 237: - case 242: - case 246: case 239: - case 238: - case 240: + case 244: + case 248: case 241: - case 217: - case 247: - case 253: - case 252: + case 240: + case 242: + case 243: + case 219: + case 249: + case 255: + case 254: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 159: - case 155: - case 154: - case 156: + case 161: case 157: - case 152: - case 151: - case 153: + case 156: case 158: + case 159: + case 154: + case 153: + case 155: case 160: - case 235: - case 148: - case 209: case 162: - case 173: - case 163: + case 237: + case 150: + case 211: case 164: - case 181: + case 175: + case 165: + case 166: + case 183: return true; } return false; @@ -62959,8 +65730,16 @@ var ts; return transformers; } ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(310); + var enabledSyntaxKindFeatures = new Array(312); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -62968,8 +65747,8 @@ var ts; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; - var onSubstituteNode = function (_, node) { return node; }; - var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; var state = 0; var diagnostics = []; var context = { @@ -63160,694 +65939,10 @@ var ts; ts.transformNodes = transformNodes; })(ts || (ts = {})); var ts; -(function (ts) { - var defaultLastEncodedSourceMapSpan = { - emittedLine: 0, - emittedColumn: 0, - sourceLine: 0, - sourceColumn: 0, - sourceIndex: 0 - }; - function createSourceMapWriter(host, writer, compilerOptions) { - if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } - var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSource; - var currentSourceText; - var sourceMapDir; - var sourceMapSourceIndex; - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan; - var lastEncodedNameIndex; - var sourceMapData; - var sourceMapDataList; - var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); - return { - initialize: initialize, - reset: reset, - setSourceFile: setSourceFile, - emitPos: emitPos, - emitNodeWithSourceMap: emitNodeWithSourceMap, - emitTokenWithSourceMap: emitTokenWithSourceMap, - getText: getText, - getSourceMappingURL: getSourceMappingURL, - }; - function skipSourceTrivia(pos) { - return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); - } - function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled || ts.fileExtensionIs(filePath, ".json")) { - return; - } - if (sourceMapData) { - reset(); - } - sourceMapDataList = outputSourceMapDataList; - currentSource = undefined; - currentSourceText = 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, - }; - 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 (sourceFileOrBundle.kind === 277) { - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle.fileName, 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() { - if (disabled) { - return; - } - if (sourceMapDataList) { - sourceMapDataList.push(sourceMapData); - } - currentSource = undefined; - sourceMapDir = undefined; - sourceMapSourceIndex = undefined; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = undefined; - lastEncodedNameIndex = undefined; - sourceMapData = undefined; - sourceMapDataList = undefined; - } - function captureSection() { - return { - version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent, - }; - } - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - ts.Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative"); - 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 = 0; - } - 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; - } - function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); - 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 - }; - } - else { - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } - } - function isPossiblySourceMap(x) { - return typeof x === "object" && !!x.mappings && typeof x.mappings === "string" && !!x.sources; - } - function emitNodeWithSourceMap(hint, node, emitCallback) { - var _a; - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(hint, node); - } - if (node) { - if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { - var text = node.sourceMapText; - var parsed = void 0; - try { - parsed = JSON.parse(text); - } - catch (_b) { - } - if (!parsed || !isPossiblySourceMap(parsed)) { - return emitCallback(hint, node); - } - var offsetLine = writer.getLine(); - var firstLineColumnOffset = writer.getColumn(); - var originalMap = parsed; - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var resolvedPathCache = ts.createMap(); - var absolutePathCache = ts.createMap(); - var sourcemapIterator = ts.sourcemaps.decodeMappings(originalMap); - for (var _c = sourcemapIterator.next(), raw = _c.value, done = _c.done; !done; _a = sourcemapIterator.next(), raw = _a.value, done = _a.done, _a) { - var pathCacheKey = "" + raw.sourceIndex; - if (!resolvedPathCache.has(pathCacheKey)) { - var rawPath = originalMap.sources[raw.sourceIndex]; - var relativePath = originalMap.sourceRoot ? ts.combinePaths(originalMap.sourceRoot, rawPath) : rawPath; - var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath); - var resolvedPath_1 = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, true); - resolvedPathCache.set(pathCacheKey, resolvedPath_1); - absolutePathCache.set(pathCacheKey, ts.getNormalizedAbsolutePath(resolvedPath_1, sourcesDirectoryPath)); - } - var resolvedPath = resolvedPathCache.get(pathCacheKey); - var absolutePath = absolutePathCache.get(pathCacheKey); - setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); - var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath); - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = __assign({}, raw, { emittedLine: raw.emittedLine + offsetLine, emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, sourceIndex: newIndex }); - } - return emitCallback(hint, node); - } - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0; - var range = emitNode && emitNode.sourceMapRange; - var _d = range || node, pos = _d.pos, end = _d.end; - var source = range && range.source; - var oldSource = currentSource; - if (source === oldSource) - source = undefined; - if (source) - setSourceFile(source); - if (node.kind !== 305 - && (emitFlags & 16) === 0 - && pos >= 0) { - emitPos(skipSourceTrivia(pos)); - } - if (source) - setSourceFile(oldSource); - if (emitFlags & 64) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - if (source) - setSourceFile(source); - if (node.kind !== 305 - && (emitFlags & 32) === 0 - && end >= 0) { - emitPos(end); - } - if (source) - setSourceFile(oldSource); - } - } - function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(token, writer, tokenPos); - } - var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0; - var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); - if ((emitFlags & 128) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - tokenPos = emitCallback(token, writer, tokenPos); - if (range) - tokenPos = range.end; - if ((emitFlags & 256) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - return tokenPos; - } - function isJsonSourceMapSource(sourceFile) { - return ts.fileExtensionIs(sourceFile.fileName, ".json"); - } - function setSourceFile(sourceFile) { - if (disabled) { - return; - } - currentSource = sourceFile; - currentSourceText = currentSource.text; - if (isJsonSourceMapSource(sourceFile)) { - return; - } - setupSourceEntry(sourceFile.fileName, sourceFile.text); - } - function setupSourceEntry(fileName, content, source) { - if (!source) { - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); - } - sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); - if (sourceMapSourceIndex === -1) { - sourceMapSourceIndex = sourceMapData.sourceMapSources.length; - sourceMapData.sourceMapSources.push(source); - sourceMapData.inputSourceFileNames.push(fileName); - if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(content); - } - } - } - function getText() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; - } - encodeLastRecordedSourceMapSpan(); - return JSON.stringify(captureSection()); - } - function getSourceMappingURL() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; - } - if (compilerOptions.inlineSourceMap) { - var base64SourceMapText = ts.base64encode(ts.sys, 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 createCommentWriter(printerOptions, emitPos) { - var extendedDiagnostics = printerOptions.extendedDiagnostics; - var newLine = ts.getNewLineCharacter(printerOptions); - var writer; - var containerPos = -1; - var containerEnd = -1; - var declarationListContainerEnd = -1; - var currentSourceFile; - var currentText; - var currentLineMap; - var detachedCommentsInfo; - var hasWrittenComment = false; - var disabled = !!printerOptions.removeComments; - return { - reset: reset, - setWriter: setWriter, - setSourceFile: setSourceFile, - emitNodeWithComments: emitNodeWithComments, - emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, - emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, - }; - function emitNodeWithComments(hint, node, emitCallback) { - if (disabled) { - emitCallback(hint, node); - return; - } - if (node) { - hasWrittenComment = false; - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0; - var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; - if ((pos < 0 && end < 0) || (pos === end)) { - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - } - else { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithComment"); - } - var isEmittedNode = node.kind !== 305; - var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 10; - var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 10; - if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); - } - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512) !== 0)) { - containerPos = pos; - } - if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024) !== 0)) { - containerEnd = end; - if (node.kind === 236) { - declarationListContainerEnd = end; - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithComment"); - } - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithComment"); - } - containerPos = savedContainerPos; - containerEnd = savedContainerEnd; - declarationListContainerEnd = savedDeclarationListContainerEnd; - if (!skipTrailingComments && isEmittedNode) { - emitTrailingComments(end); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithComment"); - } - } - } - } - function emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback) { - var leadingComments = emitNode && emitNode.leadingComments; - if (ts.some(leadingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithSynthesizedComments"); - } - ts.forEach(leadingComments, emitLeadingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithSynthesizedComments"); - } - } - emitNodeWithNestedComments(hint, node, emitFlags, emitCallback); - var trailingComments = emitNode && emitNode.trailingComments; - if (ts.some(trailingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithSynthesizedComments"); - } - ts.forEach(trailingComments, emitTrailingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithSynthesizedComments"); - } - } - } - function emitLeadingSynthesizedComment(comment) { - if (comment.kind === 2) { - writer.writeLine(); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine || comment.kind === 2) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function emitTrailingSynthesizedComment(comment) { - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - } - function writeSynthesizedComment(comment) { - var text = formatSynthesizedComment(comment); - var lineMap = comment.kind === 3 ? ts.computeLineStarts(text) : undefined; - ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); - } - function formatSynthesizedComment(comment) { - return comment.kind === 3 - ? "/*" + comment.text + "*/" - : "//" + comment.text; - } - function emitNodeWithNestedComments(hint, node, emitFlags, emitCallback) { - if (emitFlags & 2048) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - } - function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitBodyWithDetachedComments"); - } - var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = ts.getEmitFlags(node); - var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024) !== 0; - if (!skipLeadingComments) { - emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); - } - if (emitFlags & 2048 && !disabled) { - disabled = true; - emitCallback(node); - disabled = false; - } - else { - emitCallback(node); - } - if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); - } - if (!skipTrailingComments) { - emitLeadingComments(detachedRange.end, true); - if (hasWrittenComment && !writer.isAtStartOfLine()) { - writer.writeLine(); - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); - } - } - function emitLeadingComments(pos, isEmittedNode) { - hasWrittenComment = false; - if (isEmittedNode) { - forEachLeadingCommentToEmit(pos, emitLeadingComment); - } - else if (pos === 0) { - forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); - } - } - function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (isTripleSlashComment(commentPos, commentEnd)) { - emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); - } - } - function shouldWriteComment(text, pos) { - if (printerOptions.onlyPrintJsDocStyle) { - return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); - } - return true; - } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (!hasWrittenComment) { - ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); - hasWrittenComment = true; - } - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else if (kind === 3) { - writer.write(" "); - } - } - function emitLeadingCommentsOfPosition(pos) { - if (disabled || pos === -1) { - return; - } - emitLeadingComments(pos, true); - } - function emitTrailingComments(pos) { - forEachTrailingCommentToEmit(pos, emitTrailingComment); - } - function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - } - function emitTrailingCommentsOfPosition(pos, prefixSpace) { - if (disabled) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); - } - forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); - } - } - function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function forEachLeadingCommentToEmit(pos, cb) { - if (containerPos === -1 || pos !== containerPos) { - if (hasDetachedComments(pos)) { - forEachLeadingCommentWithoutDetachedComments(cb); - } - else { - ts.forEachLeadingCommentRange(currentText, pos, cb, pos); - } - } - } - function forEachTrailingCommentToEmit(end, cb) { - if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { - ts.forEachTrailingCommentRange(currentText, end, cb); - } - } - function reset() { - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - detachedCommentsInfo = undefined; - } - function setWriter(output) { - writer = output; - } - function setSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = currentSourceFile.text; - currentLineMap = ts.getLineStarts(currentSourceFile); - detachedCommentsInfo = undefined; - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; - } - function forEachLeadingCommentWithoutDetachedComments(cb) { - var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - ts.forEachLeadingCommentRange(currentText, pos, cb, pos); - } - function emitDetachedCommentsAndUpdateCommentsInfo(range) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - } - function isTripleSlashComment(commentPos, commentEnd) { - return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); - } - } - ts.createCommentWriter = createCommentWriter; -})(ts || (ts = {})); -var ts; (function (ts) { var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); @@ -63874,20 +65969,24 @@ var ts; ts.forEachEmittedFile = forEachEmittedFile; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 278) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + if (sourceFile.kind === 280) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); - var isJs = ts.isSourceFileJavaScript(sourceFile); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -63906,7 +66005,7 @@ var ts; return ".json"; } if (options.jsx === 1) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { return ".jsx"; } @@ -63923,21 +66022,15 @@ var ts; var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var newLine = host.getNewLine(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); var writer = ts.createTextWriter(newLine); - var sourceMap = ts.createSourceMapWriter(host, writer); - var declarationSourceMap = ts.createSourceMapWriter(host, writer, { - sourceMap: compilerOptions.declarationMap, - sourceRoot: compilerOptions.sourceRoot, - mapRoot: compilerOptions.mapRoot, - extendedDiagnostics: compilerOptions.extendedDiagnostics, - }); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; var exportedModulesFromDeclarationEmit; - ts.performance.mark("beforePrint"); + enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); - ts.performance.measure("printTime", "beforePrint"); + exit(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -63951,47 +66044,59 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { + if (emitOnlyDtsFiles || !jsFilePath) { + return; + } + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { emitSkipped = true; return; } - if (emitOnlyDtsFiles) { - return; - } var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, false); - var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; + var printer = createPrinter(printerOptions, { hasGlobalName: resolver.hasGlobalName, onEmitNode: transform.emitNodeWithNotification, substituteNode: transform.substituteNode, - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - onSetSourceFile: setSourceFile, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { nonJsFiles.forEach(collectLinkedAliases); @@ -64003,12 +66108,19 @@ var ts; emitterDiagnostics.add(diagnostic); } } - var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true, noEmitHelpers: true }), { + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { hasGlobalName: resolver.hasGlobalName, - onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: declarationSourceMap.emitPos, - onSetSourceFile: setSourceFileForDeclarationSourceMaps, onEmitNode: declarationTransform.emitNodeWithNotification, substituteNode: declarationTransform.substituteNode, }); @@ -64016,8 +66128,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], undefined, declarationPrinter, declarationSourceMap); - if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -64026,7 +66143,7 @@ var ts; } function collectLinkedAliases(node) { if (ts.isExportAssignment(node)) { - if (node.expression.kind === 71) { + if (node.expression.kind === 72) { resolver.collectLinkedAliases(node.expression, true); } return; @@ -64037,49 +66154,104 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { - var bundle = sourceFileOrBundle.kind === 278 ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 277 ? sourceFileOrBundle : undefined; + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } if (bundle) { - printer.writeBundle(bundle, writer, bundleInfo); + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); } else { - printer.writeFile(sourceFile, writer); + printer.writeFile(sourceFile, writer, sourceMapGenerator); } - writer.writeLine(); - var sourceMappingURL = mapRecorder.getSourceMappingURL(); - if (sourceMappingURL) { - writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); + } + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, false, sourceFiles); + } } - if (sourceMapFilePath) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), false, sourceFiles); + else { + writer.writeLine(); } ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); if (bundleInfoPath) { bundleInfo.totalLength = writer.getTextPos(); ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), false); } - mapRecorder.reset(); writer.clear(); bundleInfo = createDefaultBundleInfo(); } - function setSourceFile(node) { - sourceMap.setSourceFile(node); + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json")); } - function setSourceFileForDeclarationSourceMaps(node) { - declarationSourceMap.setSourceFile(node); + function getSourceRoot(mapOptions) { + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapFile), host.getCurrentDirectory(), host.getCanonicalFileName, true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; } } ts.emitFiles = emitFiles; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); - var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); var currentSourceFile; var nodeIdToGeneratedName; var autoGeneratedIdToGeneratedName; @@ -64091,17 +66263,19 @@ var ts; var writer; var ownWriter; var write = writeBase; - var commitPendingSemicolon = ts.noop; - var writeSemicolon = writeSemicolonInternal; - var pendingSemicolon = false; - if (printerOptions.omitTrailingSemicolon) { - commitPendingSemicolon = commitPendingSemicolonInternal; - writeSemicolon = deferWriteSemicolon; - } - var syntheticParent = { pos: -1, end: -1 }; - var moduleKind = ts.getEmitModuleKind(printerOptions); - var bundledHelpers = ts.createMap(); var isOwnFileEmit; + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; reset(); return { printNode: printNode, @@ -64126,9 +66300,9 @@ var ts; break; } switch (node.kind) { - case 277: return printFile(node); - case 278: return printBundle(node); - case 279: return printUnparsedSource(node); + case 279: return printFile(node); + case 280: return printBundle(node); + case 281: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -64138,11 +66312,11 @@ var ts; return endPrint(); } function printBundle(bundle) { - writeBundle(bundle, beginPrint()); + writeBundle(bundle, undefined, beginPrint(), undefined); return endPrint(); } function printFile(sourceFile) { - writeFile(sourceFile, beginPrint()); + writeFile(sourceFile, beginPrint(), undefined); return endPrint(); } function printUnparsedSource(unparsed) { @@ -64151,14 +66325,14 @@ var ts; } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, undefined); print(hint, node, sourceFile); reset(); writer = previousWriter; } function writeList(format, nodes, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, undefined); if (sourceFile) { setSourceFile(sourceFile); } @@ -64166,18 +66340,18 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output, bundleInfo) { + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { isOwnFileEmit = false; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { var prepend = _b[_a]; - print(4, prepend, undefined); writeLine(); + print(4, prepend, undefined); } if (bundleInfo) { bundleInfo.originalOffset = writer.getTextPos(); @@ -64191,15 +66365,15 @@ var ts; } function writeUnparsedSource(unparsed, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, undefined); print(4, unparsed, undefined); reset(); writer = previousWriter; } - function writeFile(sourceFile, output) { + function writeFile(sourceFile, output, sourceMapGenerator) { isOwnFileEmit = true; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(sourceFile); emitPrologueDirectivesIfNeeded(sourceFile); print(0, sourceFile, sourceFile); @@ -64218,19 +66392,24 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - var pipelinePhase = getPipelinePhase(0, hint); + var pipelinePhase = getPipelinePhase(0, node); pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; - comments.setSourceFile(sourceFile); - if (onSetSourceFile) { - onSetSourceFile(sourceFile); + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); } } - function setWriter(output) { - writer = output; - comments.setWriter(output); + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; } function reset() { nodeIdToGeneratedName = []; @@ -64239,66 +66418,62 @@ var ts; tempFlagsStack = []; tempFlags = 0; reservedNamesStack = []; - comments.reset(); - setWriter(undefined); + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(undefined, undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } function emit(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0, 4); + var pipelinePhase = getPipelinePhase(0, node); pipelinePhase(4, node); } function emitIdentifierName(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0, 2); + var pipelinePhase = getPipelinePhase(0, node); pipelinePhase(2, node); } function emitExpression(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0, 1); + var pipelinePhase = getPipelinePhase(0, node); pipelinePhase(1, node); } - function getPipelinePhase(phase, hint) { + function getPipelinePhase(phase, node) { switch (phase) { case 0: - if (onEmitNode) { + if (onEmitNode !== ts.noEmitNotification) { return pipelineEmitWithNotification; } case 1: - if (emitNodeWithComments && hint !== 0) { + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + case 2: + if (!commentsDisabled && node.kind !== 279) { return pipelineEmitWithComments; } - return pipelineEmitWithoutComments; - case 2: - if (onEmitSourceMapOfNode && hint !== 0) { + case 3: + if (!sourceMapsDisabled && node.kind !== 279 && !ts.isInJsonFile(node)) { return pipelineEmitWithSourceMap; } - case 3: + case 4: return pipelineEmitWithHint; default: - return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + return ts.Debug.assertNever(phase); } } - function getNextPipelinePhase(currentPhase, hint) { - return getPipelinePhase(currentPhase + 1, hint); + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0, hint)); - } - function pipelineEmitWithComments(hint, node) { - ts.Debug.assertDefined(emitNodeWithComments); - ts.Debug.assert(hint !== 0); - emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1, hint)); - } - function pipelineEmitWithoutComments(hint, node) { - var pipelinePhase = getNextPipelinePhase(1, hint); - pipelinePhase(hint, trySubstituteNode(hint, node)); - } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(hint !== 0); - ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); + var pipelinePhase = getNextPipelinePhase(0, node); + onEmitNode(hint, node, pipelinePhase); } function pipelineEmitWithHint(hint, node) { if (hint === 0) @@ -64307,236 +66482,267 @@ var ts; return emitIdentifier(ts.cast(node, ts.isIdentifier)); if (hint === 3) return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(true); + } if (hint === 4) { if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); switch (node.kind) { - case 14: case 15: case 16: + case 17: return emitLiteral(node); - case 279: + case 281: return emitUnparsedSource(node); - case 71: + case 72: return emitIdentifier(node); - case 146: - return emitQualifiedName(node); - case 147: - return emitComputedPropertyName(node); case 148: - return emitTypeParameter(node); + return emitQualifiedName(node); case 149: - return emitParameter(node); + return emitComputedPropertyName(node); case 150: - return emitDecorator(node); + return emitTypeParameter(node); case 151: - return emitPropertySignature(node); + return emitParameter(node); case 152: - return emitPropertyDeclaration(node); + return emitDecorator(node); case 153: - return emitMethodSignature(node); + return emitPropertySignature(node); case 154: - return emitMethodDeclaration(node); + return emitPropertyDeclaration(node); case 155: - return emitConstructor(node); + return emitMethodSignature(node); case 156: + return emitMethodDeclaration(node); case 157: - return emitAccessorDeclaration(node); + return emitConstructor(node); case 158: - return emitCallSignature(node); case 159: - return emitConstructSignature(node); + return emitAccessorDeclaration(node); case 160: - return emitIndexSignature(node); + return emitCallSignature(node); case 161: - return emitTypePredicate(node); + return emitConstructSignature(node); case 162: - return emitTypeReference(node); + return emitIndexSignature(node); case 163: - return emitFunctionType(node); - case 287: - return emitJSDocFunctionType(node); + return emitTypePredicate(node); case 164: - return emitConstructorType(node); + return emitTypeReference(node); case 165: - return emitTypeQuery(node); + return emitFunctionType(node); + case 289: + return emitJSDocFunctionType(node); case 166: - return emitTypeLiteral(node); + return emitConstructorType(node); case 167: - return emitArrayType(node); + return emitTypeQuery(node); case 168: - return emitTupleType(node); + return emitTypeLiteral(node); case 169: - return emitOptionalType(node); - case 171: - return emitUnionType(node); - case 172: - return emitIntersectionType(node); - case 173: - return emitConditionalType(node); - case 174: - return emitInferType(node); - case 175: - return emitParenthesizedType(node); - case 209: - return emitExpressionWithTypeArguments(node); - case 176: - return emitThisType(); - case 177: - return emitTypeOperator(node); - case 178: - return emitIndexedAccessType(node); - case 179: - return emitMappedType(node); - case 180: - return emitLiteralType(node); - case 181: - return emitImportTypeNode(node); - case 282: - write("*"); - return; - case 283: - write("?"); - return; - case 284: - return emitJSDocNullableType(node); - case 285: - return emitJSDocNonNullableType(node); - case 286: - return emitJSDocOptionalType(node); + return emitArrayType(node); case 170: - case 288: - return emitRestOrJSDocVariadicType(node); + return emitTupleType(node); + case 171: + return emitOptionalType(node); + case 173: + return emitUnionType(node); + case 174: + return emitIntersectionType(node); + case 175: + return emitConditionalType(node); + case 176: + return emitInferType(node); + case 177: + return emitParenthesizedType(node); + case 211: + return emitExpressionWithTypeArguments(node); + case 178: + return emitThisType(); + case 179: + return emitTypeOperator(node); + case 180: + return emitIndexedAccessType(node); + case 181: + return emitMappedType(node); case 182: - return emitObjectBindingPattern(node); + return emitLiteralType(node); case 183: - return emitArrayBindingPattern(node); - case 184: - return emitBindingElement(node); - case 214: - return emitTemplateSpan(node); - case 215: - return emitSemicolonClassElement(); - case 216: - return emitBlock(node); - case 217: - return emitVariableStatement(node); - case 218: - return emitEmptyStatement(); - case 219: - return emitExpressionStatement(node); - case 220: - return emitIfStatement(node); - case 221: - return emitDoStatement(node); - case 222: - return emitWhileStatement(node); - case 223: - return emitForStatement(node); - case 224: - return emitForInStatement(node); - case 225: - return emitForOfStatement(node); - case 226: - return emitContinueStatement(node); - case 227: - return emitBreakStatement(node); - case 228: - return emitReturnStatement(node); - case 229: - return emitWithStatement(node); - case 230: - return emitSwitchStatement(node); - case 231: - return emitLabeledStatement(node); - case 232: - return emitThrowStatement(node); - case 233: - return emitTryStatement(node); - case 234: - return emitDebuggerStatement(node); - case 235: - return emitVariableDeclaration(node); - case 236: - return emitVariableDeclarationList(node); - case 237: - return emitFunctionDeclaration(node); - case 238: - return emitClassDeclaration(node); - case 239: - return emitInterfaceDeclaration(node); - case 240: - return emitTypeAliasDeclaration(node); - case 241: - return emitEnumDeclaration(node); - case 242: - return emitModuleDeclaration(node); - case 243: - return emitModuleBlock(node); - case 244: - return emitCaseBlock(node); - case 245: - return emitNamespaceExportDeclaration(node); - case 246: - return emitImportEqualsDeclaration(node); - case 247: - return emitImportDeclaration(node); - case 248: - return emitImportClause(node); - case 249: - return emitNamespaceImport(node); - case 250: - return emitNamedImports(node); - case 251: - return emitImportSpecifier(node); - case 252: - return emitExportAssignment(node); - case 253: - return emitExportDeclaration(node); - case 254: - return emitNamedExports(node); - case 255: - return emitExportSpecifier(node); - case 256: + return emitImportTypeNode(node); + case 284: + writePunctuation("*"); return; + case 285: + writePunctuation("?"); + return; + case 286: + return emitJSDocNullableType(node); + case 287: + return emitJSDocNonNullableType(node); + case 288: + return emitJSDocOptionalType(node); + case 172: + case 290: + return emitRestOrJSDocVariadicType(node); + case 184: + return emitObjectBindingPattern(node); + case 185: + return emitArrayBindingPattern(node); + case 186: + return emitBindingElement(node); + case 216: + return emitTemplateSpan(node); + case 217: + return emitSemicolonClassElement(); + case 218: + return emitBlock(node); + case 219: + return emitVariableStatement(node); + case 220: + return emitEmptyStatement(false); + case 221: + return emitExpressionStatement(node); + case 222: + return emitIfStatement(node); + case 223: + return emitDoStatement(node); + case 224: + return emitWhileStatement(node); + case 225: + return emitForStatement(node); + case 226: + return emitForInStatement(node); + case 227: + return emitForOfStatement(node); + case 228: + return emitContinueStatement(node); + case 229: + return emitBreakStatement(node); + case 230: + return emitReturnStatement(node); + case 231: + return emitWithStatement(node); + case 232: + return emitSwitchStatement(node); + case 233: + return emitLabeledStatement(node); + case 234: + return emitThrowStatement(node); + case 235: + return emitTryStatement(node); + case 236: + return emitDebuggerStatement(node); + case 237: + return emitVariableDeclaration(node); + case 238: + return emitVariableDeclarationList(node); + case 239: + return emitFunctionDeclaration(node); + case 240: + return emitClassDeclaration(node); + case 241: + return emitInterfaceDeclaration(node); + case 242: + return emitTypeAliasDeclaration(node); + case 243: + return emitEnumDeclaration(node); + case 244: + return emitModuleDeclaration(node); + case 245: + return emitModuleBlock(node); + case 246: + return emitCaseBlock(node); + case 247: + return emitNamespaceExportDeclaration(node); + case 248: + return emitImportEqualsDeclaration(node); + case 249: + return emitImportDeclaration(node); + case 250: + return emitImportClause(node); + case 251: + return emitNamespaceImport(node); + case 252: + return emitNamedImports(node); + case 253: + return emitImportSpecifier(node); + case 254: + return emitExportAssignment(node); + case 255: + return emitExportDeclaration(node); + case 256: + return emitNamedExports(node); case 257: + return emitExportSpecifier(node); + case 258: + return; + case 259: return emitExternalModuleReference(node); - case 10: + case 11: return emitJsxText(node); - case 260: - case 263: - return emitJsxOpeningElementOrFragment(node); - case 261: - case 264: - return emitJsxClosingElementOrFragment(node); + case 262: case 265: - return emitJsxAttribute(node); + return emitJsxOpeningElementOrFragment(node); + case 263: case 266: - return emitJsxAttributes(node); + return emitJsxClosingElementOrFragment(node); case 267: - return emitJsxSpreadAttribute(node); + return emitJsxAttribute(node); case 268: - return emitJsxExpression(node); + return emitJsxAttributes(node); case 269: - return emitCaseClause(node); + return emitJsxSpreadAttribute(node); case 270: - return emitDefaultClause(node); + return emitJsxExpression(node); case 271: - return emitHeritageClause(node); + return emitCaseClause(node); case 272: - return emitCatchClause(node); + return emitDefaultClause(node); case 273: - return emitPropertyAssignment(node); + return emitHeritageClause(node); case 274: - return emitShorthandPropertyAssignment(node); + return emitCatchClause(node); case 275: - return emitSpreadAssignment(node); + return emitPropertyAssignment(node); case 276: + return emitShorthandPropertyAssignment(node); + case 277: + return emitSpreadAssignment(node); + case 278: return emitEnumMember(node); + case 299: + case 305: + return emitJSDocPropertyLikeTag(node); + case 300: + case 302: + case 301: + case 298: + return emitJSDocSimpleTypedTag(node); + case 295: + return emitJSDocAugmentsTag(node); + case 303: + return emitJSDocTemplateTag(node); + case 304: + return emitJSDocTypedefTag(node); + case 297: + return emitJSDocCallbackTag(node); + case 293: + return emitJSDocSignature(node); + case 292: + return emitJSDocTypeLiteral(node); + case 296: + case 294: + return emitJSDocSimpleTag(node); + case 291: + return emitJSDoc(node); } if (ts.isExpression(node)) { hint = 1; - node = trySubstituteNode(1, node); + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } } else if (ts.isToken(node)) { return writeTokenNode(node, writePunctuation); @@ -64545,84 +66751,85 @@ var ts; if (hint === 1) { switch (node.kind) { case 8: - return emitNumericLiteral(node); case 9: - case 12: + return emitNumericOrBigIntLiteral(node); + case 10: case 13: + case 14: return emitLiteral(node); - case 71: + case 72: return emitIdentifier(node); - case 86: - case 95: - case 97: - case 101: - case 99: - case 91: + case 87: + case 96: + case 98: + case 102: + case 100: + case 92: writeTokenNode(node, writeKeyword); return; - case 185: - return emitArrayLiteralExpression(node); - case 186: - return emitObjectLiteralExpression(node); case 187: - return emitPropertyAccessExpression(node); + return emitArrayLiteralExpression(node); case 188: - return emitElementAccessExpression(node); + return emitObjectLiteralExpression(node); case 189: - return emitCallExpression(node); + return emitPropertyAccessExpression(node); case 190: - return emitNewExpression(node); + return emitElementAccessExpression(node); case 191: - return emitTaggedTemplateExpression(node); + return emitCallExpression(node); case 192: - return emitTypeAssertionExpression(node); + return emitNewExpression(node); case 193: - return emitParenthesizedExpression(node); + return emitTaggedTemplateExpression(node); case 194: - return emitFunctionExpression(node); + return emitTypeAssertionExpression(node); case 195: - return emitArrowFunction(node); + return emitParenthesizedExpression(node); case 196: - return emitDeleteExpression(node); + return emitFunctionExpression(node); case 197: - return emitTypeOfExpression(node); + return emitArrowFunction(node); case 198: - return emitVoidExpression(node); + return emitDeleteExpression(node); case 199: - return emitAwaitExpression(node); + return emitTypeOfExpression(node); case 200: - return emitPrefixUnaryExpression(node); + return emitVoidExpression(node); case 201: - return emitPostfixUnaryExpression(node); + return emitAwaitExpression(node); case 202: - return emitBinaryExpression(node); + return emitPrefixUnaryExpression(node); case 203: - return emitConditionalExpression(node); + return emitPostfixUnaryExpression(node); case 204: - return emitTemplateExpression(node); + return emitBinaryExpression(node); case 205: - return emitYieldExpression(node); + return emitConditionalExpression(node); case 206: - return emitSpreadExpression(node); + return emitTemplateExpression(node); case 207: - return emitClassExpression(node); + return emitYieldExpression(node); case 208: - return; + return emitSpreadExpression(node); + case 209: + return emitClassExpression(node); case 210: - return emitAsExpression(node); - case 211: - return emitNonNullExpression(node); + return; case 212: + return emitAsExpression(node); + case 213: + return emitNonNullExpression(node); + case 214: return emitMetaProperty(node); - case 258: + case 260: return emitJsxElement(node); - case 259: + case 261: return emitJsxSelfClosingElement(node); - case 262: + case 264: return emitJsxFragment(node); - case 306: + case 308: return emitPartiallyEmittedExpression(node); - case 307: + case 309: return emitCommaList(node); } } @@ -64634,12 +66841,13 @@ var ts; writeSpace(); emit(node.constraint); } - function trySubstituteNode(hint, node) { - return node && substituteNode && substituteNode(hint, node) || node; + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1, node); + pipelinePhase(hint, substituteNode(hint, node)); } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 278 ? node : undefined; + var bundle = node.kind === 280 ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -64670,7 +66878,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -64678,13 +66886,13 @@ var ts; } return helpersEmitted; } - function emitNumericLiteral(node) { + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) - && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { + && (node.kind === 10 || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); } else { @@ -64697,7 +66905,7 @@ var ts; function emitIdentifier(node) { var writeText = node.symbol ? writeSymbol : write; writeText(getTextOfNode(node, false), node.symbol); - emitList(node, node.typeArguments, 26896); + emitList(node, node.typeArguments, 53776); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -64705,7 +66913,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71) { + if (node.kind === 72) { emitExpression(node); } else { @@ -64738,7 +66946,7 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 287 && !node.name) { + if (node.parent && node.parent.kind === 289 && !node.name) { emit(node.type); } else { @@ -64756,7 +66964,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -64766,7 +66974,7 @@ var ts; emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); - writeSemicolon(); + writeTrailingSemicolon(); } function emitMethodSignature(node) { pushNameGenerationScope(node); @@ -64777,7 +66985,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -64796,7 +67004,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 156 ? "get" : "set"); + writeKeyword(node.kind === 158 ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -64808,7 +67016,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -64820,7 +67028,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -64828,10 +67036,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } function emitTypePredicate(node) { emit(node.parameterName); @@ -64855,22 +67063,22 @@ var ts; popNameGenerationScope(node); } function emitJSDocFunctionType(node) { - write("function"); + writeKeyword("function"); emitParameters(node, node.parameters); - write(":"); + writePunctuation(":"); emit(node.type); } function emitJSDocNullableType(node) { - write("?"); + writePunctuation("?"); emit(node.type); } function emitJSDocNonNullableType(node) { - write("!"); + writePunctuation("!"); emit(node.type); } function emitJSDocOptionalType(node) { emit(node.type); - write("="); + writePunctuation("="); } function emitConstructorType(node) { pushNameGenerationScope(node); @@ -64891,8 +67099,8 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 ? 384 : 16449; - emitList(node, node.members, flags | 262144); + var flags = ts.getEmitFlags(node) & 1 ? 768 : 32897; + emitList(node, node.members, flags | 524288); writePunctuation("}"); } function emitArrayType(node) { @@ -64901,23 +67109,23 @@ var ts; writePunctuation("]"); } function emitRestOrJSDocVariadicType(node) { - write("..."); + writePunctuation("..."); emit(node.type); } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 272); + emitList(node, node.elementTypes, 528); writePunctuation("]"); } function emitOptionalType(node) { emit(node.type); - write("?"); + writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 260); + emitList(node, node.types, 516); } function emitIntersectionType(node) { - emitList(node, node.types, 264); + emitList(node, node.types, 520); } function emitConditionalType(node) { emit(node.checkType); @@ -64970,25 +67178,25 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - if (node.readonlyToken.kind !== 132) { + if (node.readonlyToken.kind !== 133) { writeKeyword("readonly"); } writeSpace(); } writePunctuation("["); - var pipelinePhase = getPipelinePhase(0, 3); + var pipelinePhase = getPipelinePhase(0, node.typeParameter); pipelinePhase(3, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); - if (node.questionToken.kind !== 55) { + if (node.questionToken.kind !== 56) { writePunctuation("?"); } } writePunctuation(":"); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); if (emitFlags & 1) { writeSpace(); } @@ -65018,12 +67226,12 @@ var ts; } function emitObjectBindingPattern(node) { writePunctuation("{"); - emitList(node, node.elements, 262576); + emitList(node, node.elements, 525136); writePunctuation("}"); } function emitArrayBindingPattern(node) { writePunctuation("["); - emitList(node, node.elements, 262448); + emitList(node, node.elements, 524880); writePunctuation("]"); } function emitBindingElement(node) { @@ -65038,8 +67246,8 @@ var ts; } function emitArrayLiteralExpression(node) { var elements = node.elements; - var preferNewLine = node.multiLine ? 32768 : 0; - emitExpressionList(node, elements, 4466 | preferNewLine); + var preferNewLine = node.multiLine ? 65536 : 0; + emitExpressionList(node, elements, 8914 | preferNewLine); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -65047,9 +67255,9 @@ var ts; if (indentedFlag) { increaseIndent(); } - var preferNewLine = node.multiLine ? 32768 : 0; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 && !ts.isJsonSourceFile(currentSourceFile) ? 32 : 0; - emitList(node, node.properties, 263122 | allowTrailingComma | preferNewLine); + var preferNewLine = node.multiLine ? 65536 : 0; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 && !ts.isJsonSourceFile(currentSourceFile) ? 64 : 0; + emitList(node, node.properties, 526226 | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); } @@ -65060,29 +67268,29 @@ var ts; if (!(ts.getEmitFlags(node) & 131072)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = ts.createToken(23); + var dotToken = ts.createToken(24); dotToken.pos = dotRangeStart; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); - increaseIndentIf(indentBeforeDot); + increaseIndentIf(indentBeforeDot, false); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); if (shouldEmitDotDot) { writePunctuation("."); } - emitTokenWithComment(23, node.expression.end, writePunctuation, node); - increaseIndentIf(indentAfterDot); + emitTokenWithComment(24, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, false); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); } function needsDotDotForPropertyAccess(expression) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, true); return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(23)); + && !ts.stringContains(text, ts.tokenToString(24)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); @@ -65093,21 +67301,21 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - emitTokenWithComment(21, node.expression.end, writePunctuation, node); + emitTokenWithComment(22, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - emitTokenWithComment(22, node.argumentExpression.end, writePunctuation, node); + emitTokenWithComment(23, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 1296); + emitExpressionList(node, node.arguments, 2576); } function emitNewExpression(node) { - emitTokenWithComment(94, node.pos, writeKeyword, node); + emitTokenWithComment(95, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 9488); + emitExpressionList(node, node.arguments, 18960); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); @@ -65122,9 +67330,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - var openParenPos = emitTokenWithComment(19, node.pos, writePunctuation, node); + var openParenPos = emitTokenWithComment(20, node.pos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + emitTokenWithComment(21, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { generateNameIfNeeded(node.name); @@ -65143,22 +67351,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - emitTokenWithComment(80, node.pos, writeKeyword, node); + emitTokenWithComment(81, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - emitTokenWithComment(103, node.pos, writeKeyword, node); + emitTokenWithComment(104, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - emitTokenWithComment(105, node.pos, writeKeyword, node); + emitTokenWithComment(106, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - emitTokenWithComment(121, node.pos, writeKeyword, node); + emitTokenWithComment(122, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -65171,24 +67379,24 @@ var ts; } function shouldEmitWhitespaceBeforeOperand(node) { var operand = node.operand; - return operand.kind === 200 - && ((node.operator === 37 && (operand.operator === 37 || operand.operator === 43)) - || (node.operator === 38 && (operand.operator === 38 || operand.operator === 44))); + return operand.kind === 202 + && ((node.operator === 38 && (operand.operator === 38 || operand.operator === 44)) + || (node.operator === 39 && (operand.operator === 39 || operand.operator === 45))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 26; + var isCommaOperator = node.operatorToken.kind !== 27; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); - increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + increaseIndentIf(indentBeforeOperator, isCommaOperator); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, writeOperator); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 ? writeKeyword : writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, true); - increaseIndentIf(indentAfterOperator, " "); + increaseIndentIf(indentAfterOperator, true); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); } @@ -65198,28 +67406,28 @@ var ts; var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); - increaseIndentIf(indentBeforeQuestion, " "); + increaseIndentIf(indentBeforeQuestion, true); emit(node.questionToken); - increaseIndentIf(indentAfterQuestion, " "); + increaseIndentIf(indentAfterQuestion, true); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); - increaseIndentIf(indentBeforeColon, " "); + increaseIndentIf(indentBeforeColon, true); emit(node.colonToken); - increaseIndentIf(indentAfterColon, " "); + increaseIndentIf(indentAfterColon, true); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); } function emitTemplateExpression(node) { emit(node.head); - emitList(node, node.templateSpans, 131072); + emitList(node, node.templateSpans, 262144); } function emitYieldExpression(node) { - emitTokenWithComment(116, node.pos, writeKeyword, node); + emitTokenWithComment(117, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - writePunctuation("..."); + emitTokenWithComment(25, node.pos, writePunctuation, node); emitExpression(node.expression); } function emitClassExpression(node) { @@ -65256,36 +67464,41 @@ var ts; emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); } function emitBlockStatements(node, forceSingleLine) { - emitTokenWithComment(17, node.pos, writePunctuation, node); - var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; + emitTokenWithComment(18, node.pos, writePunctuation, node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 768 : 129; emitList(node, node.statements, format); - emitTokenWithComment(18, node.statements.end, writePunctuation, node, !!(format & 1)); + emitTokenWithComment(19, node.statements.end, writePunctuation, node, !!(format & 1)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - writeSemicolon(); + writeTrailingSemicolon(); } - function emitEmptyStatement() { - writeSemicolon(); + function emitEmptyStatement(isEmbeddedStatement) { + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { - writeSemicolon(); + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); } } function emitIfStatement(node) { - var openParenPos = emitTokenWithComment(90, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(91, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19, openParenPos, writePunctuation, node); + emitTokenWithComment(20, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20, node.expression.end, writePunctuation, node); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - emitTokenWithComment(82, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 220) { + emitTokenWithComment(83, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222) { writeSpace(); emit(node.elseStatement); } @@ -65295,14 +67508,14 @@ var ts; } } function emitWhileClause(node, startPos) { - var openParenPos = emitTokenWithComment(106, startPos, writeKeyword, node); + var openParenPos = emitTokenWithComment(107, startPos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19, openParenPos, writePunctuation, node); + emitTokenWithComment(20, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20, node.expression.end, writePunctuation, node); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { - emitTokenWithComment(81, node.pos, writeKeyword, node); + emitTokenWithComment(82, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -65318,45 +67531,45 @@ var ts; emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89, node.pos, writeKeyword, node); writeSpace(); - var pos = emitTokenWithComment(19, openParenPos, writePunctuation, node); + var pos = emitTokenWithComment(20, openParenPos, writePunctuation, node); emitForBinding(node.initializer); - pos = emitTokenWithComment(25, node.initializer ? node.initializer.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26, node.initializer ? node.initializer.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.condition); - pos = emitTokenWithComment(25, node.condition ? node.condition.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26, node.condition ? node.condition.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.incrementor); - emitTokenWithComment(20, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitTokenWithComment(21, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19, openParenPos, writePunctuation, node); + emitTokenWithComment(20, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(92, node.initializer.end, writeKeyword, node); + emitTokenWithComment(93, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20, node.expression.end, writePunctuation, node); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - emitTokenWithComment(19, openParenPos, writePunctuation, node); + emitTokenWithComment(20, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(145, node.initializer.end, writeKeyword, node); + emitTokenWithComment(147, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20, node.expression.end, writePunctuation, node); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 236) { + if (node.kind === 238) { emit(node); } else { @@ -65365,14 +67578,14 @@ var ts; } } function emitContinueStatement(node) { - emitTokenWithComment(77, node.pos, writeKeyword, node); + emitTokenWithComment(78, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitBreakStatement(node) { - emitTokenWithComment(72, node.pos, writeKeyword, node); + emitTokenWithComment(73, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { var node = ts.getParseTreeNode(contextNode); @@ -65398,40 +67611,40 @@ var ts; return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96, node.pos, writeKeyword, node); + emitTokenWithComment(97, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitWithStatement(node) { - var openParenPos = emitTokenWithComment(107, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(108, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19, openParenPos, writePunctuation, node); + emitTokenWithComment(20, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20, node.expression.end, writePunctuation, node); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = emitTokenWithComment(98, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(99, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19, openParenPos, writePunctuation, node); + emitTokenWithComment(20, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20, node.expression.end, writePunctuation, node); + emitTokenWithComment(21, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - emitTokenWithComment(56, node.label.end, writePunctuation, node); + emitTokenWithComment(57, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - emitTokenWithComment(100, node.pos, writeKeyword, node); + emitTokenWithComment(101, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTryStatement(node) { - emitTokenWithComment(102, node.pos, writeKeyword, node); + emitTokenWithComment(103, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -65440,14 +67653,14 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - emitTokenWithComment(87, (node.catchClause || node.tryBlock).end, writeKeyword, node); + emitTokenWithComment(88, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78, node.pos, writeKeyword); - writeSemicolon(); + writeToken(79, node.pos, writeKeyword); + writeTrailingSemicolon(); } function emitVariableDeclaration(node) { emit(node.name); @@ -65457,7 +67670,7 @@ var ts; function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); writeSpace(); - emitList(node, node.declarations, 272); + emitList(node, node.declarations, 528); } function emitFunctionDeclaration(node) { emitFunctionDeclarationOrExpression(node); @@ -65505,7 +67718,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -65551,7 +67764,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18, body.statements.end, writePunctuation, body); + writeToken(19, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, true); @@ -65562,7 +67775,7 @@ var ts; emitHelpers(body); if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { decreaseIndent(); - emitList(body, body.statements, 384); + emitList(body, body.statements, 768); increaseIndent(); } else { @@ -65589,7 +67802,7 @@ var ts; emitList(node, node.heritageClauses, 0); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65); + emitList(node, node.members, 129); writePunctuation("}"); if (indentedFlag) { decreaseIndent(); @@ -65602,10 +67815,10 @@ var ts; writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256); + emitList(node, node.heritageClauses, 512); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65); + emitList(node, node.members, 129); writePunctuation("}"); } function emitTypeAliasDeclaration(node) { @@ -65619,7 +67832,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -65628,7 +67841,7 @@ var ts; emit(node.name); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 81); + emitList(node, node.members, 145); writePunctuation("}"); } function emitModuleDeclaration(node) { @@ -65640,8 +67853,8 @@ var ts; emit(node.name); var body = node.body; if (!body) - return writeSemicolon(); - while (body.kind === 242) { + return writeTrailingSemicolon(); + while (body.kind === 244) { writePunctuation("."); emit(body.name); body = body.body; @@ -65656,23 +67869,23 @@ var ts; popNameGenerationScope(node); } function emitCaseBlock(node) { - emitTokenWithComment(17, node.pos, writePunctuation, node); - emitList(node, node.clauses, 65); - emitTokenWithComment(18, node.clauses.end, writePunctuation, node, true); + emitTokenWithComment(18, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129); + emitTokenWithComment(19, node.clauses.end, writePunctuation, node, true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - emitTokenWithComment(58, node.name.end, writePunctuation, node); + emitTokenWithComment(59, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); - writeSemicolon(); + writeTrailingSemicolon(); } function emitModuleReference(node) { - if (node.kind === 71) { + if (node.kind === 72) { emitExpression(node); } else { @@ -65681,29 +67894,29 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - emitTokenWithComment(143, node.importClause.end, writeKeyword, node); + emitTokenWithComment(144, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); - writeSemicolon(); + writeTrailingSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - emitTokenWithComment(26, node.name.end, writePunctuation, node); + emitTokenWithComment(27, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - var asPos = emitTokenWithComment(39, node.pos, writePunctuation, node); + var asPos = emitTokenWithComment(40, node.pos, writePunctuation, node); writeSpace(); - emitTokenWithComment(118, asPos, writeKeyword, node); + emitTokenWithComment(119, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -65714,45 +67927,45 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - emitTokenWithComment(58, nextPos, writeOperator, node); + emitTokenWithComment(59, nextPos, writeOperator, node); } else { - emitTokenWithComment(79, nextPos, writeKeyword, node); + emitTokenWithComment(80, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitExportDeclaration(node) { - var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - nextPos = emitTokenWithComment(39, nextPos, writePunctuation, node); + nextPos = emitTokenWithComment(40, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); var fromPos = node.exportClause ? node.exportClause.end : nextPos; - emitTokenWithComment(143, fromPos, writeKeyword, node); + emitTokenWithComment(144, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamespaceExportDeclaration(node) { - var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85, node.pos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(118, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(119, nextPos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(130, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(131, nextPos, writeKeyword, node); writeSpace(); emit(node.name); - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -65762,14 +67975,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 262576); + emitList(node, node.elements, 525136); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - emitTokenWithComment(118, node.propertyName.end, writeKeyword, node); + emitTokenWithComment(119, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -65782,7 +67995,7 @@ var ts; } function emitJsxElement(node) { emit(node.openingElement); - emitList(node, node.children, 131072); + emitList(node, node.children, 262144); emit(node.closingElement); } function emitJsxSelfClosingElement(node) { @@ -65794,7 +68007,7 @@ var ts; } function emitJsxFragment(node) { emit(node.openingFragment); - emitList(node, node.children, 131072); + emitList(node, node.children, 262144); emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { @@ -65809,7 +68022,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, true)); } function emitJsxClosingElementOrFragment(node) { @@ -65820,7 +68032,7 @@ var ts; writePunctuation(">"); } function emitJsxAttributes(node) { - emitList(node, node.properties, 131328); + emitList(node, node.properties, 262656); } function emitJsxAttribute(node) { emit(node.name); @@ -65840,7 +68052,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71) { + if (node.kind === 72) { emitExpression(node); } else { @@ -65848,13 +68060,13 @@ var ts; } } function emitCaseClause(node) { - emitTokenWithComment(73, node.pos, writeKeyword, node); + emitTokenWithComment(74, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - var pos = emitTokenWithComment(79, node.pos, writeKeyword, node); + var pos = emitTokenWithComment(80, node.pos, writeKeyword, node); emitCaseOrDefaultClauseRest(node, node.statements, pos); } function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { @@ -65862,14 +68074,14 @@ var ts; (ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); - var format = 81985; + var format = 163969; if (emitAsSingleStatement) { - writeToken(56, colonPos, writePunctuation, parentNode); + writeToken(57, colonPos, writePunctuation, parentNode); writeSpace(); - format &= ~(1 | 64); + format &= ~(1 | 128); } else { - emitTokenWithComment(56, colonPos, writePunctuation, parentNode); + emitTokenWithComment(57, colonPos, writePunctuation, parentNode); } emitList(parentNode, statements, format); } @@ -65877,15 +68089,15 @@ var ts; writeSpace(); writeTokenText(node.token, writeKeyword); writeSpace(); - emitList(node, node.types, 272); + emitList(node, node.types, 528); } function emitCatchClause(node) { - var openParenPos = emitTokenWithComment(74, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(75, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - emitTokenWithComment(19, openParenPos, writePunctuation, node); + emitTokenWithComment(20, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - emitTokenWithComment(20, node.variableDeclaration.end, writePunctuation, node); + emitTokenWithComment(21, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -65912,7 +68124,7 @@ var ts; } function emitSpreadAssignment(node) { if (node.expression) { - writePunctuation("..."); + emitTokenWithComment(25, node.pos, writePunctuation, node); emitExpression(node.expression); } } @@ -65920,6 +68132,139 @@ var ts; emit(node.name); emitInitializer(node.initializer, node.name.end, node); } + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } function emitSourceFile(node) { writeLine(); var statements = node.statements; @@ -65935,41 +68280,46 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.moduleName) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.amdDependencies) { for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { var dep = _b[_a]; if (dep.name) { - write("/// "); + writeComment("/// "); } else { - write("/// "); + writeComment("/// "); } writeLine(); } } for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { var directive = files_1[_c]; - write("/// "); + writeComment("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; - write("/// "); + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); writeLine(); } } @@ -65987,7 +68337,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 272); + emitExpressionList(node, node.elements, 528); } function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { @@ -66022,13 +68372,14 @@ var ts; setSourceFile(sourceFile); emitPrologueDirectives(sourceFile.statements, true, seenPrologueDirectives); } + setSourceFile(undefined); } } function emitShebangIfNeeded(sourceFileOrBundle) { if (ts.isSourceFile(sourceFileOrBundle)) { var shebang = ts.getShebang(sourceFileOrBundle.text); if (shebang) { - write(shebang); + writeComment(shebang); writeLine(); return true; } @@ -66052,7 +68403,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328); + emitList(node, modifiers, 262656); writeSpace(); } } @@ -66066,7 +68417,7 @@ var ts; function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - emitTokenWithComment(58, equalCommentStartPos, writeOperator, container); + emitTokenWithComment(59, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -66103,30 +68454,37 @@ var ts; else { writeLine(); increaseIndent(); - emit(node); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0, node); + pipelinePhase(5, node); + } + else { + emit(node); + } decreaseIndent(); } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 24577); + emitList(parentNode, decorators, 49153); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26896); + emitList(parentNode, typeArguments, 53776); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { return emitTypeArguments(parentNode, parentNode.typeArguments); } - emitList(parentNode, typeParameters, 26896); + emitList(parentNode, typeParameters, 53776); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1296); + emitList(parentNode, parameters, 2576); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos - && !(ts.isArrowFunction(parentNode) && parentNode.type) + && ts.isArrowFunction(parentNode) + && !parentNode.type && !ts.some(parentNode.decorators) && !ts.some(parentNode.modifiers) && !ts.some(parentNode.typeParameters) @@ -66140,14 +68498,14 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1296 & ~1024); + emitList(parentNode, parameters, 2576 & ~2048); } else { emitParameters(parentNode, parameters); } } function emitParametersForIndexSignature(parentNode, parameters) { - emitList(parentNode, parameters, 4432); + emitList(parentNode, parameters, 8848); } function emitList(parentNode, children, format, start, count) { emitNodeList(emit, parentNode, children, format, start, count); @@ -66156,7 +68514,7 @@ var ts; emitNodeList(emitExpression, parentNode, children, format, start, count); } function writeDelimiter(format) { - switch (format & 28) { + switch (format & 60) { case 0: break; case 16: @@ -66166,6 +68524,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8: writeSpace(); writePunctuation("&"); @@ -66176,11 +68539,11 @@ var ts; if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; - if (isUndefined && format & 8192) { + if (isUndefined && format & 16384) { return; } var isEmpty = children === undefined || start >= children.length || count === 0; - if (isEmpty && format & 16384) { + if (isEmpty && format & 32768) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); } @@ -66189,7 +68552,7 @@ var ts; } return; } - if (format & 7680) { + if (format & 15360) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { emitTrailingCommentsOfPosition(children.pos, true); @@ -66202,41 +68565,45 @@ var ts; if (format & 1) { writeLine(); } - else if (format & 128 && !(format & 262144)) { + else if (format & 256 && !(format & 524288)) { writeSpace(); } } else { - var mayEmitInterveningComments = (format & 131072) === 0; + var mayEmitInterveningComments = (format & 262144) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { writeLine(); shouldEmitInterveningComments = false; } - else if (format & 128) { + else if (format & 256) { writeSpace(); } - if (format & 64) { + if (format & 128) { increaseIndent(); } var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = false; for (var i = 0; i < count; i++) { var child = children[start + i]; - if (previousSibling) { - if (format & 28 && previousSibling.end !== parentNode.end) { + if (format & 32) { + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + if (format & 60 && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { - if ((format & (3 | 64)) === 0) { + if ((format & (3 | 128)) === 0) { increaseIndent(); shouldDecreaseIndentAfterEmit = true; } writeLine(); shouldEmitInterveningComments = false; } - else if (previousSibling && format & 256) { + else if (previousSibling && format & 512) { writeSpace(); } } @@ -66256,100 +68623,81 @@ var ts; } previousSibling = child; } - var hasTrailingComma = (format & 32) && children.hasTrailingComma; + var hasTrailingComma = (format & 64) && children.hasTrailingComma; if (format & 16 && hasTrailingComma) { writePunctuation(","); } - if (previousSibling && format & 28 && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { + if (previousSibling && format & 60 && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { emitLeadingCommentsOfPosition(previousSibling.end); } - if (format & 64) { + if (format & 128) { decreaseIndent(); } if (shouldWriteClosingLineTerminator(parentNode, children, format)) { writeLine(); } - else if (format & 128) { + else if (format & 256) { writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } - if (format & 7680) { + if (format & 15360) { if (isEmpty && !isUndefined) { emitLeadingCommentsOfPosition(children.end); } writePunctuation(getClosingBracket(format)); } } - function commitPendingSemicolonInternal() { - if (pendingSemicolon) { - writeSemicolonInternal(); - pendingSemicolon = false; - } - } function writeLiteral(s) { - commitPendingSemicolon(); writer.writeLiteral(s); } function writeStringLiteral(s) { - commitPendingSemicolon(); writer.writeStringLiteral(s); } function writeBase(s) { - commitPendingSemicolon(); writer.write(s); } function writeSymbol(s, sym) { - commitPendingSemicolon(); writer.writeSymbol(s, sym); } function writePunctuation(s) { - commitPendingSemicolon(); writer.writePunctuation(s); } - function deferWriteSemicolon() { - pendingSemicolon = true; - } - function writeSemicolonInternal() { - writer.writePunctuation(";"); + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); } function writeKeyword(s) { - commitPendingSemicolon(); writer.writeKeyword(s); } function writeOperator(s) { - commitPendingSemicolon(); writer.writeOperator(s); } function writeParameter(s) { - commitPendingSemicolon(); writer.writeParameter(s); } + function writeComment(s) { + writer.writeComment(s); + } function writeSpace() { - commitPendingSemicolon(); writer.writeSpace(" "); } function writeProperty(s) { - commitPendingSemicolon(); writer.writeProperty(s); } function writeLine() { - commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { - commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { - commitPendingSemicolon(); writer.decreaseIndent(); } function writeToken(token, pos, writer, contextNode) { - return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) : writeTokenText(token, writer, pos); } function writeTokenNode(node, writer) { @@ -66377,23 +68725,23 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = ts.guessIndentation(lines); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var lineText = lines_2[_a]; + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); - writeLine(); + writer.rawWrite(newLine); } } } - function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + function increaseIndentIf(value, writeSpaceIfNotIndenting) { if (value) { increaseIndent(); writeLine(); } - else if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); + else if (writeSpaceIfNotIndenting) { + writeSpace(); } } function decreaseIndentIf(value1, value2) { @@ -66409,7 +68757,7 @@ var ts; return true; } if (format & 2) { - if (format & 32768) { + if (format & 65536) { return true; } var firstChild = children[0]; @@ -66448,10 +68796,10 @@ var ts; } function shouldWriteClosingLineTerminator(parentNode, children, format) { if (format & 1) { - return (format & 65536) === 0; + return (format & 131072) === 0; } else if (format & 2) { - if (format & 32768) { + if (format & 65536) { return true; } var lastChild = ts.lastOrUndefined(children); @@ -66473,11 +68821,11 @@ var ts; if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { - return (format & 32768) !== 0; + return (format & 65536) !== 0; } return startsOnNewLine; } - return (format & 32768) !== 0; + return (format & 65536) !== 0; } function needsIndentation(parent, node1, node2) { parent = skipSynthesizedParentheses(parent); @@ -66496,7 +68844,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 193 && ts.nodeIsSynthesized(node)) { + while (node.kind === 195 && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -66508,7 +68856,7 @@ var ts; else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } - else if (node.kind === 9 && node.textSourceNode) { + else if (node.kind === 10 && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); } else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { @@ -66516,19 +68864,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { - if (node.kind === 9 && node.textSourceNode) { + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } function pushNameGenerationScope(node) { if (node && ts.getEmitFlags(node) & 524288) { @@ -66555,81 +68903,81 @@ var ts; if (!node) return; switch (node.kind) { - case 216: - ts.forEach(node.statements, generateNames); - break; - case 231: - case 229: - case 221: - case 222: - generateNames(node.statement); - break; - case 220: - generateNames(node.thenStatement); - generateNames(node.elseStatement); - break; - case 223: - case 225: - case 224: - generateNames(node.initializer); - generateNames(node.statement); - break; - case 230: - generateNames(node.caseBlock); - break; - case 244: - ts.forEach(node.clauses, generateNames); - break; - case 269: - case 270: + case 218: ts.forEach(node.statements, generateNames); break; case 233: + case 231: + case 223: + case 224: + generateNames(node.statement); + break; + case 222: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 225: + case 227: + case 226: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 232: + generateNames(node.caseBlock); + break; + case 246: + ts.forEach(node.clauses, generateNames); + break; + case 271: + case 272: + ts.forEach(node.statements, generateNames); + break; + case 235: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 272: + case 274: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 217: + case 219: generateNames(node.declarationList); break; - case 236: + case 238: ts.forEach(node.declarations, generateNames); break; - case 235: - case 149: - case 184: - case 238: + case 237: + case 151: + case 186: + case 240: generateNameIfNeeded(node.name); break; - case 237: + case 239: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 182: - case 183: + case 184: + case 185: ts.forEach(node.elements, generateNames); break; - case 247: + case 249: generateNames(node.importClause); break; - case 248: + case 250: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 249: + case 251: generateNameIfNeeded(node.name); break; - case 250: + case 252: ts.forEach(node.elements, generateNames); break; - case 251: + case 253: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -66638,12 +68986,12 @@ var ts; if (!node) return; switch (node.kind) { - case 273: - case 274: - case 152: + case 275: + case 276: case 154: case 156: - case 157: + case 158: + case 159: generateNameIfNeeded(node.name); break; } @@ -66683,7 +69031,7 @@ var ts; for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); - if (local && local.flags & (67216319 | 1048576 | 2097152)) { + if (local && local.flags & (67220415 | 1048576 | 2097152)) { return false; } } @@ -66748,7 +69096,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, true); } function generateNameForModuleOrEnum(node) { @@ -66775,23 +69123,23 @@ var ts; } function generateNameForNode(node, flags) { switch (node.kind) { - case 71: + case 72: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16), !!(flags & 8)); - case 242: - case 241: + case 244: + case 243: return generateNameForModuleOrEnum(node); - case 247: - case 253: + case 249: + case 255: return generateNameForImportOrExportDeclaration(node); - case 237: - case 238: - case 252: + case 239: + case 240: + case 254: return generateNameForExportDefault(); - case 207: + case 209: return generateNameForClassExpression(); - case 154: case 156: - case 157: + case 158: + case 159: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0); @@ -66823,21 +69171,343 @@ var ts; } return node; } + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307; + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 11; + var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 11; + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512) !== 0)) { + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024) !== 0)) { + containerEnd = end; + if (node.kind === 238) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2, node); + if (emitFlags & 2048) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 + && (emitFlags & 16) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 + && (emitFlags & 32) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json"); + } } ts.createPrinter = createPrinter; function createBracketsMap() { var brackets = []; - brackets[512] = ["{", "}"]; - brackets[1024] = ["(", ")"]; - brackets[2048] = ["<", ">"]; - brackets[4096] = ["[", "]"]; + brackets[1024] = ["{", "}"]; + brackets[2048] = ["(", ")"]; + brackets[4096] = ["<", ">"]; + brackets[8192] = ["[", "]"]; return brackets; } function getOpeningBracket(format) { - return brackets[format & 7680][0]; + return brackets[format & 15360][0]; } function getClosingBracket(format) { - return brackets[format & 7680][1]; + return brackets[format & 15360][1]; } })(ts || (ts = {})); var ts; @@ -67189,15 +69859,20 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -67213,7 +69888,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -67223,7 +69898,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -67231,8 +69906,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); - var mtimeBefore = ts.sys.getModifiedTime(fileName); + var hash = system.createHash(data); + var mtimeBefore = system.getModifiedTime(fileName); if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); if (fingerprint && @@ -67242,8 +69917,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -67254,11 +69929,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -67270,36 +69945,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(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); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -67307,8 +69979,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -67333,7 +70005,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -67412,8 +70084,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); @@ -67428,11 +70100,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -67467,7 +70139,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -67480,19 +70152,23 @@ var ts; result = cache.get(name); } else { - cache.set(name, result = loader(name, containingFile)); + cache.set(name, result = loader(name, containingFile, redirectedReference)); } resolutions.push(result); } return resolutions; } - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; } if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + var seenResolvedRefs; + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; } @@ -67508,9 +70184,33 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || + return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolution(sourceFile.path); } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + return true; + } + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + return !fileExists(resolveProjectReferencePath(oldRef)); + } } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { @@ -67519,16 +70219,12 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; function shouldProgramCreateNewSourceFiles(program, newOptions) { - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -67551,7 +70247,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var modifiedFilePaths; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -67569,15 +70265,14 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json"]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; - var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { if (!resolved || resolved.extension !== undefined) { return resolved; } @@ -67588,16 +70283,16 @@ var ts; } else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; } else { - var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } var packageIdToSourceFile = ts.createMap(); var sourceFileToPackageName = ts.createMap(); @@ -67605,29 +70300,33 @@ var ts; var filesByName = ts.createMap(); var missingFilePaths; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; - var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { processingDefaultLibFiles = []; processingOtherFiles = []; if (projectReferences) { - for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { - var ref = projectReferences_1[_i]; - var parsedRef = parseProjectReferenceConfigFile(ref); - resolvedProjectReferences.push(parsedRef); - if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); - processSourceFile(dtsOutfile, false, false, undefined); + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, false, false, undefined); + } } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); } } } ts.forEach(rootNames, function (name) { return processRootFile(name, false, false); }); - var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); @@ -67636,7 +70335,7 @@ var ts; processTypeReferenceDirective(typeReferences[i], resolutions[i]); } } - if (!skipDefaultLib) { + if (rootNames.length && !skipDefaultLib) { var defaultLibraryFileName = getDefaultLibraryFileName(); if (!options.lib && defaultLibraryFileName) { processRootFile(defaultLibraryFileName, true, false); @@ -67657,10 +70356,17 @@ var ts; var oldSourceFiles = oldProgram.getSourceFiles(); for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { var oldSourceFile = oldSourceFiles_1[_a]; - if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { - host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), false); + } + }); } oldProgram = undefined; program = { @@ -67698,7 +70404,12 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -67731,7 +70442,7 @@ var ts; if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } @@ -67755,19 +70466,19 @@ var ts; } return classifiableNames; } - function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { if (structuralIsReused === 0 && !file.ambientModuleNames.length) { - return resolveModuleNamesWorker(moduleNames, containingFile); + return resolveModuleNamesWorker(moduleNames, containingFile, undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); } - var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } var unknownModuleNames; var result; @@ -67794,7 +70505,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -67804,7 +70515,7 @@ var ts; } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) : ts.emptyArray; if (!result) { ts.Debug.assert(resolutions.length === moduleNames.length); @@ -67824,29 +70535,37 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); - if (!firstUnmodifiedFile) { + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { return false; } if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); } return true; } } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return 0; @@ -67863,33 +70582,13 @@ var ts; if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { return oldProgram.structureIsReused = 0; } - var oldRefs = oldProgram.getProjectReferences(); - if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0; - } - for (var i = 0; i < projectReferences.length; i++) { - var oldRef = oldRefs[i]; - if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); - if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { - return oldProgram.structureIsReused = 0; - } - } - else { - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { - return oldProgram.structureIsReused = 0; - } - } - } + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0; } - else { - if (oldRefs) { - return oldProgram.structureIsReused = 0; - } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); } var newSourceFiles = []; - var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2; if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { @@ -67900,7 +70599,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, undefined, shouldCreateNewSourceFile); if (!newSourceFile) { return oldProgram.structureIsReused = 0; @@ -67924,7 +70623,9 @@ var ts; fileChanged = newSourceFile !== oldSourceFile; } newSourceFile.path = oldSourceFile.path; - filePaths.push(newSourceFile.path); + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { var prevKind = seenPackageNames.get(packageName); @@ -67968,14 +70669,22 @@ var ts; if (oldProgram.structureIsReused !== 2) { return oldProgram.structureIsReused; } - modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); - for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { - var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { oldProgram.structureIsReused = 1; @@ -67986,8 +70695,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { oldProgram.structureIsReused = 1; @@ -68005,27 +70714,28 @@ var ts; return oldProgram.structureIsReused = 1; } missingFilePaths = oldProgram.getMissingFilePaths(); - for (var i = 0; i < newSourceFiles.length; i++) { - filesByName.set(filePaths[i], newSourceFiles[i]); - if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { - sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { - var modifiedFile = modifiedSourceFiles_2[_c]; + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { var path = toPath(f); if (getSourceFileByPath(path)) return true; @@ -68034,11 +70744,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -68048,11 +70759,12 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { - if (!resolvedRefOpts.options.outFile) + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -68104,7 +70816,7 @@ var ts; } 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) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -68158,9 +70870,9 @@ var ts; } } function getSyntacticDiagnosticsForFile(sourceFile) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -68234,7 +70946,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -68242,62 +70954,62 @@ var ts; return diagnostics; function walk(node) { switch (parent.kind) { - case 149: - case 152: + case 151: + case 154: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } - case 154: - case 153: - case 155: case 156: + case 155: case 157: - case 194: + case 158: + case 159: + case 196: + case 239: + case 197: case 237: - case 195: - case 235: if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); return; } } switch (node.kind) { - case 246: + case 248: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 252: + case 254: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 271: + case 273: var heritageClause = node; - if (heritageClause.token === 108) { + if (heritageClause.token === 109) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 239: + case 241: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 242: + case 244: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 240: + case 242: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 241: + case 243: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 211: + case 213: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 210: + case 212: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 192: + case 194: ts.Debug.fail(); } var prevParent = parent; @@ -68310,46 +71022,46 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, 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)); } switch (parent.kind) { - case 238: - case 154: - case 153: - case 155: + case 240: case 156: + case 155: case 157: - case 194: - case 237: - case 195: + case 158: + case 159: + case 196: + case 239: + case 197: if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } - case 217: + case 219: if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 217); + return checkModifiers(nodes, parent.kind === 219); } break; - case 152: + case 154: if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 115) { + if (modifier.kind !== 116) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } return; } break; - case 149: + case 151: if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 189: - case 190: - case 209: - case 259: - case 260: + case 191: + case 192: + case 211: + case 261: + case 262: if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return; @@ -68365,21 +71077,21 @@ var ts; for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { var modifier = modifiers_1[_i]; switch (modifier.kind) { - case 76: + case 77: if (isConstValid) { continue; } - case 114: - case 112: + case 115: case 113: - case 132: - case 124: - case 117: + case 114: + case 133: + case 125: + case 118: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); break; - case 115: - case 84: - case 79: + case 116: + case 85: + case 80: } } } @@ -68424,10 +71136,22 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; } function getGlobalDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; } function getConfigFileParsingDiagnostics() { return configFileParsingDiagnostics || ts.emptyArray; @@ -68439,15 +71163,15 @@ var ts; return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 71 - ? b.kind === 71 && a.escapedText === b.escapedText - : b.kind === 9 && a.text === b.text; + return a.kind === 72 + ? b.kind === 72 && a.escapedText === b.escapedText + : b.kind === 10 && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); var imports; var moduleAugmentations; @@ -68465,12 +71189,9 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, false); - if ((file.flags & 524288) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(node); - } } if ((file.flags & 524288) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(file.endOfFileToken); + collectDynamicImportOrRequireCalls(file); } file.imports = imports || ts.emptyArray; file.moduleAugmentations = moduleAugmentations || ts.emptyArray; @@ -68504,23 +71225,35 @@ var ts; } } } - function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, true)) { - imports = ts.append(imports, node.arguments[0]); - } - else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { - imports = ts.append(imports, node.arguments[0]); - } - else if (ts.isLiteralImportTypeNode(node)) { - imports = ts.append(imports, node.argument.literal); - } - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, true)) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } } } - function collectDynamicImportOrRequireCallsForEachChild(node) { - ts.forEachChild(node, collectDynamicImportOrRequireCalls); + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } } } function getLibFileFromReference(ref) { @@ -68535,7 +71268,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -68589,11 +71322,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -68607,6 +71343,7 @@ var ts; return redirect; } function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames) { @@ -68659,9 +71396,9 @@ var ts; var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); redirectTargetsMap.add(fileFromPackageId.path, fileName); - filesByName.set(path, dupFile); + addFileToFilesByName(dupFile, path, redirectedPath); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); return dupFile; @@ -68671,14 +71408,12 @@ var ts; sourceFileToPackageName.set(path, packageId.name); } } - filesByName.set(path, file); - if (redirectedPath) { - filesByName.set(redirectedPath, file); - } + addFileToFilesByName(file, path, redirectedPath); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); var existingFile = filesByNameIgnoreCase.get(pathLowerCase); @@ -68705,23 +71440,81 @@ var ts; } return file; } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { - return undefined; - } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts") || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts") : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); }); - return result; + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, false, undefined, file, ref.pos, ref.end); }); } @@ -68730,7 +71523,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -68746,6 +71539,8 @@ var ts; } var saveResolution = true; if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; if (resolvedTypeReferenceDirective.primary) { processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } @@ -68763,6 +71558,8 @@ var ts; processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; } else { fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); @@ -68805,8 +71602,7 @@ var ts; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -68815,7 +71611,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -68828,7 +71624,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -68847,59 +71643,59 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } return allFilesBelongToPath; } function parseProjectReferenceConfigFile(ref) { - var refPath = resolveProjectReferencePath(host, ref); + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100); + addFileToFilesByName(sourceFile, sourceFilePath, undefined); if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); return undefined; } - sourceFile.path = toPath(refPath); + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, undefined, refPath); - return { commandLine: commandLine, sourceFile: sourceFile }; - } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -68927,42 +71723,19 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); } } - if (projectReferences) { - for (var i = 0; i < projectReferences.length; i++) { - var ref = projectReferences[i]; - var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; - if (resolvedRefOpts === undefined) { - createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); - continue; - } - if (!resolvedRefOpts.composite) { - createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - } - if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); - } - } - else { - createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + verifyProjectReferences(); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); } } } } - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); - } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); - } - } if (options.paths) { for (var key in options.paths) { if (!ts.hasProperty(options.paths, key)) { @@ -69009,15 +71782,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -69027,12 +71800,12 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -69042,7 +71815,7 @@ var ts; var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -69055,27 +71828,27 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } if (options.outDir || options.sourceRoot || options.mapRoot) { var dir = getCommonSourceDirectory(); - if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -69127,6 +71900,34 @@ var ts; } } } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { var needCompilerDiagnostic = true; var pathsSyntax = getOptionPathsSyntax(); @@ -69177,10 +71978,10 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(false, option1, undefined, message, arg0); } - function createDiagnosticForReference(index, message, arg0, arg1) { - var referencesSyntax = getProjectReferencesSyntax(); + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); if (referencesSyntax && referencesSyntax.elements.length > index) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); } else { programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); @@ -69194,22 +71995,6 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } - function getProjectReferencesSyntax() { - if (_referencesArrayLiteralSyntax === undefined) { - _referencesArrayLiteralSyntax = null; - if (options.configFile) { - var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); - for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { - var prop = _a[_i]; - if (ts.isArrayLiteralExpression(prop.initializer)) { - _referencesArrayLiteralSyntax = prop.initializer; - break; - } - } - } - } - return _referencesArrayLiteralSyntax; - } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; @@ -69256,7 +72041,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts")) || !!getSourceFileByPath((filePathWithoutExtension + ".tsx")); @@ -69271,21 +72056,26 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { @@ -69317,7 +72107,7 @@ var ts; var res = imports.map(function (i) { return i.text; }); for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9) { + if (aug.kind === 10) { res.push(aug.text); } } @@ -69342,13 +72132,16 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } function getReferencedFileFromImportLiteral(checker, importName) { var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } function getReferencedFiles(program, sourceFile, getCanonicalFileName) { var referencedFiles; if (sourceFile.imports && sourceFile.imports.length > 0) { @@ -69365,7 +72158,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -69375,11 +72168,41 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + addReferenceFromAmbientModule(symbol); + } + } + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -69461,6 +72284,10 @@ var ts; var latestSignature; if (sourceFile.isDeclarationFile) { latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } } else { var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, true, cancellationToken); @@ -69514,7 +72341,7 @@ var ts; if (compilerOptions.outFile || compilerOptions.out) { return getAllFileNames(state, programOfThisState); } - if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { return getAllFileNames(state, programOfThisState); } var seenMap = ts.createMap(); @@ -69560,6 +72387,13 @@ var ts; } return true; } + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { if (state.allFilesExcludingDefaultLibraryFile) { return state.allFilesExcludingDefaultLibraryFile; @@ -69588,7 +72422,7 @@ var ts; return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { - if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } var compilerOptions = programOfThisState.getCompilerOptions(); @@ -69626,8 +72460,9 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && - !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { if (!oldState.currentChangedFilePath) { ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); @@ -69639,6 +72474,8 @@ var ts; } var referencedMap = state.referencedMap; var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -69650,6 +72487,13 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); @@ -69711,31 +72555,64 @@ var ts; if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { return; } + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { return; } ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { return exportedModules && exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); })) { return; } ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); }); } - function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { - return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); }); } function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -69769,7 +72646,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -69782,7 +72659,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -69908,16 +72792,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { getProgram: function () { return program; }, getState: ts.notImplemented, @@ -69938,6 +72822,10 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; ts.maxNumberOfFilesToIterateForInvalidation = 256; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; @@ -69948,11 +72836,11 @@ var ts; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); var resolvedModuleNames = ts.createMap(); - var perDirectoryResolvedModuleNames = ts.createMap(); - var nonRelaticeModuleNameCache = ts.createMap(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); var resolvedTypeReferenceDirectives = ts.createMap(); - var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); @@ -69967,6 +72855,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -70024,7 +72913,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -70040,13 +72929,13 @@ var ts; } }); } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); if (!resolutionHost.getGlobalCache) { return primaryResult; } var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (resolvedModule) { return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; @@ -70054,10 +72943,11 @@ var ts; } return primaryResult; } - function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { var path = resolutionHost.toPath(containingFile); var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); var perDirectoryResolution = perDirectoryCache.get(dirPath); if (!perDirectoryResolution) { perDirectoryResolution = ts.createMap(); @@ -70066,20 +72956,25 @@ var ts; var resolvedModules = []; var compilerOptions = resolutionHost.getCompilationSettings(); var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; var seenNamesInFile = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { var name = names_2[_i]; var resolution = resolutionsInFile.get(name); if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || - (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { var existingResolution = resolution; var resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { resolution = resolutionInDirectory; } else { - resolution = loader(name, containingFile, compilerOptions, resolutionHost); + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); @@ -70121,11 +73016,11 @@ var ts; return oldResult.resolvedFileName === newResult.resolvedFileName; } } - function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { - return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, undefined, false); + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, undefined, false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); } function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); @@ -70158,15 +73053,9 @@ var ts; } return true; } - function filterFSRootDirectoriesToWatch(watchPath, dirPath) { - if (!canWatchDirectory(dirPath)) { - watchPath.ignore = true; - } - return watchPath; - } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -70179,12 +73068,12 @@ var ts; return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { - while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { + while (ts.pathContainsNodeModules(dirPath)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } if (isNodeModulesDirectory(dirPath)) { - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; var subDirectoryPath, subDirectory; @@ -70201,7 +73090,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive }, dirPath); + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -70229,8 +73118,9 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, nonRecursive = _a.nonRecursive, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); @@ -70280,8 +73170,9 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { if (refCount === 1) { @@ -70326,6 +73217,20 @@ var ts; cache.delete(filePath); } } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json")) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } function removeResolutionsOfFile(filePath) { removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); @@ -70380,6 +73285,8 @@ var ts; isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; } else { + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { @@ -70413,8 +73320,8 @@ var ts; if (isInDirectoryPath(rootPath, typeRootPath)) { return rootPath; } - var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { @@ -70458,87 +73365,101 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 : importModuleSpecifierPreference === "non-relative" ? 1 : 2, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0; + case "index": return 1; + case "js": return 2; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 : 0; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 : 1, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 : 0, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + if (relativePreference !== 2) + ts.Debug.assertNever(relativePreference); + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js") : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -70596,16 +73517,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -70623,7 +73534,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -70643,39 +73555,43 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -70687,6 +73603,8 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; @@ -70744,13 +73662,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json")) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0: + return ts.removeSuffix(noExtension, "/index"); + case 1: + return noExtension; + case 2: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts": + case ".d.ts": + return ".js"; + case ".tsx": + return options.jsx === 1 ? ".jsx" : ".js"; + case ".js": + case ".jsx": + case ".json": + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); @@ -70785,16 +73726,12 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { if (system.clearScreen && !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -70836,7 +73773,24 @@ var ts; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); @@ -70848,7 +73802,7 @@ var ts; reportSemanticDiagnostics = true; } } - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -70867,7 +73821,7 @@ var ts; } } if (reportSummary) { - reportSummary(diagnostics.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length); + reportSummary(getErrorCountForSummary(diagnostics)); } if (emitSkipped && diagnostics.length > 0) { return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; @@ -70879,6 +73833,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { if (system === void 0) { system = ts.sys; } if (!createProgram) { @@ -70888,7 +73861,7 @@ var ts; host; var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -70902,17 +73875,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -70928,15 +73894,7 @@ var ts; function emitFilesAndReportErrorUsingBuilder(builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - var reportSummary = function (errorCount) { - if (errorCount === 1) { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions); - } - else { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions); - } - }; - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); } } function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { @@ -70952,18 +73910,19 @@ var ts; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -70986,9 +73945,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -71001,7 +73961,8 @@ var ts; fileExists: function (path) { return host.fileExists(path); }, readFile: readFile, getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; var newLine = updateNewLine(); if (configFileName && host.configFileParsingResult) { @@ -71056,17 +74017,18 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : currentDirectory, false); compilerHost.resolveModuleNames = host.resolveModuleNames ? - (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : - (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? - (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : - (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; synchronizeProgram(); watchConfigFileWildCardDirectories(); @@ -71089,9 +74051,9 @@ var ts; } } var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(undefined, undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(undefined, undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -71115,7 +74077,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); if (needsUpdateInTypeRootWatch) { @@ -71224,8 +74186,8 @@ var ts; var hostSourceFile = sourceFilesCache.get(path); return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); } - function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { - var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); if (hostSourceFileInfo) { if (isFileMissingOnHost(hostSourceFileInfo)) { (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); @@ -71234,8 +74196,10 @@ var ts; if (hostSourceFileInfo.fileWatcher) { hostSourceFileInfo.fileWatcher.close(); } - sourceFilesCache.delete(oldSourceFile.path); - resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } } } } @@ -71275,12 +74239,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -71304,7 +74263,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -71312,6 +74273,7 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { resolutionCache.invalidateResolutionOfFile(path); } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); scheduleProgramUpdate(); } @@ -71348,6 +74310,8 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); return; @@ -71395,7 +74359,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -71407,87 +74372,61 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - function createFileMap() { + function createFileMap(toPath) { var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts"); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json") ? ".json" : @@ -71499,7 +74438,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json")) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -71510,13 +74453,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts"); + var dts = ts.changeExtension(out, ".d.ts"); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -71527,748 +74474,759 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts"); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); + }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + var unchangedOutputs = createFileMap(toPath); + var projectStatus = createFileMap(toPath); var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects - }; - } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - addProject(arg); - } - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } - } - ts.performBuild = performBuild; - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1)); - }); - } - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + watchWildCardDirectories(resolved, cfg); + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + if (!ts.fileExtensionIs(fileName, ".d.ts") && + (ts.fileExtensionIs(fileName, ".ts") || ts.fileExtensionIs(fileName, ".tsx"))) { + return false; + } + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts"))) { + return true; + } + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } var program = ts.createProgram(programOptions); var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + function getFilesToClean() { + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); if (defaultOptions.dry) { - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json")) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -72303,6 +75261,7 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: + case UpToDateStatusType.ComputingUpstream: break; default: ts.assertType(status); @@ -72310,6 +75269,133 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +var ts; +(function (ts) { + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; + } + function anyValue(name, comment) { + return { kind: 0, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.release.js.map var ts; (function (ts) { @@ -72330,7 +75416,7 @@ var ts; return !!ts.sys.writeOutputIsTTY && ts.sys.writeOutputIsTTY(); } function shouldBePretty(options) { - if (typeof options.pretty === "undefined") { + if (!options || typeof options.pretty === "undefined") { return defaultIsPretty(); } return options.pretty; @@ -72354,28 +75440,10 @@ var ts; ts.filter(ts.optionDeclarations.slice(), function (v) { return !!v.showInSimplifiedHelpView; }); } function executeCommandLine(args) { - if (args.length > 0 && ((args[0].toLowerCase() === "--build") || (args[0].toLowerCase() === "-b"))) { - var reportDiag_1 = ts.createDiagnosticReporter(ts.sys, defaultIsPretty()); - var report = function (message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return reportDiag_1(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); - }; - var buildHost = { - error: report, - verbose: report, - message: report, - errorDiagnostic: function (d) { return reportDiag_1(d); } - }; - var result = ts.performBuild(args.slice(1), ts.createCompilerHost({}), buildHost, ts.sys); - // undefined = in watch mode, do not exit - if (result !== undefined) { - return ts.sys.exit(result); - } - else { - return; + if (args.length > 0 && args[0].charCodeAt(0) === 45 /* minus */) { + var firstOption = args[0].slice(args[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); + if (firstOption === "build" || firstOption === "b") { + return performBuild(args.slice(1)); } } var commandLine = ts.parseCommandLine(args); @@ -72440,6 +75508,11 @@ var ts; var commandLineOptions = commandLine.options; if (configFileName) { var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, ts.sys, reportDiagnostic); // TODO: GH#18217 + if (commandLineOptions.showConfig) { + // tslint:disable-next-line:no-null-keyword + ts.sys.write(JSON.stringify(ts.convertToTSConfig(configParseResult, configFileName, ts.sys), null, 4) + ts.sys.newLine); + return ts.sys.exit(ts.ExitStatus.Success); + } updateReportDiagnostic(configParseResult.options); if (ts.isWatchSet(configParseResult.options)) { reportWatchModeWithoutSysSupport(); @@ -72450,6 +75523,11 @@ var ts; } } else { + if (commandLineOptions.showConfig) { + // tslint:disable-next-line:no-null-keyword + ts.sys.write(JSON.stringify(ts.convertToTSConfig(commandLine, ts.combinePaths(ts.sys.getCurrentDirectory(), "tsconfig.json"), ts.sys), null, 4) + ts.sys.newLine); + return ts.sys.exit(ts.ExitStatus.Success); + } updateReportDiagnostic(commandLineOptions); if (ts.isWatchSet(commandLineOptions)) { reportWatchModeWithoutSysSupport(); @@ -72467,6 +75545,52 @@ var ts; ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } + function performBuild(args) { + var _a = ts.parseBuildCommand(args), buildOptions = _a.buildOptions, projects = _a.projects, errors = _a.errors; + if (errors.length > 0) { + errors.forEach(reportDiagnostic); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (buildOptions.help) { + ts.printVersion(); + ts.printHelp(ts.buildOpts, "--build "); + return ts.sys.exit(ts.ExitStatus.Success); + } + // Update to pretty if host supports it + updateReportDiagnostic(); + if (projects.length === 0) { + ts.printVersion(); + ts.printHelp(ts.buildOpts, "--build "); + return ts.sys.exit(ts.ExitStatus.Success); + } + if (!ts.sys.getModifiedTime || !ts.sys.setModifiedTime || (buildOptions.clean && !ts.sys.deleteFile)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (buildOptions.watch) { + reportWatchModeWithoutSysSupport(); + } + // TODO: change this to host if watch => watchHost otherwiue without watch + var buildHost = buildOptions.watch ? + ts.createSolutionBuilderWithWatchHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createWatchStatusReporter()) : + ts.createSolutionBuilderHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createReportErrorSummary(buildOptions)); + buildHost.beforeCreateProgram = enableStatistics; + buildHost.afterProgramEmitAndDiagnostics = reportStatistics; + var builder = ts.createSolutionBuilder(buildHost, projects, buildOptions); + if (buildOptions.clean) { + return ts.sys.exit(builder.cleanAllProjects()); + } + if (buildOptions.watch) { + builder.buildAllProjects(); + return builder.startWatching(); + } + return ts.sys.exit(builder.buildAllProjects()); + } + function createReportErrorSummary(options) { + return shouldBePretty(options) ? + function (errorCount) { return ts.sys.write(ts.getErrorSummaryText(errorCount, ts.sys.newLine)); } : + undefined; + } function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) { var host = ts.createCompilerHost(options); enableStatistics(options); @@ -72478,18 +75602,18 @@ var ts; configFileParsingDiagnostics: configFileParsingDiagnostics }; var program = ts.createProgram(programOptions); - var exitStatus = ts.emitFilesAndReportErrors(program, reportDiagnostic, function (s) { return ts.sys.write(s + ts.sys.newLine); }); + var exitStatus = ts.emitFilesAndReportErrors(program, reportDiagnostic, function (s) { return ts.sys.write(s + ts.sys.newLine); }, createReportErrorSummary(options)); reportStatistics(program); return ts.sys.exit(exitStatus); } function updateWatchCompilationHost(watchCompilerHost) { var compileUsingBuilder = watchCompilerHost.createProgram; - watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) { ts.Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); if (options !== undefined) { enableStatistics(options); } - return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics); + return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); }; var emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; // TODO: GH#18217 watchCompilerHost.afterProgramCreate = function (builderProgram) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 4111b40028b..d7f25907257 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -21,7 +21,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -86,7 +86,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -101,6 +101,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -490,10 +491,33 @@ var ts; return result; } ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ function flatMap(array, mapfn) { var result; if (array) { - result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { for (var i = 0; i < array.length; i++) { var v = mapfn(array[i], i); if (v) { @@ -508,7 +532,7 @@ var ts; } return result; } - ts.flatMap = flatMap; + ts.flatMapToMutable = flatMapToMutable; function flatMapIterator(iter, mapfn) { var first = iter.next(); if (first.done) { @@ -729,19 +753,25 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) - return []; + return ts.emptyArray; var last = array[0]; var deduplicated = [last]; for (var i = 1; i < array.length; i++) { @@ -772,7 +802,7 @@ var ts; } ts.insertSorted = insertSorted; function sortAndDeduplicate(array, comparer, equalityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); } ts.sortAndDeduplicate = sortAndDeduplicate; function arrayIsEqualTo(array1, array2, equalityComparer) { @@ -784,7 +814,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -925,7 +955,7 @@ var ts; * Returns a new sorted array. */ function sort(array, comparer) { - return array.slice().sort(comparer); + return (array.length === 0 ? array : array.slice().sort(comparer)); } ts.sort = sort; function arrayIterator(array) { @@ -1031,12 +1061,25 @@ var ts; * @param offset An offset into `array` at which to start the search. */ function binarySearch(array, value, keySelector, keyComparer, offset) { - if (!array || array.length === 0) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { return -1; } var low = offset || 0; var high = array.length - 1; - var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); var midKey = keySelector(array[middle]); @@ -1053,7 +1096,7 @@ var ts; } return ~low; } - ts.binarySearch = binarySearch; + ts.binarySearchKey = binarySearchKey; function reduceLeft(array, f, initial, start, count) { if (array && array.length > 0) { var size = array.length; @@ -1161,7 +1204,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1281,6 +1324,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1445,7 +1492,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1948,6 +1997,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -1967,6 +2020,33 @@ var ts; var counts; var marks; var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; /** * Marks a performance event. * @@ -2042,6 +2122,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2061,368 +2501,370 @@ var ts; SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; // Literals SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; - SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; - SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; // Pseudo-literals - SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; + SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail"; // Punctuation - SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken"; // Assignments - SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken"; // Identifiers - SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; + SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier"; // Reserved words - SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword"; // Strict mode reserved words - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword"; // Contextual keywords - SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; - SyntaxKind[SyntaxKind["InferKeyword"] = 126] = "InferKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 127] = "IsKeyword"; - SyntaxKind[SyntaxKind["KeyOfKeyword"] = 128] = "KeyOfKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 129] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 130] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 131] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 132] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 133] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 134] = "NumberKeyword"; - SyntaxKind[SyntaxKind["ObjectKeyword"] = 135] = "ObjectKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 136] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 137] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 138] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword"; - SyntaxKind[SyntaxKind["UnknownKeyword"] = 142] = "UnknownKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 143] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 144] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 145] = "OfKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 146] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 147] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 148] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 149] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 150] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 151] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 152] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 153] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 154] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 155] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 156] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 157] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 158] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 159] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 160] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 161] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 162] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 163] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 164] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 165] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 166] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 167] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 168] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 169] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 170] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 171] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 172] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 173] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 174] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 175] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 176] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 177] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 178] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 179] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 180] = "LiteralType"; - SyntaxKind[SyntaxKind["ImportType"] = 181] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 182] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 183] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 184] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 185] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 186] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 187] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 188] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 189] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 190] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 191] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 192] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 193] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 194] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 195] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 196] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 197] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 198] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 199] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 200] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 201] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 202] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 203] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 204] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 205] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 206] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 207] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 208] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 209] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 210] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 211] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 212] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 213] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 214] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 215] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 216] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 217] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 218] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 219] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 220] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 221] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 222] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 223] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 224] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 225] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 226] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 227] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 228] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 229] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 230] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 231] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 232] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 233] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 234] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 235] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 236] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 237] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 238] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 239] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 240] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 241] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 242] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 243] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 244] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 245] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 246] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 247] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 248] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 249] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 250] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 251] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 252] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 253] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 254] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 255] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 256] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 218] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 257] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 258] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 259] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 260] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 261] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 262] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 263] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 264] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 265] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 266] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 267] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 268] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 269] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 270] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 271] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 272] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 273] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 274] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 275] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 276] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 277] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 278] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 279] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 280] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 281] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 282] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 283] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 284] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 285] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 286] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 287] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 288] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 289] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 290] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 291] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 292] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 310] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; // Markers - SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 145] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 161] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 181] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 145] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode"; - /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -2622,7 +3064,10 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; + // Errors (cont.) + NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors"; // State NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; @@ -2678,6 +3123,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2709,14 +3156,15 @@ var ts; // of a type, such as the global `Promise` type in lib.d.ts). TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; // with call signatures. - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var SymbolFlags; (function (SymbolFlags) { @@ -2747,38 +3195,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2853,14 +3301,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2870,29 +3319,27 @@ var ts; TypeFlags[TypeFlags["Number"] = 8] = "Number"; TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 64] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 128] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 256] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 512] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 1024] = "ESSymbol"; - TypeFlags[TypeFlags["UniqueESSymbol"] = 2048] = "UniqueESSymbol"; - TypeFlags[TypeFlags["Void"] = 4096] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 8192] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 16384] = "Null"; - TypeFlags[TypeFlags["Never"] = 32768] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 65536] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 131072] = "Object"; - TypeFlags[TypeFlags["Union"] = 262144] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 524288] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 1048576] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 2097152] = "IndexedAccess"; - TypeFlags[TypeFlags["Conditional"] = 4194304] = "Conditional"; - TypeFlags[TypeFlags["Substitution"] = 8388608] = "Substitution"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; - /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; - /* @internal */ - TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes"; + TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt"; + TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 16384] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 65536] = "Null"; + TypeFlags[TypeFlags["Never"] = 131072] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 524288] = "Object"; + TypeFlags[TypeFlags["Union"] = 1048576] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 4194304] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; /* @internal */ TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ @@ -2902,40 +3349,41 @@ var ts; /* @internal */ TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 24576] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 448] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 27072] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 192] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 2944] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 2240] = "StringOrNumberLiteralOrUnique"; + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 29120] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 29148] = "PossiblyFalsy"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 16839967] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 32764] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 68] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 168] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 272] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 544] = "EnumLike"; - TypeFlags[TypeFlags["ESSymbolLike"] = 3072] = "ESSymbolLike"; - TypeFlags[TypeFlags["VoidLike"] = 12288] = "VoidLike"; + TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike"; + TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; /* @internal */ - TypeFlags[TypeFlags["DisjointDomains"] = 16809468] = "DisjointDomains"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 786432] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 917504] = "StructuredType"; - TypeFlags[TypeFlags["TypeVariable"] = 2162688] = "TypeVariable"; - TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 14745600] = "InstantiableNonPrimitive"; - TypeFlags[TypeFlags["InstantiablePrimitive"] = 1048576] = "InstantiablePrimitive"; - TypeFlags[TypeFlags["Instantiable"] = 15794176] = "Instantiable"; - TypeFlags[TypeFlags["StructuredOrInstantiable"] = 16711680] = "StructuredOrInstantiable"; + TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion"; + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ @@ -2970,6 +3418,7 @@ var ts; ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -2981,6 +3430,13 @@ var ts; Variance[Variance["Bivariant"] = 3] = "Bivariant"; Variance[Variance["Independent"] = 4] = "Independent"; })(Variance = ts.Variance || (ts.Variance = {})); + /* @internal */ + var JsxReferenceKind; + (function (JsxReferenceKind) { + JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component"; + JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function"; + JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed"; + })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {})); var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; @@ -3006,9 +3462,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3027,22 +3482,31 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue"; + // Object.defineProperty(exports || module.exports, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports"; + // Object.defineProperty(Foo.prototype, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3279,25 +3743,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3316,25 +3776,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3414,6 +3873,7 @@ var ts; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; + EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); var ListFormat; (function (ListFormat) { @@ -3428,64 +3888,66 @@ var ts; ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma"; // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + ListFormat[ListFormat["Indented"] = 128] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings"; // Brackets/Braces - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + ListFormat[ListFormat["Braces"] = 1024] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 49152] = "Optional"; // Other - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; + ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters"; + ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment"; })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); /* @internal */ var PragmaKindFlags; @@ -3578,20 +4040,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3809,17 +4257,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4140,11 +4592,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4755,7 +5208,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4794,6 +5247,11 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4806,7 +5264,7 @@ var ts; An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), - An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), @@ -4850,14 +5308,14 @@ var ts; Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), @@ -4913,7 +5371,7 @@ var ts; Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), - A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), @@ -4996,7 +5454,7 @@ var ts; _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), - Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), @@ -5027,7 +5485,7 @@ var ts; Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), @@ -5037,7 +5495,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5065,6 +5522,15 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5156,6 +5622,15 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5269,7 +5744,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5363,7 +5840,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5461,6 +5938,18 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5491,9 +5980,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5501,6 +5990,7 @@ var ts; _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), @@ -5528,6 +6018,15 @@ var ts; If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5558,6 +6057,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5622,6 +6122,7 @@ var ts; Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -5686,150 +6187,108 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { - return token >= 71 /* Identifier */; + return token >= 72 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; /* @internal */ function tokenIsIdentifierOrKeywordOrGreaterThan(token) { - return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 118 /* AbstractKeyword */, + any: 120 /* AnyKeyword */, + as: 119 /* AsKeyword */, + bigint: 146 /* BigIntKeyword */, + boolean: 123 /* BooleanKeyword */, + break: 73 /* BreakKeyword */, + case: 74 /* CaseKeyword */, + catch: 75 /* CatchKeyword */, + class: 76 /* ClassKeyword */, + continue: 78 /* ContinueKeyword */, + const: 77 /* ConstKeyword */ + }, + _a["" + "constructor"] = 124 /* ConstructorKeyword */, + _a.debugger = 79 /* DebuggerKeyword */, + _a.declare = 125 /* DeclareKeyword */, + _a.default = 80 /* DefaultKeyword */, + _a.delete = 81 /* DeleteKeyword */, + _a.do = 82 /* DoKeyword */, + _a.else = 83 /* ElseKeyword */, + _a.enum = 84 /* EnumKeyword */, + _a.export = 85 /* ExportKeyword */, + _a.extends = 86 /* ExtendsKeyword */, + _a.false = 87 /* FalseKeyword */, + _a.finally = 88 /* FinallyKeyword */, + _a.for = 89 /* ForKeyword */, + _a.from = 144 /* FromKeyword */, + _a.function = 90 /* FunctionKeyword */, + _a.get = 126 /* GetKeyword */, + _a.if = 91 /* IfKeyword */, + _a.implements = 109 /* ImplementsKeyword */, + _a.import = 92 /* ImportKeyword */, + _a.in = 93 /* InKeyword */, + _a.infer = 127 /* InferKeyword */, + _a.instanceof = 94 /* InstanceOfKeyword */, + _a.interface = 110 /* InterfaceKeyword */, + _a.is = 128 /* IsKeyword */, + _a.keyof = 129 /* KeyOfKeyword */, + _a.let = 111 /* LetKeyword */, + _a.module = 130 /* ModuleKeyword */, + _a.namespace = 131 /* NamespaceKeyword */, + _a.never = 132 /* NeverKeyword */, + _a.new = 95 /* NewKeyword */, + _a.null = 96 /* NullKeyword */, + _a.number = 135 /* NumberKeyword */, + _a.object = 136 /* ObjectKeyword */, + _a.package = 112 /* PackageKeyword */, + _a.private = 113 /* PrivateKeyword */, + _a.protected = 114 /* ProtectedKeyword */, + _a.public = 115 /* PublicKeyword */, + _a.readonly = 133 /* ReadonlyKeyword */, + _a.require = 134 /* RequireKeyword */, + _a.global = 145 /* GlobalKeyword */, + _a.return = 97 /* ReturnKeyword */, + _a.set = 137 /* SetKeyword */, + _a.static = 116 /* StaticKeyword */, + _a.string = 138 /* StringKeyword */, + _a.super = 98 /* SuperKeyword */, + _a.switch = 99 /* SwitchKeyword */, + _a.symbol = 139 /* SymbolKeyword */, + _a.this = 100 /* ThisKeyword */, + _a.throw = 101 /* ThrowKeyword */, + _a.true = 102 /* TrueKeyword */, + _a.try = 103 /* TryKeyword */, + _a.type = 140 /* TypeKeyword */, + _a.typeof = 104 /* TypeOfKeyword */, + _a.undefined = 141 /* UndefinedKeyword */, + _a.unique = 142 /* UniqueKeyword */, + _a.unknown = 143 /* UnknownKeyword */, + _a.var = 105 /* VarKeyword */, + _a.void = 106 /* VoidKeyword */, + _a.while = 107 /* WhileKeyword */, + _a.with = 108 /* WithKeyword */, + _a.yield = 117 /* YieldKeyword */, + _a.async = 121 /* AsyncKeyword */, + _a.await = 122 /* AwaitKeyword */, + _a.of = 147 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, ">": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -5964,11 +6423,28 @@ var ts; } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { - ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } } var res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } if (line < lineStarts.length - 1) { ts.Debug.assert(res < lineStarts[line + 1]); } @@ -6407,6 +6883,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6417,8 +6894,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, - isIdentifier: function () { return token === 71 /* Identifier */ || token > 107 /* LastReservedWord */; }, - isReservedWord: function () { return token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */; }, + isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; }, isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, @@ -6436,6 +6913,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6511,18 +6989,29 @@ var ts; end = pos; } } + var result; if (tokenFlags & 512 /* ContainsSeparator */) { - var result = mainFragment; + result = mainFragment; if (decimalFragment) { result += "." + decimalFragment; } if (scientificFragment) { result += scientificFragment; } - return "" + +result; } else { - return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + return { + type: 8 /* NumericLiteral */, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type: type, value: tokenValue }; } } function scanOctalDigits() { @@ -6537,21 +7026,21 @@ var ts; * returning -1 if the given number is unavailable. */ function scanExactNumberOfHexDigits(count, canHaveSeparators) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; } /** * Scans as many hexadecimal digits as are available in the text, - * returning -1 if the given number of digits was unavailable. + * returning "" if the given number of digits was unavailable. */ function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { - var digits = 0; - var value = 0; + var valueChars = []; var allowSeparator = false; var isPreviousTokenSeparator = false; - while (digits < minCount || scanAsManyAsPossible) { + while (valueChars.length < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); if (canHaveSeparators && ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; @@ -6569,29 +7058,24 @@ var ts; continue; } allowSeparator = canHaveSeparators; - if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { - value = value * 16 + ch - 48 /* _0 */; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase } - else if (ch >= 65 /* A */ && ch <= 70 /* F */) { - value = value * 16 + ch - 65 /* A */ + 10; - } - else if (ch >= 97 /* a */ && ch <= 102 /* f */) { - value = value * 16 + ch - 97 /* a */ + 10; - } - else { + else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) || + (ch >= 97 /* a */ && ch <= 102 /* f */))) { break; } + valueChars.push(ch); pos++; - digits++; isPreviousTokenSeparator = false; } - if (digits < minCount) { - value = -1; + if (valueChars.length < minCount) { + valueChars = []; } if (text.charCodeAt(pos - 1) === 95 /* _ */) { error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } - return value; + return String.fromCharCode.apply(String, valueChars); } function scanString(jsxAttributeString) { if (jsxAttributeString === void 0) { jsxAttributeString = false; } @@ -6643,7 +7127,7 @@ var ts; contents += text.substring(start, pos); tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; break; } var currChar = text.charCodeAt(pos); @@ -6651,14 +7135,14 @@ var ts; if (currChar === 96 /* backtick */) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; break; } // '${' if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 14 /* TemplateHead */ : 15 /* TemplateMiddle */; + resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */; break; } // Escape character @@ -6751,7 +7235,8 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; var isInvalidExtendedEscape = false; // Validate the value of the digit if (escapedValue < 0) { @@ -6833,20 +7318,18 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } - return token = 71 /* Identifier */; + return token = 72 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); - var value = 0; + var value = ""; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. - var numberOfDigits = 0; var separatorAllowed = false; var isPreviousTokenSeparator = false; while (true) { @@ -6868,29 +7351,45 @@ var ts; continue; } separatorAllowed = true; - var valueOfCh = ch - 48 /* _0 */; - if (!isDigit(ch) || valueOfCh >= base) { + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { break; } - value = value * base + valueOfCh; + value += text[pos]; pos++; - numberOfDigits++; isPreviousTokenSeparator = false; } - // Invalid binaryIntegerLiteral or octalIntegerLiteral - if (numberOfDigits === 0) { - return -1; - } if (text.charCodeAt(pos - 1) === 95 /* _ */) { // Literal ends with underscore - not allowed error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); - return value; } return value; } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110 /* n */) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9 /* BigIntLiteral */; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + var numericValue = tokenFlags & 128 /* BinarySpecifier */ + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & 256 /* OctalSpecifier */ + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return 8 /* NumericLiteral */; + } + } function scan() { + var _a; startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6929,6 +7428,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6942,82 +7459,87 @@ var ts; case 33 /* exclamation */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 35 /* ExclamationEqualsEqualsToken */; + return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */; } - return pos += 2, token = 33 /* ExclamationEqualsToken */; + return pos += 2, token = 34 /* ExclamationEqualsToken */; } pos++; - return token = 51 /* ExclamationToken */; + return token = 52 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); - return token = 9 /* StringLiteral */; + return token = 10 /* StringLiteral */; case 96 /* backtick */: return token = scanTemplateAndSetTokenValue(); case 37 /* percent */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 64 /* PercentEqualsToken */; + return pos += 2, token = 65 /* PercentEqualsToken */; } pos++; - return token = 42 /* PercentToken */; + return token = 43 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { - return pos += 2, token = 53 /* AmpersandAmpersandToken */; + return pos += 2, token = 54 /* AmpersandAmpersandToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 68 /* AmpersandEqualsToken */; + return pos += 2, token = 69 /* AmpersandEqualsToken */; } pos++; - return token = 48 /* AmpersandToken */; + return token = 49 /* AmpersandToken */; case 40 /* openParen */: pos++; - return token = 19 /* OpenParenToken */; + return token = 20 /* OpenParenToken */; case 41 /* closeParen */: pos++; - return token = 20 /* CloseParenToken */; + return token = 21 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 61 /* AsteriskEqualsToken */; + return pos += 2, token = 62 /* AsteriskEqualsToken */; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 62 /* AsteriskAsteriskEqualsToken */; + return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */; } - return pos += 2, token = 40 /* AsteriskAsteriskToken */; + return pos += 2, token = 41 /* AsteriskAsteriskToken */; } pos++; - return token = 39 /* AsteriskToken */; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } + return token = 40 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { - return pos += 2, token = 43 /* PlusPlusToken */; + return pos += 2, token = 44 /* PlusPlusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 59 /* PlusEqualsToken */; + return pos += 2, token = 60 /* PlusEqualsToken */; } pos++; - return token = 37 /* PlusToken */; + return token = 38 /* PlusToken */; case 44 /* comma */: pos++; - return token = 26 /* CommaToken */; + return token = 27 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { - return pos += 2, token = 44 /* MinusMinusToken */; + return pos += 2, token = 45 /* MinusMinusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 60 /* MinusEqualsToken */; + return pos += 2, token = 61 /* MinusEqualsToken */; } pos++; - return token = 38 /* MinusToken */; + return token = 39 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber(); + tokenValue = scanNumber().value; return token = 8 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { - return pos += 3, token = 24 /* DotDotDotToken */; + return pos += 3, token = 25 /* DotDotDotToken */; } pos++; - return token = 23 /* DotToken */; + return token = 24 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -7068,43 +7590,43 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 63 /* SlashEqualsToken */; + return pos += 2, token = 64 /* SlashEqualsToken */; } pos++; - return token = 41 /* SlashToken */; + return token = 42 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); - if (value < 0) { + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { error(ts.Diagnostics.Hexadecimal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0x" + tokenValue; tokenFlags |= 64 /* HexSpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 2); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { error(ts.Diagnostics.Binary_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0b" + tokenValue; tokenFlags |= 128 /* BinarySpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 8); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { error(ts.Diagnostics.Octal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0o" + tokenValue; tokenFlags |= 256 /* OctalSpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } // Try to parse as an octal if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { @@ -7125,14 +7647,14 @@ var ts; case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - tokenValue = scanNumber(); - return token = 8 /* NumericLiteral */; + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; case 58 /* colon */: pos++; - return token = 56 /* ColonToken */; + return token = 57 /* ColonToken */; case 59 /* semicolon */: pos++; - return token = 25 /* SemicolonToken */; + return token = 26 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7145,20 +7667,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 65 /* LessThanLessThanEqualsToken */; + return pos += 3, token = 66 /* LessThanLessThanEqualsToken */; } - return pos += 2, token = 45 /* LessThanLessThanToken */; + return pos += 2, token = 46 /* LessThanLessThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 30 /* LessThanEqualsToken */; + return pos += 2, token = 31 /* LessThanEqualsToken */; } if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */) { - return pos += 2, token = 28 /* LessThanSlashToken */; + return pos += 2, token = 29 /* LessThanSlashToken */; } pos++; - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7171,15 +7693,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 34 /* EqualsEqualsEqualsToken */; + return pos += 3, token = 35 /* EqualsEqualsEqualsToken */; } - return pos += 2, token = 32 /* EqualsEqualsToken */; + return pos += 2, token = 33 /* EqualsEqualsToken */; } if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { - return pos += 2, token = 36 /* EqualsGreaterThanToken */; + return pos += 2, token = 37 /* EqualsGreaterThanToken */; } pos++; - return token = 58 /* EqualsToken */; + return token = 59 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7191,25 +7713,25 @@ var ts; } } pos++; - return token = 29 /* GreaterThanToken */; + return token = 30 /* GreaterThanToken */; case 63 /* question */: pos++; - return token = 55 /* QuestionToken */; + return token = 56 /* QuestionToken */; case 91 /* openBracket */: pos++; - return token = 21 /* OpenBracketToken */; + return token = 22 /* OpenBracketToken */; case 93 /* closeBracket */: pos++; - return token = 22 /* CloseBracketToken */; + return token = 23 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 70 /* CaretEqualsToken */; + return pos += 2, token = 71 /* CaretEqualsToken */; } pos++; - return token = 50 /* CaretToken */; + return token = 51 /* CaretToken */; case 123 /* openBrace */: pos++; - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; case 124 /* bar */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7221,22 +7743,22 @@ var ts; } } if (text.charCodeAt(pos + 1) === 124 /* bar */) { - return pos += 2, token = 54 /* BarBarToken */; + return pos += 2, token = 55 /* BarBarToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 69 /* BarEqualsToken */; + return pos += 2, token = 70 /* BarEqualsToken */; } pos++; - return token = 49 /* BarToken */; + return token = 50 /* BarToken */; case 125 /* closeBrace */: pos++; - return token = 18 /* CloseBraceToken */; + return token = 19 /* CloseBraceToken */; case 126 /* tilde */: pos++; - return token = 52 /* TildeToken */; + return token = 53 /* TildeToken */; case 64 /* at */: pos++; - return token = 57 /* AtToken */; + return token = 58 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -7274,29 +7796,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 29 /* GreaterThanToken */) { + if (token === 30 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } - return pos += 2, token = 47 /* GreaterThanGreaterThanGreaterThanToken */; + return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 66 /* GreaterThanGreaterThanEqualsToken */; + return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */; } pos++; - return token = 46 /* GreaterThanGreaterThanToken */; + return token = 47 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { pos++; - return token = 31 /* GreaterThanEqualsToken */; + return token = 32 /* GreaterThanEqualsToken */; } } return token; } function reScanSlashToken() { - if (token === 41 /* SlashToken */ || token === 63 /* SlashEqualsToken */) { + if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -7341,7 +7863,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12 /* RegularExpressionLiteral */; + token = 13 /* RegularExpressionLiteral */; } return token; } @@ -7349,7 +7871,7 @@ var ts; * Unconditionally back up and scan a template expression portion. */ function reScanTemplateToken() { - ts.Debug.assert(token === 18 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -7366,14 +7888,14 @@ var ts; if (char === 60 /* lessThan */) { if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; - return token = 28 /* LessThanSlashToken */; + return token = 29 /* LessThanSlashToken */; } pos++; - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; } if (char === 123 /* openBrace */) { pos++; - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; } // First non-whitespace character on this line. var firstNonWhitespace = 0; @@ -7405,7 +7927,7 @@ var ts; } pos++; } - return firstNonWhitespace === -1 ? 11 /* JsxTextAllWhiteSpaces */ : 10 /* JsxText */; + return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -7431,7 +7953,7 @@ var ts; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(/*jsxAttributeString*/ true); - return token = 9 /* StringLiteral */; + return token = 10 /* StringLiteral */; default: // If this scans anything other than `{`, it's a parse error. return scan(); @@ -7455,43 +7977,43 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - return token = 57 /* AtToken */; + return token = 58 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - return token = 39 /* AsteriskToken */; + return token = 40 /* AsteriskToken */; case 123 /* openBrace */: - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; case 125 /* closeBrace */: - return token = 18 /* CloseBraceToken */; + return token = 19 /* CloseBraceToken */; case 91 /* openBracket */: - return token = 21 /* OpenBracketToken */; + return token = 22 /* OpenBracketToken */; case 93 /* closeBracket */: - return token = 22 /* CloseBracketToken */; + return token = 23 /* CloseBracketToken */; case 60 /* lessThan */: - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; case 61 /* equals */: - return token = 58 /* EqualsToken */; + return token = 59 /* EqualsToken */; case 44 /* comma */: - return token = 26 /* CommaToken */; + return token = 27 /* CommaToken */; case 46 /* dot */: - return token = 23 /* DotToken */; + return token = 24 /* DotToken */; case 96 /* backtick */: while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { pos++; } tokenValue = text.substring(tokenPos + 1, pos); pos++; - return token = 13 /* NoSubstitutionTemplateLiteral */; + return token = 14 /* NoSubstitutionTemplateLiteral */; } if (isIdentifierStart(ch, 6 /* Latest */)) { while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7568,10 +8090,12 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); -/** Non-internal stuff goes here */ var ts; (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -7588,7 +8112,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7635,7 +8158,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -7644,7 +8166,9 @@ var ts; writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, - writeSymbol: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, getTextPos: function () { return str.length; }, getLine: function () { return 0; }, getColumn: function () { return 0; }, @@ -7670,22 +8194,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7790,6 +8301,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -7850,7 +8367,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 277 /* SourceFile */) { + while (node && node.kind !== 279 /* SourceFile */) { node = node.parent; } return node; @@ -7858,11 +8375,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 216 /* Block */: - case 244 /* CaseBlock */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return true; } return false; @@ -7996,7 +8513,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8014,12 +8531,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8046,35 +8571,37 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) || + ts.isBigIntLiteral(node))) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (node.singleQuote) { return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; } else { return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; } - case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return "`" + escapeText(node.text, 96 /* backtick */) + "`"; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: // tslint:disable-next-line no-invalid-template-strings return "`" + escapeText(node.text, 96 /* backtick */) + "${"; - case 15 /* TemplateMiddle */: + case 16 /* TemplateMiddle */: // tslint:disable-next-line no-invalid-template-strings return "}" + escapeText(node.text, 96 /* backtick */) + "${"; - case 16 /* TemplateTail */: + case 17 /* TemplateTail */: return "}" + escapeText(node.text, 96 /* backtick */) + "`"; case 8 /* NumericLiteral */: - case 12 /* RegularExpressionLiteral */: + case 9 /* BigIntLiteral */: + case 13 /* RegularExpressionLiteral */: return node.text; } return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -8097,15 +8624,15 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 235 /* VariableDeclaration */ && node.parent.kind === 272 /* CatchClause */; + return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { - return ts.isModuleDeclaration(node) && node.name.kind === 9 /* StringLiteral */; + return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */; } ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { @@ -8129,11 +8656,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 242 /* ModuleDeclaration */ && (!node.body); + return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 277 /* SourceFile */ || - node.kind === 242 /* ModuleDeclaration */ || + return node.kind === 279 /* SourceFile */ || + node.kind === 244 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -8150,9 +8677,9 @@ var ts; // - 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 switch (node.parent.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.isExternalModule(node.parent); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; @@ -8168,22 +8695,22 @@ var ts; ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 277 /* SourceFile */: - case 244 /* CaseBlock */: - case 272 /* CatchClause */: - case 242 /* ModuleDeclaration */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 274 /* CatchClause */: + case 244 /* ModuleDeclaration */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; - case 216 /* Block */: + case 218 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -8193,9 +8720,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: - case 291 /* JSDocSignature */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 293 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -8205,25 +8732,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 287 /* JSDocFunctionType */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; default: ts.assertType(node); @@ -8233,8 +8760,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: return true; default: return false; @@ -8243,15 +8770,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 217 /* VariableStatement */: - case 238 /* ClassDeclaration */: - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 219 /* VariableStatement */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: return true; default: return false; @@ -8281,12 +8808,13 @@ var ts; ts.getNameFromIndexInfo = getNameFromIndexInfo; function getTextOfPropertyName(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return name.escapedText; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: return ts.Debug.assertNever(name); @@ -8295,11 +8823,11 @@ var ts; ts.getTextOfPropertyName = getTextOfPropertyName; function entityNameToString(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); default: throw ts.Debug.assertNever(name); @@ -8344,7 +8872,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 216 /* Block */) { + if (node.body && node.body.kind === 218 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -8358,7 +8886,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* 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 @@ -8367,25 +8895,25 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 240 /* TypeAliasDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: errorNode = node.name; break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -8421,6 +8949,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8430,11 +8962,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 189 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; + return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 189 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { @@ -8442,20 +8974,20 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 219 /* ExpressionStatement */ - && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 221 /* ExpressionStatement */ + && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return node.kind !== 10 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 149 /* Parameter */ || - node.kind === 148 /* TypeParameter */ || - node.kind === 194 /* FunctionExpression */ || - node.kind === 195 /* ArrowFunction */ || - node.kind === 193 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 151 /* Parameter */ || + node.kind === 150 /* TypeParameter */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 197 /* ArrowFunction */ || + node.kind === 195 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -8471,46 +9003,48 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 181 /* LastTypeNode */) { + if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) { return true; } switch (node.kind) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 134 /* NumberKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 140 /* UndefinedKeyword */: - case 131 /* NeverKeyword */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: return true; - case 105 /* VoidKeyword */: - return node.parent.kind !== 198 /* VoidExpression */; - case 209 /* ExpressionWithTypeArguments */: + case 106 /* VoidKeyword */: + return node.parent.kind !== 200 /* VoidExpression */; + case 211 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 148 /* TypeParameter */: - return node.parent.kind === 179 /* MappedType */ || node.parent.kind === 174 /* InferType */; + case 150 /* TypeParameter */: + return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container - case 71 /* Identifier */: + case 72 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 189 /* 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 === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 187 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 146 /* QualifiedName */: - case 187 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: { + case 148 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + case 100 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 165 /* TypeQuery */) { + if (parent.kind === 167 /* TypeQuery */) { return false; } - if (parent.kind === 181 /* ImportType */) { + if (parent.kind === 183 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -8519,40 +9053,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 181 /* LastTypeNode */) { + if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return node === parent.constraint; - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return node === parent.constraint; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 149 /* Parameter */: - case 235 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: return node === parent.type; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return node === parent.type; - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return node === parent.type; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return node === parent.type; - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -8577,23 +9111,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitor(node); - case 244 /* CaseBlock */: - case 216 /* Block */: - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 229 /* WithStatement */: - case 230 /* SwitchStatement */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 231 /* LabeledStatement */: - case 233 /* TryStatement */: - case 272 /* CatchClause */: + case 246 /* CaseBlock */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -8603,26 +9137,26 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 241 /* EnumDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* 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. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 147 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 149 /* 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(node.name.expression); @@ -8645,10 +9179,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 167 /* ArrayType */) { + if (node && node.kind === 169 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 162 /* TypeReference */) { + else if (node && node.kind === 164 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -8658,12 +9192,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 166 /* TypeLiteral */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 168 /* TypeLiteral */: return node.members; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return node.properties; } } @@ -8671,14 +9205,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 184 /* BindingElement */: - case 276 /* EnumMember */: - case 149 /* Parameter */: - case 273 /* PropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 274 /* ShorthandPropertyAssignment */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 278 /* EnumMember */: + case 151 /* Parameter */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 276 /* ShorthandPropertyAssignment */: + case 237 /* VariableDeclaration */: return true; } } @@ -8690,8 +9224,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 236 /* VariableDeclarationList */ - && node.parent.parent.kind === 217 /* VariableStatement */; + return node.parent.kind === 238 /* VariableDeclarationList */ + && node.parent.parent.kind === 219 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -8702,13 +9236,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return true; } return false; @@ -8719,7 +9253,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 231 /* LabeledStatement */) { + if (node.statement.kind !== 233 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -8727,17 +9261,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 216 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 186 /* ObjectLiteralExpression */; + return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 154 /* MethodDeclaration */ && - (node.parent.kind === 186 /* ObjectLiteralExpression */ || - node.parent.kind === 207 /* ClassExpression */); + return node.kind === 156 /* MethodDeclaration */ && + (node.parent.kind === 188 /* ObjectLiteralExpression */ || + node.parent.kind === 209 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -8750,7 +9284,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 273 /* PropertyAssignment */) { + if (property.kind === 275 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -8787,14 +9321,14 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 277 /* SourceFile */); + ts.Debug.assert(node.kind !== 279 /* SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* 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 @@ -8809,9 +9343,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8822,26 +9356,26 @@ var ts; node = node.parent; } break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 242 /* ModuleDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 241 /* EnumDeclaration */: - case 277 /* SourceFile */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 244 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 243 /* EnumDeclaration */: + case 279 /* SourceFile */: return node; } } @@ -8851,9 +9385,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return container; } } @@ -8875,27 +9409,27 @@ var ts; return node; } switch (node.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: node = node.parent; break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return node; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8911,14 +9445,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 194 /* FunctionExpression */ || func.kind === 195 /* ArrowFunction */) { + if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 193 /* ParenthesizedExpression */) { + while (parent.kind === 195 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 189 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -8929,8 +9463,8 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) - && node.expression.kind === 97 /* SuperKeyword */; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 98 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; /** @@ -8938,20 +9472,20 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) - && node.expression.kind === 99 /* ThisKeyword */; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 100 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; - case 71 /* Identifier */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 148 /* QualifiedName */: return node; } return undefined; @@ -8959,10 +9493,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return node.tag; - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -8971,25 +9505,25 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: // classes are valid targets return true; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 238 /* ClassDeclaration */; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: + return parent.kind === 240 /* ClassDeclaration */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 238 /* ClassDeclaration */; - case 149 /* Parameter */: + && parent.kind === 240 /* ClassDeclaration */; + case 151 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 155 /* Constructor */ - || parent.kind === 154 /* MethodDeclaration */ - || parent.kind === 157 /* SetAccessor */) - && grandparent.kind === 238 /* ClassDeclaration */; + && (parent.kind === 157 /* Constructor */ + || parent.kind === 156 /* MethodDeclaration */ + || parent.kind === 159 /* SetAccessor */) + && grandparent.kind === 240 /* ClassDeclaration */; } return false; } @@ -9005,10 +9539,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 154 /* MethodDeclaration */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 159 /* SetAccessor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -9017,9 +9551,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 260 /* JsxOpeningElement */ || - parent.kind === 259 /* JsxSelfClosingElement */ || - parent.kind === 261 /* JsxClosingElement */) { + if (parent.kind === 262 /* JsxOpeningElement */ || + parent.kind === 261 /* JsxSelfClosingElement */ || + parent.kind === 263 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -9027,56 +9561,57 @@ var ts; ts.isJSXTagName = isJSXTagName; function isExpressionNode(node) { switch (node.kind) { - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 12 /* RegularExpressionLiteral */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 191 /* TaggedTemplateExpression */: - case 210 /* AsExpression */: - case 192 /* TypeAssertionExpression */: - case 211 /* NonNullExpression */: - case 193 /* ParenthesizedExpression */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: - case 195 /* ArrowFunction */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: - case 202 /* BinaryExpression */: - case 203 /* ConditionalExpression */: - case 206 /* SpreadElement */: - case 204 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 208 /* OmittedExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 205 /* YieldExpression */: - case 199 /* AwaitExpression */: - case 212 /* MetaProperty */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 13 /* RegularExpressionLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 212 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 208 /* SpreadElement */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 210 /* OmittedExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 207 /* YieldExpression */: + case 201 /* AwaitExpression */: + case 214 /* MetaProperty */: return true; - case 146 /* QualifiedName */: - while (node.parent.kind === 146 /* QualifiedName */) { + case 148 /* QualifiedName */: + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node); - case 71 /* Identifier */: - if (node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node)) { + return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node); + case 72 /* Identifier */: + if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 99 /* ThisKeyword */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: return isInExpressionContext(node); default: return false; @@ -9086,49 +9621,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 276 /* EnumMember */: - case 273 /* PropertyAssignment */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 186 /* BindingElement */: return parent.initializer === node; - case 219 /* ExpressionStatement */: - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 228 /* ReturnStatement */: - case 229 /* WithStatement */: - case 230 /* SwitchStatement */: - case 269 /* CaseClause */: - case 232 /* ThrowStatement */: + case 221 /* ExpressionStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 230 /* ReturnStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 234 /* ThrowStatement */: return parent.expression === node; - case 223 /* ForStatement */: + case 225 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 236 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 236 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) || forInStatement.expression === node; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return node === parent.expression; - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return node === parent.expression; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return node === parent.expression; - case 150 /* Decorator */: - case 268 /* JsxExpression */: - case 267 /* JsxSpreadAttribute */: - case 275 /* SpreadAssignment */: + case 152 /* Decorator */: + case 270 /* JsxExpression */: + case 269 /* JsxSpreadAttribute */: + case 277 /* SpreadAssignment */: return true; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -9136,7 +9671,7 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */; + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -9145,21 +9680,21 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9173,15 +9708,15 @@ var ts; ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && - (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */); + (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { - if (callExpression.kind !== 189 /* CallExpression */) { + if (callExpression.kind !== 191 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 /* Identifier */ || expression.escapedText !== "require") { + if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") { return false; } if (args.length !== 1) { @@ -9199,29 +9734,29 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; decl = node.parent; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.right === node) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) { name = node.parent.left; decl = name; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54 /* BarBarToken */) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) { if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { name = node.parent.parent.name; decl = node.parent.parent; } - else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.parent.right === node.parent) { + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) { name = node.parent.parent.left; decl = name; } @@ -9229,42 +9764,55 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && - ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; } return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { - if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9273,47 +9821,47 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 194 /* FunctionExpression */ || - initializer.kind === 207 /* ClassExpression */ || - initializer.kind === 195 /* ArrowFunction */) { + if (initializer.kind === 196 /* FunctionExpression */ || + initializer.kind === 209 /* ClassExpression */ || + initializer.kind === 197 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : - ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { - var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; - if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) { return parent.left; } } @@ -9321,7 +9869,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9336,7 +9884,7 @@ var ts; return name.escapedText === initializer.escapedText; } if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { - return (initializer.expression.kind === 99 /* ThisKeyword */ || + return (initializer.expression.kind === 100 /* ThisKeyword */ || ts.isIdentifier(initializer.expression) && (initializer.expression.escapedText === "window" || initializer.expression.escapedText === "self" || @@ -9365,13 +9913,36 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { - if (expr.operatorToken.kind !== 58 /* EqualsToken */ || + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 59 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } @@ -9380,13 +9951,13 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { - if (lhs.expression.kind === 99 /* ThisKeyword */) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + else if (isModuleExportsPropertyAccessExpression(lhs)) { // module.exports = expr return 2 /* ModuleExports */; } @@ -9411,7 +9982,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9420,12 +9991,12 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && - expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; @@ -9434,7 +10005,7 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { @@ -9443,14 +10014,14 @@ var ts; ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return node.parent; - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return node.parent.parent; - case 189 /* CallExpression */: - return node.parent; - case 180 /* LiteralType */: + case 191 /* CallExpression */: + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; + case 182 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -9460,12 +10031,12 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return node.moduleSpecifier; - case 246 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 257 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 181 /* ImportType */: + case 248 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 183 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; default: return ts.Debug.assertNever(node); @@ -9474,11 +10045,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return undefined; default: return ts.Debug.assertNever(node); @@ -9486,19 +10057,19 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 247 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 149 /* Parameter */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 274 /* ShorthandPropertyAssignment */: - case 273 /* PropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 151 /* Parameter */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 276 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -9506,14 +10077,13 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 287 /* JSDocFunctionType */ && - node.parameters.length > 0 && - node.parameters[0].name && - node.parameters[0].name.escapedText === "new"; + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -9523,27 +10093,27 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 /* EqualsToken */ + node.expression.operatorToken.kind === 59 /* EqualsToken */ ? node.expression.right : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 /* BarBarToken */ + node.expression.right.operatorToken.kind === 55 /* BarBarToken */ ? node.expression.right.right : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return node.initializer; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return node.initializer; } } @@ -9553,7 +10123,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 242 /* ModuleDeclaration */ + node.body.kind === 244 /* ModuleDeclaration */ ? node.body : undefined; } @@ -9568,10 +10138,14 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.addRange(result, node.jsDoc); } - if (node.kind === 149 /* Parameter */) { + if (node.kind === 151 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 150 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9579,11 +10153,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 273 /* PropertyAssignment */ || - parent.kind === 152 /* PropertyDeclaration */ || - parent.kind === 219 /* ExpressionStatement */ && node.kind === 187 /* PropertyAccessExpression */ || + if (parent.kind === 275 /* PropertyAssignment */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ || getNestedModuleDeclaration(parent) || - ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */) { + ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) { return parent; } // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. @@ -9594,7 +10168,7 @@ var ts; // var x = function(name) { return name.length; } else if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node || - ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */)) { + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) { return parent.parent; } else if (parent.parent && parent.parent.parent && @@ -9617,7 +10191,7 @@ var ts; if (!decl) { return undefined; } - var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; @@ -9652,7 +10226,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 288 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9665,31 +10239,31 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? - binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; - return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 193 /* ParenthesizedExpression */: - case 185 /* ArrayLiteralExpression */: - case 206 /* SpreadElement */: - case 211 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 187 /* ArrayLiteralExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: node = parent; break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -9716,22 +10290,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 216 /* Block */: - case 217 /* VariableStatement */: - case 229 /* WithStatement */: - case 220 /* IfStatement */: - case 230 /* SwitchStatement */: - case 244 /* CaseBlock */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 231 /* LabeledStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 233 /* TryStatement */: - case 272 /* CatchClause */: + case 218 /* Block */: + case 219 /* VariableStatement */: + case 231 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: return true; } return false; @@ -9748,27 +10322,33 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 175 /* ParenthesizedType */); + return walkUp(node, 177 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 193 /* ParenthesizedExpression */); + return walkUp(node, 195 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function skipParentheses(node) { - while (node.kind === 193 /* ParenthesizedExpression */) { + while (node.kind === 195 /* ParenthesizedExpression */) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { + if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 196 /* DeleteExpression */; + return node && node.kind === 198 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -9786,35 +10366,39 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 72 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { - return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 147 /* ComputedPropertyName */ && + return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 149 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -9822,32 +10406,32 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 276 /* EnumMember */: - case 273 /* PropertyAssignment */: - case 187 /* PropertyAccessExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 189 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: // Name on right hand side of dot in a type query or type reference if (parent.right === node) { - while (parent.kind === 146 /* QualifiedName */) { + while (parent.kind === 148 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 165 /* TypeQuery */ || parent.kind === 162 /* TypeReference */; + return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */; } return false; - case 184 /* BindingElement */: - case 251 /* ImportSpecifier */: + case 186 /* BindingElement */: + case 253 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 255 /* ExportSpecifier */: - case 265 /* JsxAttribute */: + case 257 /* ExportSpecifier */: + case 267 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -9862,15 +10446,16 @@ var ts; // export { x as } from ... // export = // export default + // module.exports = function isAliasSymbolDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ || - node.kind === 245 /* NamespaceExportDeclaration */ || - node.kind === 248 /* ImportClause */ && !!node.name || - node.kind === 249 /* NamespaceImport */ || - node.kind === 251 /* ImportSpecifier */ || - node.kind === 255 /* ExportSpecifier */ || - node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + return node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + node.kind === 250 /* ImportClause */ && !!node.name || + node.kind === 251 /* NamespaceImport */ || + node.kind === 253 /* ImportSpecifier */ || + node.kind === 257 /* ExportSpecifier */ || + node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9879,7 +10464,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -9890,12 +10475,12 @@ var ts; } ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; function getClassExtendsHeritageElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; @@ -9907,7 +10492,7 @@ var ts; } ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -9941,11 +10526,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 72 /* FirstKeyword */ <= token && token <= 145 /* LastKeyword */; + return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 117 /* FirstContextualKeyword */ <= token && token <= 145 /* LastContextualKeyword */; + return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -9957,6 +10542,11 @@ var ts; return token !== undefined && isNonContextualKeyword(token); } ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; function isTrivia(token) { return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; } @@ -9975,14 +10565,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (hasModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -9996,10 +10586,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256 /* Async */); @@ -10024,7 +10614,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 147 /* ComputedPropertyName */ && + return name.kind === 149 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -10040,12 +10630,12 @@ var ts; ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return name.escapedText; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); @@ -10061,9 +10651,9 @@ var ts; ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: return true; default: @@ -10072,11 +10662,11 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? ts.idText(node) : node.text; + return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -10091,7 +10681,7 @@ var ts; * Includes the word "Symbol" with unicode escapes */ function isESSymbolIdentifier(node) { - return node.kind === 71 /* Identifier */ && node.escapedText === "Symbol"; + return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { @@ -10100,11 +10690,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 149 /* Parameter */; + return root.kind === 151 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 184 /* BindingElement */) { + while (node.kind === 186 /* BindingElement */) { node = node.parent.parent; } return node; @@ -10112,15 +10702,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 155 /* Constructor */ - || kind === 194 /* FunctionExpression */ - || kind === 237 /* FunctionDeclaration */ - || kind === 195 /* ArrowFunction */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 242 /* ModuleDeclaration */ - || kind === 277 /* SourceFile */; + return kind === 157 /* Constructor */ + || kind === 196 /* FunctionExpression */ + || kind === 239 /* FunctionDeclaration */ + || kind === 197 /* ArrowFunction */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 244 /* ModuleDeclaration */ + || kind === 279 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -10139,38 +10729,38 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 190 /* NewExpression */: + case 192 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 200 /* PrefixUnaryExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 199 /* AwaitExpression */: - case 203 /* ConditionalExpression */: - case 205 /* YieldExpression */: + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: return 1 /* Right */; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (operator) { - case 40 /* AsteriskAsteriskToken */: - case 58 /* EqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 69 /* BarEqualsToken */: + case 41 /* AsteriskAsteriskToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: return 1 /* Right */; } } @@ -10179,15 +10769,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 202 /* BinaryExpression */) { + if (expression.kind === 204 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 200 /* PrefixUnaryExpression */ || expression.kind === 201 /* PostfixUnaryExpression */) { + else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -10197,116 +10787,116 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return 0; - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return 1; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return 2; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return 4; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (operatorKind) { - case 26 /* CommaToken */: + case 27 /* CommaToken */: return 0; - case 58 /* EqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 69 /* BarEqualsToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: return 3; default: return getBinaryOperatorPrecedence(operatorKind); } - case 200 /* PrefixUnaryExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 199 /* AwaitExpression */: + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: return 16; - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return 17; - case 189 /* CallExpression */: + case 191 /* CallExpression */: return 18; - case 190 /* NewExpression */: + case 192 /* NewExpression */: return hasArguments ? 19 : 18; - case 191 /* TaggedTemplateExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 193 /* TaggedTemplateExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return 19; - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 71 /* Identifier */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 72 /* Identifier */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 207 /* ClassExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 193 /* ParenthesizedExpression */: - case 208 /* OmittedExpression */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 195 /* ParenthesizedExpression */: + case 210 /* OmittedExpression */: return 20; default: return -1; } } ts.getOperatorPrecedence = getOperatorPrecedence; - /* @internal */ function getBinaryOperatorPrecedence(kind) { switch (kind) { - case 54 /* BarBarToken */: + case 55 /* BarBarToken */: return 5; - case 53 /* AmpersandAmpersandToken */: + case 54 /* AmpersandAmpersandToken */: return 6; - case 49 /* BarToken */: + case 50 /* BarToken */: return 7; - case 50 /* CaretToken */: + case 51 /* CaretToken */: return 8; - case 48 /* AmpersandToken */: + case 49 /* AmpersandToken */: return 9; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: return 10; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: return 11; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return 12; - case 37 /* PlusToken */: - case 38 /* MinusToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: return 13; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: return 14; - case 40 /* AsteriskAsteriskToken */: + case 41 /* AsteriskAsteriskToken */: return 15; } // -1 is lower than all other precedences. Returning it will cause binary expression @@ -10374,7 +10964,7 @@ var ts; if (fileName) { return fileDiagnostics.get(fileName) || []; } - var fileDiags = ts.flatMap(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); if (!nonFileDiagnostics.length) { return fileDiags; } @@ -10432,7 +11022,7 @@ var ts; } function isIntrinsicJsxName(name) { var ch = name.charCodeAt(0); - return (ch >= 97 /* a */ && ch <= 122 /* z */) || name.indexOf("-") > -1; + return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-"); } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -10515,16 +11105,10 @@ var ts; lineStart = true; } } - function writeTextOfNode(text, node) { - var s = getTextOfNodeFromSourceText(text, node); - write(s); - updateLineCountAndPosFor(s); - } reset(); return { write: write, rawWrite: rawWrite, - writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, increaseIndent: function () { indent++; }, @@ -10547,10 +11131,77 @@ var ts; writePunctuation: write, writeSpace: write, writeStringLiteral: write, - writeSymbol: write + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write }; } ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; function getResolvedExternalModuleName(host, file, referenceFile) { return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } @@ -10613,7 +11264,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10627,7 +11278,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10686,11 +11337,11 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { - return id.originalKeywordKind === 99 /* ThisKeyword */; + return id.originalKeywordKind === 100 /* ThisKeyword */; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { @@ -10701,10 +11352,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 156 /* GetAccessor */) { + if (accessor.kind === 158 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 157 /* SetAccessor */) { + else if (accessor.kind === 159 /* SetAccessor */) { setAccessor = accessor; } else { @@ -10724,10 +11375,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 156 /* GetAccessor */ && !getAccessor) { + if (member.kind === 158 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 157 /* SetAccessor */ && !setAccessor) { + if (member.kind === 159 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -10748,7 +11399,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10764,7 +11415,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -10773,7 +11424,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 289 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -10807,13 +11458,13 @@ var ts; function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { if (comments && comments.length > 0) { if (leadingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } var emitInterveningSeparator = false; for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { var comment = comments_1[_i]; if (emitInterveningSeparator) { - writer.write(" "); + writer.writeSpace(" "); emitInterveningSeparator = false; } writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); @@ -10825,7 +11476,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -10943,7 +11594,7 @@ var ts; } else { // Single line comment of style //.... - writer.write(text.substring(commentPos, commentEnd)); + writer.writeComment(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; @@ -10952,14 +11603,14 @@ var ts; var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { // trimmed forward and ending spaces text - writer.write(currentLineText); + writer.writeComment(currentLineText); if (end !== commentEnd) { writer.writeLine(); } } else { // Empty string - make sure we write empty line - writer.writeLiteral(newLine); + writer.rawWrite(newLine); } } function calculateIndent(text, pos, end) { @@ -11013,7 +11664,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4 /* NestedNamespace */ || (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace)) { + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* Export */; } return flags; @@ -11021,44 +11672,49 @@ var ts; ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { - case 115 /* StaticKeyword */: return 32 /* Static */; - case 114 /* PublicKeyword */: return 4 /* Public */; - case 113 /* ProtectedKeyword */: return 16 /* Protected */; - case 112 /* PrivateKeyword */: return 8 /* Private */; - case 117 /* AbstractKeyword */: return 128 /* Abstract */; - case 84 /* ExportKeyword */: return 1 /* Export */; - case 124 /* DeclareKeyword */: return 2 /* Ambient */; - case 76 /* ConstKeyword */: return 2048 /* Const */; - case 79 /* DefaultKeyword */: return 512 /* Default */; - case 120 /* AsyncKeyword */: return 256 /* Async */; - case 132 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 116 /* StaticKeyword */: return 32 /* Static */; + case 115 /* PublicKeyword */: return 4 /* Public */; + case 114 /* ProtectedKeyword */: return 16 /* Protected */; + case 113 /* PrivateKeyword */: return 8 /* Private */; + case 118 /* AbstractKeyword */: return 128 /* Abstract */; + case 85 /* ExportKeyword */: return 1 /* Export */; + case 125 /* DeclareKeyword */: return 2 /* Ambient */; + case 77 /* ConstKeyword */: return 2048 /* Const */; + case 80 /* DefaultKeyword */: return 512 /* Default */; + case 121 /* AsyncKeyword */: return 256 /* Async */; + case 133 /* ReadonlyKeyword */: return 64 /* Readonly */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 54 /* BarBarToken */ - || token === 53 /* AmpersandAmpersandToken */ - || token === 51 /* ExclamationToken */; + return token === 55 /* BarBarToken */ + || token === 54 /* AmpersandAmpersandToken */ + || token === 52 /* ExclamationToken */; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 58 /* FirstAssignment */ && token <= 70 /* LastAssignment */; + return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment - ? node.operatorToken.kind === 58 /* EqualsToken */ + ? node.operatorToken.kind === 59 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) && ts.isLeftHandSideExpression(node.left); } @@ -11066,8 +11722,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 186 /* ObjectLiteralExpression */ - || kind === 185 /* ArrayLiteralExpression */; + return kind === 188 /* ObjectLiteralExpression */ + || kind === 187 /* ArrayLiteralExpression */; } return false; } @@ -11076,17 +11732,8 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; function isPropertyAccessEntityNameExpression(node) { @@ -11098,17 +11745,17 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 186 /* ObjectLiteralExpression */ && + return expression.kind === 188 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 185 /* ArrayLiteralExpression */ && + return expression.kind === 187 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -11120,10 +11767,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * 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. @@ -11262,6 +11909,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11352,6 +12021,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11449,8 +12120,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -11527,23 +12198,47 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 201 /* PostfixUnaryExpression */: - case 200 /* PrefixUnaryExpression */: + case 195 /* ParenthesizedExpression */: + return accessKind(parent); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: var operator = parent.operator; - return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 202 /* BinaryExpression */: + return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 204 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? - operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 275 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 187 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11634,7 +12329,7 @@ var ts; } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { - return type.flags & 131072 /* Object */ ? type.objectFlags : 0; + return type.flags & 524288 /* Object */ ? type.objectFlags : 0; } ts.getObjectFlags = getObjectFlags; function typeHasCallOrConstructSignatures(type, checker) { @@ -11685,6 +12380,31 @@ var ts; return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) + || kind === 120 /* AnyKeyword */ + || kind === 143 /* UnknownKeyword */ + || kind === 135 /* NumberKeyword */ + || kind === 146 /* BigIntKeyword */ + || kind === 136 /* ObjectKeyword */ + || kind === 123 /* BooleanKeyword */ + || kind === 138 /* StringKeyword */ + || kind === 139 /* SymbolKeyword */ + || kind === 100 /* ThisKeyword */ + || kind === 106 /* VoidKeyword */ + || kind === 141 /* UndefinedKeyword */ + || kind === 96 /* NullKeyword */ + || kind === 132 /* NeverKeyword */ + || kind === 211 /* ExpressionWithTypeArguments */ + || kind === 284 /* JSDocAllType */ + || kind === 285 /* JSDocUnknownType */ + || kind === 286 /* JSDocNullableType */ + || kind === 287 /* JSDocNonNullableType */ + || kind === 288 /* JSDocOptionalType */ + || kind === 289 /* JSDocFunctionType */ + || kind === 290 /* JSDocVariadicType */; + } + ts.isTypeNodeKind = isTypeNodeKind; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11769,13 +12489,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -11912,9 +12625,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 148 /* TypeParameter */) { + if (d && d.kind === 150 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 239 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) { return current; } } @@ -11922,7 +12635,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 155 /* Constructor */; + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11952,14 +12665,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 235 /* VariableDeclaration */) { + if (node.kind === 237 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 236 /* VariableDeclarationList */) { + if (node && node.kind === 238 /* VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 217 /* VariableStatement */) { + if (node && node.kind === 219 /* VariableStatement */) { flags |= getFlags(node); } return flags; @@ -12103,38 +12816,34 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; - case 219 /* ExpressionStatement */: + break; + case 221 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return expr.name; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; - case 193 /* ParenthesizedExpression */: { + break; + case 195 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 231 /* LabeledStatement */: { + case 233 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12153,31 +12862,36 @@ var ts; /** @internal */ function getNonAssignedNameOfDeclaration(declaration) { switch (declaration.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return declaration; - case 303 /* JSDocPropertyTag */: - case 297 /* JSDocParameterTag */: { + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 146 /* QualifiedName */) { + if (name.kind === 148 /* QualifiedName */) { return name.right; } break; } - case 202 /* BinaryExpression */: { + case 191 /* CallExpression */: + case 204 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: case 3 /* PrototypeProperty */: return expr.left.name; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr.arguments[1]; default: return undefined; } } - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 252 /* ExportAssignment */: { + case 254 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } @@ -12211,15 +12925,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12240,6 +12953,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12363,10 +13093,23 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -12384,684 +13127,688 @@ var ts; return node.kind === 8 /* NumericLiteral */; } ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9 /* BigIntLiteral */; + } + ts.isBigIntLiteral = isBigIntLiteral; function isStringLiteral(node) { - return node.kind === 9 /* StringLiteral */; + return node.kind === 10 /* StringLiteral */; } ts.isStringLiteral = isStringLiteral; function isJsxText(node) { - return node.kind === 10 /* JsxText */; + return node.kind === 11 /* JsxText */; } ts.isJsxText = isJsxText; function isRegularExpressionLiteral(node) { - return node.kind === 12 /* RegularExpressionLiteral */; + return node.kind === 13 /* RegularExpressionLiteral */; } ts.isRegularExpressionLiteral = isRegularExpressionLiteral; function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13 /* NoSubstitutionTemplateLiteral */; + return node.kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; // Pseudo-literals function isTemplateHead(node) { - return node.kind === 14 /* TemplateHead */; + return node.kind === 15 /* TemplateHead */; } ts.isTemplateHead = isTemplateHead; function isTemplateMiddle(node) { - return node.kind === 15 /* TemplateMiddle */; + return node.kind === 16 /* TemplateMiddle */; } ts.isTemplateMiddle = isTemplateMiddle; function isTemplateTail(node) { - return node.kind === 16 /* TemplateTail */; + return node.kind === 17 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; function isIdentifier(node) { - return node.kind === 71 /* Identifier */; + return node.kind === 72 /* Identifier */; } ts.isIdentifier = isIdentifier; // Names function isQualifiedName(node) { - return node.kind === 146 /* QualifiedName */; + return node.kind === 148 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 147 /* ComputedPropertyName */; + return node.kind === 149 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 148 /* TypeParameter */; + return node.kind === 150 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 149 /* Parameter */; + return node.kind === 151 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 150 /* Decorator */; + return node.kind === 152 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 151 /* PropertySignature */; + return node.kind === 153 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 152 /* PropertyDeclaration */; + return node.kind === 154 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 153 /* MethodSignature */; + return node.kind === 155 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 154 /* MethodDeclaration */; + return node.kind === 156 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 155 /* Constructor */; + return node.kind === 157 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 156 /* GetAccessor */; + return node.kind === 158 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 157 /* SetAccessor */; + return node.kind === 159 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 158 /* CallSignature */; + return node.kind === 160 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 159 /* ConstructSignature */; + return node.kind === 161 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 160 /* IndexSignature */; + return node.kind === 162 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 157 /* SetAccessor */ || node.kind === 156 /* GetAccessor */; + return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 161 /* TypePredicate */; + return node.kind === 163 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 162 /* TypeReference */; + return node.kind === 164 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 163 /* FunctionType */; + return node.kind === 165 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 164 /* ConstructorType */; + return node.kind === 166 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 165 /* TypeQuery */; + return node.kind === 167 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 166 /* TypeLiteral */; + return node.kind === 168 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 167 /* ArrayType */; + return node.kind === 169 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 168 /* TupleType */; + return node.kind === 170 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 171 /* UnionType */; + return node.kind === 173 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 172 /* IntersectionType */; + return node.kind === 174 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 173 /* ConditionalType */; + return node.kind === 175 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 174 /* InferType */; + return node.kind === 176 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 175 /* ParenthesizedType */; + return node.kind === 177 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 176 /* ThisType */; + return node.kind === 178 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 177 /* TypeOperator */; + return node.kind === 179 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 178 /* IndexedAccessType */; + return node.kind === 180 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 179 /* MappedType */; + return node.kind === 181 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 180 /* LiteralType */; + return node.kind === 182 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 181 /* ImportType */; + return node.kind === 183 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 182 /* ObjectBindingPattern */; + return node.kind === 184 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 183 /* ArrayBindingPattern */; + return node.kind === 185 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 184 /* BindingElement */; + return node.kind === 186 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 185 /* ArrayLiteralExpression */; + return node.kind === 187 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 186 /* ObjectLiteralExpression */; + return node.kind === 188 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 187 /* PropertyAccessExpression */; + return node.kind === 189 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 188 /* ElementAccessExpression */; + return node.kind === 190 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 189 /* CallExpression */; + return node.kind === 191 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 190 /* NewExpression */; + return node.kind === 192 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 191 /* TaggedTemplateExpression */; + return node.kind === 193 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 192 /* TypeAssertionExpression */; + return node.kind === 194 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 193 /* ParenthesizedExpression */; + return node.kind === 195 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 306 /* PartiallyEmittedExpression */) { + while (node.kind === 308 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 194 /* FunctionExpression */; + return node.kind === 196 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 195 /* ArrowFunction */; + return node.kind === 197 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 196 /* DeleteExpression */; + return node.kind === 198 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 197 /* TypeOfExpression */; + return node.kind === 199 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 198 /* VoidExpression */; + return node.kind === 200 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 199 /* AwaitExpression */; + return node.kind === 201 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 200 /* PrefixUnaryExpression */; + return node.kind === 202 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 201 /* PostfixUnaryExpression */; + return node.kind === 203 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 202 /* BinaryExpression */; + return node.kind === 204 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 203 /* ConditionalExpression */; + return node.kind === 205 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 204 /* TemplateExpression */; + return node.kind === 206 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 205 /* YieldExpression */; + return node.kind === 207 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 206 /* SpreadElement */; + return node.kind === 208 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 207 /* ClassExpression */; + return node.kind === 209 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 208 /* OmittedExpression */; + return node.kind === 210 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */; + return node.kind === 211 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 210 /* AsExpression */; + return node.kind === 212 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 211 /* NonNullExpression */; + return node.kind === 213 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 212 /* MetaProperty */; + return node.kind === 214 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; // Misc function isTemplateSpan(node) { - return node.kind === 214 /* TemplateSpan */; + return node.kind === 216 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 215 /* SemicolonClassElement */; + return node.kind === 217 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Block function isBlock(node) { - return node.kind === 216 /* Block */; + return node.kind === 218 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 217 /* VariableStatement */; + return node.kind === 219 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 218 /* EmptyStatement */; + return node.kind === 220 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 219 /* ExpressionStatement */; + return node.kind === 221 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 220 /* IfStatement */; + return node.kind === 222 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 221 /* DoStatement */; + return node.kind === 223 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 222 /* WhileStatement */; + return node.kind === 224 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 223 /* ForStatement */; + return node.kind === 225 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 224 /* ForInStatement */; + return node.kind === 226 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 225 /* ForOfStatement */; + return node.kind === 227 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 226 /* ContinueStatement */; + return node.kind === 228 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 227 /* BreakStatement */; + return node.kind === 229 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isBreakOrContinueStatement(node) { - return node.kind === 227 /* BreakStatement */ || node.kind === 226 /* ContinueStatement */; + return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 228 /* ReturnStatement */; + return node.kind === 230 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 229 /* WithStatement */; + return node.kind === 231 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 230 /* SwitchStatement */; + return node.kind === 232 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 231 /* LabeledStatement */; + return node.kind === 233 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 232 /* ThrowStatement */; + return node.kind === 234 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 233 /* TryStatement */; + return node.kind === 235 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 234 /* DebuggerStatement */; + return node.kind === 236 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 235 /* VariableDeclaration */; + return node.kind === 237 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 236 /* VariableDeclarationList */; + return node.kind === 238 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 237 /* FunctionDeclaration */; + return node.kind === 239 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 238 /* ClassDeclaration */; + return node.kind === 240 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 239 /* InterfaceDeclaration */; + return node.kind === 241 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 240 /* TypeAliasDeclaration */; + return node.kind === 242 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 241 /* EnumDeclaration */; + return node.kind === 243 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */; + return node.kind === 244 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 243 /* ModuleBlock */; + return node.kind === 245 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 244 /* CaseBlock */; + return node.kind === 246 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 245 /* NamespaceExportDeclaration */; + return node.kind === 247 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */; + return node.kind === 248 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 247 /* ImportDeclaration */; + return node.kind === 249 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 248 /* ImportClause */; + return node.kind === 250 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 249 /* NamespaceImport */; + return node.kind === 251 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 250 /* NamedImports */; + return node.kind === 252 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 251 /* ImportSpecifier */; + return node.kind === 253 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 252 /* ExportAssignment */; + return node.kind === 254 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 253 /* ExportDeclaration */; + return node.kind === 255 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 254 /* NamedExports */; + return node.kind === 256 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 255 /* ExportSpecifier */; + return node.kind === 257 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 256 /* MissingDeclaration */; + return node.kind === 258 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; // Module References function isExternalModuleReference(node) { - return node.kind === 257 /* ExternalModuleReference */; + return node.kind === 259 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 258 /* JsxElement */; + return node.kind === 260 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 259 /* JsxSelfClosingElement */; + return node.kind === 261 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 260 /* JsxOpeningElement */; + return node.kind === 262 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 261 /* JsxClosingElement */; + return node.kind === 263 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 262 /* JsxFragment */; + return node.kind === 264 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 263 /* JsxOpeningFragment */; + return node.kind === 265 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 264 /* JsxClosingFragment */; + return node.kind === 266 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 265 /* JsxAttribute */; + return node.kind === 267 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 266 /* JsxAttributes */; + return node.kind === 268 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 267 /* JsxSpreadAttribute */; + return node.kind === 269 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 268 /* JsxExpression */; + return node.kind === 270 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 269 /* CaseClause */; + return node.kind === 271 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 270 /* DefaultClause */; + return node.kind === 272 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 271 /* HeritageClause */; + return node.kind === 273 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 272 /* CatchClause */; + return node.kind === 274 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 273 /* PropertyAssignment */; + return node.kind === 275 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 274 /* ShorthandPropertyAssignment */; + return node.kind === 276 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 275 /* SpreadAssignment */; + return node.kind === 277 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 276 /* EnumMember */; + return node.kind === 278 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 277 /* SourceFile */; + return node.kind === 279 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 278 /* Bundle */; + return node.kind === 280 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 279 /* UnparsedSource */; + return node.kind === 281 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 281 /* JSDocTypeExpression */; + return node.kind === 283 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 282 /* JSDocAllType */; + return node.kind === 284 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 283 /* JSDocUnknownType */; + return node.kind === 285 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 284 /* JSDocNullableType */; + return node.kind === 286 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 285 /* JSDocNonNullableType */; + return node.kind === 287 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 286 /* JSDocOptionalType */; + return node.kind === 288 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 287 /* JSDocFunctionType */; + return node.kind === 289 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 288 /* JSDocVariadicType */; + return node.kind === 290 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 289 /* JSDocComment */; + return node.kind === 291 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 293 /* JSDocAugmentsTag */; + return node.kind === 295 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 294 /* JSDocClassTag */; + return node.kind === 296 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocEnumTag(node) { - return node.kind === 296 /* JSDocEnumTag */; + return node.kind === 298 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 299 /* JSDocThisTag */; + return node.kind === 301 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 297 /* JSDocParameterTag */; + return node.kind === 299 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 298 /* JSDocReturnTag */; + return node.kind === 300 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 300 /* JSDocTypeTag */; + return node.kind === 302 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 301 /* JSDocTemplateTag */; + return node.kind === 303 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 302 /* JSDocTypedefTag */; + return node.kind === 304 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 303 /* JSDocPropertyTag */; + return node.kind === 305 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */; + return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 290 /* JSDocTypeLiteral */; + return node.kind === 292 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocCallbackTag(node) { - return node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 297 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocSignature(node) { - return node.kind === 291 /* JSDocSignature */; + return node.kind === 293 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); @@ -13072,7 +13819,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 304 /* SyntaxList */; + return n.kind === 306 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13082,7 +13829,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 146 /* FirstNode */; + return kind >= 148 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13091,7 +13838,7 @@ var ts; * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 145 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */; } ts.isToken = isToken; // Node Arrays @@ -13103,7 +13850,7 @@ var ts; // Literals /* @internal */ function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */; + return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */; } ts.isLiteralKind = isLiteralKind; function isLiteralExpression(node) { @@ -13113,7 +13860,7 @@ var ts; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { - return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; + return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isTemplateLiteralToken(node) { @@ -13122,12 +13869,16 @@ var ts; ts.isTemplateLiteralToken = isTemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node) { var kind = node.kind; - return kind === 15 /* TemplateMiddle */ - || kind === 16 /* TemplateTail */; + return kind === 16 /* TemplateMiddle */ + || kind === 17 /* TemplateTail */; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isStringTextContainingNode(node) { - return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -13140,17 +13891,17 @@ var ts; /* @internal */ function isModifierKind(token) { switch (token) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 79 /* DefaultKeyword */: - case 84 /* ExportKeyword */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 115 /* StaticKeyword */: + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 80 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 116 /* StaticKeyword */: return true; } return false; @@ -13163,7 +13914,7 @@ var ts; ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */; + return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -13172,23 +13923,23 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 146 /* QualifiedName */ - || kind === 71 /* Identifier */; + return kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 9 /* StringLiteral */ + return kind === 72 /* Identifier */ + || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 147 /* ComputedPropertyName */; + || kind === 149 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 182 /* ObjectBindingPattern */ - || kind === 183 /* ArrayBindingPattern */; + return kind === 72 /* Identifier */ + || kind === 184 /* ObjectBindingPattern */ + || kind === 185 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -13203,13 +13954,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; default: return false; @@ -13218,14 +13969,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 163 /* FunctionType */: - case 287 /* JSDocFunctionType */: - case 164 /* ConstructorType */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 166 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -13240,29 +13991,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 155 /* Constructor */ - || kind === 152 /* PropertyDeclaration */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 160 /* IndexSignature */ - || kind === 215 /* SemicolonClassElement */; + return kind === 157 /* Constructor */ + || kind === 154 /* PropertyDeclaration */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 162 /* IndexSignature */ + || kind === 217 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */); + return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */); + return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return true; default: return false; @@ -13272,11 +14023,11 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 159 /* ConstructSignature */ - || kind === 158 /* CallSignature */ - || kind === 151 /* PropertySignature */ - || kind === 153 /* MethodSignature */ - || kind === 160 /* IndexSignature */; + return kind === 161 /* ConstructSignature */ + || kind === 160 /* CallSignature */ + || kind === 153 /* PropertySignature */ + || kind === 155 /* MethodSignature */ + || kind === 162 /* IndexSignature */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -13285,51 +14036,28 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 273 /* PropertyAssignment */ - || kind === 274 /* ShorthandPropertyAssignment */ - || kind === 275 /* SpreadAssignment */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 275 /* PropertyAssignment */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 277 /* SpreadAssignment */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type - function isTypeNodeKind(kind) { - return (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) - || kind === 119 /* AnyKeyword */ - || kind === 142 /* UnknownKeyword */ - || kind === 134 /* NumberKeyword */ - || kind === 135 /* ObjectKeyword */ - || kind === 122 /* BooleanKeyword */ - || kind === 137 /* StringKeyword */ - || kind === 138 /* SymbolKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 105 /* VoidKeyword */ - || kind === 140 /* UndefinedKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 131 /* NeverKeyword */ - || kind === 209 /* ExpressionWithTypeArguments */ - || kind === 282 /* JSDocAllType */ - || kind === 283 /* JSDocUnknownType */ - || kind === 284 /* JSDocNullableType */ - || kind === 285 /* JSDocNonNullableType */ - || kind === 286 /* JSDocOptionalType */ - || kind === 287 /* JSDocFunctionType */ - || kind === 288 /* JSDocVariadicType */; - } /** * Node test that determines whether a node is a valid type node. * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* * of a TypeNode. */ function isTypeNode(node) { - return isTypeNodeKind(node.kind); + return ts.isTypeNodeKind(node.kind); } ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return true; } return false; @@ -13340,8 +14068,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 183 /* ArrayBindingPattern */ - || kind === 182 /* ObjectBindingPattern */; + return kind === 185 /* ArrayBindingPattern */ + || kind === 184 /* ObjectBindingPattern */; } return false; } @@ -13349,15 +14077,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 185 /* ArrayLiteralExpression */ - || kind === 186 /* ObjectLiteralExpression */; + return kind === 187 /* ArrayLiteralExpression */ + || kind === 188 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 184 /* BindingElement */ - || kind === 208 /* OmittedExpression */; + return kind === 186 /* BindingElement */ + || kind === 210 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -13366,9 +14094,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: return true; } return false; @@ -13389,8 +14117,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 182 /* ObjectBindingPattern */: - case 186 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: return true; } return false; @@ -13402,8 +14130,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: return true; } return false; @@ -13412,26 +14140,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 187 /* PropertyAccessExpression */ - || kind === 146 /* QualifiedName */ - || kind === 181 /* ImportType */; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */ + || kind === 183 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 187 /* PropertyAccessExpression */ - || kind === 146 /* QualifiedName */; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 191 /* TaggedTemplateExpression */: - case 150 /* Decorator */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 152 /* Decorator */: return true; default: return false; @@ -13439,13 +14167,13 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 189 /* CallExpression */ || node.kind === 190 /* NewExpression */; + return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 204 /* TemplateExpression */ - || kind === 13 /* NoSubstitutionTemplateLiteral */; + return kind === 206 /* TemplateExpression */ + || kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; /* @internal */ @@ -13455,33 +14183,34 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - case 190 /* NewExpression */: - case 189 /* CallExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 191 /* TaggedTemplateExpression */: - case 185 /* ArrayLiteralExpression */: - case 193 /* ParenthesizedExpression */: - case 186 /* ObjectLiteralExpression */: - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: - case 71 /* Identifier */: - case 12 /* RegularExpressionLiteral */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 192 /* NewExpression */: + case 191 /* CallExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 193 /* TaggedTemplateExpression */: + case 187 /* ArrayLiteralExpression */: + case 195 /* ParenthesizedExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 72 /* Identifier */: + case 13 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 101 /* TrueKeyword */: - case 97 /* SuperKeyword */: - case 211 /* NonNullExpression */: - case 212 /* MetaProperty */: - case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 102 /* TrueKeyword */: + case 98 /* SuperKeyword */: + case 213 /* NonNullExpression */: + case 214 /* MetaProperty */: + case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: return false; @@ -13494,13 +14223,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 199 /* AwaitExpression */: - case 192 /* TypeAssertionExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 194 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13509,11 +14238,11 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return true; - case 200 /* PrefixUnaryExpression */: - return expr.operator === 43 /* PlusPlusToken */ || - expr.operator === 44 /* MinusMinusToken */; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 44 /* PlusPlusToken */ || + expr.operator === 45 /* MinusMinusToken */; default: return false; } @@ -13530,15 +14259,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 203 /* ConditionalExpression */: - case 205 /* YieldExpression */: - case 195 /* ArrowFunction */: - case 202 /* BinaryExpression */: - case 206 /* SpreadElement */: - case 210 /* AsExpression */: - case 208 /* OmittedExpression */: - case 307 /* CommaListExpression */: - case 306 /* PartiallyEmittedExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + case 197 /* ArrowFunction */: + case 204 /* BinaryExpression */: + case 208 /* SpreadElement */: + case 212 /* AsExpression */: + case 210 /* OmittedExpression */: + case 309 /* CommaListExpression */: + case 308 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13546,18 +14275,18 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 192 /* TypeAssertionExpression */ - || kind === 210 /* AsExpression */; + return kind === 194 /* TypeAssertionExpression */ + || kind === 212 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 306 /* PartiallyEmittedExpression */; + return node.kind === 308 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 305 /* NotEmittedStatement */; + return node.kind === 307 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13568,13 +14297,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return true; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13582,7 +14311,7 @@ var ts; ts.isIterationStatement = isIterationStatement; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 224 /* ForInStatement */ || node.kind === 225 /* ForOfStatement */; + return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13606,113 +14335,113 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 243 /* ModuleBlock */ - || kind === 242 /* ModuleDeclaration */ - || kind === 71 /* Identifier */; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */ + || kind === 72 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 243 /* ModuleBlock */ - || kind === 242 /* ModuleDeclaration */; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 242 /* ModuleDeclaration */; + return kind === 72 /* Identifier */ + || kind === 244 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 250 /* NamedImports */ - || kind === 249 /* NamespaceImport */; + return kind === 252 /* NamedImports */ + || kind === 251 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */ || node.kind === 241 /* EnumDeclaration */; + return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 195 /* ArrowFunction */ - || kind === 184 /* BindingElement */ - || kind === 238 /* ClassDeclaration */ - || kind === 207 /* ClassExpression */ - || kind === 155 /* Constructor */ - || kind === 241 /* EnumDeclaration */ - || kind === 276 /* EnumMember */ - || kind === 255 /* ExportSpecifier */ - || kind === 237 /* FunctionDeclaration */ - || kind === 194 /* FunctionExpression */ - || kind === 156 /* GetAccessor */ - || kind === 248 /* ImportClause */ - || kind === 246 /* ImportEqualsDeclaration */ - || kind === 251 /* ImportSpecifier */ - || kind === 239 /* InterfaceDeclaration */ - || kind === 265 /* JsxAttribute */ - || kind === 154 /* MethodDeclaration */ - || kind === 153 /* MethodSignature */ - || kind === 242 /* ModuleDeclaration */ - || kind === 245 /* NamespaceExportDeclaration */ - || kind === 249 /* NamespaceImport */ - || kind === 149 /* Parameter */ - || kind === 273 /* PropertyAssignment */ - || kind === 152 /* PropertyDeclaration */ - || kind === 151 /* PropertySignature */ - || kind === 157 /* SetAccessor */ - || kind === 274 /* ShorthandPropertyAssignment */ - || kind === 240 /* TypeAliasDeclaration */ - || kind === 148 /* TypeParameter */ - || kind === 235 /* VariableDeclaration */ - || kind === 302 /* JSDocTypedefTag */ - || kind === 295 /* JSDocCallbackTag */ - || kind === 303 /* JSDocPropertyTag */; + return kind === 197 /* ArrowFunction */ + || kind === 186 /* BindingElement */ + || kind === 240 /* ClassDeclaration */ + || kind === 209 /* ClassExpression */ + || kind === 157 /* Constructor */ + || kind === 243 /* EnumDeclaration */ + || kind === 278 /* EnumMember */ + || kind === 257 /* ExportSpecifier */ + || kind === 239 /* FunctionDeclaration */ + || kind === 196 /* FunctionExpression */ + || kind === 158 /* GetAccessor */ + || kind === 250 /* ImportClause */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 253 /* ImportSpecifier */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 267 /* JsxAttribute */ + || kind === 156 /* MethodDeclaration */ + || kind === 155 /* MethodSignature */ + || kind === 244 /* ModuleDeclaration */ + || kind === 247 /* NamespaceExportDeclaration */ + || kind === 251 /* NamespaceImport */ + || kind === 151 /* Parameter */ + || kind === 275 /* PropertyAssignment */ + || kind === 154 /* PropertyDeclaration */ + || kind === 153 /* PropertySignature */ + || kind === 159 /* SetAccessor */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 150 /* TypeParameter */ + || kind === 237 /* VariableDeclaration */ + || kind === 304 /* JSDocTypedefTag */ + || kind === 297 /* JSDocCallbackTag */ + || kind === 305 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 237 /* FunctionDeclaration */ - || kind === 256 /* MissingDeclaration */ - || kind === 238 /* ClassDeclaration */ - || kind === 239 /* InterfaceDeclaration */ - || kind === 240 /* TypeAliasDeclaration */ - || kind === 241 /* EnumDeclaration */ - || kind === 242 /* ModuleDeclaration */ - || kind === 247 /* ImportDeclaration */ - || kind === 246 /* ImportEqualsDeclaration */ - || kind === 253 /* ExportDeclaration */ - || kind === 252 /* ExportAssignment */ - || kind === 245 /* NamespaceExportDeclaration */; + return kind === 239 /* FunctionDeclaration */ + || kind === 258 /* MissingDeclaration */ + || kind === 240 /* ClassDeclaration */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 243 /* EnumDeclaration */ + || kind === 244 /* ModuleDeclaration */ + || kind === 249 /* ImportDeclaration */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 255 /* ExportDeclaration */ + || kind === 254 /* ExportAssignment */ + || kind === 247 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 227 /* BreakStatement */ - || kind === 226 /* ContinueStatement */ - || kind === 234 /* DebuggerStatement */ - || kind === 221 /* DoStatement */ - || kind === 219 /* ExpressionStatement */ - || kind === 218 /* EmptyStatement */ - || kind === 224 /* ForInStatement */ - || kind === 225 /* ForOfStatement */ - || kind === 223 /* ForStatement */ - || kind === 220 /* IfStatement */ - || kind === 231 /* LabeledStatement */ - || kind === 228 /* ReturnStatement */ - || kind === 230 /* SwitchStatement */ - || kind === 232 /* ThrowStatement */ - || kind === 233 /* TryStatement */ - || kind === 217 /* VariableStatement */ - || kind === 222 /* WhileStatement */ - || kind === 229 /* WithStatement */ - || kind === 305 /* NotEmittedStatement */ - || kind === 309 /* EndOfDeclarationMarker */ - || kind === 308 /* MergeDeclarationMarker */; + return kind === 229 /* BreakStatement */ + || kind === 228 /* ContinueStatement */ + || kind === 236 /* DebuggerStatement */ + || kind === 223 /* DoStatement */ + || kind === 221 /* ExpressionStatement */ + || kind === 220 /* EmptyStatement */ + || kind === 226 /* ForInStatement */ + || kind === 227 /* ForOfStatement */ + || kind === 225 /* ForStatement */ + || kind === 222 /* IfStatement */ + || kind === 233 /* LabeledStatement */ + || kind === 230 /* ReturnStatement */ + || kind === 232 /* SwitchStatement */ + || kind === 234 /* ThrowStatement */ + || kind === 235 /* TryStatement */ + || kind === 219 /* VariableStatement */ + || kind === 224 /* WhileStatement */ + || kind === 231 /* WithStatement */ + || kind === 307 /* NotEmittedStatement */ + || kind === 311 /* EndOfDeclarationMarker */ + || kind === 310 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + if (node.kind === 150 /* TypeParameter */) { + return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -13739,10 +14468,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 216 /* Block */) + if (node.kind !== 218 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 233 /* TryStatement */ || node.parent.kind === 272 /* CatchClause */) { + if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) { return false; } } @@ -13752,81 +14481,81 @@ var ts; /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 257 /* ExternalModuleReference */ - || kind === 146 /* QualifiedName */ - || kind === 71 /* Identifier */; + return kind === 259 /* ExternalModuleReference */ + || kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; } ts.isModuleReference = isModuleReference; // JSX /* @internal */ function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 99 /* ThisKeyword */ - || kind === 71 /* Identifier */ - || kind === 187 /* PropertyAccessExpression */; + return kind === 100 /* ThisKeyword */ + || kind === 72 /* Identifier */ + || kind === 189 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 258 /* JsxElement */ - || kind === 268 /* JsxExpression */ - || kind === 259 /* JsxSelfClosingElement */ - || kind === 10 /* JsxText */ - || kind === 262 /* JsxFragment */; + return kind === 260 /* JsxElement */ + || kind === 270 /* JsxExpression */ + || kind === 261 /* JsxSelfClosingElement */ + || kind === 11 /* JsxText */ + || kind === 264 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 265 /* JsxAttribute */ - || kind === 267 /* JsxSpreadAttribute */; + return kind === 267 /* JsxAttribute */ + || kind === 269 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 268 /* JsxExpression */; + return kind === 10 /* StringLiteral */ + || kind === 270 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 260 /* JsxOpeningElement */ - || kind === 259 /* JsxSelfClosingElement */; + return kind === 262 /* JsxOpeningElement */ + || kind === 261 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 269 /* CaseClause */ - || kind === 270 /* DefaultClause */; + return kind === 271 /* CaseClause */ + || kind === 272 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */; + return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 289 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */; + return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 157 /* SetAccessor */; + return node.kind === 159 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 156 /* GetAccessor */; + return node.kind === 158 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -13856,12 +14585,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 162 /* TypeReference */ || node.kind === 209 /* ExpressionWithTypeArguments */; + return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13890,15 +14619,14 @@ var ts; } ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { - return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; + return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isStringLiteralLike = isStringLiteralLike; })(ts || (ts = {})); /* @internal */ (function (ts) { - /** @internal */ function isNamedImportsOrExports(node) { - return node.kind === 250 /* NamedImports */ || node.kind === 254 /* NamedExports */; + return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function Symbol(flags, name) { @@ -13943,10 +14671,9 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - /* @internal */ function formatStringFromArgs(text, args, baseIndex) { if (baseIndex === void 0) { baseIndex = 0; } - return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); }); + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; function getLocaleSpecificMessage(message) { @@ -13975,7 +14702,6 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; - /* @internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -14000,7 +14726,6 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; - /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -14037,14 +14762,12 @@ var ts; function getDiagnosticFilePath(diagnostic) { return diagnostic.file ? diagnostic.file.path : undefined; } - /* @internal */ function compareDiagnostics(d1, d2) { return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || 0 /* EqualTo */; } ts.compareDiagnostics = compareDiagnostics; - /* @internal */ function compareDiagnosticsSkipRelatedInformation(d1, d2) { return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || ts.compareValues(d1.start, d2.start) || @@ -14105,6 +14828,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14121,9 +14856,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14135,13 +14869,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14336,7 +15071,6 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; - /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -14414,8 +15148,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14637,6 +15369,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14697,6 +15436,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14923,36 +15663,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15080,14 +15841,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15258,6 +16019,98 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: // 0b or 0B + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: // 0o or 0O + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + var nIndex = stringValue.length - 1; + // Skip leading 0s + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + // Omit leading "0b", "0o", or "0x", and trailing "n" + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + var digit = digitChar <= 57 /* _9 */ + ? digitChar - 48 /* _0 */ + : 10 + digitChar - + (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; })(ts || (ts = {})); var ts; (function (ts) { @@ -15277,10 +16130,10 @@ var ts; var SourceFileConstructor; // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 277 /* SourceFile */) { + if (kind === 279 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 71 /* Identifier */) { + else if (kind === 72 /* Identifier */) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } else if (!ts.isNodeKind(kind)) { @@ -15329,28 +16182,29 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 145 /* LastToken */) { + if (!node || node.kind <= 147 /* LastToken */) { return; } switch (node.kind) { - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -15358,7 +16212,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -15366,405 +16220,399 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 168 /* TupleType */: + case 170 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 174 /* InferType */: + case 176 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 181 /* ImportType */: + case 183 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 175 /* ParenthesizedType */: - case 177 /* TypeOperator */: + case 177 /* ParenthesizedType */: + case 179 /* TypeOperator */: return visitNode(cbNode, node.type); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 179 /* MappedType */: + case 181 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return visitNode(cbNode, node.literal); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 210 /* AsExpression */: + case 212 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return visitNode(cbNode, node.name); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 277 /* SourceFile */: + case 279 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: return visitNode(cbNode, node.label); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 269 /* CaseClause */: + case 271 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 150 /* Decorator */: + case 152 /* Decorator */: return visitNode(cbNode, node.expression); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 276 /* EnumMember */: + case 278 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 250 /* NamedImports */: - case 254 /* NamedExports */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 169 /* OptionalType */: - case 170 /* RestType */: - case 281 /* JSDocTypeExpression */: - case 285 /* JSDocNonNullableType */: - case 284 /* JSDocNullableType */: - case 286 /* JSDocOptionalType */: - case 288 /* JSDocVariadicType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 283 /* JSDocTypeExpression */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 288 /* JSDocOptionalType */: + case 290 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 289 /* JSDocComment */: + case 291 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: - if (node.isNameFirst) { - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression); - } - else { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - } - case 298 /* JSDocReturnTag */: - return visitNode(cbNode, node.typeExpression); - case 300 /* JSDocTypeTag */: - return visitNode(cbNode, node.typeExpression); - case 293 /* JSDocAugmentsTag */: - return visitNode(cbNode, node.class); - case 301 /* JSDocTemplateTag */: - return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302 /* JSDocTypedefTag */: - if (node.typeExpression && - node.typeExpression.kind === 281 /* JSDocTypeExpression */) { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName); - } - else { - return visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - } - case 295 /* JSDocCallbackTag */: - return visitNode(cbNode, node.fullName) || + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303 /* JSDocTemplateTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304 /* JSDocTypedefTag */: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 /* JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297 /* JSDocCallbackTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299 /* JSDocThisTag */: - return visitNode(cbNode, node.typeExpression); - case 296 /* JSDocEnumTag */: - return visitNode(cbNode, node.typeExpression); - case 291 /* JSDocSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - ts.forEach(node.typeParameters, cbNode) || + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293 /* JSDocSignature */: + return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290 /* JSDocTypeLiteral */: - if (node.jsDocPropertyTags) { - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); - } - } - return; - case 306 /* PartiallyEmittedExpression */: + case 292 /* JSDocTypeLiteral */: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294 /* JSDocTag */: + case 296 /* JSDocClassTag */: + return visitNode(cbNode, node.tagName); + case 308 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15774,7 +16622,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15943,8 +16791,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -15978,18 +16830,18 @@ var ts; sourceFile.endOfFileToken = parseTokenNode(); } else { - var statement = createNode(219 /* ExpressionStatement */); + var statement = createNode(221 /* ExpressionStatement */); switch (token()) { - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: statement.expression = parseArrayLiteralExpression(); break; - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: statement.expression = parseTokenNode(); break; - case 38 /* MinusToken */: - if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) { + case 39 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) { statement.expression = parsePrefixUnaryExpression(); } else { @@ -15997,8 +16849,8 @@ var ts; } break; case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) { + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) { statement.expression = parseLiteralNode(); break; } @@ -16134,7 +16986,7 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // 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(277 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -16339,20 +17191,20 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token() === 71 /* Identifier */) { + if (token() === 72 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token() === 116 /* YieldKeyword */ && inYieldContext()) { + if (token() === 117 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) { + if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token() > 107 /* LastReservedWord */; + return token() > 108 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -16395,29 +17247,29 @@ var ts; } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token() === 25 /* SemicolonToken */) { + if (token() === 26 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 25 /* SemicolonToken */) { + if (token() === 26 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } return true; } else { - return parseExpected(25 /* SemicolonToken */); + return parseExpected(26 /* SemicolonToken */); } } function createNode(kind, pos) { nodeCount++; var p = pos >= 0 ? pos : scanner.getStartPos(); return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : - kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } function createNodeWithJSDoc(kind, pos) { @@ -16459,7 +17311,7 @@ var ts; parseErrorAtCurrentToken(diagnosticMessage, arg0); } var result = createNode(kind); - if (kind === 71 /* Identifier */) { + if (kind === 72 /* Identifier */) { result.escapedText = ""; } else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { @@ -16480,9 +17332,9 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(71 /* Identifier */); + var node = createNode(72 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 71 /* Identifier */) { + if (token() !== 72 /* Identifier */) { node.originalKeywordKind = token(); } node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); @@ -16491,7 +17343,7 @@ var ts; } // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; - return createMissingNode(71 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -16501,16 +17353,16 @@ var ts; } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || + token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { var node = parseLiteralNode(); node.text = internIdentifier(node.text); return node; } - if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -16522,13 +17374,13 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(147 /* ComputedPropertyName */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(149 /* ComputedPropertyName */); + parseExpected(22 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker // will error if it sees a comma expression. node.expression = allowInAnd(parseExpression); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function parseContextualModifier(t) { @@ -16543,20 +17395,20 @@ var ts; } function nextTokenCanFollowModifier() { switch (token()) { - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; - case 84 /* ExportKeyword */: + return nextToken() === 84 /* EnumKeyword */; + case 85 /* ExportKeyword */: nextToken(); - if (token() === 79 /* DefaultKeyword */) { + if (token() === 80 /* DefaultKeyword */) { return lookAhead(nextTokenCanFollowDefaultKeyword); } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - case 79 /* DefaultKeyword */: + return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + case 80 /* DefaultKeyword */: return nextTokenCanFollowDefaultKeyword(); - case 115 /* StaticKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: + case 116 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: nextToken(); return canFollowModifier(); default: @@ -16567,18 +17419,18 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 21 /* OpenBracketToken */ - || token() === 17 /* OpenBraceToken */ - || token() === 39 /* AsteriskToken */ - || token() === 24 /* DotDotDotToken */ + return token() === 22 /* OpenBracketToken */ + || token() === 18 /* OpenBraceToken */ + || token() === 40 /* AsteriskToken */ + || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenCanFollowDefaultKeyword() { nextToken(); - return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ || - token() === 109 /* InterfaceKeyword */ || - (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ || + token() === 110 /* InterfaceKeyword */ || + (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -16596,9 +17448,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -16606,21 +17458,29 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 22 /* OpenBracketToken */: + case 40 /* AsteriskToken */: + case 25 /* DotDotDotToken */: + case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` // That way we won't consume the body of a class in its heritage clause. - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -16635,37 +17495,39 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); + return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern(); case 19 /* TypeParameters */: return isIdentifier(); case 15 /* ArrayLiteralMembers */: - if (token() === 26 /* CommaToken */) { - return true; + switch (token()) { + case 27 /* CommaToken */: + case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; } // falls through case 11 /* ArgumentExpressions */: - return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(/*isJSDocParameter*/ false); case 17 /* JSDocParameters */: return isStartOfParameter(/*isJSDocParameter*/ true); case 20 /* TypeArguments */: case 21 /* TupleElementTypes */: - return token() === 26 /* CommaToken */ || isStartOfType(); + return token() === 27 /* CommaToken */ || isStartOfType(); case 22 /* HeritageClauses */: return isHeritageClause(); case 23 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; } return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17 /* OpenBraceToken */); - if (nextToken() === 18 /* CloseBraceToken */) { + ts.Debug.assert(token() === 18 /* OpenBraceToken */); + if (nextToken() === 19 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // @@ -16674,7 +17536,7 @@ var ts; // extends {} extends // extends {} implements var next = nextToken(); - return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */; + return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */; } return true; } @@ -16691,8 +17553,8 @@ var ts; return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 /* ImplementsKeyword */ || - token() === 85 /* ExtendsKeyword */) { + if (token() === 109 /* ImplementsKeyword */ || + token() === 86 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -16720,37 +17582,37 @@ var ts; case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: case 23 /* ImportOrExportSpecifiers */: - return token() === 18 /* CloseBraceToken */; + return token() === 19 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); case 19 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; + return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: case 21 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token() === 22 /* CloseBracketToken */; + return token() === 23 /* CloseBracketToken */; case 17 /* JSDocParameters */: case 16 /* Parameters */: case 18 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 20 /* TypeArguments */: // All other tokens should cause the type-argument to terminate except comma token - return token() !== 26 /* CommaToken */; + return token() !== 27 /* CommaToken */; case 22 /* HeritageClauses */: - return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; + return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; + return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */; case 14 /* JsxChildren */: - return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash); default: return false; } @@ -16770,7 +17632,7 @@ var ts; // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -16940,20 +17802,20 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 155 /* Constructor */: - case 160 /* IndexSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 152 /* PropertyDeclaration */: - case 215 /* SemicolonClassElement */: + case 157 /* Constructor */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 217 /* SemicolonClassElement */: return true; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ && - methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */; + var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */; return !nameIsConstructor; } } @@ -16962,8 +17824,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: return true; } } @@ -16972,58 +17834,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 217 /* VariableStatement */: - case 216 /* Block */: - case 220 /* IfStatement */: - case 219 /* ExpressionStatement */: - case 232 /* ThrowStatement */: - case 228 /* ReturnStatement */: - case 230 /* SwitchStatement */: - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 218 /* EmptyStatement */: - case 233 /* TryStatement */: - case 231 /* LabeledStatement */: - case 221 /* DoStatement */: - case 234 /* DebuggerStatement */: - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: - case 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 219 /* VariableStatement */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 221 /* ExpressionStatement */: + case 234 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 232 /* SwitchStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 220 /* EmptyStatement */: + case 235 /* TryStatement */: + case 233 /* LabeledStatement */: + case 223 /* DoStatement */: + case 236 /* DebuggerStatement */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 276 /* EnumMember */; + return node.kind === 278 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 151 /* PropertySignature */: - case 158 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 153 /* PropertySignature */: + case 160 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 235 /* VariableDeclaration */) { + if (node.kind !== 237 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -17044,7 +17906,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 149 /* Parameter */) { + if (node.kind !== 151 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -17101,7 +17963,7 @@ var ts; var startPos = scanner.getStartPos(); list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(26 /* CommaToken */)) { + if (parseOptional(27 /* CommaToken */)) { // No need to check for a zero length node since we know we parsed a comma continue; } @@ -17111,13 +17973,13 @@ var ts; } // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. - parseExpected(26 /* CommaToken */); + parseExpected(27 /* CommaToken */); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // 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 (considerSemicolonAsDelimiter && token() === 25 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } if (startPos === scanner.getStartPos()) { @@ -17168,8 +18030,8 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); - while (parseOptional(23 /* DotToken */)) { - if (token() === 27 /* LessThanToken */) { + while (parseOptional(24 /* DotToken */)) { + if (token() === 28 /* LessThanToken */) { // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting entity.jsdocDotPos = dotPos; break; @@ -17180,7 +18042,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(146 /* QualifiedName */, entity.pos); + var node = createNode(148 /* QualifiedName */, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -17211,33 +18073,33 @@ 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(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(204 /* TemplateExpression */); + var template = createNode(206 /* TemplateExpression */); template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); var list = []; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */); + } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { - var span = createNode(214 /* TemplateSpan */); + var span = createNode(216 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 18 /* CloseBraceToken */) { + if (token() === 19 /* CloseBraceToken */) { reScanTemplateToken(); literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(16 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */)); + literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */)); } span.literal = literal; return finishNode(span); @@ -17247,18 +18109,17 @@ var ts; } function parseTemplateHead() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); return fragment; } function parseTemplateMiddleOrTemplateTail() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind"); + ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind"); return fragment; } function parseLiteralLikeNode(kind) { var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = text; + node.text = scanner.getTokenValue(); if (scanner.hasExtendedUnicodeEscape()) { node.hasExtendedUnicodeEscape = true; } @@ -17280,24 +18141,24 @@ var ts; } // TYPES function parseTypeReference() { - var node = createNode(162 /* TypeReference */); + var node = createNode(164 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + if (!scanner.hasPrecedingLineBreak() && token() === 28 /* LessThanToken */) { + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */); } return finishNode(node); } // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return ts.nodeIsMissing(node.typeName); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: { + case 165 /* FunctionType */: + case 166 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -17305,20 +18166,20 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(161 /* TypePredicate */, lhs.pos); + var node = createNode(163 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(176 /* ThisType */); + var node = createNode(178 /* ThisType */); nextToken(); return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(282 /* JSDocAllType */); + var result = createNode(284 /* JSDocAllType */); if (postFixEquals) { - return createPostfixType(286 /* JSDocOptionalType */, result); + return createPostfixType(288 /* JSDocOptionalType */, result); } else { nextToken(); @@ -17326,7 +18187,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(285 /* JSDocNonNullableType */); + var result = createNode(287 /* JSDocNonNullableType */); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -17344,64 +18205,66 @@ var ts; // Foo // Foo(?= // (?| - if (token() === 26 /* CommaToken */ || - token() === 18 /* CloseBraceToken */ || - token() === 20 /* CloseParenToken */ || - token() === 29 /* GreaterThanToken */ || - token() === 58 /* EqualsToken */ || - token() === 49 /* BarToken */) { - var result = createNode(283 /* JSDocUnknownType */, pos); + if (token() === 27 /* CommaToken */ || + token() === 19 /* CloseBraceToken */ || + token() === 21 /* CloseParenToken */ || + token() === 30 /* GreaterThanToken */ || + token() === 59 /* EqualsToken */ || + token() === 50 /* BarToken */) { + var result = createNode(285 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(284 /* JSDocNullableType */, pos); + var result = createNode(286 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(287 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); nextToken(); - fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); } - var node = createNode(162 /* TypeReference */); + var node = createNode(164 /* TypeReference */); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(149 /* Parameter */); - if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { + var parameter = createNode(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) { parameter.name = parseIdentifierName(); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); } parameter.type = parseJSDocType(); return finishNode(parameter); } function parseJSDocType() { - var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { - var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); + var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } - if (token() === 58 /* EqualsToken */) { - return createPostfixType(286 /* JSDocOptionalType */, type); + if (token() === 59 /* EqualsToken */) { + return createPostfixType(288 /* JSDocOptionalType */, type); } return type; } function parseTypeQuery() { - var node = createNode(165 /* TypeQuery */); - parseExpected(103 /* TypeOfKeyword */); + var node = createNode(167 /* TypeQuery */); + parseExpected(104 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(148 /* TypeParameter */); + var node = createNode(150 /* TypeParameter */); node.name = parseIdentifier(); - if (parseOptional(85 /* ExtendsKeyword */)) { + if (parseOptional(86 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the // user writes a constraint that is an expression and not an actual type, then parse // it out as an expression (so we can recover well), but report that a type is needed @@ -17420,39 +18283,39 @@ var ts; node.expression = parseUnaryExpressionOrHigher(); } } - if (parseOptional(58 /* EqualsToken */)) { + if (parseOptional(59 /* EqualsToken */)) { node.default = parseType(); } return finishNode(node); } function parseTypeParameters() { - if (token() === 27 /* LessThanToken */) { - return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + if (token() === 28 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */); } } function parseParameterType() { - if (parseOptional(56 /* ColonToken */)) { + if (parseOptional(57 /* ColonToken */)) { return parseType(); } return undefined; } function isStartOfParameter(isJSDocParameter) { - return token() === 24 /* DotDotDotToken */ || + return token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 /* AtToken */ || + token() === 58 /* AtToken */ || isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseParameter() { - var node = createNodeWithJSDoc(149 /* Parameter */); - if (token() === 99 /* ThisKeyword */) { + var node = createNodeWithJSDoc(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); @@ -17467,7 +18330,7 @@ var ts; // to avoid this we'll advance cursor to the next token. nextToken(); } - node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.questionToken = parseOptionalToken(56 /* QuestionToken */); node.type = parseParameterType(); node.initializer = parseInitializer(); return finishNode(node); @@ -17489,16 +18352,16 @@ var ts; return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { - if (returnToken === 36 /* EqualsGreaterThanToken */) { + if (returnToken === 37 /* EqualsGreaterThanToken */) { parseExpected(returnToken); return true; } - else if (parseOptional(56 /* ColonToken */)) { + else if (parseOptional(57 /* ColonToken */)) { return true; } - else if (isType && token() === 36 /* EqualsGreaterThanToken */) { + else if (isType && token() === 37 /* EqualsGreaterThanToken */) { // This is easy to get backward, especially in type contexts, so parse the type anyway - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); nextToken(); return true; } @@ -17519,7 +18382,7 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (!parseExpected(19 /* OpenParenToken */)) { + if (!parseExpected(20 /* OpenParenToken */)) { signature.parameters = createMissingList(); return false; } @@ -17532,12 +18395,12 @@ var ts; parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - return parseExpected(20 /* CloseParenToken */); + return parseExpected(21 /* CloseParenToken */); } function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. // First check if it was a comma. If so, we're done with the member. - if (parseOptional(26 /* CommaToken */)) { + if (parseOptional(27 /* CommaToken */)) { return; } // Didn't have a comma. We must have a (possible ASI) semicolon. @@ -17545,15 +18408,15 @@ var ts; } function parseSignatureMember(kind) { var node = createNodeWithJSDoc(kind); - if (kind === 159 /* ConstructSignature */) { - parseExpected(94 /* NewKeyword */); + if (kind === 161 /* ConstructSignature */) { + parseExpected(95 /* NewKeyword */); } - fillSignature(56 /* ColonToken */, 4 /* Type */, node); + fillSignature(57 /* ColonToken */, 4 /* Type */, node); parseTypeMemberSemicolon(); return finishNode(node); } function isIndexSignature() { - return token() === 21 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { // The only allowed sequence is: @@ -17573,7 +18436,7 @@ var ts; // [] // nextToken(); - if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) { + if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) { return true; } if (ts.isModifierKind(token())) { @@ -17592,39 +18455,39 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token() !== 55 /* QuestionToken */) { + if (token() !== 56 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; + return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(node) { - node.kind = 160 /* IndexSignature */; - node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.kind = 162 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(node) { node.name = parsePropertyName(); - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - node.kind = 153 /* MethodSignature */; + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + node.kind = 155 /* MethodSignature */; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] - fillSignature(56 /* ColonToken */, 4 /* Type */, node); + fillSignature(57 /* ColonToken */, 4 /* Type */, node); } else { - node.kind = 151 /* PropertySignature */; + node.kind = 153 /* PropertySignature */; node.type = parseTypeAnnotation(); - if (token() === 58 /* EqualsToken */) { + if (token() === 59 /* 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. @@ -17636,7 +18499,7 @@ var ts; } function isTypeMemberStart() { // Return true if we have the start of a signature member - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return true; } var idToken = false; @@ -17646,7 +18509,7 @@ var ts; nextToken(); } // Index signatures and computed property names are type members - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers @@ -17657,21 +18520,21 @@ var ts; // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token() === 19 /* OpenParenToken */ || - token() === 27 /* LessThanToken */ || - token() === 55 /* QuestionToken */ || - token() === 56 /* ColonToken */ || - token() === 26 /* CommaToken */ || + return token() === 20 /* OpenParenToken */ || + token() === 28 /* LessThanToken */ || + token() === 56 /* QuestionToken */ || + token() === 57 /* ColonToken */ || + token() === 27 /* CommaToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(158 /* CallSignature */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseSignatureMember(160 /* CallSignature */); } - if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(159 /* ConstructSignature */); + if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161 /* ConstructSignature */); } var node = createNodeWithJSDoc(0 /* Unknown */); node.modifiers = parseModifiers(); @@ -17682,30 +18545,30 @@ var ts; } function nextTokenIsOpenParenOrLessThan() { nextToken(); - return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; + return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */; } function nextTokenIsDot() { - return nextToken() === 23 /* DotToken */; + return nextToken() === 24 /* DotToken */; } function nextTokenIsOpenParenOrLessThanOrDot() { switch (nextToken()) { - case 19 /* OpenParenToken */: - case 27 /* LessThanToken */: - case 23 /* DotToken */: + case 20 /* OpenParenToken */: + case 28 /* LessThanToken */: + case 24 /* DotToken */: return true; } return false; } function parseTypeLiteral() { - var node = createNode(166 /* TypeLiteral */); + var node = createNode(168 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { members = parseList(4 /* TypeMembers */, parseTypeMember); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { members = createMissingList(); @@ -17714,89 +18577,89 @@ var ts; } function isStartOfMappedType() { nextToken(); - if (token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { - return nextToken() === 132 /* ReadonlyKeyword */; + if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + return nextToken() === 133 /* ReadonlyKeyword */; } - if (token() === 132 /* ReadonlyKeyword */) { + if (token() === 133 /* ReadonlyKeyword */) { nextToken(); } - return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; + return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */; } function parseMappedTypeParameter() { - var node = createNode(148 /* TypeParameter */); + var node = createNode(150 /* TypeParameter */); node.name = parseIdentifier(); - parseExpected(92 /* InKeyword */); + parseExpected(93 /* InKeyword */); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(179 /* MappedType */); - parseExpected(17 /* OpenBraceToken */); - if (token() === 132 /* ReadonlyKeyword */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { + var node = createNode(181 /* MappedType */); + parseExpected(18 /* OpenBraceToken */); + if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { node.readonlyToken = parseTokenNode(); - if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) { - parseExpectedToken(132 /* ReadonlyKeyword */); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + parseExpectedToken(133 /* ReadonlyKeyword */); } } - parseExpected(21 /* OpenBracketToken */); + parseExpected(22 /* OpenBracketToken */); node.typeParameter = parseMappedTypeParameter(); - parseExpected(22 /* CloseBracketToken */); - if (token() === 55 /* QuestionToken */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { + parseExpected(23 /* CloseBracketToken */); + if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { node.questionToken = parseTokenNode(); - if (node.questionToken.kind !== 55 /* QuestionToken */) { - parseExpectedToken(55 /* QuestionToken */); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + parseExpectedToken(56 /* QuestionToken */); } } node.type = parseTypeAnnotation(); parseSemicolon(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseTupleElementType() { var pos = getNodePos(); - if (parseOptional(24 /* DotDotDotToken */)) { - var node = createNode(170 /* RestType */, pos); + if (parseOptional(25 /* DotDotDotToken */)) { + var node = createNode(172 /* RestType */, pos); node.type = parseType(); return finishNode(node); } var type = parseType(); - if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 284 /* JSDocNullableType */ && type.pos === type.type.pos) { - type.kind = 169 /* OptionalType */; + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 171 /* OptionalType */; } return type; } function parseTupleType() { - var node = createNode(168 /* TupleType */); - node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + var node = createNode(170 /* TupleType */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(175 /* ParenthesizedType */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(177 /* ParenthesizedType */); + parseExpected(20 /* OpenParenToken */); node.type = parseType(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseFunctionOrConstructorType() { var pos = getNodePos(); - var kind = parseOptional(94 /* NewKeyword */) ? 164 /* ConstructorType */ : 163 /* FunctionType */; + var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */; var node = createNodeWithJSDoc(kind, pos); - fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 23 /* DotToken */ ? undefined : node; + return token() === 24 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(180 /* LiteralType */); + var node = createNode(182 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(200 /* PrefixUnaryExpression */); - unaryMinusExpression.operator = 38 /* MinusToken */; + unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 39 /* MinusToken */; nextToken(); } - var expression = token() === 101 /* TrueKeyword */ || token() === 86 /* FalseKeyword */ + var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */ ? parseTokenNode() : parseLiteralLikeNode(token()); if (negative) { @@ -17809,79 +18672,82 @@ var ts; } function isStartOfTypeOfImportType() { nextToken(); - return token() === 91 /* ImportKeyword */; + return token() === 92 /* ImportKeyword */; } function parseImportType() { sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; - var node = createNode(181 /* ImportType */); - if (parseOptional(103 /* TypeOfKeyword */)) { + var node = createNode(183 /* ImportType */); + if (parseOptional(104 /* TypeOfKeyword */)) { node.isTypeOf = true; } - parseExpected(91 /* ImportKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(92 /* ImportKeyword */); + parseExpected(20 /* OpenParenToken */); node.argument = parseType(); - parseExpected(20 /* CloseParenToken */); - if (parseOptional(23 /* DotToken */)) { + parseExpected(21 /* CloseParenToken */); + if (parseOptional(24 /* DotToken */)) { node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); } node.typeArguments = tryParseTypeArguments(); return finishNode(node); } - function nextTokenIsNumericLiteral() { - return nextToken() === 8 /* NumericLiteral */; + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */; } function parseNonArrayType() { switch (token()) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 138 /* SymbolKeyword */: - case 122 /* BooleanKeyword */: - case 140 /* UndefinedKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 139 /* SymbolKeyword */: + case 123 /* BooleanKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: return parseJSDocAllType(/*postfixEquals*/ false); - case 61 /* AsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: return parseJSDocAllType(/*postfixEquals*/ true); - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseJSDocFunctionType(); - case 51 /* ExclamationToken */: + case 52 /* ExclamationToken */: return parseJSDocNonNullableType(); - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return parseLiteralTypeNode(); - case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); - case 105 /* VoidKeyword */: - case 95 /* NullKeyword */: + case 39 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 106 /* VoidKeyword */: + case 96 /* NullKeyword */: return parseTokenNode(); - case 99 /* ThisKeyword */: { + case 100 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 103 /* TypeOfKeyword */: + case 104 /* TypeOfKeyword */: return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: return parseTupleType(); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return parseParenthesizedType(); - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return parseImportType(); default: return parseTypeReference(); @@ -17889,42 +18755,44 @@ var ts; } function isStartOfType(inStartOfParameter) { switch (token()) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 141 /* UniqueKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 103 /* TypeOfKeyword */: - case 131 /* NeverKeyword */: - case 17 /* OpenBraceToken */: - case 21 /* OpenBracketToken */: - case 27 /* LessThanToken */: - case 49 /* BarToken */: - case 48 /* AmpersandToken */: - case 94 /* NewKeyword */: - case 9 /* StringLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 142 /* UniqueKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 104 /* TypeOfKeyword */: + case 132 /* NeverKeyword */: + case 18 /* OpenBraceToken */: + case 22 /* OpenBracketToken */: + case 28 /* LessThanToken */: + case 50 /* BarToken */: + case 49 /* AmpersandToken */: + case 95 /* NewKeyword */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 135 /* ObjectKeyword */: - case 39 /* AsteriskToken */: - case 55 /* QuestionToken */: - case 51 /* ExclamationToken */: - case 24 /* DotDotDotToken */: - case 126 /* InferKeyword */: - case 91 /* ImportKeyword */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 136 /* ObjectKeyword */: + case 40 /* AsteriskToken */: + case 56 /* QuestionToken */: + case 52 /* ExclamationToken */: + case 25 /* DotDotDotToken */: + case 127 /* InferKeyword */: + case 92 /* ImportKeyword */: return true; - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return !inStartOfParameter; - case 38 /* MinusToken */: - return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); - case 19 /* OpenParenToken */: + case 39 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); @@ -17934,35 +18802,35 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 51 /* ExclamationToken */: - type = createPostfixType(285 /* JSDocNonNullableType */, type); + case 52 /* ExclamationToken */: + type = createPostfixType(287 /* JSDocNonNullableType */, type); break; - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createPostfixType(284 /* JSDocNullableType */, type); + type = createPostfixType(286 /* JSDocNullableType */, type); break; - case 21 /* OpenBracketToken */: - parseExpected(21 /* OpenBracketToken */); + case 22 /* OpenBracketToken */: + parseExpected(22 /* OpenBracketToken */); if (isStartOfType()) { - var node = createNode(178 /* IndexedAccessType */, type.pos); + var node = createNode(180 /* IndexedAccessType */, type.pos); node.objectType = type; node.indexType = parseType(); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); type = finishNode(node); } else { - var node = createNode(167 /* ArrayType */, type.pos); + var node = createNode(169 /* ArrayType */, type.pos); node.elementType = type; - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); type = finishNode(node); } break; @@ -17979,16 +18847,16 @@ var ts; return finishNode(postfix); } function parseTypeOperator(operator) { - var node = createNode(177 /* TypeOperator */); + var node = createNode(179 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseInferType() { - var node = createNode(174 /* InferType */); - parseExpected(126 /* InferKeyword */); - var typeParameter = createNode(148 /* TypeParameter */); + var node = createNode(176 /* InferType */); + parseExpected(127 /* InferKeyword */); + var typeParameter = createNode(150 /* TypeParameter */); typeParameter.name = parseIdentifier(); node.typeParameter = finishNode(typeParameter); return finishNode(node); @@ -17996,10 +18864,10 @@ var ts; function parseTypeOperatorOrHigher() { var operator = token(); switch (operator) { - case 128 /* KeyOfKeyword */: - case 141 /* UniqueKeyword */: + case 129 /* KeyOfKeyword */: + case 142 /* UniqueKeyword */: return parseTypeOperator(operator); - case 126 /* InferKeyword */: + case 127 /* InferKeyword */: return parseInferType(); } return parsePostfixTypeOrHigher(); @@ -18019,27 +18887,27 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(172 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(171 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */); } function isStartOfFunctionType() { - if (token() === 27 /* LessThanToken */) { + if (token() === 28 /* LessThanToken */) { return true; } - return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token() === 99 /* ThisKeyword */) { + if (isIdentifier() || token() === 100 /* ThisKeyword */) { nextToken(); return true; } - if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) { + if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -18049,7 +18917,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -18057,17 +18925,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || - token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || + token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token() === 20 /* CloseParenToken */) { + if (token() === 21 /* CloseParenToken */) { nextToken(); - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -18079,7 +18947,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(161 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -18090,7 +18958,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -18101,49 +18969,50 @@ var ts; return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) { + if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) { return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); - if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { - var node = createNode(173 /* ConditionalType */, type.pos); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) { + var node = createNode(175 /* ConditionalType */, type.pos); node.checkType = type; // The type following 'extends' is not permitted to be another conditional type node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); - parseExpected(55 /* QuestionToken */); + parseExpected(56 /* QuestionToken */); node.trueType = parseTypeWorker(); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.falseType = parseTypeWorker(); return finishNode(node); } return type; } function parseTypeAnnotation() { - return parseOptional(56 /* ColonToken */) ? parseType() : undefined; + return parseOptional(57 /* ColonToken */) ? parseType() : undefined; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { switch (token()) { - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 19 /* OpenParenToken */: - case 21 /* OpenBracketToken */: - case 17 /* OpenBraceToken */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 94 /* NewKeyword */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 71 /* Identifier */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 20 /* OpenParenToken */: + case 22 /* OpenBracketToken */: + case 18 /* OpenBraceToken */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 95 /* NewKeyword */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 72 /* Identifier */: return true; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); default: return isIdentifier(); @@ -18154,18 +19023,18 @@ var ts; return true; } switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 27 /* LessThanToken */: - case 121 /* AwaitKeyword */: - case 116 /* YieldKeyword */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 28 /* LessThanToken */: + case 122 /* AwaitKeyword */: + case 117 /* YieldKeyword */: // Yield/await always starts an expression. Either it is an identifier (in which case // it is definitely an expression). Or it's a keyword (either because we're in // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. @@ -18183,10 +19052,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 17 /* OpenBraceToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && - token() !== 57 /* AtToken */ && + return token() !== 18 /* OpenBraceToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + token() !== 58 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -18200,7 +19069,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) { + while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -18209,7 +19078,7 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(58 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { // AssignmentExpression[in,yield]: @@ -18254,7 +19123,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -18270,7 +19139,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 116 /* YieldKeyword */) { + if (token() === 117 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -18299,15 +19168,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(205 /* YieldExpression */); + var node = createNode(207 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 39 /* AsteriskToken */ || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + (token() === 40 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -18318,20 +19187,20 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(195 /* ArrowFunction */, asyncModifier.pos); + node = createNode(197 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(195 /* ArrowFunction */, identifier.pos); + node = createNode(197 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(149 /* Parameter */, identifier.pos); + var parameter = createNode(151 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); - node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -18356,8 +19225,8 @@ var ts; // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */); - arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return finishNode(arrowFunction); @@ -18367,10 +19236,10 @@ var ts; // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -18380,28 +19249,28 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) { + if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) { return 0 /* False */; } } var first = token(); var second = nextToken(); - if (first === 19 /* OpenParenToken */) { - if (second === 20 /* CloseParenToken */) { + if (first === 20 /* OpenParenToken */) { + if (second === 21 /* CloseParenToken */) { // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. var third = nextToken(); switch (third) { - case 36 /* EqualsGreaterThanToken */: - case 56 /* ColonToken */: - case 17 /* OpenBraceToken */: + case 37 /* EqualsGreaterThanToken */: + case 57 /* ColonToken */: + case 18 /* OpenBraceToken */: return 1 /* True */; default: return 0 /* False */; @@ -18413,42 +19282,42 @@ var ts; // ({ x }) => { } // ([ x ]) // ({ x }) - if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) { + if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) { return 2 /* Unknown */; } // Simple case: "(..." // This is an arrow function with a rest parameter. - if (second === 24 /* DotDotDotToken */) { + if (second === 25 /* DotDotDotToken */) { return 1 /* True */; } // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. - if (ts.isModifierKind(second) && second !== 120 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { return 1 /* True */; } // If we had "(" followed by something that's not an identifier, // then this definitely doesn't look like a lambda. "this" is not // valid, but we want to parse it and then give a semantic error. - if (!isIdentifier() && second !== 99 /* ThisKeyword */) { + if (!isIdentifier() && second !== 100 /* ThisKeyword */) { return 0 /* False */; } switch (nextToken()) { - case 56 /* ColonToken */: + case 57 /* ColonToken */: // If we have something like "(a:", then we must have a // type-annotated parameter in an arrow function expression. return 1 /* True */; - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: nextToken(); // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 58 /* EqualsToken */ || token() === 20 /* CloseParenToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) { return 1 /* True */; } // Otherwise it is definitely not a lambda. return 0 /* False */; - case 26 /* CommaToken */: - case 58 /* EqualsToken */: - case 20 /* CloseParenToken */: + case 27 /* CommaToken */: + case 59 /* EqualsToken */: + case 21 /* CloseParenToken */: // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function return 2 /* Unknown */; } @@ -18456,7 +19325,7 @@ var ts; return 0 /* False */; } else { - ts.Debug.assert(first === 27 /* LessThanToken */); + ts.Debug.assert(first === 28 /* LessThanToken */); // If we have "<" not followed by an identifier, // then this definitely is not an arrow function. if (!isIdentifier()) { @@ -18466,17 +19335,17 @@ var ts; if (sourceFile.languageVariant === 1 /* JSX */) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 85 /* ExtendsKeyword */) { + if (third === 86 /* ExtendsKeyword */) { var fourth = nextToken(); switch (fourth) { - case 58 /* EqualsToken */: - case 29 /* GreaterThanToken */: + case 59 /* EqualsToken */: + case 30 /* GreaterThanToken */: return false; default: return true; } } - else if (third === 26 /* CommaToken */) { + else if (third === 27 /* CommaToken */) { return true; } return false; @@ -18495,7 +19364,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); @@ -18508,23 +19377,23 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { return 1 /* True */; } } return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNodeWithJSDoc(195 /* ArrowFunction */); + var node = createNodeWithJSDoc(197 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. @@ -18534,7 +19403,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) { + if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) { return undefined; } // Parsing a signature isn't enough. @@ -18545,19 +19414,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { + if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); } - if (token() !== 25 /* SemicolonToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && + if (token() !== 26 /* SemicolonToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -18582,20 +19451,20 @@ var ts; } function parseConditionalExpressionRest(leftOperand) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - var questionToken = parseOptionalToken(55 /* QuestionToken */); + var questionToken = parseOptionalToken(56 /* QuestionToken */); if (!questionToken) { return leftOperand; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(203 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(205 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56 /* ColonToken */); + node.colonToken = parseExpectedToken(57 /* ColonToken */); node.whenFalse = ts.nodeIsPresent(node.colonToken) ? parseAssignmentExpressionOrHigher() - : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -18603,7 +19472,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 145 /* OfKeyword */; + return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -18632,16 +19501,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 92 /* InKeyword */ && inDisallowInContext()) { + if (token() === 93 /* InKeyword */ && inDisallowInContext()) { break; } - if (token() === 118 /* AsKeyword */) { + if (token() === 119 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -18662,51 +19531,51 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 92 /* InKeyword */) { + if (inDisallowInContext() && token() === 93 /* InKeyword */) { return false; } return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(202 /* BinaryExpression */, left.pos); + var node = createNode(204 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(210 /* AsExpression */, left.pos); + var node = createNode(212 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(200 /* PrefixUnaryExpression */); + var node = createNode(202 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(196 /* DeleteExpression */); + var node = createNode(198 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(197 /* TypeOfExpression */); + var node = createNode(199 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(198 /* VoidExpression */); + var node = createNode(200 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 121 /* AwaitKeyword */) { + if (token() === 122 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -18716,7 +19585,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(199 /* AwaitExpression */); + var node = createNode(201 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -18740,7 +19609,7 @@ var ts; */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? + return token() === 41 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } @@ -18757,10 +19626,10 @@ var ts; */ var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40 /* AsteriskAsteriskToken */) { + if (token() === 41 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 192 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) { parseErrorAt(pos, end, 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 { @@ -18785,23 +19654,23 @@ var ts; */ function parseSimpleUnaryExpression() { switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: return parsePrefixUnaryExpression(); - case 80 /* DeleteKeyword */: + case 81 /* DeleteKeyword */: return parseDeleteExpression(); - case 103 /* TypeOfKeyword */: + case 104 /* TypeOfKeyword */: return parseTypeOfExpression(); - case 105 /* VoidKeyword */: + case 106 /* VoidKeyword */: return parseVoidExpression(); - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // This is modified UnaryExpression grammar in TypeScript // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); - case 121 /* AwaitKeyword */: + case 122 /* AwaitKeyword */: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -18824,16 +19693,16 @@ var ts; // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 121 /* AwaitKeyword */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 122 /* AwaitKeyword */: return false; - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression if (sourceFile.languageVariant !== 1 /* JSX */) { return false; @@ -18856,21 +19725,21 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseUpdateExpression() { - if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(200 /* PrefixUnaryExpression */); + if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) { + var node = createNode(202 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(201 /* PostfixUnaryExpression */, expression.pos); + if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -18911,7 +19780,7 @@ var ts; // 3)we have a MemberExpression which either completes the LeftHandSideExpression, // or starts the beginning of the first four CallExpression productions. var expression; - if (token() === 91 /* ImportKeyword */) { + if (token() === 92 /* ImportKeyword */) { if (lookAhead(nextTokenIsOpenParenOrLessThan)) { // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" // For example: @@ -18926,8 +19795,8 @@ var ts; var fullStart = scanner.getStartPos(); nextToken(); // advance past the 'import' nextToken(); // advance past the dot - var node = createNode(212 /* MetaProperty */, fullStart); - node.keywordToken = 91 /* ImportKeyword */; + var node = createNode(214 /* MetaProperty */, fullStart); + node.keywordToken = 92 /* ImportKeyword */; node.name = parseIdentifierName(); expression = finishNode(node); sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; @@ -18937,7 +19806,7 @@ var ts; } } else { - expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); } // Now, we *may* be complete. However, we might have consumed the start of a // CallExpression. As such, we need to consume the rest of it here to be complete. @@ -18996,22 +19865,22 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) { + if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(187 /* PropertyAccessExpression */, expression.pos); + var node = createNode(189 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - parseExpectedToken(23 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 260 /* JsxOpeningElement */) { - var node = createNode(258 /* JsxElement */, opening.pos); + if (opening.kind === 262 /* JsxOpeningElement */) { + var node = createNode(260 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -19020,15 +19889,15 @@ var ts; } result = finishNode(node); } - else if (opening.kind === 263 /* JsxOpeningFragment */) { - var node = createNode(262 /* JsxFragment */, opening.pos); + else if (opening.kind === 265 /* JsxOpeningFragment */) { + var node = createNode(264 /* JsxFragment */, opening.pos); node.openingFragment = opening; node.children = parseJsxChildren(node.openingFragment); node.closingFragment = parseJsxClosingFragment(inExpressionContext); result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 259 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -19039,15 +19908,15 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token() === 27 /* LessThanToken */) { + if (inExpressionContext && token() === 28 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(202 /* BinaryExpression */, result.pos); + var badNode = createNode(204 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -19055,8 +19924,8 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10 /* JsxText */); - node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; + var node = createNode(11 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; currentToken = scanner.scanJsxToken(); return finishNode(node); } @@ -19072,15 +19941,15 @@ var ts; parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); } return undefined; - case 28 /* LessThanSlashToken */: + case 29 /* LessThanSlashToken */: case 7 /* ConflictMarkerTrivia */: return undefined; - case 10 /* JsxText */: - case 11 /* JsxTextAllWhiteSpaces */: + case 11 /* JsxText */: + case 12 /* JsxTextAllWhiteSpaces */: return parseJsxText(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); default: return ts.Debug.assertNever(token); @@ -19101,16 +19970,16 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(266 /* JsxAttributes */); + var jsxAttributes = createNode(268 /* JsxAttributes */); jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(27 /* LessThanToken */); - if (token() === 29 /* GreaterThanToken */) { + parseExpected(28 /* LessThanToken */); + if (token() === 30 /* GreaterThanToken */) { // See below for explanation of scanJsxText - var node_1 = createNode(263 /* JsxOpeningFragment */, fullStart); + var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart); scanJsxText(); return finishNode(node_1); } @@ -19118,23 +19987,23 @@ var ts; var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; - if (token() === 29 /* GreaterThanToken */) { + if (token() === 30 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(260 /* JsxOpeningElement */, fullStart); + node = createNode(262 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { - parseExpected(41 /* SlashToken */); + parseExpected(42 /* SlashToken */); if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(259 /* JsxSelfClosingElement */, fullStart); + node = createNode(261 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.typeArguments = typeArguments; @@ -19148,10 +20017,10 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token() === 99 /* ThisKeyword */ ? + var expression = token() === 100 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); + while (parseOptional(24 /* DotToken */)) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -19159,33 +20028,33 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(268 /* JsxExpression */); - if (!parseExpected(17 /* OpenBraceToken */)) { + var node = createNode(270 /* JsxExpression */); + if (!parseExpected(18 /* OpenBraceToken */)) { return undefined; } - if (token() !== 18 /* CloseBraceToken */) { - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + if (token() !== 19 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { - parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(265 /* JsxAttribute */); + var node = createNode(267 /* JsxAttribute */); node.name = parseIdentifierName(); - if (token() === 58 /* EqualsToken */) { + if (token() === 59 /* EqualsToken */) { switch (scanJsxAttributeValue()) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: node.initializer = parseLiteralNode(); break; default: @@ -19196,72 +20065,72 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(267 /* JsxSpreadAttribute */); - parseExpected(17 /* OpenBraceToken */); - parseExpected(24 /* DotDotDotToken */); + var node = createNode(269 /* JsxSpreadAttribute */); + parseExpected(18 /* OpenBraceToken */); + parseExpected(25 /* DotDotDotToken */); node.expression = parseExpression(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(261 /* JsxClosingElement */); - parseExpected(28 /* LessThanSlashToken */); + var node = createNode(263 /* JsxClosingElement */); + parseExpected(29 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxClosingFragment(inExpressionContext) { - var node = createNode(264 /* JsxClosingFragment */); - parseExpected(28 /* LessThanSlashToken */); + var node = createNode(266 /* JsxClosingFragment */); + parseExpected(29 /* LessThanSlashToken */); if (ts.tokenIsIdentifierOrKeyword(token())) { parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(192 /* TypeAssertionExpression */); - parseExpected(27 /* LessThanToken */); + var node = createNode(194 /* TypeAssertionExpression */); + parseExpected(28 /* LessThanToken */); node.type = parseType(); - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(23 /* DotToken */); + var dotToken = parseOptionalToken(24 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; } - if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(211 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName - if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(188 /* ElementAccessExpression */, expression.pos); + if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) { + var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; - if (token() === 22 /* CloseBracketToken */) { - indexedAccess.argumentExpression = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + if (token() === 23 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); } else { var argument = allowInAnd(parseExpression); @@ -19270,7 +20139,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } @@ -19282,13 +20151,13 @@ var ts; } } function isTemplateStartOfTaggedTemplate() { - return token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */; + return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */; } function parseTaggedTemplateRest(tag, typeArguments) { - var tagExpression = createNode(191 /* TaggedTemplateExpression */, tag.pos); + var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos); tagExpression.tag = tag; tagExpression.typeArguments = typeArguments; - tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); return finishNode(tagExpression); @@ -19296,7 +20165,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 27 /* LessThanToken */) { + if (token() === 28 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -19309,15 +20178,15 @@ var ts; expression = parseTaggedTemplateRest(expression, typeArguments); continue; } - var callExpr = createNode(189 /* CallExpression */, expression.pos); + var callExpr = createNode(191 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(189 /* CallExpression */, expression.pos); + else if (token() === 20 /* OpenParenToken */) { + var callExpr = createNode(191 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -19327,17 +20196,17 @@ var ts; } } function parseArgumentList() { - parseExpected(19 /* OpenParenToken */); + parseExpected(20 /* OpenParenToken */); var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(27 /* LessThanToken */)) { + if (!parseOptional(28 /* LessThanToken */)) { return undefined; } var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); - if (!parseExpected(29 /* GreaterThanToken */)) { + if (!parseExpected(30 /* GreaterThanToken */)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } @@ -19349,34 +20218,34 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 19 /* OpenParenToken */: // foo( - case 13 /* NoSubstitutionTemplateLiteral */: // foo `...` - case 14 /* TemplateHead */: // foo `...${100}...` + case 20 /* OpenParenToken */: // foo( + case 14 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 15 /* TemplateHead */: // foo `...${100}...` // these are the only tokens can legally follow a type argument // list. So we definitely want to treat them as type arg lists. - case 23 /* DotToken */: // foo. - case 20 /* CloseParenToken */: // foo) - case 22 /* CloseBracketToken */: // foo] - case 56 /* ColonToken */: // foo: - case 25 /* SemicolonToken */: // foo; - case 55 /* QuestionToken */: // foo? - case 32 /* EqualsEqualsToken */: // foo == - case 34 /* EqualsEqualsEqualsToken */: // foo === - case 33 /* ExclamationEqualsToken */: // foo != - case 35 /* ExclamationEqualsEqualsToken */: // foo !== - case 53 /* AmpersandAmpersandToken */: // foo && - case 54 /* BarBarToken */: // foo || - case 50 /* CaretToken */: // foo ^ - case 48 /* AmpersandToken */: // foo & - case 49 /* BarToken */: // foo | - case 18 /* CloseBraceToken */: // foo } + case 24 /* DotToken */: // foo. + case 21 /* CloseParenToken */: // foo) + case 23 /* CloseBracketToken */: // foo] + case 57 /* ColonToken */: // foo: + case 26 /* SemicolonToken */: // foo; + case 56 /* QuestionToken */: // foo? + case 33 /* EqualsEqualsToken */: // foo == + case 35 /* EqualsEqualsEqualsToken */: // foo === + case 34 /* ExclamationEqualsToken */: // foo != + case 36 /* ExclamationEqualsEqualsToken */: // foo !== + case 54 /* AmpersandAmpersandToken */: // foo && + case 55 /* BarBarToken */: // foo || + case 51 /* CaretToken */: // foo ^ + case 49 /* AmpersandToken */: // foo & + case 50 /* BarToken */: // foo | + case 19 /* CloseBraceToken */: // foo } case 1 /* EndOfFileToken */: // foo // these cases can't legally follow a type arg list. However, they're not legal // expressions either. The user is probably in the middle of a generic type. So // treat it as such. return true; - case 26 /* CommaToken */: // foo, - case 17 /* OpenBraceToken */: // foo { + case 27 /* CommaToken */: // foo, + case 18 /* OpenBraceToken */: // foo { // We don't want to treat these as type arguments. Otherwise we'll parse this // as an invocation expression. Instead, we want to parse out the expression // in isolation from the type arguments. @@ -19388,22 +20257,23 @@ var ts; function parsePrimaryExpression() { switch (token()) { case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return parseLiteralNode(); - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return parseTokenNode(); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return parseParenthesizedExpression(); - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: return parseArrayLiteralExpression(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseObjectLiteralExpression(); - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. // If we encounter `async [no LineTerminator here] function` then this is an async // function; otherwise, its an identifier. @@ -19411,75 +20281,76 @@ var ts; break; } return parseFunctionExpression(); - case 75 /* ClassKeyword */: + case 76 /* ClassKeyword */: return parseClassExpression(); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseFunctionExpression(); - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: return parseNewExpressionOrNewDotTarget(); - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) { return parseLiteralNode(); } break; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNodeWithJSDoc(193 /* ParenthesizedExpression */); - parseExpected(19 /* OpenParenToken */); + var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(206 /* SpreadElement */); - parseExpected(24 /* DotDotDotToken */); + var node = createNode(208 /* SpreadElement */); + parseExpected(25 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(208 /* OmittedExpression */) : + return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(185 /* ArrayLiteralExpression */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(187 /* ArrayLiteralExpression */); + parseExpected(22 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function parseObjectLiteralElement() { var node = createNodeWithJSDoc(0 /* Unknown */); - if (parseOptionalToken(24 /* DotDotDotToken */)) { - node.kind = 275 /* SpreadAssignment */; + if (parseOptionalToken(25 /* DotDotDotToken */)) { + node.kind = 277 /* SpreadAssignment */; node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* GetAccessor */); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); } - if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 157 /* SetAccessor */); + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); } - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } // check if it is short-hand property assignment or normal property assignment @@ -19487,30 +20358,30 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */); if (isShorthandPropertyAssignment) { - node.kind = 274 /* ShorthandPropertyAssignment */; - var equalsToken = parseOptionalToken(58 /* EqualsToken */); + node.kind = 276 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(59 /* EqualsToken */); if (equalsToken) { node.equalsToken = equalsToken; node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } } else { - node.kind = 273 /* PropertyAssignment */; - parseExpected(56 /* ColonToken */); + node.kind = 275 /* PropertyAssignment */; + parseExpected(57 /* ColonToken */); node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(186 /* ObjectLiteralExpression */); - parseExpected(17 /* OpenBraceToken */); + var node = createNode(188 /* ObjectLiteralExpression */); + parseExpected(18 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseFunctionExpression() { @@ -19523,10 +20394,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNodeWithJSDoc(194 /* FunctionExpression */); + var node = createNodeWithJSDoc(196 /* FunctionExpression */); node.modifiers = parseModifiers(); - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; node.name = @@ -19534,7 +20405,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlock(isGenerator | isAsync); if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -19546,10 +20417,10 @@ var ts; } function parseNewExpressionOrNewDotTarget() { var fullStart = scanner.getStartPos(); - parseExpected(94 /* NewKeyword */); - if (parseOptional(23 /* DotToken */)) { - var node_2 = createNode(212 /* MetaProperty */, fullStart); - node_2.keywordToken = 94 /* NewKeyword */; + parseExpected(95 /* NewKeyword */); + if (parseOptional(24 /* DotToken */)) { + var node_2 = createNode(214 /* MetaProperty */, fullStart); + node_2.keywordToken = 95 /* NewKeyword */; node_2.name = parseIdentifierName(); return finishNode(node_2); } @@ -19565,23 +20436,23 @@ var ts; } break; } - var node = createNode(190 /* NewExpression */, fullStart); + var node = createNode(192 /* NewExpression */, fullStart); node.expression = expression; node.typeArguments = typeArguments; - if (node.typeArguments || token() === 19 /* OpenParenToken */) { + if (node.typeArguments || token() === 20 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(216 /* Block */); - if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(218 /* Block */); + if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -19608,52 +20479,52 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(218 /* EmptyStatement */); - parseExpected(25 /* SemicolonToken */); + var node = createNode(220 /* EmptyStatement */); + parseExpected(26 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(220 /* IfStatement */); - parseExpected(90 /* IfKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(222 /* IfStatement */); + parseExpected(91 /* IfKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined; + node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(221 /* DoStatement */); - parseExpected(81 /* DoKeyword */); + var node = createNode(223 /* DoStatement */); + parseExpected(82 /* DoKeyword */); node.statement = parseStatement(); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. - parseOptional(25 /* SemicolonToken */); + parseOptional(26 /* SemicolonToken */); return finishNode(node); } function parseWhileStatement() { - var node = createNode(222 /* WhileStatement */); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(224 /* WhileStatement */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(88 /* ForKeyword */); - var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(89 /* ForKeyword */); + var awaitToken = parseOptionalToken(122 /* AwaitKeyword */); + parseExpected(20 /* OpenParenToken */); var initializer; - if (token() !== 25 /* SemicolonToken */) { - if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { + if (token() !== 26 /* SemicolonToken */) { + if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -19661,33 +20532,33 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(145 /* OfKeyword */) : parseOptional(145 /* OfKeyword */)) { - var forOfStatement = createNode(225 /* ForOfStatement */, pos); + if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) { + var forOfStatement = createNode(227 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } - else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(224 /* ForInStatement */, pos); + else if (parseOptional(93 /* InKeyword */)) { + var forInStatement = createNode(226 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(223 /* ForStatement */, pos); + var forStatement = createNode(225 /* ForStatement */, pos); forStatement.initializer = initializer; - parseExpected(25 /* SemicolonToken */); - if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { + parseExpected(26 /* SemicolonToken */); + if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(25 /* SemicolonToken */); - if (token() !== 20 /* CloseParenToken */) { + parseExpected(26 /* SemicolonToken */); + if (token() !== 21 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -19695,7 +20566,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 227 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -19703,8 +20574,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(228 /* ReturnStatement */); - parseExpected(96 /* ReturnKeyword */); + var node = createNode(230 /* ReturnStatement */); + parseExpected(97 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -19712,42 +20583,42 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(229 /* WithStatement */); - parseExpected(107 /* WithKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(231 /* WithStatement */); + parseExpected(108 /* WithKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(269 /* CaseClause */); - parseExpected(73 /* CaseKeyword */); + var node = createNode(271 /* CaseClause */); + parseExpected(74 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(270 /* DefaultClause */); - parseExpected(79 /* DefaultKeyword */); - parseExpected(56 /* ColonToken */); + var node = createNode(272 /* DefaultClause */); + parseExpected(80 /* DefaultKeyword */); + parseExpected(57 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(230 /* SwitchStatement */); - parseExpected(98 /* SwitchKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(232 /* SwitchStatement */); + parseExpected(99 /* SwitchKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(244 /* CaseBlock */); - parseExpected(17 /* OpenBraceToken */); + parseExpected(21 /* CloseParenToken */); + var caseBlock = createNode(246 /* CaseBlock */); + parseExpected(18 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); node.caseBlock = finishNode(caseBlock); return finishNode(node); } @@ -19759,32 +20630,32 @@ 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(232 /* ThrowStatement */); - parseExpected(100 /* ThrowKeyword */); + var node = createNode(234 /* ThrowStatement */); + parseExpected(101 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(233 /* TryStatement */); - parseExpected(102 /* TryKeyword */); + var node = createNode(235 /* TryStatement */); + parseExpected(103 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token() === 87 /* FinallyKeyword */) { - parseExpected(87 /* FinallyKeyword */); + if (!node.catchClause || token() === 88 /* FinallyKeyword */) { + parseExpected(88 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(272 /* CatchClause */); - parseExpected(74 /* CatchKeyword */); - if (parseOptional(19 /* OpenParenToken */)) { + var result = createNode(274 /* CatchClause */); + parseExpected(75 /* CatchKeyword */); + if (parseOptional(20 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); } else { // Keep shape of node to avoid degrading performance. @@ -19794,8 +20665,8 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(234 /* DebuggerStatement */); - parseExpected(78 /* DebuggerKeyword */); + var node = createNode(236 /* DebuggerStatement */); + parseExpected(79 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); } @@ -19805,13 +20676,13 @@ var ts; // a colon. var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); - if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - node.kind = 231 /* LabeledStatement */; + if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) { + node.kind = 233 /* LabeledStatement */; node.label = expression; node.statement = parseStatement(); } else { - node.kind = 219 /* ExpressionStatement */; + node.kind = 221 /* ExpressionStatement */; node.expression = expression; parseSemicolon(); } @@ -19823,25 +20694,25 @@ var ts; } function nextTokenIsClassKeywordOnSameLine() { nextToken(); - return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: return true; // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; // however, an identifier cannot be followed by another identifier on the same line. This is what we @@ -19864,41 +20735,41 @@ var ts; // I {} // // could be legal, it would add complexity for very little gain. - case 109 /* InterfaceKeyword */: - case 139 /* TypeKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 132 /* ReadonlyKeyword */: + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: nextToken(); // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 144 /* GlobalKeyword */: + case 145 /* GlobalKeyword */: nextToken(); - return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; - case 91 /* ImportKeyword */: + return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */; + case 92 /* ImportKeyword */: nextToken(); - return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); - case 84 /* ExportKeyword */: + return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 85 /* ExportKeyword */: nextToken(); - if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ || - token() === 118 /* AsKeyword */) { + if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ || + token() === 119 /* AsKeyword */) { return true; } continue; - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: nextToken(); continue; default: @@ -19911,50 +20782,50 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 57 /* AtToken */: - case 25 /* SemicolonToken */: - case 17 /* OpenBraceToken */: - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 90 /* IfKeyword */: - case 81 /* DoKeyword */: - case 106 /* WhileKeyword */: - case 88 /* ForKeyword */: - case 77 /* ContinueKeyword */: - case 72 /* BreakKeyword */: - case 96 /* ReturnKeyword */: - case 107 /* WithKeyword */: - case 98 /* SwitchKeyword */: - case 100 /* ThrowKeyword */: - case 102 /* TryKeyword */: - case 78 /* DebuggerKeyword */: + case 58 /* AtToken */: + case 26 /* SemicolonToken */: + case 18 /* OpenBraceToken */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 91 /* IfKeyword */: + case 82 /* DoKeyword */: + case 107 /* WhileKeyword */: + case 89 /* ForKeyword */: + case 78 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 97 /* ReturnKeyword */: + case 108 /* WithKeyword */: + case 99 /* SwitchKeyword */: + case 101 /* ThrowKeyword */: + case 103 /* TryKeyword */: + case 79 /* DebuggerKeyword */: // 'catch' and 'finally' do not actually indicate that the code is part of a statement, // however, we say they are here so that we may gracefully parse them and error later. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return true; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); - case 76 /* ConstKeyword */: - case 84 /* ExportKeyword */: + case 77 /* ConstKeyword */: + case 85 /* ExportKeyword */: return isStartOfDeclaration(); - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 109 /* InterfaceKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: - case 139 /* TypeKeyword */: - case 144 /* GlobalKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 110 /* InterfaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 140 /* TypeKeyword */: + case 145 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 116 /* StaticKeyword */: + case 133 /* 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); @@ -19964,7 +20835,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */; + return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -19973,67 +20844,67 @@ var ts; } function parseStatement() { switch (token()) { - case 25 /* SemicolonToken */: + case 26 /* SemicolonToken */: return parseEmptyStatement(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); - case 104 /* VarKeyword */: - return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); - case 110 /* LetKeyword */: + case 105 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + case 111 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); } break; - case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(createNodeWithJSDoc(237 /* FunctionDeclaration */)); - case 75 /* ClassKeyword */: - return parseClassDeclaration(createNodeWithJSDoc(238 /* ClassDeclaration */)); - case 90 /* IfKeyword */: + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */)); + case 76 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */)); + case 91 /* IfKeyword */: return parseIfStatement(); - case 81 /* DoKeyword */: + case 82 /* DoKeyword */: return parseDoStatement(); - case 106 /* WhileKeyword */: + case 107 /* WhileKeyword */: return parseWhileStatement(); - case 88 /* ForKeyword */: + case 89 /* ForKeyword */: return parseForOrForInOrForOfStatement(); - case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(226 /* ContinueStatement */); - case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(227 /* BreakStatement */); - case 96 /* ReturnKeyword */: + case 78 /* ContinueKeyword */: + return parseBreakOrContinueStatement(228 /* ContinueStatement */); + case 73 /* BreakKeyword */: + return parseBreakOrContinueStatement(229 /* BreakStatement */); + case 97 /* ReturnKeyword */: return parseReturnStatement(); - case 107 /* WithKeyword */: + case 108 /* WithKeyword */: return parseWithStatement(); - case 98 /* SwitchKeyword */: + case 99 /* SwitchKeyword */: return parseSwitchStatement(); - case 100 /* ThrowKeyword */: + case 101 /* ThrowKeyword */: return parseThrowStatement(); - case 102 /* TryKeyword */: + case 103 /* TryKeyword */: // Include 'catch' and 'finally' for error recovery. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return parseTryStatement(); - case 78 /* DebuggerKeyword */: + case 79 /* DebuggerKeyword */: return parseDebuggerStatement(); - case 57 /* AtToken */: + case 58 /* AtToken */: return parseDeclaration(); - case 120 /* AsyncKeyword */: - case 109 /* InterfaceKeyword */: - case 139 /* TypeKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 83 /* EnumKeyword */: - case 84 /* ExportKeyword */: - case 91 /* ImportKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: - case 144 /* GlobalKeyword */: + case 121 /* AsyncKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 84 /* EnumKeyword */: + case 85 /* ExportKeyword */: + case 92 /* ImportKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 118 /* AbstractKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + case 145 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -20042,7 +20913,7 @@ var ts; return parseExpressionOrLabeledStatement(); } function isDeclareModifier(modifier) { - return modifier.kind === 124 /* DeclareKeyword */; + return modifier.kind === 125 /* DeclareKeyword */; } function parseDeclaration() { var node = createNodeWithJSDoc(0 /* Unknown */); @@ -20061,33 +20932,33 @@ var ts; } function parseDeclarationWorker(node) { switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: return parseVariableStatement(node); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseFunctionDeclaration(node); - case 75 /* ClassKeyword */: + case 76 /* ClassKeyword */: return parseClassDeclaration(node); - case 109 /* InterfaceKeyword */: + case 110 /* InterfaceKeyword */: return parseInterfaceDeclaration(node); - case 139 /* TypeKeyword */: + case 140 /* TypeKeyword */: return parseTypeAliasDeclaration(node); - case 83 /* EnumKeyword */: + case 84 /* EnumKeyword */: return parseEnumDeclaration(node); - case 144 /* GlobalKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: + case 145 /* GlobalKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: return parseModuleDeclaration(node); - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return parseImportDeclarationOrImportEqualsDeclaration(node); - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: nextToken(); switch (token()) { - case 79 /* DefaultKeyword */: - case 58 /* EqualsToken */: + case 80 /* DefaultKeyword */: + case 59 /* EqualsToken */: return parseExportAssignment(node); - case 118 /* AsKeyword */: + case 119 /* AsKeyword */: return parseNamespaceExportDeclaration(node); default: return parseExportDeclaration(node); @@ -20096,7 +20967,7 @@ var ts; if (node.decorators || node.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 missing = createMissingNode(256 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; @@ -20107,10 +20978,10 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) { + if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -20118,25 +20989,25 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token() === 26 /* CommaToken */) { - return createNode(208 /* OmittedExpression */); + if (token() === 27 /* CommaToken */) { + return createNode(210 /* OmittedExpression */); } - var node = createNode(184 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(184 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56 /* ColonToken */) { + if (tokenIsIdentifier && token() !== 57 /* ColonToken */) { node.name = propertyName; } else { - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -20144,27 +21015,27 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(182 /* ObjectBindingPattern */); - parseExpected(17 /* OpenBraceToken */); + var node = createNode(184 /* ObjectBindingPattern */); + parseExpected(18 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(183 /* ArrayBindingPattern */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(185 /* ArrayBindingPattern */); + parseExpected(22 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier(); + return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -20173,10 +21044,10 @@ var ts; return parseVariableDeclaration(/*allowExclamation*/ true); } function parseVariableDeclaration(allowExclamation) { - var node = createNode(235 /* VariableDeclaration */); + var node = createNode(237 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); - if (allowExclamation && node.name.kind === 71 /* Identifier */ && - token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (allowExclamation && node.name.kind === 72 /* Identifier */ && + token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -20186,14 +21057,14 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(236 /* VariableDeclarationList */); + var node = createNode(238 /* VariableDeclarationList */); switch (token()) { - case 104 /* VarKeyword */: + case 105 /* VarKeyword */: break; - case 110 /* LetKeyword */: + case 111 /* LetKeyword */: node.flags |= 1 /* Let */; break; - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: node.flags |= 2 /* Const */; break; default: @@ -20209,7 +21080,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() === 145 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -20221,44 +21092,44 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; + return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */; } function parseVariableStatement(node) { - node.kind = 217 /* VariableStatement */; + node.kind = 219 /* VariableStatement */; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return finishNode(node); } function parseFunctionDeclaration(node) { - node.kind = 237 /* FunctionDeclaration */; - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.kind = 239 /* FunctionDeclaration */; + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); return finishNode(node); } function parseConstructorDeclaration(node) { - node.kind = 155 /* Constructor */; - parseExpected(123 /* ConstructorKeyword */); - fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.kind = 157 /* Constructor */; + parseExpected(124 /* ConstructorKeyword */); + fillSignature(57 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); return finishNode(node); } function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { - node.kind = 154 /* MethodDeclaration */; + node.kind = 156 /* MethodDeclaration */; node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); return finishNode(node); } function parsePropertyDeclaration(node) { - node.kind = 152 /* PropertyDeclaration */; - if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.kind = 154 /* PropertyDeclaration */; + if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -20278,12 +21149,12 @@ var ts; return finishNode(node); } function parsePropertyOrMethodDeclaration(node) { - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } return parsePropertyDeclaration(node); @@ -20291,13 +21162,13 @@ var ts; function parseAccessorDeclaration(node, kind) { node.kind = kind; node.name = parsePropertyName(); - fillSignature(56 /* ColonToken */, 0 /* None */, node); + fillSignature(57 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */); return finishNode(node); } function isClassMemberStart() { var idToken; - if (token() === 57 /* AtToken */) { + if (token() === 58 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. @@ -20314,7 +21185,7 @@ var ts; } nextToken(); } - if (token() === 39 /* AsteriskToken */) { + if (token() === 40 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. @@ -20324,24 +21195,24 @@ var ts; nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... if (idToken !== undefined) { // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!ts.isKeyword(idToken) || idToken === 136 /* SetKeyword */ || idToken === 125 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. switch (token()) { - case 19 /* OpenParenToken */: // Method declaration - case 27 /* LessThanToken */: // Generic Method declaration - case 51 /* ExclamationToken */: // Non-null assertion on property name - case 56 /* ColonToken */: // Type Annotation for declaration - case 58 /* EqualsToken */: // Initializer for declaration - case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. + case 20 /* OpenParenToken */: // Method declaration + case 28 /* LessThanToken */: // Generic Method declaration + case 52 /* ExclamationToken */: // Non-null assertion on property name + case 57 /* ColonToken */: // Type Annotation for declaration + case 59 /* EqualsToken */: // Initializer for declaration + case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. return true; default: // Covers @@ -20359,10 +21230,10 @@ var ts; var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(57 /* AtToken */)) { + if (!parseOptional(58 /* AtToken */)) { break; } - var decorator = createNode(150 /* Decorator */, decoratorStart); + var decorator = createNode(152 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -20382,7 +21253,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) { + if (token() === 77 /* 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)) { @@ -20401,7 +21272,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -20411,21 +21282,21 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 25 /* SemicolonToken */) { - var result = createNode(215 /* SemicolonClassElement */); + if (token() === 26 /* SemicolonToken */) { + var result = createNode(217 /* SemicolonClassElement */); nextToken(); return finishNode(result); } var node = createNodeWithJSDoc(0 /* Unknown */); node.decorators = parseDecorators(); node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* GetAccessor */); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); } - if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 157 /* SetAccessor */); + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); } - if (token() === 123 /* ConstructorKeyword */) { + if (token() === 124 /* ConstructorKeyword */) { return parseConstructorDeclaration(node); } if (isIndexSignature()) { @@ -20434,37 +21305,37 @@ var ts; // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || + token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || - token() === 39 /* AsteriskToken */ || - token() === 21 /* OpenBracketToken */) { + token() === 40 /* AsteriskToken */ || + token() === 22 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(node); } if (node.decorators || node.modifiers) { // treat this as a property declaration with a missing name. - node.name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 207 /* ClassExpression */); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */); } function parseClassDeclaration(node) { - return parseClassDeclarationOrExpression(node, 238 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(node, kind) { node.kind = kind; - parseExpected(75 /* ClassKeyword */); + parseExpected(76 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } node.members = parseClassMembers(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -20482,7 +21353,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses() { // ClassTail[Yield,Await] : (Modified) See 14.5 @@ -20494,33 +21365,33 @@ var ts; } function parseHeritageClause() { var tok = token(); - ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. - var node = createNode(271 /* HeritageClause */); + ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(273 /* HeritageClause */); node.token = tok; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); } function parseExpressionWithTypeArguments() { - var node = createNode(209 /* ExpressionWithTypeArguments */); + var node = createNode(211 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); node.typeArguments = tryParseTypeArguments(); return finishNode(node); } function tryParseTypeArguments() { - return token() === 27 /* LessThanToken */ - ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + return token() === 28 /* LessThanToken */ + ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */) : undefined; } function isHeritageClause() { - return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(node) { - node.kind = 239 /* InterfaceDeclaration */; - parseExpected(109 /* InterfaceKeyword */); + node.kind = 241 /* InterfaceDeclaration */; + parseExpected(110 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); @@ -20528,11 +21399,11 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(node) { - node.kind = 240 /* TypeAliasDeclaration */; - parseExpected(139 /* TypeKeyword */); + node.kind = 242 /* TypeAliasDeclaration */; + parseExpected(140 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(58 /* EqualsToken */); + parseExpected(59 /* EqualsToken */); node.type = parseType(); parseSemicolon(); return finishNode(node); @@ -20542,18 +21413,18 @@ 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 = createNodeWithJSDoc(276 /* EnumMember */); + var node = createNodeWithJSDoc(278 /* EnumMember */); node.name = parsePropertyName(); node.initializer = allowInAnd(parseInitializer); return finishNode(node); } function parseEnumDeclaration(node) { - node.kind = 241 /* EnumDeclaration */; - parseExpected(83 /* EnumKeyword */); + node.kind = 243 /* EnumDeclaration */; + parseExpected(84 /* EnumKeyword */); node.name = parseIdentifier(); - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -20561,10 +21432,10 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(243 /* ModuleBlock */); - if (parseExpected(17 /* OpenBraceToken */)) { + var node = createNode(245 /* ModuleBlock */); + if (parseExpected(18 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -20572,20 +21443,20 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(node, flags) { - node.kind = 242 /* ModuleDeclaration */; + node.kind = 244 /* ModuleDeclaration */; // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(23 /* DotToken */) + node.body = parseOptional(24 /* DotToken */) ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(node) { - node.kind = 242 /* ModuleDeclaration */; - if (token() === 144 /* GlobalKeyword */) { + node.kind = 244 /* ModuleDeclaration */; + if (token() === 145 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -20594,7 +21465,7 @@ var ts; node.name = parseLiteralNode(); node.name.text = internIdentifier(node.name.text); } - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -20604,68 +21475,68 @@ var ts; } function parseModuleDeclaration(node) { var flags = 0; - if (token() === 144 /* GlobalKeyword */) { + if (token() === 145 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(node); } - else if (parseOptional(130 /* NamespaceKeyword */)) { + else if (parseOptional(131 /* NamespaceKeyword */)) { flags |= 16 /* Namespace */; } else { - parseExpected(129 /* ModuleKeyword */); - if (token() === 9 /* StringLiteral */) { + parseExpected(130 /* ModuleKeyword */); + if (token() === 10 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(node); } } return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { - return token() === 133 /* RequireKeyword */ && + return token() === 134 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 19 /* OpenParenToken */; + return nextToken() === 20 /* OpenParenToken */; } function nextTokenIsSlash() { - return nextToken() === 41 /* SlashToken */; + return nextToken() === 42 /* SlashToken */; } function parseNamespaceExportDeclaration(node) { - node.kind = 245 /* NamespaceExportDeclaration */; - parseExpected(118 /* AsKeyword */); - parseExpected(130 /* NamespaceKeyword */); + node.kind = 247 /* NamespaceExportDeclaration */; + parseExpected(119 /* AsKeyword */); + parseExpected(131 /* NamespaceKeyword */); node.name = parseIdentifier(); parseSemicolon(); return finishNode(node); } function parseImportDeclarationOrImportEqualsDeclaration(node) { - parseExpected(91 /* ImportKeyword */); + parseExpected(92 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 143 /* FromKeyword */) { + if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) { return parseImportEqualsDeclaration(node, identifier); } } // Import statement - node.kind = 247 /* ImportDeclaration */; + node.kind = 249 /* ImportDeclaration */; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || // import id - token() === 39 /* AsteriskToken */ || // import * - token() === 17 /* OpenBraceToken */) { // import { + token() === 40 /* AsteriskToken */ || // import * + token() === 18 /* OpenBraceToken */) { // import { node.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(143 /* FromKeyword */); + parseExpected(144 /* FromKeyword */); } node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(node); } function parseImportEqualsDeclaration(node, identifier) { - node.kind = 246 /* ImportEqualsDeclaration */; + node.kind = 248 /* ImportEqualsDeclaration */; node.name = identifier; - parseExpected(58 /* EqualsToken */); + parseExpected(59 /* EqualsToken */); node.moduleReference = parseModuleReference(); parseSemicolon(); return finishNode(node); @@ -20677,7 +21548,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(248 /* ImportClause */, fullStart); + var importClause = createNode(250 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -20686,8 +21557,8 @@ var ts; // If there was no default import or if there is comma token after default import // parse namespace or named imports if (!importClause.name || - parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(250 /* NamedImports */); + parseOptional(27 /* CommaToken */)) { + importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */); } return finishNode(importClause); } @@ -20697,15 +21568,15 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(257 /* ExternalModuleReference */); - parseExpected(133 /* RequireKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(259 /* ExternalModuleReference */); + parseExpected(134 /* RequireKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = parseModuleSpecifier(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9 /* StringLiteral */) { + if (token() === 10 /* StringLiteral */) { var result = parseLiteralNode(); result.text = internIdentifier(result.text); return result; @@ -20720,9 +21591,9 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(249 /* NamespaceImport */); - parseExpected(39 /* AsteriskToken */); - parseExpected(118 /* AsKeyword */); + var namespaceImport = createNode(251 /* NamespaceImport */); + parseExpected(40 /* AsteriskToken */); + parseExpected(119 /* AsKeyword */); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } @@ -20735,14 +21606,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(255 /* ExportSpecifier */); + return parseImportOrExportSpecifier(257 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(251 /* ImportSpecifier */); + return parseImportOrExportSpecifier(253 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -20756,9 +21627,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 118 /* AsKeyword */) { + if (token() === 119 /* AsKeyword */) { node.propertyName = identifierName; - parseExpected(118 /* AsKeyword */); + parseExpected(119 /* AsKeyword */); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -20767,24 +21638,24 @@ var ts; else { node.name = identifierName; } - if (kind === 251 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(node) { - node.kind = 253 /* ExportDeclaration */; - if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(143 /* FromKeyword */); + node.kind = 255 /* ExportDeclaration */; + if (parseOptional(40 /* AsteriskToken */)) { + parseExpected(144 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(254 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(256 /* 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() === 143 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(143 /* FromKeyword */); + if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(144 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -20792,12 +21663,12 @@ var ts; return finishNode(node); } function parseExportAssignment(node) { - node.kind = 252 /* ExportAssignment */; - if (parseOptional(58 /* EqualsToken */)) { + node.kind = 254 /* ExportAssignment */; + if (parseOptional(59 /* EqualsToken */)) { node.isExportEquals = true; } else { - parseExpected(79 /* DefaultKeyword */); + parseExpected(80 /* DefaultKeyword */); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -20812,10 +21683,10 @@ var ts; } function isAnExternalModuleIndicatorNode(node) { return ts.hasModifier(node, 1 /* Export */) - || node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */ - || node.kind === 247 /* ImportDeclaration */ - || node.kind === 252 /* ExportAssignment */ - || node.kind === 253 /* ExportDeclaration */ + || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */ + || node.kind === 249 /* ImportDeclaration */ + || node.kind === 254 /* ExportAssignment */ + || node.kind === 255 /* ExportDeclaration */ ? node : undefined; } @@ -20828,7 +21699,7 @@ var ts; return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); } function isImportMeta(node) { - return ts.isMetaProperty(node) && node.keywordToken === 91 /* ImportKeyword */ && node.name.escapedText === "meta"; + return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta"; } var ParsingContext; (function (ParsingContext) { @@ -20879,11 +21750,11 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); - var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); + var result = createNode(283 /* JSDocTypeExpression */); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } fixupParentReferences(result); return finishNode(result); @@ -20971,7 +21842,7 @@ var ts; } loop: while (true) { switch (token()) { - case 57 /* AtToken */: + case 58 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingWhitespace(comments); addTag(parseTag(indent)); @@ -20991,7 +21862,7 @@ var ts; state = 0 /* BeginningOfLine */; indent = 0; break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: var asterisk = scanner.getTokenText(); if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { // If we've already seen an asterisk, then we can no longer parse a tag on this line @@ -21004,13 +21875,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21025,7 +21889,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21047,7 +21913,7 @@ var ts; } } function createJSDocComment() { - var result = createNode(289 /* JSDocComment */, start); + var result = createNode(291 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -21081,61 +21947,60 @@ var ts; } } var precedingLineBreak = scanner.hasPrecedingLineBreak(); - while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { if (token() === 4 /* NewLineTrivia */) { precedingLineBreak = true; } - else if (token() === 39 /* AsteriskToken */) { + else if (token() === 40 /* AsteriskToken */) { precedingLineBreak = false; } nextJSDocToken(); } } function parseTag(indent) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getTokenPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": case "extends": - tag = parseAugmentsTag(atToken, tagName); + tag = parseAugmentsTag(start, tagName); break; case "class": case "constructor": - tag = parseClassTag(atToken, tagName); + tag = parseClassTag(start, tagName); break; case "this": - tag = parseThisTag(atToken, tagName); + tag = parseThisTag(start, tagName); break; case "enum": - tag = parseEnumTag(atToken, tagName); + tag = parseEnumTag(start, tagName); break; case "arg": case "argument": case "param": - return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent); + return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent); case "return": case "returns": - tag = parseReturnTag(atToken, tagName); + tag = parseReturnTag(start, tagName); break; case "template": - tag = parseTemplateTag(atToken, tagName); + tag = parseTemplateTag(start, tagName); break; case "type": - tag = parseTypeTag(atToken, tagName); + tag = parseTypeTag(start, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName, indent); + tag = parseTypedefTag(start, tagName, indent); break; case "callback": - tag = parseCallbackTag(atToken, tagName, indent); + tag = parseCallbackTag(start, tagName, indent); break; default: - tag = parseUnknownTag(atToken, tagName); + tag = parseUnknownTag(start, tagName); break; } if (!tag.comment) { @@ -21165,7 +22030,7 @@ var ts; } indent = 0; break; - case 57 /* AtToken */: + case 58 /* AtToken */: scanner.setTextPos(scanner.getTextPos() - 1); // falls through case 1 /* EndOfFileToken */: @@ -21184,9 +22049,9 @@ var ts; indent += whitespace.length; } break; - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: state = 2 /* SavingComments */; - if (lookAhead(function () { return nextJSDocToken() === 57 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { pushComment(scanner.getTokenText()); nextJSDocToken(); pushComment(scanner.getTokenText()); @@ -21194,7 +22059,7 @@ var ts; } pushComment(scanner.getTokenText()); break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; @@ -21214,9 +22079,8 @@ var ts; removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } - function parseUnknownTag(atToken, tagName) { - var result = createNode(292 /* JSDocTag */, atToken.pos); - result.atToken = atToken; + function parseUnknownTag(start, tagName) { + var result = createNode(294 /* JSDocTag */, start); result.tagName = tagName; return finishNode(result); } @@ -21235,37 +22099,37 @@ var ts; } function tryParseTypeExpression() { skipWhitespaceOrAsterisk(); - return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; + return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { - if (token() === 13 /* NoSubstitutionTemplateLiteral */) { + if (token() === 14 /* NoSubstitutionTemplateLiteral */) { // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; } // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' - var isBracketed = parseOptional(21 /* OpenBracketToken */); + var isBracketed = parseOptional(22 /* OpenBracketToken */); var name = parseJSDocEntityName(); if (isBracketed) { skipWhitespace(); // May have an optional default, e.g. '[foo = 42]' - if (parseOptionalToken(58 /* EqualsToken */)) { + if (parseOptionalToken(59 /* EqualsToken */)) { parseExpression(); } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); } return { name: name, isBracketed: isBracketed }; } function isObjectOrObjectArrayTypeReference(node) { switch (node.kind) { - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return true; - case 167 /* ArrayType */: + case 169 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; } } - function parseParameterOrPropertyTag(atToken, tagName, target, indent) { + function parseParameterOrPropertyTag(start, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -21275,17 +22139,14 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(303 /* JSDocPropertyTag */, atToken.pos) : - createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + createNode(305 /* JSDocPropertyTag */, start) : + createNode(299 /* JSDocParameterTag */, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; } - result.atToken = atToken; result.tagName = tagName; result.typeExpression = typeExpression; result.name = name; @@ -21294,22 +22155,22 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 167 /* ArrayType */) { + if (typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -21317,81 +22178,74 @@ var ts; } } } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) { + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(298 /* JSDocReturnTag */, atToken.pos); - result.atToken = atToken; + var result = createNode(300 /* JSDocReturnTag */, start); result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) { + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(300 /* JSDocTypeTag */, atToken.pos); - result.atToken = atToken; + var result = createNode(302 /* JSDocTypeTag */, start); result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } - function parseAugmentsTag(atToken, tagName) { - var result = createNode(293 /* JSDocAugmentsTag */, atToken.pos); - result.atToken = atToken; + function parseAugmentsTag(start, tagName) { + var result = createNode(295 /* JSDocAugmentsTag */, start); result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } function parseExpressionWithTypeArgumentsForAugments() { - var usedBrace = parseOptional(17 /* OpenBraceToken */); - var node = createNode(209 /* ExpressionWithTypeArguments */); + var usedBrace = parseOptional(18 /* OpenBraceToken */); + var node = createNode(211 /* ExpressionWithTypeArguments */); node.expression = parsePropertyAccessEntityNameExpression(); node.typeArguments = tryParseTypeArguments(); var res = finishNode(node); if (usedBrace) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } return res; } function parsePropertyAccessEntityNameExpression() { var node = parseJSDocIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var prop = createNode(187 /* PropertyAccessExpression */, node.pos); + while (parseOptional(24 /* DotToken */)) { + var prop = createNode(189 /* PropertyAccessExpression */, node.pos); prop.expression = node; prop.name = parseJSDocIdentifierName(); node = finishNode(prop); } return node; } - function parseClassTag(atToken, tagName) { - var tag = createNode(294 /* JSDocClassTag */, atToken.pos); - tag.atToken = atToken; + function parseClassTag(start, tagName) { + var tag = createNode(296 /* JSDocClassTag */, start); tag.tagName = tagName; return finishNode(tag); } - function parseThisTag(atToken, tagName) { - var tag = createNode(299 /* JSDocThisTag */, atToken.pos); - tag.atToken = atToken; + function parseThisTag(start, tagName) { + var tag = createNode(301 /* JSDocThisTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseEnumTag(atToken, tagName) { - var tag = createNode(296 /* JSDocEnumTag */, atToken.pos); - tag.atToken = atToken; + function parseEnumTag(start, tagName) { + var tag = createNode(298 /* JSDocEnumTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseTypedefTag(atToken, tagName, indent) { + function parseTypedefTag(start, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); - typedefTag.atToken = atToken; + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304 /* JSDocTypedefTag */, start); typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); @@ -21403,12 +22257,11 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); } - if (child.kind === 300 /* JSDocTypeTag */) { + if (child.kind === 302 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -21421,7 +22274,7 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 167 /* ArrayType */) { + if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? @@ -21439,8 +22292,8 @@ var ts; return undefined; } var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(242 /* ModuleDeclaration */, pos); + if (parseOptional(24 /* DotToken */)) { + var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos); if (nested) { jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } @@ -21453,25 +22306,23 @@ var ts; } return typeNameOrNamespaceName; } - function parseCallbackTag(atToken, tagName, indent) { - var callbackTag = createNode(295 /* JSDocCallbackTag */, atToken.pos); - callbackTag.atToken = atToken; + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297 /* JSDocCallbackTag */, start); callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); skipWhitespace(); callbackTag.comment = parseTagComments(indent); var child; - var start = scanner.getStartPos(); - var jsdocSignature = createNode(291 /* JSDocSignature */, start); + var jsdocSignature = createNode(293 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { - if (parseOptionalJsdoc(57 /* AtToken */)) { + if (parseOptionalJsdoc(58 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 298 /* JSDocReturnTag */) { + if (tag && tag.kind === 300 /* JSDocReturnTag */) { return tag; } } @@ -21505,18 +22356,18 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { - case 57 /* AtToken */: + case 58 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); - if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -21529,13 +22380,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 71 /* Identifier */: + case 72 /* Identifier */: canParseTag = false; break; case 1 /* EndOfFileToken */: @@ -21543,17 +22394,16 @@ var ts; } } } - function tryParseChildTag(target) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */); - atToken.end = scanner.getTextPos(); + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getStartPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); skipWhitespace(); var t; switch (tagName.escapedText) { case "type": - return target === 1 /* Property */ && parseTypeTag(atToken, tagName); + return target === 1 /* Property */ && parseTypeTag(start, tagName); case "prop": case "property": t = 1 /* Property */; @@ -21569,28 +22419,25 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(start, tagName, target, indent); } - function parseTemplateTag(atToken, tagName) { + function parseTemplateTag(start, tagName) { // the template tag looks like '@template {Constraint} T,U,V' var constraint; - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { constraint = parseJSDocTypeExpression(); } var typeParameters = []; var typeParametersPos = getNodePos(); do { skipWhitespace(); - var typeParameter = createNode(148 /* TypeParameter */); + var typeParameter = createNode(150 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); finishNode(typeParameter); skipWhitespace(); typeParameters.push(typeParameter); - } while (parseOptionalJsdoc(26 /* CommaToken */)); - var result = createNode(301 /* JSDocTemplateTag */, atToken.pos); - result.atToken = atToken; + } while (parseOptionalJsdoc(27 /* CommaToken */)); + var result = createNode(303 /* JSDocTemplateTag */, start); result.tagName = tagName; result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -21609,16 +22456,16 @@ var ts; } function parseJSDocEntityName() { var entity = parseJSDocIdentifierName(); - if (parseOptional(21 /* OpenBracketToken */)) { - parseExpected(22 /* CloseBracketToken */); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> // but it's not worth it to enforce that restriction. } - while (parseOptional(23 /* DotToken */)) { + while (parseOptional(24 /* DotToken */)) { var name = parseJSDocIdentifierName(); - if (parseOptional(21 /* OpenBracketToken */)) { - parseExpected(22 /* CloseBracketToken */); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); } entity = createQualifiedName(entity, name); } @@ -21626,11 +22473,11 @@ var ts; } function parseJSDocIdentifierName(message) { if (!ts.tokenIsIdentifierOrKeyword(token())) { - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(71 /* Identifier */, pos); + var result = createNode(72 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); @@ -21756,9 +22603,9 @@ var ts; } function shouldCheckNode(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 71 /* Identifier */: + case 72 /* Identifier */: return true; } return false; @@ -22336,10 +23183,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 71 /* Identifier */) { + if (lhs.kind === 72 /* Identifier */) { return lhs.escapedText === rhs.escapedText; } - if (lhs.kind === 99 /* ThisKeyword */) { + if (lhs.kind === 100 /* ThisKeyword */) { return true; } // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only @@ -22396,7 +23243,8 @@ var ts; ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.symbol", "lib.esnext.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], - ["esnext.intl", "lib.esnext.intl.d.ts"] + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -22412,8 +23260,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22427,6 +23274,61 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22468,26 +23370,11 @@ var ts; description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date }, { - name: "pretty", + name: "showConfig", type: "boolean", - showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental - }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, // Basic { @@ -22503,6 +23390,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22521,6 +23410,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22533,6 +23423,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22540,6 +23431,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22557,6 +23449,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22666,6 +23559,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22674,6 +23568,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22682,14 +23577,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22698,6 +23603,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22706,6 +23612,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22739,6 +23646,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22751,6 +23659,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22758,6 +23667,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22767,6 +23677,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22782,6 +23693,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22793,6 +23705,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22803,6 +23716,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22875,42 +23789,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h }, - { - name: "diagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_diagnostic_information - }, - { - name: "extendedDiagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_verbose_diagnostic_information - }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22969,12 +23853,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22987,6 +23873,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23032,6 +23919,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23039,6 +23927,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23066,6 +23955,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23093,7 +23983,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23146,20 +24074,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23195,16 +24124,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23216,7 +24144,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23224,7 +24152,7 @@ var ts; 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)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23260,7 +24188,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23303,9 +24231,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23318,7 +24256,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23445,6 +24411,9 @@ var ts; } var result = ts.parseJsonText(configFileName, configFileText); var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; @@ -23584,7 +24553,7 @@ var ts; var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 273 /* PropertyAssignment */) { + if (element.kind !== 275 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -23632,20 +24601,24 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { - case 101 /* TrueKeyword */: + case 102 /* TrueKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return true; - case 86 /* FalseKeyword */: + case 87 /* FalseKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return false; - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for return null; // tslint:disable-line:no-null-keyword - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } @@ -23662,13 +24635,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 200 /* PrefixUnaryExpression */: - if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + case 202 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return -Number(valueExpression.operand.text); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -23685,7 +24658,7 @@ var ts; return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); } - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -23725,6 +24698,115 @@ var ts; } return false; } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return false; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + } + return function (path) { return includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return !excludeRe.test(path); }; + } + return function (_) { return false; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } /** * Generate tsconfig configuration when running command line "--init" * @param options commandlineOptions to be generated into tsconfig.json @@ -23735,62 +24817,6 @@ var ts; var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - // There is a typeMap associated with this command-line option so use it to map value back to its name - return ts.forEachEntry(customTypeMap, function (mapValue, key) { - if (mapValue === value) { - return key; - } - }); - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_3 = function (name) { - if (ts.hasProperty(options, name)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - return "continue"; - } - var value = options[name]; - var optionDefinition = optionsNameMap.get(name.toLowerCase()); - if (optionDefinition) { - var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap_1) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result.set(name, value); - } - else { - if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); - } - } - } - } - }; - for (var name in options) { - _loop_3(name); - } - return result; - } function getDefaultValueForOption(option) { switch (option.type) { case "number": @@ -23939,7 +24965,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23956,8 +24983,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23993,19 +25034,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24013,7 +25053,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24027,17 +25066,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24123,11 +25178,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24155,26 +25205,30 @@ var ts; } function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { - errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return undefined; - } - var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return undefined; + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } } + return extendedConfigPath; } - return extendedConfigPath; + // If the path isn't a rooted or relative path, resolve like a module + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24182,7 +25236,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24396,7 +25450,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24421,10 +25475,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24434,9 +25493,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24444,7 +25519,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24455,16 +25530,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24597,7 +25672,7 @@ var ts; } } /** - * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. * Also converts enum values back to strings. */ /* @internal */ @@ -24653,6 +25728,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24662,14 +25743,15 @@ var ts; Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; Extensions[Extensions["Json"] = 2] = "Json"; - Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */ + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24678,48 +25760,97 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24761,9 +25892,13 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24782,8 +25917,10 @@ var ts; trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24792,13 +25929,12 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - if (!options.preserveSymlinks) { - resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); - } + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -24807,14 +25943,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } - return ts.forEach(typeRoots, function (typeRoot) { + return ts.firstDefined(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24830,8 +25966,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - var resolvedFile = resolvedTypeScriptOnly(result && result.value); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + var resolvedFile = resolvedTypeScriptOnly(result); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -24869,14 +26013,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -24887,29 +26035,56 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); } ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + /*@internal*/ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName) { + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); - var perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = ts.createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); } - function getOrCreateCacheForModuleName(nonRelativeModuleName) { + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); - var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); } - return perModuleNameCache; + return result; } function createPerModuleNameCache() { var directoryPathMap = ts.createMap(); @@ -24984,13 +26159,19 @@ var ts; return perFolderCache && perFolderCache.get(moduleName); } ts.resolveModuleNameFromCache = resolveModuleNameFromCache; - function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } var containingDirectory = ts.getDirectoryPath(containingFile); - var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { @@ -25012,10 +26193,10 @@ var ts; } switch (moduleResolution) { case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; default: return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); @@ -25024,7 +26205,7 @@ var ts; perFolderCache.set(moduleName, result); if (!ts.isExternalModuleNameRelative(moduleName)) { // put result in per-module name cache - cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); } } } @@ -25099,15 +26280,28 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25145,7 +26339,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25164,7 +26358,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25175,95 +26369,72 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!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); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; - function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? - tryResolve(Extensions.JavaScript) : - (tryResolve(Extensions.TypeScript) || - tryResolve(Extensions.JavaScript) || - (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); if (result && result.value) { var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25277,7 +26448,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25294,29 +26465,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25324,10 +26496,15 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; /** * This will be called on the successfully resolved path from `loadModuleFromFile`. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) @@ -25365,52 +26542,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @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; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - if (extensions === Extensions.Json) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25420,16 +26591,17 @@ var ts; return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.TSConfig: case Extensions.Json: return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25443,40 +26615,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25488,6 +26653,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25499,51 +26665,72 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { - // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25555,6 +26742,7 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TSConfig: case Extensions.Json: return extension === ".json" /* Json */; case Extensions.TypeScript: @@ -25563,87 +26751,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25651,11 +26881,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25664,68 +26894,69 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } - function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } if (!ts.isExternalModuleNameRelative(moduleName)) { - var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25740,9 +26971,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25771,24 +27002,24 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: if (!(ts.hasModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. other uninstantiated module declarations. - case 243 /* ModuleBlock */: { + case 245 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateWorker(n); @@ -25810,9 +27041,9 @@ var ts; }); return state_1; } - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return getModuleInstanceState(node); - case 71 /* Identifier */: + case 72 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should // be considered the same as type alias if (node.isInJSDocNamespace) { @@ -25957,19 +27188,23 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + 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.kind === 252 /* ExportAssignment */) { + if (node.kind === 254 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -25978,7 +27213,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -25990,36 +27225,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: return "__constructor" /* Constructor */; - case 163 /* FunctionType */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: + case 165 /* FunctionType */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: return "__call" /* Call */; - case 164 /* ConstructorType */: - case 159 /* ConstructSignature */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: return "__new" /* New */; - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return "__index" /* Index */; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 149 /* Parameter */: + case 151 /* 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 === 287 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -26088,7 +27323,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26116,7 +27352,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; } @@ -26143,7 +27379,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 255 /* ExportSpecifier */ || (node.kind === 246 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -26166,12 +27402,12 @@ var ts; // 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.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26210,7 +27446,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 195 /* ArrowFunction */) { + if (node.kind !== 197 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -26242,7 +27478,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property intialization checks. - currentReturnTarget = isIIFE || node.kind === 155 /* Constructor */ ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; @@ -26255,13 +27491,13 @@ var ts; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { node.flags |= emitFlags; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 155 /* Constructor */) { + if (node.kind === 157 /* Constructor */) { node.returnFlowNode = currentFlow; } } @@ -26304,8 +27540,8 @@ var ts; } } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -26334,81 +27570,82 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: bindWhileStatement(node); break; - case 221 /* DoStatement */: + case 223 /* DoStatement */: bindDoStatement(node); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: bindForStatement(node); break; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: bindIfStatement(node); break; - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: bindTryStatement(node); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: bindSwitchStatement(node); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: bindCaseBlock(node); break; - case 269 /* CaseClause */: + case 271 /* CaseClause */: bindCaseClause(node); break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: bindLabeledStatement(node); break; - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: bindCallExpressionFlow(node); break; - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 277 /* SourceFile */: { + case 279 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; default: @@ -26419,24 +27656,26 @@ var ts; } function isNarrowingExpression(expr) { switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return isNarrowableReference(expr); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return hasNarrowableArgument(expr); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 200 /* PrefixUnaryExpression */: - return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 202 /* PrefixUnaryExpression */: + return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 199 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || + return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && @@ -26451,7 +27690,7 @@ var ts; } } } - if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26465,32 +27704,32 @@ var ts; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return isNarrowableReference(expr.left); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); - case 92 /* InKeyword */: + case 93 /* InKeyword */: return isNarrowableInOperands(expr.left, expr.right); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return isNarrowableOperand(expr.right); } } @@ -26525,8 +27764,8 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -26564,34 +27803,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 220 /* IfStatement */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: return parent.expression === node; - case 223 /* ForStatement */: - case 203 /* ConditionalExpression */: + case 225 /* ForStatement */: + case 205 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 193 /* ParenthesizedExpression */) { + if (node.kind === 195 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 200 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 202 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 54 /* BarBarToken */); + return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 55 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 193 /* ParenthesizedExpression */ || - node.parent.kind === 200 /* PrefixUnaryExpression */ && - node.parent.operator === 51 /* ExclamationToken */) { + while (node.parent.kind === 195 /* ParenthesizedExpression */ || + node.parent.kind === 202 /* PrefixUnaryExpression */ && + node.parent.operator === 52 /* ExclamationToken */) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -26632,7 +27871,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 231 /* LabeledStatement */ + var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */ ? ts.lastOrUndefined(activeLabels) : undefined; // if do statement is wrapped in labeled statement then target labels for break/continue with or without @@ -26666,13 +27905,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 225 /* ForOfStatement */) { + if (node.kind === 227 /* ForOfStatement */) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 236 /* VariableDeclarationList */) { + if (node.initializer.kind !== 238 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -26694,7 +27933,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 228 /* ReturnStatement */) { + if (node.kind === 230 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -26714,7 +27953,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 227 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -26810,7 +28049,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 270 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; @@ -26834,7 +28073,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -26878,14 +28116,14 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } - if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { + if (!node.statement || node.statement.kind !== 223 /* DoStatement */) { // do statement sets current flow inside bindDoStatement addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -26896,10 +28134,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 185 /* ArrayLiteralExpression */) { + else if (node.kind === 187 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 206 /* SpreadElement */) { + if (e.kind === 208 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -26907,16 +28145,16 @@ var ts; } } } - else if (node.kind === 186 /* ObjectLiteralExpression */) { + else if (node.kind === 188 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 273 /* PropertyAssignment */) { + if (p.kind === 275 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 274 /* ShorthandPropertyAssignment */) { + else if (p.kind === 276 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 275 /* SpreadAssignment */) { + else if (p.kind === 277 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -26924,7 +28162,7 @@ var ts; } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -26935,7 +28173,7 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51 /* ExclamationToken */) { + if (node.operator === 52 /* ExclamationToken */) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; @@ -26945,20 +28183,20 @@ var ts; } else { bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -26972,7 +28210,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 188 /* ElementAccessExpression */) { + if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -26983,7 +28221,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -27021,6 +28259,7 @@ var ts; } } function bindJSDocTypeAlias(node) { + node.tagName.parent = node; if (node.fullName) { setParentPointers(node, node.fullName); } @@ -27030,10 +28269,10 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 193 /* ParenthesizedExpression */) { + while (expr.kind === 195 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 194 /* FunctionExpression */ || expr.kind === 195 /* ArrowFunction */) { + if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -27041,7 +28280,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -27050,54 +28289,54 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 186 /* ObjectLiteralExpression */: - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 266 /* JsxAttributes */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 268 /* JsxAttributes */: return 1 /* IsContainer */; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 179 /* MappedType */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: - case 287 /* JSDocFunctionType */: - case 163 /* FunctionType */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 164 /* ConstructorType */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 289 /* JSDocFunctionType */: + case 165 /* FunctionType */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 166 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 272 /* CatchClause */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 244 /* CaseBlock */: + case 274 /* CatchClause */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 246 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 216 /* Block */: + case 218 /* 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 @@ -27130,45 +28369,45 @@ var ts; // 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 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 277 /* SourceFile */: + case 279 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 186 /* ObjectLiteralExpression */: - case 239 /* InterfaceDeclaration */: - case 266 /* JsxAttributes */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 188 /* ObjectLiteralExpression */: + case 241 /* InterfaceDeclaration */: + case 268 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 291 /* JSDocSignature */: - case 160 /* IndexSignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 287 /* JSDocFunctionType */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 240 /* TypeAliasDeclaration */: - case 179 /* MappedType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 293 /* JSDocSignature */: + case 162 /* IndexSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 289 /* JSDocFunctionType */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -27189,11 +28428,11 @@ var ts; : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 277 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 277 /* SourceFile */ || body.kind === 243 /* ModuleBlock */)) { + var body = node.kind === 279 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 253 /* ExportDeclaration */ || stat.kind === 252 /* ExportAssignment */) { + if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { return true; } } @@ -27221,7 +28460,7 @@ var ts; } else { var pattern = void 0; - if (node.name.kind === 9 /* StringLiteral */) { + if (node.name.kind === 10 /* StringLiteral */) { var text = node.name.text; if (ts.hasZeroOrOneAsteriskCharacter(text)) { pattern = ts.tryParsePattern(text); @@ -27230,7 +28469,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27250,7 +28489,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27277,7 +28516,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) { continue; } var identifier = prop.name; @@ -27289,7 +28528,7 @@ var ts; // 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 === 273 /* PropertyAssignment */ || prop.kind === 274 /* ShorthandPropertyAssignment */ || prop.kind === 154 /* MethodDeclaration */ + var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -27321,10 +28560,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -27338,9 +28577,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27358,9 +28594,9 @@ var ts; currentFlow = { flags: 2 /* Start */ }; parent = typeAlias; bind(typeAlias.typeExpression); - if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { + if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27376,8 +28612,8 @@ var ts; // check for reserved words used as identifiers in strict mode code. function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && + node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 117 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && !(node.flags & 4194304 /* Ambient */)) { // Report error only if there are no parse errors in file @@ -27413,7 +28649,7 @@ var ts; } function checkStrictModeDeleteExpression(node) { // Grammar checking - if (inStrictMode && node.expression.kind === 71 /* Identifier */) { + if (inStrictMode && node.expression.kind === 72 /* 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); @@ -27424,7 +28660,7 @@ var ts; return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71 /* Identifier */) { + if (name && name.kind === 72 /* 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 @@ -27465,8 +28701,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 277 /* SourceFile */ && - blockScopeContainer.kind !== 242 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 279 /* SourceFile */ && + blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -27492,7 +28728,7 @@ var ts; function checkStrictModePrefixUnaryExpression(node) { // Grammar checking if (inStrictMode) { - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -27561,7 +28797,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 145 /* LastToken */) { + if (node.kind > 147 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -27585,7 +28821,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27623,7 +28859,7 @@ var ts; function bindWorker(node) { switch (node.kind) { /* Strict mode checks */ - case 71 /* Identifier */: + case 72 /* Identifier */: // for typedef type names with namespaces, bind the new jsdoc type symbol here // because it requires all containing namespaces to be in effect, namely the // current "blockScopeContainer" needs to be set to its immediate namespace parent. @@ -27632,32 +28868,32 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through - case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 274 /* ShorthandPropertyAssignment */)) { + case 100 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; - case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27681,142 +28917,155 @@ var ts; // Nothing to do break; default: - ts.Debug.fail("Unknown special property assignment kind"); + ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return checkStrictModeCatchClause(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return checkStrictModeWithStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 176 /* ThisType */: + case 178 /* ThisType */: seenThisKeyword = true; return; - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: break; // Binding the children will handle everything - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return bindTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return bindParameter(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return bindPropertyWorker(node); - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 276 /* EnumMember */: + case 278 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); - case 237 /* FunctionDeclaration */: + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); + case 239 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); - case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); - case 163 /* FunctionType */: - case 287 /* JSDocFunctionType */: - case 291 /* JSDocSignature */: - case 164 /* ConstructorType */: + case 158 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); + case 159 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + case 166 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 179 /* MappedType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 181 /* MappedType */: return bindAnonymousTypeWorker(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return bindFunctionExpression(node); - case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + case 191 /* CallExpression */: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; // Nothing to do + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); - case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - case 241 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); + case 242 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + case 243 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return bindJsxAttributes(node); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return bindImportClause(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return bindExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return bindExportAssignment(node); - case 277 /* SourceFile */: + case 279 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 216 /* Block */: + case 218 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 297 /* JSDocParameterTag */: - if (node.parent.kind === 291 /* JSDocSignature */) { + case 299 /* JSDocParameterTag */: + if (node.parent.kind === 293 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 290 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { break; } // falls through - case 303 /* JSDocPropertyTag */: + case 305 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -27848,37 +29097,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27905,6 +29152,21 @@ var ts; } return true; } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } function bindExportsPropertyAssignment(node) { // When we create a property via 'exports.foo = bar', the 'exports.foo' property access // expression is the declaration @@ -27914,7 +29176,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27941,17 +29203,17 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. - if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) { var l = thisContainer.parent.left; if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); @@ -27964,18 +29226,18 @@ var ts; declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } break; - case 155 /* Constructor */: - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: // this.foo assignment in a source file // Do not bind. It would be nice to support this someday though. break; @@ -27984,10 +29246,10 @@ var ts; } } function bindSpecialPropertyDeclaration(node) { - if (node.expression.kind === 99 /* ThisKeyword */) { + if (node.expression.kind === 100 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 277 /* SourceFile */) { + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -28001,7 +29263,11 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28018,11 +29284,17 @@ var ts; classPrototype.parent = lhs; bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } function bindSpecialPropertyAssignment(node) { var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28046,42 +29318,48 @@ var ts; node.expression.parent = node; bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); } - function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) - : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; - namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ + : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28090,11 +29368,14 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -28103,7 +29384,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28145,7 +29426,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 238 /* ClassDeclaration */) { + if (node.kind === 240 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); } else { @@ -28187,8 +29468,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28200,15 +29484,15 @@ var ts; // 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 */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } function bindParameter(node) { - if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -28220,7 +29504,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28238,10 +29522,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28279,26 +29563,26 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 174 /* InferType */) { + else if (node.parent.kind === 176 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28313,13 +29597,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 218 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) || // report error on class declarations - node.kind === 238 /* ClassDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28357,24 +29639,23 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return true; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.hasModifier(s, 2048 /* Const */); default: return false; } } - /* @internal */ function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || @@ -28395,6 +29676,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28406,58 +29690,58 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return computeNewExpression(node, subtreeFlags); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); - case 149 /* Parameter */: + case 151 /* Parameter */: return computeParameter(node, subtreeFlags); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return computeCatchClause(node, subtreeFlags); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 155 /* Constructor */: + case 157 /* Constructor */: return computeConstructor(node, subtreeFlags); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return computePropertyDeclaration(node, subtreeFlags); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return computeMethod(node, subtreeFlags); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -28470,61 +29754,61 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } - if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + if (expression.kind === 92 /* ImportKeyword */) { + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 186 /* ObjectLiteralExpression */) { + if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ESNext if they contain rest transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 185 /* ArrayLiteralExpression */) { + else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ - || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { + else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ + || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28535,25 +29819,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28563,8 +29847,8 @@ 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 (expressionKind === 210 /* AsExpression */ - || expressionKind === 192 /* TypeAssertionExpression */) { + if (expressionKind === 212 /* AsExpression */ + || expressionKind === 194 /* TypeAssertionExpression */) { transformFlags |= 3 /* AssertTypeScript */; } // If the expression of a ParenthesizedExpression is a destructuring assignment, @@ -28588,44 +29872,44 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 85 /* ExtendsKeyword */: + case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; - case 108 /* ImplementsKeyword */: + case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; @@ -28634,7 +29918,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28645,7 +29929,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28657,7 +29941,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28667,11 +29951,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28687,7 +29971,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28698,7 +29982,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28712,11 +29996,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28724,10 +30008,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28739,7 +30023,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28752,13 +30036,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28771,7 +30055,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28787,13 +30071,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28803,7 +30087,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28820,26 +30104,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28847,18 +30133,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28866,7 +30154,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28877,22 +30165,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28901,7 +30189,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28912,7 +30200,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28921,78 +30209,78 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { - case 120 /* AsyncKeyword */: - case 199 /* AwaitExpression */: + case 121 /* AsyncKeyword */: + case 201 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 306 /* PartiallyEmittedExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; break; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 211 /* NonNullExpression */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 213 /* NonNullExpression */: + case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: - case 10 /* JsxText */: - case 261 /* JsxClosingElement */: - case 262 /* JsxFragment */: - case 263 /* JsxOpeningFragment */: - case 264 /* JsxClosingFragment */: - case 265 /* JsxAttribute */: - case 266 /* JsxAttributes */: - case 267 /* JsxSpreadAttribute */: - case 268 /* JsxExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 11 /* JsxText */: + case 263 /* JsxClosingElement */: + case 264 /* JsxFragment */: + case 265 /* JsxOpeningFragment */: + case 266 /* JsxClosingFragment */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 270 /* JsxExpression */: // These nodes are Jsx syntax. transformFlags |= 4 /* AssertJsx */; break; - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 204 /* TemplateExpression */: - case 191 /* TaggedTemplateExpression */: - case 274 /* ShorthandPropertyAssignment */: - case 115 /* StaticKeyword */: - case 212 /* MetaProperty */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + case 276 /* ShorthandPropertyAssignment */: + case 116 /* StaticKeyword */: + case 214 /* MetaProperty */: // These nodes are ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { transformFlags |= 192 /* AssertES2015 */; } @@ -29002,65 +30290,69 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } break; - case 225 /* ForOfStatement */: + case 9 /* BigIntLiteral */: + transformFlags |= 8 /* AssertESNext */; + break; + case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { transformFlags |= 8 /* AssertESNext */; } transformFlags |= 192 /* AssertES2015 */; break; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 148 /* TypeParameter */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 161 /* TypePredicate */: - case 162 /* TypeReference */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 165 /* TypeQuery */: - case 166 /* TypeLiteral */: - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 169 /* OptionalType */: - case 170 /* RestType */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 173 /* ConditionalType */: - case 174 /* InferType */: - case 175 /* ParenthesizedType */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 176 /* ThisType */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 180 /* LiteralType */: - case 245 /* NamespaceExportDeclaration */: + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 163 /* TypePredicate */: + case 164 /* TypeReference */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 167 /* TypeQuery */: + case 168 /* TypeLiteral */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 176 /* InferType */: + case 177 /* ParenthesizedType */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = 3 /* AssertTypeScript */; excludeFlags = -3 /* TypeExcludes */; break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29069,93 +30361,93 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + case 208 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; - case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + case 277 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; - case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + case 184 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; - case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + case 185 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; - case 150 /* Decorator */: + case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; - case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + case 188 /* ObjectLiteralExpression */: + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; } break; - case 185 /* ArrayLiteralExpression */: - case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + case 187 /* ArrayLiteralExpression */: + case 192 /* NewExpression */: + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } break; - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + case 279 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29168,71 +30460,71 @@ var ts; * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather * than calling this function. */ - /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) { + if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { return -3 /* TypeExcludes */; } switch (kind) { - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; - case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; - case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; - case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; - case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 137 /* StringKeyword */: - case 135 /* ObjectKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 148 /* TypeParameter */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 187 /* ArrayLiteralExpression */: + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + case 244 /* ModuleDeclaration */: + return 647001409 /* ModuleExcludes */; + case 151 /* Parameter */: + return 637535553 /* ParameterExcludes */; + case 197 /* ArrowFunction */: + return 653604161 /* ArrowFunctionExcludes */; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return 653620545 /* FunctionExcludes */; + case 238 /* VariableDeclarationList */: + return 639894849 /* VariableDeclarationListExcludes */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 638121281 /* ClassExcludes */; + case 157 /* Constructor */: + return 653616449 /* ConstructorExcludes */; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return 653616449 /* MethodOrAccessorExcludes */; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 138 /* StringKeyword */: + case 136 /* ObjectKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; - case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; - case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 306 /* PartiallyEmittedExpression */: - case 193 /* ParenthesizedExpression */: - case 97 /* SuperKeyword */: + case 188 /* ObjectLiteralExpression */: + return 638358849 /* ObjectLiteralExcludes */; + case 274 /* CatchClause */: + return 637797697 /* CatchClauseExcludes */; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return 637666625 /* BindingPatternExcludes */; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + case 195 /* ParenthesizedExpression */: + case 98 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29290,7 +30582,7 @@ var ts; if (shouldBail) return; // Visit the type's related types, if any - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var objectType = type; var objectFlags = objectType.objectFlags; if (objectFlags & 4 /* Reference */) { @@ -29306,16 +30598,16 @@ var ts; visitObjectType(objectType); } } - if (type.flags & 65536 /* TypeParameter */) { + if (type.flags & 262144 /* TypeParameter */) { visitTypeParameter(type); } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { visitUnionOrIntersectionType(type); } - if (type.flags & 1048576 /* Index */) { + if (type.flags & 4194304 /* Index */) { visitIndexType(type); } - if (type.flags & 2097152 /* IndexedAccess */) { + if (type.flags & 8388608 /* IndexedAccess */) { visitIndexedAccessType(type); } } @@ -29404,7 +30696,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 165 /* TypeQuery */) { + if (d.type && d.type.kind === 167 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -29447,6 +30739,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29467,7 +30771,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29476,10 +30781,12 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); @@ -29638,27 +30945,13 @@ var ts; var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); return parsed ? isImplementationOfOverload(parsed) : undefined; }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return ts.Debug.fail(); - links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); - } - return links.immediateTarget; - }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { - var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isParameter); @@ -29682,15 +30975,17 @@ var ts; getNumberType: function () { return numberType; }, createPromiseType: createPromiseType, createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, getESSymbolType: function () { return esSymbolType; }, getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -29698,7 +30993,7 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, - getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, @@ -29752,7 +31047,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29775,24 +31071,43 @@ var ts; var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); - var undefinedType = createIntrinsicType(8192 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(8192 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(16384 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(16384 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); - var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); - var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); - var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(4096 /* Void */, "void"); - var neverType = createIntrinsicType(32768 /* Never */, "never"); - var silentNeverType = createIntrinsicType(32768 /* Never */, "never"); - var implicitNeverType = createIntrinsicType(32768 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -29805,18 +31120,18 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(65536 /* TypeParameter */); - var markerSubType = createType(65536 /* TypeParameter */); + var markerSuperType = createType(262144 /* TypeParameter */); + var markerSubType = createType(262144 /* TypeParameter */); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(65536 /* TypeParameter */); + var markerOtherType = createType(262144 /* TypeParameter */); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29828,6 +31143,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29846,6 +31163,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29857,7 +31175,9 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29865,6 +31185,7 @@ var ts; var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -29890,84 +31211,99 @@ var ts; TypeFacts[TypeFacts["None"] = 0] = "None"; TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; - TypeFacts[TypeFacts["TypeofEQBoolean"] = 4] = "TypeofEQBoolean"; - TypeFacts[TypeFacts["TypeofEQSymbol"] = 8] = "TypeofEQSymbol"; - TypeFacts[TypeFacts["TypeofEQObject"] = 16] = "TypeofEQObject"; - TypeFacts[TypeFacts["TypeofEQFunction"] = 32] = "TypeofEQFunction"; - TypeFacts[TypeFacts["TypeofEQHostObject"] = 64] = "TypeofEQHostObject"; - TypeFacts[TypeFacts["TypeofNEString"] = 128] = "TypeofNEString"; - TypeFacts[TypeFacts["TypeofNENumber"] = 256] = "TypeofNENumber"; - TypeFacts[TypeFacts["TypeofNEBoolean"] = 512] = "TypeofNEBoolean"; - TypeFacts[TypeFacts["TypeofNESymbol"] = 1024] = "TypeofNESymbol"; - TypeFacts[TypeFacts["TypeofNEObject"] = 2048] = "TypeofNEObject"; - TypeFacts[TypeFacts["TypeofNEFunction"] = 4096] = "TypeofNEFunction"; - TypeFacts[TypeFacts["TypeofNEHostObject"] = 8192] = "TypeofNEHostObject"; - TypeFacts[TypeFacts["EQUndefined"] = 16384] = "EQUndefined"; - TypeFacts[TypeFacts["EQNull"] = 32768] = "EQNull"; - TypeFacts[TypeFacts["EQUndefinedOrNull"] = 65536] = "EQUndefinedOrNull"; - TypeFacts[TypeFacts["NEUndefined"] = 131072] = "NEUndefined"; - TypeFacts[TypeFacts["NENull"] = 262144] = "NENull"; - TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; - TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; - TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["All"] = 4194303] = "All"; + TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; + TypeFacts[TypeFacts["All"] = 16777215] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. - TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; - TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; - TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; - TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; - TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; - TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; - TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; - TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; - TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; - TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; - TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; - TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; - TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; - TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; - TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; - TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; - TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; - TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; - TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; - TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; - TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; - TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; - TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; - TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; - TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; - TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts"; + TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts"; + TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, number: 2 /* TypeofEQNumber */, - boolean: 4 /* TypeofEQBoolean */, - symbol: 8 /* TypeofEQSymbol */, - undefined: 16384 /* EQUndefined */, - object: 16 /* TypeofEQObject */, - function: 32 /* TypeofEQFunction */ + bigint: 4 /* TypeofEQBigInt */, + boolean: 8 /* TypeofEQBoolean */, + symbol: 16 /* TypeofEQSymbol */, + undefined: 65536 /* EQUndefined */, + object: 32 /* TypeofEQObject */, + function: 64 /* TypeofEQFunction */ }); var typeofNEFacts = ts.createMapFromTemplate({ - string: 128 /* TypeofNEString */, - number: 256 /* TypeofNENumber */, - boolean: 512 /* TypeofNEBoolean */, - symbol: 1024 /* TypeofNESymbol */, - undefined: 131072 /* NEUndefined */, - object: 2048 /* TypeofNEObject */, - function: 4096 /* TypeofNEFunction */ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ }); var typeofTypesByName = ts.createMapFromTemplate({ string: stringType, number: numberType, + bigint: bigintType, boolean: booleanType, symbol: esSymbolType, undefined: undefinedType @@ -29988,6 +31324,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30123,35 +31461,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30184,10 +31522,14 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { - target = cloneSymbol(target); + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); } // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { @@ -30197,8 +31539,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30217,55 +31560,56 @@ var ts; else if (target.flags & 1024 /* NamespaceModule */) { error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } - else { + else { // error var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30281,7 +31625,8 @@ var ts; } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { - target.set(id, target.has(id) ? mergeSymbol(target.get(id), sourceSymbol) : sourceSymbol); + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); }); } function mergeModuleAugmentation(moduleName) { @@ -30343,7 +31688,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { - return node.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -30373,8 +31718,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30401,17 +31746,17 @@ var ts; } if (declaration.pos <= usage.pos) { // declaration is before usage - if (declaration.kind === 184 /* BindingElement */) { + if (declaration.kind === 186 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 184 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 235 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage); } - else if (declaration.kind === 235 /* VariableDeclaration */) { + else if (declaration.kind === 237 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -30430,12 +31775,12 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 252 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -30443,9 +31788,9 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 217 /* VariableStatement */: - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 219 /* VariableStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -30466,16 +31811,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 152 /* PropertyDeclaration */ && + current.parent.kind === 154 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 154 /* MethodDeclaration */) { + if (declaration.kind === 156 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -30517,27 +31862,35 @@ var ts; // - 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 & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 149 /* Parameter */ || - lastLocation.kind === 148 /* TypeParameter */ + lastLocation.kind === 151 /* Parameter */ || + lastLocation.kind === 150 /* TypeParameter */ // local types not visible outside the function body : false; } - if (meaning & 67216319 /* 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 === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (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 === 151 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } - else if (location.kind === 173 /* ConditionalType */) { + else if (location.kind === 175 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -30551,14 +31904,14 @@ var ts; } } switch (location.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -30582,7 +31935,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 255 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) { break; } } @@ -30596,13 +31949,13 @@ var ts; } } break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* 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 @@ -30612,17 +31965,20 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } } } break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30637,7 +31993,7 @@ var ts; } break loop; } - if (location.kind === 207 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -30645,11 +32001,11 @@ var ts; } } break; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. - if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { + if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30665,29 +32021,29 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -30700,7 +32056,7 @@ var ts; } } break; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -30709,7 +32065,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 === 149 /* Parameter */) { + if (location.parent && location.parent.kind === 151 /* Parameter */) { location = location.parent; } // @@ -30722,8 +32078,8 @@ var ts; location = location.parent; } break; - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); break; @@ -30737,13 +32093,13 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { result.isReferenced |= meaning; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30752,7 +32108,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30807,16 +32163,15 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -30825,12 +32180,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: // For `namespace N { N; }` + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -30842,7 +32197,7 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 148 /* TypeParameter */) { + if (decl.kind === 150 /* TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 @@ -30897,10 +32252,10 @@ var ts; */ function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -30910,9 +32265,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30931,29 +32286,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30964,7 +32322,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30981,6 +32339,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -30996,13 +32357,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node; - case 248 /* ImportClause */: + case 250 /* ImportClause */: return node.parent; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return node.parent.parent; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -31012,7 +32373,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -31050,7 +32411,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31104,7 +32465,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31160,7 +32521,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31194,7 +32555,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31204,20 +32565,20 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 252 /* ExportAssignment */: - case 202 /* BinaryExpression */: + case 257 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 254 /* ExportAssignment */: + case 204 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -31228,10 +32589,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31262,7 +32623,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31278,11 +32639,11 @@ var ts; var node = getDeclarationOfAliasSymbol(symbol); if (!node) return ts.Debug.fail(); - if (node.kind === 252 /* ExportAssignment */) { + if (node.kind === 254 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 255 /* ExportSpecifier */) { + else if (node.kind === 257 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -31300,22 +32661,22 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 146 /* QualifiedName */) { + if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31324,19 +32685,19 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; - if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + if (name.kind === 72 /* Identifier */) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; } } - else if (name.kind === 146 /* QualifiedName */ || name.kind === 187 /* PropertyAccessExpression */) { - var left = name.kind === 146 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 146 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) { + var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -31344,7 +32705,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31379,15 +32740,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31395,9 +32756,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31405,8 +32778,18 @@ var ts; return symbol && symbol.valueDeclaration; } } - function resolveExternalModuleName(location, moduleReferenceExpression) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); } function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { if (isForAugmentation === void 0) { isForAugmentation = false; } @@ -31434,7 +32817,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31453,7 +32836,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31485,7 +32868,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31493,7 +32876,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31505,24 +32888,28 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { return exported; } var merged = cloneSymbol(exported); @@ -31543,7 +32930,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 277 /* SourceFile */)) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); return symbol; } @@ -31611,7 +32998,7 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 32764 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -31701,6 +33088,50 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } /** * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` @@ -31709,10 +33140,12 @@ var ts; var container = getParentOfSymbol(symbol); if (container) { var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { - return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope } - return ts.append(additionalContainers, container); + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); } var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); if (!ts.length(candidates)) { @@ -31750,13 +33183,13 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 155 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -31779,7 +33212,7 @@ var ts; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(131072 /* Object */); + var type = createType(524288 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; type.members = undefined; @@ -31834,12 +33267,12 @@ var ts; } } switch (location.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -31850,7 +33283,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31900,7 +33333,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31936,7 +33372,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -31951,10 +33387,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: continue; default: return false; @@ -31965,11 +33401,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -32007,7 +33443,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32061,10 +33507,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -32111,21 +33557,21 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 165 /* TypeQuery */ || + if (entityName.parent.kind === 167 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 147 /* ComputedPropertyName */) { + entityName.parent.kind === 149 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || - entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ || + entityName.parent.kind === 248 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32138,7 +33584,7 @@ var ts; } function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } - var nodeFlags = 3112960 /* IgnoreErrors */; + var nodeFlags = 70221824 /* IgnoreErrors */; if (flags & 2 /* UseOnlyExternalAliasing */) { nodeFlags |= 128 /* UseOnlyExternalAliasing */; } @@ -32148,6 +33594,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32164,15 +33613,15 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 164 /* ConstructorType */ : 163 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 159 /* ConstructSignature */ : 158 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */; } - var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 return writer; } } @@ -32180,7 +33629,7 @@ var ts; if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -32230,9 +33679,15 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, - visitedSymbols: undefined, + visitedTypes: undefined, + symbolDepth: undefined, inferTypeParameters: undefined, approximateLength: 0 }; @@ -32256,85 +33711,92 @@ var ts; } if (type.flags & 1 /* Any */) { context.approximateLength += 3; - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } if (type.flags & 2 /* Unknown */) { - return ts.createKeywordTypeNode(142 /* UnknownKeyword */); + return ts.createKeywordTypeNode(143 /* UnknownKeyword */); } if (type.flags & 4 /* String */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(137 /* StringKeyword */); + return ts.createKeywordTypeNode(138 /* StringKeyword */); } if (type.flags & 8 /* Number */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(134 /* NumberKeyword */); + return ts.createKeywordTypeNode(135 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146 /* BigIntKeyword */); } if (type.flags & 16 /* Boolean */) { context.approximateLength += 7; - return ts.createKeywordTypeNode(122 /* BooleanKeyword */); + return ts.createKeywordTypeNode(123 /* BooleanKeyword */); } - if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { + if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined)); + return enumLiteralName; } - if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + if (type.flags & 1056 /* EnumLike */) { + return symbolToTypeNode(type.symbol, context, 67897832 /* Type */); } - if (type.flags & 64 /* StringLiteral */) { + if (type.flags & 128 /* StringLiteral */) { context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & 128 /* NumberLiteral */) { + if (type.flags & 256 /* NumberLiteral */) { context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } - if (type.flags & 256 /* BooleanLiteral */) { + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512 /* BooleanLiteral */) { context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 2048 /* UniqueESSymbol */) { + if (type.flags & 8192 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } context.approximateLength += 13; - return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); + return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */)); } - if (type.flags & 4096 /* Void */) { + if (type.flags & 16384 /* Void */) { context.approximateLength += 4; - return ts.createKeywordTypeNode(105 /* VoidKeyword */); + return ts.createKeywordTypeNode(106 /* VoidKeyword */); } - if (type.flags & 8192 /* Undefined */) { + if (type.flags & 32768 /* Undefined */) { context.approximateLength += 9; - return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + return ts.createKeywordTypeNode(141 /* UndefinedKeyword */); } - if (type.flags & 16384 /* Null */) { + if (type.flags & 65536 /* Null */) { context.approximateLength += 4; - return ts.createKeywordTypeNode(95 /* NullKeyword */); + return ts.createKeywordTypeNode(96 /* NullKeyword */); } - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { context.approximateLength += 5; - return ts.createKeywordTypeNode(131 /* NeverKeyword */); + return ts.createKeywordTypeNode(132 /* NeverKeyword */); } - if (type.flags & 1024 /* ESSymbol */) { + if (type.flags & 4096 /* ESSymbol */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(138 /* SymbolKeyword */); + return ts.createKeywordTypeNode(139 /* SymbolKeyword */); } - if (type.flags & 16777216 /* NonPrimitive */) { + if (type.flags & 67108864 /* NonPrimitive */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(135 /* ObjectKeyword */); + return ts.createKeywordTypeNode(136 /* ObjectKeyword */); } - if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { + if (type.flags & 262144 /* TypeParameter */ && type.isThisType) { if (context.flags & 4194304 /* InObjectTypeLiteral */) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; @@ -32348,16 +33810,16 @@ var ts; } var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); return typeReferenceToTypeNode(type); } - if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && - type.flags & 65536 /* TypeParameter */ && + type.flags & 262144 /* TypeParameter */ && ts.length(type.symbol.declarations) && ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && @@ -32368,20 +33830,23 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } - if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { - var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -32392,23 +33857,23 @@ var ts; } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & 1048576 /* Index */) { + if (type.flags & 4194304 /* Index */) { var indexedType = type.type; context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 2097152 /* IndexedAccess */) { + if (type.flags & 8388608 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } - if (type.flags & 4194304 /* Conditional */) { + if (type.flags & 16777216 /* Conditional */) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); var saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; @@ -32419,12 +33884,12 @@ var ts; context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } - if (type.flags & 8388608 /* Substitution */) { + if (type.flags & 33554432 /* Substitution */) { return typeToTypeNodeHelper(type.typeVariable, context); } return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; var appropriateConstraintTypeNode; @@ -32443,43 +33908,52 @@ var ts; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { + var typeId = "" + type.id; var symbol = type.symbol; var id; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects - else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } - else if (context.visitedSymbols && context.visitedSymbols.has(id)) { + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { - context.approximateLength += 3; - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return createElidedInformationPlaceholder(context); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.visitedSymbols) { - context.visitedSymbols = ts.createMap(); + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); } - context.visitedSymbols.set(id, true); + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); var result = createTypeNodeFromObjectType(type); - context.visitedSymbols.delete(id); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); return result; } } @@ -32493,11 +33967,11 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 277 /* SourceFile */ || declaration.parent.kind === 243 /* ModuleBlock */; + return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } @@ -32514,12 +33988,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 163 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 164 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context); return signatureNode; } } @@ -32546,8 +34020,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32586,7 +34060,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32599,7 +34073,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32651,17 +34125,22 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 158 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 159 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ? - createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : - resolvedType.stringIndexInfo; - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context)); + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context); + } + typeElements.push(indexSignature); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); @@ -32692,31 +34171,34 @@ var ts; return typeElements.length ? typeElements : undefined; } } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; if (propertySymbol.valueDeclaration) { @@ -32728,10 +34210,16 @@ var ts; } else { var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; } @@ -32782,7 +34270,7 @@ var ts; } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 137 /* StringKeyword */ : 134 /* NumberKeyword */); + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -32795,7 +34283,7 @@ var ts; } context.approximateLength += (name.length + 4); return ts.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { var typeParameters; @@ -32806,7 +34294,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -32825,18 +34313,18 @@ var ts; returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } if (context.flags & 256 /* SuppressAnyReturnType */) { - if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) { returnTypeNode = undefined; } } else if (!returnTypeNode) { - returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */); } context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32847,7 +34335,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32859,9 +34347,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -32870,16 +34358,16 @@ var ts; var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; - var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - parameterDeclaration.name.kind === 146 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; - var questionToken = isOptional ? ts.createToken(55 /* QuestionToken */) : undefined; + var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); @@ -32888,21 +34376,34 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 184 /* BindingElement */) { + if (clone.kind === 186 /* BindingElement */) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32913,13 +34414,22 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + var parentSpecifiers; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); - if (ts.length(parents)) { - for (var _i = 0, _a = parents; _i < _a.length; _i++) { - var parent = _a[_i]; + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); @@ -32942,6 +34452,24 @@ var ts; } return [symbol]; } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } } } function typeParametersToTypeParameterDeclarations(symbol, context) { @@ -32979,7 +34507,7 @@ var ts; return top; } function getSpecifierForModuleSymbol(symbol, context) { - var file = ts.getDeclarationOfKind(symbol, 277 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -33009,7 +34537,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33017,12 +34552,20 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); @@ -33116,6 +34659,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33156,7 +34702,7 @@ var ts; if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { - var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); @@ -33169,12 +34715,12 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 24576 /* Nullable */)) { - if (t.flags & (256 /* BooleanLiteral */ | 512 /* EnumLiteral */)) { - var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 262144 /* Union */) { + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) { + var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33184,9 +34730,9 @@ var ts; result.push(t); } } - if (flags & 16384 /* Null */) + if (flags & 65536 /* Null */) result.push(nullType); - if (flags & 8192 /* Undefined */) + if (flags & 32768 /* Undefined */) result.push(undefinedType); return result || types; } @@ -33201,8 +34747,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 175 /* ParenthesizedType */; }); - if (node.kind === 240 /* TypeAliasDeclaration */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; }); + if (node.kind === 242 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -33210,11 +34756,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 243 /* ModuleBlock */ && + node.parent.kind === 245 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); } /** * Gets a human-readable name for a symbol. @@ -33237,27 +34783,30 @@ var ts; var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 235 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 207 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var nameType = symbol.nameType; if (nameType) { - if (nameType.flags & 64 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; } - if (nameType && nameType.flags & 2048 /* UniqueESSymbol */) { + if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; } } @@ -33274,27 +34823,27 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 237 /* FunctionDeclaration */: - case 241 /* EnumDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 243 /* EnumDeclaration */: + case 248 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -33302,53 +34851,53 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 246 /* ImportEqualsDeclaration */ && parent.kind !== 277 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 155 /* Constructor */: - case 159 /* ConstructSignature */: - case 158 /* CallSignature */: - case 160 /* IndexSignature */: - case 149 /* Parameter */: - case 243 /* ModuleBlock */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 166 /* TypeLiteral */: - case 162 /* TypeReference */: - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 175 /* ParenthesizedType */: + case 157 /* Constructor */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 151 /* Parameter */: + case 245 /* ModuleBlock */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 164 /* TypeReference */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 177 /* 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 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: return false; // Type parameters are always visible - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: // Source file and namespace export are always visible - case 277 /* SourceFile */: - case 245 /* NamespaceExportDeclaration */: + case 279 /* SourceFile */: + case 247 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return false; default: return false; @@ -33357,11 +34906,11 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + if (node.parent && node.parent.kind === 254 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + else if (node.parent.kind === 257 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33382,7 +34931,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33431,6 +34980,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33439,6 +34990,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33452,12 +35005,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 235 /* VariableDeclaration */: - case 236 /* VariableDeclarationList */: - case 251 /* ImportSpecifier */: - case 250 /* NamedImports */: - case 249 /* NamespaceImport */: - case 248 /* ImportClause */: + case 237 /* VariableDeclaration */: + case 238 /* VariableDeclarationList */: + case 253 /* ImportSpecifier */: + case 252 /* NamedImports */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: return false; default: return true; @@ -33487,28 +35040,36 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); + return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); - if (source.flags & 32768 /* Never */) { + source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); + if (source.flags & 131072 /* Never */) { return emptyObjectType; } - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } - var members = ts.createSymbolTable(); - var names = ts.createUnderscoreEscapedMap(); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var name = properties_2[_i]; - names.set(ts.getTextOfPropertyName(name), true); + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - if (!names.has(prop.escapedName) + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getNonReadonlySymbol(prop)); + members.set(prop.escapedName, getSpreadSymbol(prop)); } } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); @@ -33532,8 +35093,12 @@ var ts; if (isTypeAny(parentType)) { return parentType; } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } var type; - if (pattern.kind === 182 /* ObjectBindingPattern */) { + if (pattern.kind === 184 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -33551,51 +35116,9 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - var isLate = isLateBindableName(name); - var isWellKnown = ts.isComputedPropertyName(name) && ts.isWellKnownSymbolSyntactically(name.expression); - if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { - var exprType = checkExpression(name.expression); - if (isTypeAssignableToKind(exprType, 3072 /* ESSymbolLike */)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); - } - return anyType; - } - var indexerType = isTypeAssignableToKind(exprType, 168 /* NumberLike */) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); - if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(parentType, 1 /* Number */)) { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType)); - } - } - return indexerType || 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. - var nameType = isLate ? checkComputedPropertyName(name) : undefined; - var text = isLate ? getLateBoundNameFromType(nameType) : - isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : - ts.getTextOfPropertyName(name); - // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation - if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { - parentType = getNonNullableType(parentType); - } - if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType)); - } - return anyType; - } - var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); - type = declaredType && getFlowTypeOfReference(declaration, declaredType) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || - getIndexTypeOfType(parentType, 0 /* String */); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return errorType; - } + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); } } else { @@ -33603,27 +35126,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33631,11 +35154,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { - type = getTypeWithFacts(type, 131072 /* NEUndefined */); + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) { + type = getTypeWithFacts(type, 524288 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33647,11 +35170,11 @@ var ts; } function isNullOrUndefined(node) { var expr = ts.skipParentheses(node); - return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 185 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -33661,11 +35184,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 224 /* ForInStatement */) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (65536 /* TypeParameter */ | 1048576 /* Index */) ? getExtractStringType(indexType) : stringType; + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 225 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* 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, @@ -33683,8 +35206,8 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no @@ -33698,11 +35221,11 @@ var ts; return autoArrayType; } } - if (declaration.kind === 149 /* Parameter */) { + if (declaration.kind === 151 /* 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 === 157 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 156 /* GetAccessor */); + if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -33714,16 +35237,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33743,16 +35272,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33760,14 +35289,14 @@ var ts; var types; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = ts.isBinaryExpression(declaration) ? declaration : + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33775,9 +35304,11 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33785,26 +35316,24 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; } } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(24576 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33823,7 +35352,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33837,10 +35366,35 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); - if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + if (type.flags & 524288 /* Object */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33864,9 +35418,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33875,9 +35427,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 155 /* Constructor */ || - thisContainer.kind === 237 /* FunctionDeclaration */ || - (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 157 /* Constructor */ || + thisContainer.kind === 239 /* FunctionDeclaration */ || + (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -33889,8 +35441,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33898,7 +35450,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33912,8 +35464,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33952,7 +35504,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var hasRestElement = !!(lastElement && lastElement.kind === 184 /* BindingElement */ && lastElement.dotDotDotToken); + var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken); if (elements.length === 0 || elements.length === 1 && hasRestElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -33975,7 +35527,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 182 /* ObjectBindingPattern */ + return pattern.kind === 184 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -33997,7 +35549,7 @@ var ts; reportErrorsFromWidening(declaration, type); } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & 2048 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } return getWidenedType(type); @@ -34005,16 +35557,16 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 149 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -34050,19 +35602,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } - if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + if (declaration.kind === 254 /* ExportAssignment */) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && - (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34076,7 +35635,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34098,6 +35657,14 @@ var ts; || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } @@ -34108,7 +35675,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 156 /* GetAccessor */) { + if (accessor.kind === 158 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -34135,9 +35702,9 @@ var ts; return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); } function getTypeOfAccessorsWorker(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */); + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34165,14 +35732,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34181,7 +35746,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* 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)); } } @@ -34189,13 +35754,13 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 2162688 /* TypeVariable */ ? baseConstructorType : undefined; + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34221,9 +35786,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 202 /* BinaryExpression */ || - declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + else if (declaration.kind === 204 /* BinaryExpression */ || + declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) { + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34232,11 +35797,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34261,7 +35826,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34270,22 +35835,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34342,7 +35899,7 @@ var ts; var target = getTargetType(type); return target === checkBase || ts.some(getBaseTypes(target), check); } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return ts.some(type.types, check); } return false; @@ -34366,35 +35923,35 @@ var ts; return undefined; } switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 287 /* JSDocFunctionType */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 179 /* MappedType */: - case 173 /* ConditionalType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 181 /* MappedType */: + case 175 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 179 /* MappedType */) { + if (node.kind === 181 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 173 /* ConditionalType */) { + else if (node.kind === 175 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */ || node.kind === 239 /* InterfaceDeclaration */) && + (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } @@ -34402,7 +35959,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, 239 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -34411,9 +35968,9 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 239 /* InterfaceDeclaration */ || - node.kind === 238 /* ClassDeclaration */ || - node.kind === 207 /* ClassExpression */ || + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || + node.kind === 209 /* ClassExpression */ || ts.isTypeAlias(node)) { var declaration = node; result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); @@ -34440,27 +35997,24 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { return true; } - if (type.flags & 2162688 /* TypeVariable */) { + if (type.flags & 8650752 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34486,7 +36040,7 @@ var ts; ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag checkExpression(extended.expression); } - if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */)) { + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -34496,7 +36050,18 @@ var ts; return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } return type.resolvedBaseConstructorType = errorType; } type.resolvedBaseConstructorType = baseConstructorType; @@ -34525,13 +36090,15 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 1 /* Any */))) { + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? 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 @@ -34542,8 +36109,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34560,7 +36127,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { @@ -34590,14 +36157,14 @@ var ts; // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return !!(type.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 524288 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -34616,7 +36183,7 @@ var ts; } } else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -34633,7 +36200,7 @@ var ts; function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 /* InterfaceDeclaration */) { + if (declaration.kind === 241 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -34642,7 +36209,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34674,7 +36241,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536 /* TypeParameter */); + type.thisType = createType(262144 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -34691,7 +36258,7 @@ var ts; return errorType; } var declaration = ts.find(symbol.declarations, function (d) { - return ts.isJSDocTypeAlias(d) || d.kind === 240 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */; }); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. @@ -34715,10 +36282,10 @@ var ts; return links.declaredType; } function isStringConcatExpression(expr) { - if (expr.kind === 9 /* StringLiteral */) { + if (expr.kind === 10 /* StringLiteral */) { return true; } - else if (expr.kind === 202 /* BinaryExpression */) { + else if (expr.kind === 204 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -34729,15 +36296,15 @@ var ts; return !(member.flags & 4194304 /* Ambient */); } switch (expr.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return true; - case 200 /* PrefixUnaryExpression */: - return expr.operator === 38 /* MinusToken */ && + case 202 /* PrefixUnaryExpression */: + return expr.operator === 39 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -34751,10 +36318,10 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241 /* EnumDeclaration */) { + if (declaration.kind === 243 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) { return links.enumKind = 1 /* Literal */; } if (!isLiteralEnumMember(member)) { @@ -34766,7 +36333,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -34778,19 +36345,19 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241 /* EnumDeclaration */) { + if (declaration.kind === 243 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); - if (enumType_1.flags & 262144 /* Union */) { - enumType_1.flags |= 512 /* EnumLiteral */; + if (enumType_1.flags & 1048576 /* Union */) { + enumType_1.flags |= 1024 /* EnumLiteral */; enumType_1.symbol = symbol; } return links.declaredType = enumType_1; @@ -34813,7 +36380,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(65536 /* TypeParameter */); + var type = createType(262144 /* TypeParameter */); type.symbol = symbol; links.declaredType = type; } @@ -34857,22 +36424,23 @@ var ts; */ function isThislessType(node) { switch (node.kind) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 135 /* ObjectKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: - case 180 /* LiteralType */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + case 182 /* LiteralType */: return true; - case 167 /* ArrayType */: + case 169 /* ArrayType */: return isThislessType(node.elementType); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -34898,7 +36466,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 155 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -34914,12 +36482,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -34963,7 +36531,7 @@ var ts; * Indicates whether a type can be used as a late-bound name. */ function isTypeUsableAsLateBoundName(type) { - return !!(type.flags & 2240 /* StringOrNumberLiteralOrUnique */); + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); } /** * Indicates whether a declaration name is definitely late-bindable. @@ -35006,10 +36574,10 @@ var ts; * Gets the symbolic name for a late-bound member from its type. */ function getLateBoundNameFromType(type) { - if (type.flags & 2048 /* UniqueESSymbol */) { + if (type.flags & 8192 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35029,7 +36597,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35174,7 +36742,7 @@ var ts; return needApparentType ? getApparentType(ref) : ref; } } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } return needApparentType ? getApparentType(type) : type; @@ -35283,7 +36851,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35303,7 +36871,7 @@ var ts; function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { return s; } } @@ -35337,8 +36905,7 @@ var ts; // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional // parameters and may differ in return types. When signatures differ in return types, the resulting return // type is the union of the constituent return types. - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + function getUnionSignatures(signatureLists) { var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { @@ -35384,8 +36951,8 @@ var ts; 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 callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -35420,7 +36987,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35443,7 +37010,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35481,7 +37048,7 @@ var ts; if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 2162688 /* TypeVariable */)) { + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -35497,6 +37064,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35514,7 +37082,7 @@ var ts; var modifiers = getMappedTypeModifiers(type.mappedType); var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; - var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; @@ -35524,6 +37092,7 @@ var ts; inferredProp.nameType = prop.nameType; inferredProp.propertyType = getTypeOfSymbol(prop); inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -35542,12 +37111,12 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateModifiers = getMappedTypeModifiers(type); - var include = keyofStringsOnly ? 64 /* StringLiteral */ : 2240 /* StringOrNumberLiteralOrUnique */; + var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); @@ -35557,11 +37126,9 @@ var ts; } } else { - // First, if the constraint type is a type parameter, obtain the base constraint. Then, - // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 14745600 /* InstantiableNonPrimitive */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 1048576 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); @@ -35573,7 +37140,7 @@ var ts; var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. - if (t.flags & 2240 /* StringOrNumberLiteralOrUnique */) { + if (t.flags & 8576 /* StringOrNumberLiteralOrUnique */) { var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || @@ -35585,7 +37152,7 @@ var ts; // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks // mode, if the underlying property is optional we remove 'undefined' from the type. prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; @@ -35608,7 +37175,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35621,8 +37188,8 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 177 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; + return constraintDeclaration.kind === 179 /* TypeOperator */ && + constraintDeclaration.operator === 129 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { @@ -35638,16 +37205,16 @@ var ts; // the modifiers type is T. Otherwise, the modifiers type is {}. var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 1048576 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } function getMappedTypeModifiers(type) { var declaration = type.declaration; - return (declaration.readonlyToken ? declaration.readonlyToken.kind === 38 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | - (declaration.questionToken ? declaration.questionToken.kind === 38 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); } function getMappedTypeOptionality(type) { var modifiers = getMappedTypeModifiers(type); @@ -35666,7 +37233,7 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { if (type.objectFlags & 4 /* Reference */) { resolveTypeReferenceMembers(type); } @@ -35683,10 +37250,10 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 262144 /* Union */) { + else if (type.flags & 1048576 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -35694,7 +37261,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; @@ -35703,7 +37270,7 @@ var ts; * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -35727,7 +37294,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { break; } } @@ -35737,12 +37304,13 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 786432 /* UnionOrIntersection */ ? + return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { - return obj.properties.some(function (property) { + var list = obj.properties; + return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); @@ -35750,7 +37318,7 @@ var ts; } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 262144 /* Union */)) { + if (!(unionType.flags & 1048576 /* Union */)) { return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); @@ -35769,24 +37337,33 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : - type.flags & 2097152 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : - type.flags & 4194304 /* Conditional */ ? getConstraintOfConditionalType(type) : + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { var rootTrueType = type.root.trueType; - var rootTrueConstraint = rootTrueType.flags & 8388608 /* Substitution */ ? rootTrueType.substitute : rootTrueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); } return type.resolvedDefaultConstraint; @@ -35798,11 +37375,12 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); - if (!(instantiated.flags & 32768 /* Never */)) { + if (!(instantiated.flags & 131072 /* Never */)) { return instantiated; } } @@ -35817,23 +37395,23 @@ var ts; var hasDisjointDomainType = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 15794176 /* Instantiable */) { + if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). var constraint = getConstraintOfType(t); - while (constraint && constraint.flags & (65536 /* TypeParameter */ | 1048576 /* Index */ | 4194304 /* Conditional */)) { + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { constraint = getConstraintOfType(constraint); } if (constraint) { // A constraint that isn't a union type implies that the final type would be a non-union // type as well. Since non-union constraints are of no interest, we can exit here. - if (!(constraint.flags & 262144 /* Union */)) { + if (!(constraint.flags & 1048576 /* Union */)) { return undefined; } constraints = ts.append(constraints, constraint); } } - else if (t.flags & 16809468 /* DisjointDomains */) { + else if (t.flags & 67238908 /* DisjointDomains */) { hasDisjointDomainType = true; } } @@ -35845,7 +37423,7 @@ var ts; // intersection operation to reduce the union constraints. for (var _b = 0, _c = type.types; _b < _c.length; _b++) { var t = _c[_b]; - if (t.flags & 16809468 /* DisjointDomains */) { + if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } } @@ -35855,11 +37433,11 @@ var ts; return undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; + return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -35877,6 +37455,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35884,8 +37463,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35897,45 +37486,42 @@ var ts; return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { - if (t.flags & 65536 /* TypeParameter */) { + if (t.flags & 262144 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint); } - if (t.flags & 786432 /* UnionOrIntersection */) { + if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 262144 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 524288 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 1048576 /* Index */) { + if (t.flags & 4194304 /* Index */) { return keyofConstraintType; } - if (t.flags & 2097152 /* IndexedAccess */) { + if (t.flags & 8388608 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } - if (t.flags & 4194304 /* Conditional */) { + if (t.flags & 16777216 /* Conditional */) { var constraint = getConstraintOfConditionalType(t); return constraint && getBaseConstraint(constraint); } - if (t.flags & 8388608 /* Substitution */) { + if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35985,26 +37571,42 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 /* StringLike */ ? globalStringType : + t.flags & 296 /* NumberLike */ ? globalNumberType : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 528 /* BooleanLike */ ? globalBooleanType : + t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : + t.flags & 4194304 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var indexTypes; - var isUnion = containingType.flags & 262144 /* Union */; + var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; @@ -36029,10 +37631,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36117,27 +37719,31 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 917504 /* StructuredType */) { + if (type.flags & 3670016 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -36151,7 +37757,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 917504 /* StructuredType */) { + if (type.flags & 3670016 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -36205,12 +37811,12 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 286 /* JSDocOptionalType */ + node.type && node.type.kind === 288 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -36244,7 +37850,7 @@ var ts; return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -36269,30 +37875,32 @@ var ts; } function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { - if (!typeArguments) { - typeArguments = []; - } - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { - defaultType = anyType; - } - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - typeArguments.length = typeParameters.length; - } + if (!numTypeParameters) { + return []; } - return typeArguments; + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); @@ -36305,7 +37913,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36318,7 +37926,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36328,7 +37936,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 180 /* LiteralType */) { + if (type && type.kind === 182 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter @@ -36342,20 +37950,20 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 156 /* GetAccessor */ || declaration.kind === 157 /* SetAccessor */) && + if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) && !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 155 /* Constructor */ ? + var classType = declaration.kind === 157 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36386,7 +37994,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36409,13 +38017,13 @@ var ts; if (!node) return false; switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node.escapedText === "arguments" && ts.isExpressionNode(node); - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return node.name.kind === 147 /* ComputedPropertyName */ + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node.name.kind === 149 /* ComputedPropertyName */ && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -36473,7 +38081,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36490,7 +38098,7 @@ var ts; function createTypePredicateFromTypePredicateNode(node, func) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71 /* Identifier */) { + if (parameterName.kind === 72 /* Identifier */) { return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); } else { @@ -36500,7 +38108,7 @@ var ts; function getTypePredicateParameterIndex(parameterList, parameter) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { return i; } } @@ -36514,6 +38122,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36539,7 +38148,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 155 /* Constructor */) { + if (declaration.kind === 157 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -36549,12 +38158,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -36569,8 +38178,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36611,7 +38224,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36628,7 +38241,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 === 155 /* Constructor */ || signature.declaration.kind === 159 /* ConstructSignature */; // TODO: GH#18217 + var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217 var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -36642,7 +38255,7 @@ var ts; return symbol.members.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 134 /* NumberKeyword */ : 137 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -36669,7 +38282,7 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */); return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { @@ -36677,13 +38290,13 @@ var ts; if (typeParameter.symbol) { for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.parent.kind === 174 /* InferType */) { + if (declaration.parent.kind === 176 /* InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. var grandParent = declaration.parent.parent; - if (grandParent.kind === 162 /* TypeReference */) { + if (grandParent.kind === 164 /* TypeReference */) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -36708,7 +38321,7 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter // declaration, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 149 /* Parameter */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } } @@ -36732,7 +38345,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -36805,10 +38418,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36838,7 +38451,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36865,9 +38478,9 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -36893,14 +38506,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36908,7 +38535,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36917,16 +38544,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -36949,13 +38581,13 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { - var result = createType(8388608 /* Substitution */); + var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 168 /* TupleType */ && node.elementTypes.length === 1; + return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1; } function getImpliedConstraint(typeVariable, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : @@ -36964,9 +38596,9 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 289 /* JSDocComment */) { + while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 173 /* ConditionalType */ && node === parent.trueType) { + if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -36977,7 +38609,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */); + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -37035,23 +38667,23 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getNullableType(type, 16384 /* Null */) : type; + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37078,9 +38710,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: return declaration; } } @@ -37089,7 +38721,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 131072 /* Object */)) { + if (!(type.flags & 524288 /* Object */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } @@ -37100,10 +38732,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37131,6 +38763,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37157,12 +38792,21 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType; + } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -37211,7 +38855,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(65536 /* TypeParameter */); + var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); if (i < maxLength) { var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); property.type = typeParameter; @@ -37233,7 +38877,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536 /* TypeParameter */); + type.thisType = createType(262144 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -37268,8 +38912,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var lastElement = ts.lastOrUndefined(node.elementTypes); - var restElement_1 = lastElement && lastElement.kind === 170 /* RestType */ ? lastElement : undefined; - var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 169 /* OptionalType */ && n !== restElement_1; }) + 1; + var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1; var elementTypes = ts.map(node.elementTypes, function (n) { var type = getTypeFromTypeNode(n); return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; @@ -37278,6 +38922,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37308,16 +38960,17 @@ var ts; var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 27072 /* Unit */ && combined & 27072 /* Unit */) { + if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) { return true; } combined |= t.flags; - if (combined & 24576 /* Nullable */ && combined & (131072 /* Object */ | 16777216 /* NonPrimitive */) || - combined & 16777216 /* NonPrimitive */ && combined & (16809468 /* DisjointDomains */ & ~16777216 /* NonPrimitive */) || - combined & 68 /* StringLike */ && combined & (16809468 /* DisjointDomains */ & ~68 /* StringLike */) || - combined & 168 /* NumberLike */ && combined & (16809468 /* DisjointDomains */ & ~168 /* NumberLike */) || - combined & 3072 /* ESSymbolLike */ && combined & (16809468 /* DisjointDomains */ & ~3072 /* ESSymbolLike */) || - combined & 12288 /* VoidLike */ && combined & (16809468 /* DisjointDomains */ & ~12288 /* VoidLike */)) { + if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) || + combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || + combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || + combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || + combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) || + combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || + combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) { return true; } } @@ -37325,20 +38978,18 @@ var ts; } function addTypeToUnion(typeSet, includes, type) { var flags = type.flags; - if (flags & 262144 /* Union */) { + if (flags & 1048576 /* Union */) { return addTypesToUnion(typeSet, includes, type.types); } // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are // another form of 'never' (in that they have an empty value domain). We could in theory turn // intersections of unit types into 'never' upon construction, but deferring the reduction makes it // easier to reason about their origin. - if (!(flags & 32768 /* Never */ || flags & 524288 /* Intersection */ && isEmptyIntersectionType(type))) { + if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { includes |= flags & ~939524096 /* ConstructionFlags */; - if (flags & 3 /* AnyOrUnknown */) { - if (type === wildcardType) - includes |= 268435456 /* Wildcard */; - } - else if (!strictNullChecks && flags & 24576 /* Nullable */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(flags & 134217728 /* ContainsWideningType */)) includes |= 134217728 /* NonWideningType */; } @@ -37346,10 +38997,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37364,15 +39012,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - 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 isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37386,11 +39025,11 @@ var ts; } function isSetOfLiteralsFromSameEnum(types) { var first = types[0]; - if (first.flags & 512 /* EnumLiteral */) { + if (first.flags & 1024 /* EnumLiteral */) { var firstEnum = getParentOfSymbol(first.symbol); for (var i = 1; i < types.length; i++) { var other = types[i]; - if (!(other.flags & 512 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { return false; } } @@ -37415,10 +39054,11 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || - t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37441,25 +39081,27 @@ var ts; } var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); - if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1 /* Literal */: + if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + neverType; + } } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { - removeRedundantLiteralTypes(typeSet, includes); - } - break; - case 2 /* Subtype */: - removeSubtypes(typeSet); - break; - } - if (typeSet.length === 0) { - return includes & 16384 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : - includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -37496,7 +39138,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -37506,10 +39148,11 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 24576 /* Nullable */); - type = createType(262144 /* Union */ | propagatedFlags | unionOfUnitTypes); + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(1048576 /* Union */ | propagatedFlags); unionTypes.set(id, type); type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; /* Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. @@ -37531,11 +39174,14 @@ var ts; } function addTypeToIntersection(typeSet, includes, type) { var flags = type.flags; - if (flags & 524288 /* Intersection */) { + if (flags & 2097152 /* Intersection */) { return addTypesToIntersection(typeSet, includes, type.types); } - if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { - includes |= 536870912 /* EmptyObject */; + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912 /* EmptyObject */)) { + includes |= 536870912 /* EmptyObject */; + typeSet.push(type); + } } else { includes |= flags & ~939524096 /* ConstructionFlags */; @@ -37543,10 +39189,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37555,8 +39198,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37566,9 +39209,10 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 4 /* String */ && includes & 64 /* StringLiteral */ || - t.flags & 8 /* Number */ && includes & 128 /* NumberLiteral */ || - t.flags & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */; + var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37581,10 +39225,11 @@ var ts; for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { var u = unionTypes_1[_i]; if (!containsType(u.types, type)) { - var primitive = type.flags & 64 /* StringLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ ? numberType : - type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : - undefined; + var primitive = type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + undefined; if (!primitive || !containsType(u.types, primitive)) { return false; } @@ -37597,13 +39242,16 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; }); + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } var i = index + 1; // Remove all but the first union of primitive types and collect them in // the unionTypes array. while (i < types.length) { var t = types[i]; - if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) { + if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -37632,7 +39280,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */); + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -37648,22 +39296,23 @@ var ts; function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); - if (includes & 32768 /* Never */) { + if (includes & 131072 /* Never */) { return neverType; } if (includes & 1 /* Any */) { return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; } - if (!strictNullChecks && includes & 24576 /* Nullable */) { - return includes & 8192 /* Undefined */ ? undefinedType : nullType; + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 32768 /* Undefined */ ? undefinedType : nullType; } - if (includes & 4 /* String */ && includes & 64 /* StringLiteral */ || - includes & 8 /* Number */ && includes & 128 /* NumberLiteral */ || - includes & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */) { + if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 536870912 /* EmptyObject */ && !(includes & 131072 /* Object */)) { - typeSet.push(emptyObjectType); + if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { return unknownType; @@ -37671,8 +39320,8 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - if (includes & 262144 /* Union */) { - if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) { + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -37680,15 +39329,15 @@ var ts; } // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. - var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 262144 /* Union */) !== 0; }); + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; }); var unionType = typeSet[unionIndex_1]; return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 24576 /* Nullable */); - type = createType(524288 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(2097152 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. @@ -37705,7 +39354,7 @@ var ts; return links.resolvedType; } function createIndexType(type, stringsOnly) { - var result = createType(1048576 /* Index */); + var result = createType(4194304 /* Index */); result.type = type; result.stringsOnly = stringsOnly; return result; @@ -37715,14 +39364,22 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } - function getLiteralTypeFromPropertyName(prop, include) { + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) : - name && name.kind === 147 /* ComputedPropertyName */ && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : - getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); } if (type && type.flags & include) { return type; @@ -37730,8 +39387,8 @@ var ts; } return neverType; } - function getLiteralTypeFromPropertyNames(type, include) { - return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromPropertyName(t, include); })); + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); } function getNonEnumNumberIndexInfo(type) { var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); @@ -37739,16 +39396,16 @@ var ts; } function getIndexType(type, stringsOnly) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } - return type.flags & 262144 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - type.flags & 524288 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : type === wildcardType ? wildcardType : type.flags & 1 /* Any */ ? keyofConstraintType : - stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */) : - getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, 2048 /* UniqueESSymbol */)]) : - getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */ | 2048 /* UniqueESSymbol */)]) : - getLiteralTypeFromPropertyNames(type, 2240 /* StringOrNumberLiteralOrUnique */); + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) : + getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */); } function getExtractStringType(type) { if (keyofStringsOnly) { @@ -37759,17 +39416,17 @@ var ts; } function getIndexTypeOrString(type) { var indexType = getExtractStringType(getIndexType(type)); - return indexType.flags & 32768 /* Never */ ? stringType : indexType; + return indexType.flags & 131072 /* Never */ ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { switch (node.operator) { - case 128 /* KeyOfKeyword */: + case 129 /* KeyOfKeyword */: links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); break; - case 141 /* UniqueKeyword */: - links.resolvedType = node.type.kind === 138 /* SymbolKeyword */ + case 142 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 139 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) : errorType; break; @@ -37778,7 +39435,7 @@ var ts; return links.resolvedType; // TODO: GH#18217 } function createIndexedAccessType(objectType, indexType) { - var type = createType(2097152 /* IndexedAccess */); + var type = createType(8388608 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; return type; @@ -37799,56 +39456,63 @@ var ts; if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { return true; } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { return ts.every(type.types, isJSLiteralType); } - if (type.flags & 524288 /* Intersection */) { + if (type.flags & 2097152 /* Intersection */) { return ts.some(type.types, isJSLiteralType); } - if (type.flags & 15794176 /* Instantiable */) { + if (type.flags & 63176704 /* Instantiable */) { return isJSLiteralType(getResolvedBaseConstraint(type)); } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - undefined; + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } - if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { - if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) { + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { return objectType; } - var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { - var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = getIndexNodeForAccessExpression(accessNode); error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { @@ -37856,7 +39520,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768 /* Never */) { + if (indexType.flags & 131072 /* Never */) { return neverType; } if (isJSLiteralType(objectType)) { @@ -37882,15 +39546,15 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { return anyType; } if (accessNode) { - var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; - if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { @@ -37900,30 +39564,38 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 /* ElementAccessExpression */ + ? accessNode.argumentExpression + : accessNode.kind === 180 /* IndexedAccessType */ + ? accessNode.indexType + : accessNode.kind === 149 /* ComputedPropertyName */ + ? accessNode.expression + : accessNode; } function isGenericObjectType(type) { - return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); } function isGenericIndexType(type) { - return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); - } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); } function getSimplifiedType(type) { - return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 1048576 /* Union */) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // the type itself if no transformation is possible. @@ -37935,37 +39607,20 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); - } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 1048576 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 63176704 /* Instantiable */)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +39628,7 @@ var ts; if (isGenericMappedType(objectType)) { return type.simplified = substituteIndexedMappedType(objectType, type); } - if (objectType.flags & 65536 /* TypeParameter */) { + if (objectType.flags & 262144 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); @@ -37986,7 +39641,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -37995,7 +39651,7 @@ var ts; // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 188 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } @@ -38011,19 +39667,30 @@ var ts; // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38031,7 +39698,7 @@ var ts; var objectType = getTypeFromTypeNode(node.objectType); var indexType = getTypeFromTypeNode(node.indexType); var resolved = getIndexedAccessType(objectType, indexType, node); - links.resolvedType = resolved.flags & 2097152 /* IndexedAccess */ && + links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && resolved.objectType === objectType && resolved.indexType === indexType ? getConstrainedTypeVariable(resolved, node) : resolved; @@ -38053,7 +39720,7 @@ var ts; return links.resolvedType; } function getActualTypeVariable(type) { - return type.flags & 8388608 /* Substitution */ ? type.typeVariable : type; + return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); @@ -38064,7 +39731,7 @@ var ts; // If this is a distributive conditional type and the check type is generic we need to defer // resolution of the conditional type such that a later instantiation will properly distribute // over union types. - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 15794176 /* Instantiable */); + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); @@ -38103,7 +39770,7 @@ var ts; } // Return a deferred type for a check that is neither definitely true nor definitely false var erasedCheckType = getActualTypeVariable(checkType); - var result = createType(4194304 /* Conditional */); + var result = createType(16777216 /* Conditional */); result.root = root; result.checkType = erasedCheckType; result.extendsType = extendsType; @@ -38135,7 +39802,7 @@ var ts; return true; } while (node) { - if (node.kind === 173 /* ConditionalType */) { + if (node.kind === 175 /* ConditionalType */) { if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { return true; } @@ -38158,7 +39825,7 @@ var ts; extendsType: getTypeFromTypeNode(node.extendsType), trueType: getTypeFromTypeNode(node.trueType), falseType: getTypeFromTypeNode(node.falseType), - isDistributive: !!(checkType.flags & 65536 /* TypeParameter */), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, @@ -38201,7 +39868,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38231,7 +39898,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38245,7 +39912,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38278,6 +39945,9 @@ var ts; function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } /** * Since the source of spread types are object literals, which are not binary, * this function should be called in a left folding style, with left = previous result of getSpreadType @@ -38290,21 +39960,37 @@ var ts; if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { return unknownType; } - if (left.flags & 32768 /* Never */) { + if (left.flags & 131072 /* Never */) { return right; } - if (right.flags & 32768 /* Never */) { + if (right.flags & 131072 /* Never */) { return left; } - if (left.flags & 262144 /* Union */) { + if (left.flags & 1048576 /* Union */) { return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); } - if (right.flags & 262144 /* Union */) { + if (right.flags & 1048576 /* Union */) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); } - if (right.flags & (272 /* BooleanLike */ | 168 /* NumberLike */ | 68 /* StringLike */ | 544 /* EnumLike */ | 16777216 /* NonPrimitive */ | 1048576 /* Index */)) { + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { return left; } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & 2097152 /* Intersection */) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); var stringIndexInfo; @@ -38324,7 +40010,7 @@ var ts; skippedPrivateMembers.set(rightProp.escapedName, true); } else if (isSpreadableProperty(rightProp)) { - members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { @@ -38339,7 +40025,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); var result = createSymbol(flags, leftProp.escapedName); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -38348,27 +40034,28 @@ var ts; } } else { - members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= typeFlags | 268435456 /* ContainsObjectLiteral */; - spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); + spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */) - ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) - : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable + return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isReadonly && !isSetonlyAccessor) { return prop; } var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); var result = createSymbol(flags, prop.escapedName); - result.type = getTypeOfSymbol(prop); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); result.declarations = prop.declarations; result.nameType = prop.nameType; result.syntheticOrigin = prop; @@ -38387,10 +40074,11 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; + freshType.freshType = freshType; type.freshType = freshType; } return type.freshType; @@ -38398,21 +40086,27 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + return type.flags & 2944 /* Literal */ ? type.regularType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } + function isFreshLiteralType(type) { + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; + } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', // where NNN is the text representation of a numeric literal and SSS are the characters // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where // EEE is a unique id for the containing enum type. - var qualifier = typeof value === "number" ? "#" : "@"; - var key = enumId ? enumId + qualifier + value : qualifier + value; + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); var type = literalTypes.get(key); if (!type) { - var flags = (typeof value === "number" ? 128 /* NumberLiteral */ : 64 /* StringLiteral */) | (enumId ? 512 /* EnumLiteral */ : 0); + var flags = (typeof value === "number" ? 256 /* NumberLiteral */ : + typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) | + (enumId ? 1024 /* EnumLiteral */ : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; } return type; } @@ -38424,7 +40118,7 @@ var ts; return links.resolvedType; } function createUniqueESSymbolType(symbol) { - var type = createType(2048 /* UniqueESSymbol */); + var type = createType(8192 /* UniqueESSymbol */); type.symbol = symbol; return type; } @@ -38439,9 +40133,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 239 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) { if (!ts.hasModifier(container, 32 /* Static */) && - (container.kind !== 155 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -38457,87 +40151,89 @@ var ts; } function getTypeFromTypeNode(node) { switch (node.kind) { - case 119 /* AnyKeyword */: - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: + case 120 /* AnyKeyword */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: return anyType; - case 142 /* UnknownKeyword */: + case 143 /* UnknownKeyword */: return unknownType; - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: return stringType; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: return numberType; - case 122 /* BooleanKeyword */: + case 146 /* BigIntKeyword */: + return bigintType; + case 123 /* BooleanKeyword */: return booleanType; - case 138 /* SymbolKeyword */: + case 139 /* SymbolKeyword */: return esSymbolType; - case 105 /* VoidKeyword */: + case 106 /* VoidKeyword */: return voidType; - case 140 /* UndefinedKeyword */: + case 141 /* UndefinedKeyword */: return undefinedType; - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: return nullType; - case 131 /* NeverKeyword */: + case 132 /* NeverKeyword */: return neverType; - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; - case 176 /* ThisType */: - case 99 /* ThisKeyword */: + case 178 /* ThisType */: + case 100 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return getTypeFromTypeReference(node); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return booleanType; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return getTypeFromOptionalTypeNode(node); - case 171 /* UnionType */: + case 173 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 175 /* ParenthesizedType */: - case 170 /* RestType */: - case 285 /* JSDocNonNullableType */: - case 281 /* JSDocTypeExpression */: + case 177 /* ParenthesizedType */: + case 172 /* RestType */: + case 287 /* JSDocNonNullableType */: + case 283 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 287 /* JSDocFunctionType */: - case 291 /* JSDocSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 174 /* InferType */: + case 176 /* InferType */: return getTypeFromInferTypeNode(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode - case 71 /* Identifier */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 148 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -38604,7 +40300,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38618,10 +40314,10 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function wildcardMapper(type) { - return type.flags & 65536 /* TypeParameter */ ? wildcardType : type; + return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; } function cloneTypeParameter(typeParameter) { - var result = createType(65536 /* TypeParameter */); + var result = createType(262144 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -38667,7 +40363,7 @@ var ts; } function instantiateSymbol(symbol, mapper) { var links = getSymbolLinks(symbol); - if (links.type && !maybeTypeOfKind(links.type, 131072 /* Object */ | 15794176 /* Instantiable */)) { + if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { // If the type of the symbol is already resolved, and if that type could not possibly // be affected by instantiation, simply return the symbol itself. return symbol; @@ -38705,7 +40401,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38715,7 +40411,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38747,8 +40443,8 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 146 /* QualifiedName */ || - node.parent.kind === 162 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + return !(node.kind === 148 /* QualifiedName */ || + node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks @@ -38756,26 +40452,36 @@ var ts; // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 216 /* Block */ ? "quit" : n === container_3; })) { + if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) { return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { - case 176 /* ThisType */: + case 178 /* ThisType */: return !!tp.isThisType; - case 71 /* Identifier */: + case 72 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return true; } return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38785,30 +40491,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38825,13 +40535,19 @@ var ts; var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); var modifiers = getMappedTypeModifiers(type); return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38864,61 +40580,77 @@ var ts; if (root.isDistributive) { var checkType_1 = root.checkType; var instantiatedType = mapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & (262144 /* Union */ | 32768 /* Never */)) { + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return mapper(type); + } + if (flags & 524288 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } function getWildcardInstantiation(type) { - return type.flags & (32764 /* Primitive */ | 3 /* AnyOrUnknown */ | 32768 /* Never */) ? type : + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); } function instantiateIndexInfo(info, mapper) { @@ -38927,34 +40659,34 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 202 /* BinaryExpression */: - return node.operatorToken.kind === 54 /* BarBarToken */ && + case 204 /* BinaryExpression */: + return node.operatorToken.kind === 55 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 266 /* JsxAttributes */: - return ts.some(node.properties, isContextSensitive); - case 265 /* JsxAttribute */: { + case 268 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 268 /* JsxExpression */: { + case 270 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -38971,7 +40703,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 195 /* ArrowFunction */) { + if (node.kind !== 197 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -38984,14 +40716,14 @@ var ts; function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. var body = node.body; - return body.kind === 216 /* Block */ ? false : isContextSensitive(body); + return body.kind === 218 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); @@ -39002,7 +40734,7 @@ var ts; return result; } } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -39017,6 +40749,9 @@ var ts; function compareTypesAssignable(source, target) { return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } function isTypeSubtypeOf(source, target) { return isTypeRelatedTo(source, target, subtypeRelation); } @@ -39032,11 +40767,12 @@ var ts; // Note that this check ignores type parameters and only considers the // inheritance hierarchy. function isTypeDerivedFrom(source, target) { - return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : - target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : - source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39062,33 +40798,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { - case 268 /* JsxExpression */: - case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); - case 202 /* BinaryExpression */: + case 270 /* JsxExpression */: + case 195 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: - case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage); } break; - case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); - case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); - case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + case 188 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation); + case 187 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation); + case 268 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target, relation); + case 197 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39097,15 +40898,17 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */) + continue; // Don't elaborate on indexes on generic variables + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39114,10 +40917,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39125,16 +40928,19 @@ var ts; var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; var issuedElaboration = false; if (!targetProp) { - var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39168,8 +40974,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39201,9 +41007,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39221,17 +41032,17 @@ var ts; prop = _a[_i]; if (ts.isSpreadAssignment(prop)) return [3 /*break*/, 7]; - type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), 2240 /* StringOrNumberLiteralOrUnique */); - if (!type || (type.flags & 32768 /* Never */)) { + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 131072 /* Never */)) { return [3 /*break*/, 7]; } _b = prop.kind; switch (_b) { - case 157 /* SetAccessor */: return [3 /*break*/, 2]; - case 156 /* GetAccessor */: return [3 /*break*/, 2]; - case 154 /* MethodDeclaration */: return [3 /*break*/, 2]; - case 274 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 273 /* PropertyAssignment */: return [3 /*break*/, 4]; + case 159 /* SetAccessor */: return [3 /*break*/, 2]; + case 158 /* GetAccessor */: return [3 /*break*/, 2]; + case 156 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 275 /* PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -39252,8 +41063,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39283,14 +41094,15 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 154 /* MethodDeclaration */ && - kind !== 153 /* MethodSignature */ && kind !== 155 /* Constructor */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ && + kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -39308,11 +41120,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39324,7 +41136,7 @@ var ts; var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && - (getFalsyFlags(sourceType) & 24576 /* Nullable */) === (getFalsyFlags(targetType) & 24576 /* Nullable */); + (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); var related = callbacks ? // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : @@ -39338,13 +41150,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39416,12 +41228,15 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 131072 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 /* NonPrimitive */ ? true : - type.flags & 262144 /* Union */ ? ts.some(type.types, isEmptyObjectType) : - type.flags & 524288 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : + return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 /* NonPrimitive */ ? true : + type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : false; } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type); + } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { if (sourceSymbol === targetSymbol) { return true; @@ -39458,43 +41273,45 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 3 /* AnyOrUnknown */ || s & 32768 /* Never */ || source === wildcardType) + if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType) return true; - if (t & 32768 /* Never */) + if (t & 131072 /* Never */) return false; - if (s & 68 /* StringLike */ && t & 4 /* String */) + if (s & 132 /* StringLike */ && t & 4 /* String */) return true; - if (s & 64 /* StringLiteral */ && s & 512 /* EnumLiteral */ && - t & 64 /* StringLiteral */ && !(t & 512 /* EnumLiteral */) && + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && + t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 168 /* NumberLike */ && t & 8 /* Number */) + if (s & 296 /* NumberLike */ && t & 8 /* Number */) return true; - if (s & 128 /* NumberLiteral */ && s & 512 /* EnumLiteral */ && - t & 128 /* NumberLiteral */ && !(t & 512 /* EnumLiteral */) && + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && + t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 272 /* BooleanLike */ && t & 16 /* Boolean */) + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) return true; - if (s & 3072 /* ESSymbolLike */ && t & 1024 /* ESSymbol */) + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) + return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) return true; if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 512 /* EnumLiteral */ && t & 512 /* EnumLiteral */) { - if (s & 262144 /* Union */ && t & 262144 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 448 /* Literal */ && t & 448 /* Literal */ && + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 8192 /* Undefined */ && (!strictNullChecks || t & (8192 /* Undefined */ | 4096 /* Void */))) + if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */))) return true; - if (s & 16384 /* Null */ && (!strictNullChecks || t & 16384 /* Null */)) + if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */)) return true; - if (s & 131072 /* Object */ && t & 16777216 /* NonPrimitive */) + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) return true; - if (s & 2048 /* UniqueESSymbol */ || t & 2048 /* UniqueESSymbol */) + if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) @@ -39502,30 +41319,30 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (8 /* Number */ | 128 /* NumberLiteral */) && !(s & 512 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 128 /* NumberLiteral */ && t & 512 /* EnumLiteral */)) + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; } return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(target)) { target = target.regularType; } if (source === target || - relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */) { + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */) { + if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) { return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); } return false; @@ -39545,6 +41362,7 @@ var ts; */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -39552,7 +41370,7 @@ var ts; var depth = 0; var expandingFlags = 0 /* None */; var overflow = false; - var isIntersectionConstituent = false; + var suppressNextError = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (overflow) { @@ -39579,15 +41397,27 @@ var ts; } } var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } if (errorOutputContainer) { errorOutputContainer.error = diag; } diagnostics.add(diag); // TODO: GH#18217 } return result !== 0 /* False */; - function reportError(message, arg0, arg1, arg2) { + function reportError(message, arg0, arg1, arg2, arg3) { ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } } function reportRelationError(message, source, target) { var sourceType = typeToString(source); @@ -39620,7 +41450,7 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 786432 /* UnionOrIntersection */)) { + if (!(type.flags & 3145728 /* UnionOrIntersection */)) { return false; } // at this point we know that this is union or intersection type possibly with nullable constituents. @@ -39628,7 +41458,7 @@ var ts; var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 24576 /* Nullable */) { + if (t.flags & 98304 /* Nullable */) { continue; } if (seenNonNullable) { @@ -39644,24 +41474,24 @@ var ts; * * Ternary.Maybe if they are related with assumptions of other relationships, or * * Ternary.False if they are not related. */ - function isRelatedTo(source, target, reportErrors, headMessage) { + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(target)) { target = target.regularType; } - if (source.flags & 8388608 /* Substitution */) { + if (source.flags & 33554432 /* Substitution */) { source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } - if (target.flags & 8388608 /* Substitution */) { + if (target.flags & 33554432 /* Substitution */) { target = target.typeVariable; } - if (source.flags & 2097152 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { source = getSimplifiedType(source); } - if (target.flags & 2097152 /* IndexedAccess */) { + if (target.flags & 8388608 /* IndexedAccess */) { target = getSimplifiedType(target); } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. @@ -39673,10 +41503,10 @@ var ts; // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" // when dealing with generics. // * We also don't deal with primitive source types, since we already halt elaboration below. - if (target.flags & 262144 /* Union */ && source.flags & 131072 /* Object */ && - target.types.length <= 3 && maybeTypeOfKind(target, 24576 /* Nullable */)) { - var nullStrippedTarget = extractTypesOfKind(target, ~24576 /* Nullable */); - if (!(nullStrippedTarget.flags & (262144 /* Union */ | 32768 /* Never */))) { + if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); + if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { target = nullStrippedTarget; } } @@ -39686,11 +41516,12 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (isObjectLiteralType(source) && source.flags & 33554432 /* FreshLiteral */) { - var discriminantType = target.flags & 262144 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) { + var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -39705,14 +41536,11 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && - !hasCommonProperties(source, target)) { + !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); var constructs = getSignaturesOfType(source, 1 /* Construct */); @@ -39728,25 +41556,24 @@ var ts; } var result = 0 /* False */; var saveErrorInfo = errorInfo; - var saveIsIntersectionConstituent = isIntersectionConstituent; - isIntersectionConstituent = false; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); } else { - if (target.flags & 262144 /* Union */) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */) && !(target.flags & 32764 /* Primitive */)); + if (target.flags & 1048576 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); } - else if (target.flags & 524288 /* Intersection */) { - isIntersectionConstituent = true; + else if (target.flags & 2097152 /* Intersection */) { + isIntersectionConstituent = true; // set here to affect the following trio of checks result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 524288 /* Intersection */) { + else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -39762,13 +41589,13 @@ var ts; // breaking the intersection apart. result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } - if (!result && (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - if (!result && source.flags & 524288 /* Intersection */) { + if (!result && source.flags & 2097152 /* Intersection */) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -39778,22 +41605,23 @@ var ts; // we need to check this constraint against a union on the target side. Also, given a type // variable V constrained to 'string | number', 'V & number' has a combined constraint of // 'string & number | number & number' which reduces to just 'number'. - var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 262144 /* Union */)); + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */)); if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 131072 /* Object */ && target.flags & 32764 /* Primitive */) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 131072 /* Object */ && globalObjectType === source) { + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } - else if (ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && target.flags & 524288 /* Intersection */) { + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { var targetTypes = target.types; var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); @@ -39803,6 +41631,10 @@ var ts; return result; } } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } reportRelationError(headMessage, source, target); } return result; @@ -39810,49 +41642,23 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); + if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); } - if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { + if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { @@ -39862,17 +41668,18 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. if (!errorNode) return { value: ts.Debug.fail() }; - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { @@ -39901,13 +41708,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +41733,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 262144 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -39936,16 +41746,17 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; } function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { var sourceObjectFlags = ts.getObjectFlags(source); - if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 262144 /* Union */) { + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { return ts.find(unionTarget.types, function (target) { - if (target.flags & 131072 /* Object */) { + if (target.flags & 524288 /* Object */) { var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); if (overlapObjFlags & 4 /* Reference */) { return source.target === target.target; @@ -39963,39 +41774,33 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); - if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } + if (target.flags & 1048576 /* Union */) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; var targetTypes = target.types; for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); + var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); if (!related) { return 0 /* False */; } @@ -40005,7 +41810,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 262144 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -40030,9 +41835,10 @@ var ts; } return result; } - function typeArgumentsRelatedTo(source, target, variances, reportErrors) { - var sources = source.typeArguments || ts.emptyArray; - var targets = target.typeArguments || ts.emptyArray; + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } @@ -40086,7 +41892,7 @@ var ts; // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function recursiveTypeRelatedTo(source, target, reportErrors) { + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { if (overflow) { return 0 /* False */; } @@ -40129,7 +41935,7 @@ var ts; expandingFlags |= 1 /* Source */; if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) expandingFlags |= 2 /* Target */; - var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -40152,13 +41958,57 @@ var ts; function getConstraintForRelation(type) { return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } - function structuredTypeRelatedTo(source, target, reportErrors) { + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288 /* Object */)) { + if (flags & 4194304 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 8388608 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 16777216 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 65536 /* TypeParameter */) { - // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144 /* TypeParameter */) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -40168,9 +42018,9 @@ var ts; } } } - else if (target.flags & 1048576 /* Index */) { + else if (target.flags & 4194304 /* Index */) { // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 1048576 /* Index */) { + if (source.flags & 4194304 /* Index */) { if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } @@ -40181,20 +42031,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } - else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (target.flags & 8388608 /* IndexedAccess */) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40203,23 +42058,24 @@ var ts; var template = getTemplateTypeFromMappedType(target); var modifiers = getMappedTypeModifiers(target); if (!(modifiers & 8 /* ExcludeOptional */)) { - if (template.flags & 2097152 /* IndexedAccess */ && template.objectType === source && + if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source && template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } } - if (source.flags & 2162688 /* TypeVariable */) { - if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + if (source.flags & 8650752 /* TypeVariable */) { + if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { // A type S[K] is related to a type T[J] if S is related to T and K is related to J. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { result &= isRelatedTo(source.indexType, target.indexType, reportErrors); @@ -40230,29 +42086,32 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 65536 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~16777216 /* NonPrimitive */))) { + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { errorInfo = saveErrorInfo; return result; } } - else { - var instantiated = getTypeWithThisArgument(constraint, source); - if (result = isRelatedTo(instantiated, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; } } - else if (source.flags & 1048576 /* Index */) { + else if (source.flags & 4194304 /* Index */) { if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { errorInfo = saveErrorInfo; return result; } } - else if (source.flags & 4194304 /* Conditional */) { - if (target.flags & 4194304 /* Conditional */) { + else if (source.flags & 16777216 /* Conditional */) { + if (target.flags & 16777216 /* Conditional */) { // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, // and Y1 is related to Y2. @@ -40285,13 +42144,33 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); - if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { return result; } // The type arguments did not relate appropriately, but it may be because we have no variance @@ -40318,36 +42197,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40370,10 +42239,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40386,7 +42255,24 @@ var ts; var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } } return 0 /* False */; } @@ -40433,8 +42319,8 @@ var ts; } } var properties = getPropertiesOfObjectType(target); - for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { - var targetProp = properties_3[_b]; + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { @@ -40504,35 +42390,8 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { + if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -40562,8 +42421,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40660,7 +42519,7 @@ var ts; continue; } // Skip over symbol-named members - if (prop.nameType && prop.nameType.flags & 2048 /* UniqueESSymbol */) { + if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) { continue; } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { @@ -40755,6 +42614,51 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -40762,62 +42666,71 @@ var ts; result.objectFlags |= 8192 /* MarkerType */; return result; } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } // Return an array containing the variance of each type parameter. The variance is effectively // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } function getVariances(type) { if (!strictFunctionTypes) { return ts.emptyArray; } - var typeParameters = type.typeParameters || ts.emptyArray; - var variances = type.variances; - if (!variances) { - if (type === globalArrayType || type === globalReadonlyArrayType) { - // Arrays are known to be covariant, no need to spend time computing this - variances = [1 /* Covariant */]; - } - else { - // The emptyArray singleton is used to signal a recursive invocation. - type.variances = ts.emptyArray; - variances = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - // We first compare instantiations where the type parameter is replaced with - // marker types that have a known subtype relationship. From this we can infer - // invariance, covariance, contravariance or bivariance. - var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); - var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); - var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | - (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); - // If the instantiations appear to be related bivariantly it may be because the - // type parameter is independent (i.e. it isn't witnessed anywhere in the generic - // type). To determine this we compare instantiations where the type parameter is - // replaced with marker types that are known to be unrelated. - if (variance === 3 /* Bivariant */ && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { - variance = 4 /* Independent */; - } - variances.push(variance); - } - } - type.variances = variances; + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return ts.emptyArray; } - return variances; + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } // Return true if the given type reference has a 'void' type argument for a covariant type parameter. // See comment at call in recursiveTypeRelatedTo for when this case matters. function hasCovariantVoidArgument(type, variances) { for (var i = 0; i < variances.length; i++) { - if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 4096 /* Void */) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { return true; } } return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -40910,13 +42823,13 @@ var ts; // levels, but unequal at some level beyond that. function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 131072 /* Object */) { + if (depth >= 5 && type.flags & 524288 /* Object */) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 131072 /* Object */ && t.symbol === symbol) { + if (t.flags & 524288 /* Object */ && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -40971,12 +42884,8 @@ var ts; return true; } // A source signature partially matches a target signature if the target signature has no fewer required - // parameters and no more overall parameters than the source signature (where a signature with a rest - // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = sourceHasRestParameter ? 1 : 0; - var targetRestCount = targetHasRestParameter ? 1 : 0; - if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) { + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { return true; } return false; @@ -41022,7 +42931,7 @@ var ts; for (var i = 0; i < targetLen; i++) { var s = getTypeAtPosition(source, i); var t = getTypeAtPosition(target, i); - var related = compareTypes(s, t); + var related = compareTypes(t, s); if (!related) { return 0 /* False */; } @@ -41043,8 +42952,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41067,9 +42976,9 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 24576 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 24576 /* Nullable */) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) : getUnionType(types, 2 /* Subtype */); } // Return the leftmost type for which no type to the right is a subtype. @@ -41082,11 +42991,14 @@ var ts; function isReadonlyArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 24576 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isEmptyArrayLiteralType(type) { var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; @@ -41096,40 +43008,47 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { - return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); + return !(type.flags & (109440 /* Unit */ | 131072 /* Never */)); } function isUnitType(type) { - return !!(type.flags & 27072 /* Unit */); + return !!(type.flags & 109440 /* Unit */); } function isLiteralType(type) { return type.flags & 16 /* Boolean */ ? true : - type.flags & 262144 /* Union */ ? type.flags & 512 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : + type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 /* StringLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : - type; + return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 512 /* BooleanLiteral */ ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : - type; + return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : + type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : + type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; } function getWidenedUniqueESSymbolType(type) { - return type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : type; } function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { @@ -41148,13 +43067,21 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41163,15 +43090,16 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : - type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : - type.flags & 29148 /* PossiblyFalsy */; + return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 : + type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 : + type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 : + type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 : + type.flags & 117724 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 29120 /* DefinitelyFalsy */); }) : + return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) : type; } function extractDefinitelyFalsyTypes(type) { @@ -41180,10 +43108,13 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : - type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + type.flags & 64 /* BigInt */ ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) || + type.flags & 128 /* StringLiteral */ && type.value === "" || + type.flags & 256 /* NumberLiteral */ && type.value === 0 || + type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : neverType; } /** @@ -41192,15 +43123,15 @@ var ts; * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both */ function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (8192 /* Undefined */ | 16384 /* Null */); + var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */); return missing === 0 ? type : - missing === 8192 /* Undefined */ ? getUnionType([type, undefinedType]) : - missing === 16384 /* Null */ ? getUnionType([type, nullType]) : + missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 65536 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } function getOptionalType(type) { ts.Debug.assert(strictNullChecks); - return type.flags & 8192 /* Undefined */ ? type : getUnionType([type, undefinedType]); + return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { if (!deferredGlobalNonNullableTypeAlias) { @@ -41210,7 +43141,7 @@ var ts; if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); } - return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -41253,7 +43184,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && type.flags & 33554432 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -41263,7 +43194,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; + regularNew.flags = resolved.flags; regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); type.regularType = regularNew; return regularNew; @@ -41351,15 +43282,15 @@ var ts; } function getWidenedTypeWithContext(type, context) { if (type.flags & 402653184 /* RequiresWidening */) { - if (type.flags & 24576 /* Nullable */) { + if (type.flags & 98304 /* Nullable */) { return anyType; } if (isObjectLiteralType(type)) { return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); - var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 24576 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). @@ -41385,7 +43316,7 @@ var ts; function reportWideningErrorsInType(type) { var errorReported = false; if (type.flags & 134217728 /* ContainsWideningType */) { - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } @@ -41421,68 +43352,90 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { - case 202 /* BinaryExpression */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + case 204 /* BinaryExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 149 /* Parameter */: + case 151 /* Parameter */: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - if (!declaration.name) { + case 289 /* JSDocFunctionType */: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; break; - case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + case 181 /* MappedType */: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41531,11 +43484,11 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - return !!(type.flags & 15794176 /* Instantiable */ || + return !!(type.flags & 63176704 /* Instantiable */ || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || - type.flags & 786432 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -41544,13 +43497,13 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || !!(type.flags & 786432 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { - if (!(t.flags & 64 /* StringLiteral */)) { + if (!(t.flags & 128 /* StringLiteral */)) { return; } var name = ts.escapeLeadingUnderscores(t.value); @@ -41571,25 +43524,25 @@ var ts; * property is computed by inferring from the source property type to X for the type * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ - function inferTypeForHomomorphicMappedType(source, target) { - var key = source.id + "," + target.id; + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } reverseMappedCache.set(key, undefined); - var type = createReverseMappedType(source, target); + var type = createReverseMappedType(source, target, constraint); reverseMappedCache.set(key, type); return type; } - function createReverseMappedType(source, target) { + function createReverseMappedType(source, target, constraint) { var properties = getPropertiesOfType(source); if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { return undefined; } // If any property contains context sensitive functions that have been skipped, the source type // is incomplete and we can't infer a meaningful input type. - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var prop = properties_4[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { return undefined; } @@ -41597,13 +43550,13 @@ var ts; // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been // applied to the element type(s). if (isArrayType(source)) { - return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isReadonlyArrayType(source)) { - return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isTupleType(source)) { - var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); @@ -41613,30 +43566,46 @@ var ts; var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; + reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); } - function inferReverseMappedType(sourceType, target) { - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = target.flags & 524288 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; - if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (!sourceProp) { - return targetProp; - } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3 /*break*/, 3]; + return [4 /*yield*/, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; } - } - return undefined; + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -41658,7 +43627,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41684,8 +43655,8 @@ var ts; } return; } - if (source.flags & 262144 /* Union */ && target.flags & 262144 /* Union */ && !(source.flags & 512 /* EnumLiteral */ && target.flags & 512 /* EnumLiteral */) || - source.flags & 524288 /* Intersection */ && target.flags & 524288 /* Intersection */) { + if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) || + source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -41708,7 +43679,7 @@ var ts; (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } - else if (t.flags & (128 /* NumberLiteral */ | 64 /* StringLiteral */)) { + else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) { var b = getBaseTypeOfLiteralType(t); if (typeIdenticalToSomeType(b, target.types)) { (matchingTypes || (matchingTypes = [])).push(t, b); @@ -41723,7 +43694,7 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 2162688 /* TypeVariable */) { + if (target.flags & 8650752 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding @@ -41731,7 +43702,7 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType) { + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -41744,19 +43715,39 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } - if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 63176704 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments @@ -41773,12 +43764,12 @@ var ts; } } } - else if (source.flags & 1048576 /* Index */ && target.flags & 1048576 /* Index */) { + else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { contravariant = !contravariant; inferFromTypes(source.type, target.type); contravariant = !contravariant; } - else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 1048576 /* Index */) { + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; var savePriority = priority; @@ -41787,17 +43778,20 @@ var ts; priority = savePriority; contravariant = !contravariant; } - else if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (source.flags & 4194304 /* Conditional */ && target.flags & 4194304 /* Conditional */) { + else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } - else if (target.flags & 786432 /* UnionOrIntersection */) { + else if (target.flags & 16777216 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -41822,7 +43816,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 262144 /* Union */) { + else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -41831,10 +43825,25 @@ var ts; } } else { - if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } - if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -41844,7 +43853,7 @@ var ts; // an instantiation of the same generic type), we do not explore this target as it would yield // no further inferences. We exclude the static side of classes from this check since it shares // its symbol with the instance side which would lead to false positives. - var isNonConstructorObject = target.flags & 131072 /* Object */ && + var isNonConstructorObject = target.flags & 524288 /* Object */ && !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { @@ -41860,6 +43869,13 @@ var ts; } } } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { @@ -41872,7 +43888,7 @@ var ts; } } function getInferenceInfoForType(type) { - if (type.flags & 2162688 /* TypeVariable */) { + if (type.flags & 8650752 /* TypeVariable */) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -41882,6 +43898,44 @@ var ts; } return undefined; } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* HomomorphicMappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } function inferFromObjectTypes(source, target) { if (isGenericMappedType(source) && isGenericMappedType(target)) { // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer @@ -41891,31 +43945,7 @@ var ts; } if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 1048576 /* Index */) { - // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, - // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source - // type and then make a secondary inference from that type to T. We make a secondary inference - // such that direct inferences to T get priority over inferences to Partial, for example. - var inference = getInferenceInfoForType(constraintType.type); - if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - var savePriority = priority; - priority |= 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; - } - } - return; - } - if (constraintType.flags & 65536 /* TypeParameter */) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. - var savePriority = priority; - priority |= 4 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { return; } } @@ -41928,33 +43958,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41964,12 +43999,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -42000,8 +44043,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42020,11 +44063,11 @@ var ts; reducedTypes.push(t); } } - return type.flags & 262144 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42042,7 +44085,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42055,10 +44098,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42069,16 +44111,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42095,7 +44140,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42124,11 +44169,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42137,7 +44211,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 165 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 146 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the @@ -42146,20 +44220,20 @@ var ts; // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } - if (node.kind === 99 /* ThisKeyword */) { + if (node.kind === 100 /* ThisKeyword */) { return "0"; } - if (node.kind === 187 /* PropertyAccessExpression */) { + if (node.kind === 189 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); return key && key + "." + ts.idText(node.name); } - if (node.kind === 184 /* BindingElement */) { + if (node.kind === 186 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 184 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -42168,14 +44242,14 @@ var ts; } function getBindingElementNameText(element) { var parent = element.parent; - if (parent.kind === 182 /* ObjectBindingPattern */) { + if (parent.kind === 184 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.idText(name); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return name.text; default: @@ -42189,29 +44263,29 @@ var ts; } function isMatchingReference(source, target) { switch (source.kind) { - case 71 /* Identifier */: - return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 235 /* VariableDeclaration */ || target.kind === 184 /* BindingElement */) && + case 72 /* Identifier */: + return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99 /* ThisKeyword */: - return target.kind === 99 /* ThisKeyword */; - case 97 /* SuperKeyword */: - return target.kind === 97 /* SuperKeyword */; - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 100 /* ThisKeyword */: + return target.kind === 100 /* ThisKeyword */; + case 98 /* SuperKeyword */: + return target.kind === 98 /* SuperKeyword */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 184 /* BindingElement */: - if (target.kind !== 187 /* PropertyAccessExpression */) + case 186 /* BindingElement */: + if (target.kind !== 189 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 184 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 235 /* VariableDeclaration */) { + if (source.parent.parent.kind === 237 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; return !!maybeId && isMatchingReference(maybeId, t.expression); } @@ -42224,7 +44298,7 @@ var ts; undefined; } function containsMatchingReference(source, target) { - while (source.kind === 187 /* PropertyAccessExpression */) { + while (source.kind === 189 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -42237,32 +44311,52 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 187 /* PropertyAccessExpression */ && + return target.kind === 189 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71 /* Identifier */) { + if (expr.kind === 72 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 187 /* PropertyAccessExpression */) { + if (expr.kind === 189 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 262144 /* Union */) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; + function isDiscriminantType(type) { + if (type.flags & 1048576 /* Union */) { + if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { + return true; } } return false; } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576 /* Union */); + } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -42289,7 +44383,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -42302,16 +44396,35 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 32768 /* Never */) { + if (assignedType.flags & 131072 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42319,8 +44432,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42335,55 +44448,66 @@ var ts; function getTypeFacts(type) { var flags = type.flags; if (flags & 4 /* String */) { - return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; } - if (flags & 64 /* StringLiteral */) { + if (flags & 128 /* StringLiteral */) { var isEmpty = type.value === ""; return strictNullChecks ? - isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : + isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; } if (flags & (8 /* Number */ | 32 /* Enum */)) { - return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; } - if (flags & 128 /* NumberLiteral */) { + if (flags & 256 /* NumberLiteral */) { var isZero = type.value === 0; return strictNullChecks ? - isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : - isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; + isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : + isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : + isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; } if (flags & 16 /* Boolean */) { - return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; } - if (flags & 272 /* BooleanLike */) { + if (flags & 528 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 524288 /* Object */) { + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ : + strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } - if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { - return 2457472 /* UndefinedFacts */; + if (flags & (16384 /* Void */ | 32768 /* Undefined */)) { + return 9830144 /* UndefinedFacts */; } - if (flags & 16384 /* Null */) { - return 2340752 /* NullFacts */; + if (flags & 65536 /* Null */) { + return 9363232 /* NullFacts */; } - if (flags & 3072 /* ESSymbolLike */) { - return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; } - if (flags & 16777216 /* NonPrimitive */) { - return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } - if (flags & 15794176 /* Instantiable */) { + if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 786432 /* UnionOrIntersection */) { + if (flags & 3145728 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } - return 4194303 /* All */; + return 16777215 /* All */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -42391,7 +44515,7 @@ var ts; function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); + return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); } return type; } @@ -42403,7 +44527,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42411,15 +44535,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 185 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 273 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 225 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -42436,21 +44560,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return stringType; - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return undefinedType; - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -42458,7 +44582,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 182 /* ObjectBindingPattern */ ? + var type = pattern.kind === 184 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -42476,39 +44600,39 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 224 /* ForInStatement */) { + if (node.parent.parent.kind === 226 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 225 /* ForOfStatement */) { + if (node.parent.parent.kind === 227 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 235 /* VariableDeclaration */ ? + return node.kind === 237 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { - return node.kind === 235 /* VariableDeclaration */ && node.initializer && + return node.kind === 237 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 184 /* BindingElement */ && node.parent.kind === 202 /* BinaryExpression */ && + node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return getReferenceCandidate(node.left); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return getReferenceCandidate(node.right); } } @@ -42516,13 +44640,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 193 /* ParenthesizedExpression */ || - parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + return parent.kind === 195 /* ParenthesizedExpression */ || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 269 /* CaseClause */) { + if (clause.kind === 271 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -42538,14 +44662,31 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271 /* CaseClause */) { + if (clause.expression.kind === 10 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { - return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 262144 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -42554,34 +44695,37 @@ var ts; } return true; } - if (source.flags & 512 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); + return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); } return f(type) ? type : neverType; } function mapType(type, mapper, noReductions) { - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { return type; } - if (!(type.flags & 262144 /* Union */)) { + if (!(type.flags & 1048576 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42604,12 +44748,14 @@ var ts; // typeWithPrimitives have been replaced with occurrences of string literals and numeric // literals in typeWithLiterals, respectively. function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* StringLiteral */) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* NumberLiteral */)) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) { return mapType(typeWithPrimitives, function (t) { - return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 64 /* StringLiteral */) : - t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 128 /* NumberLiteral */) : - t; + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : + t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : + t; }); } return typeWithPrimitives; @@ -42643,9 +44789,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 32768 /* Never */ ? + return elementType.flags & 131072 /* Never */ ? autoArrayType : - createArrayType(elementType.flags & 262144 /* Union */ ? + createArrayType(elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType); } @@ -42661,9 +44807,9 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - if (!(t.flags & 32768 /* Never */)) { + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; } @@ -42685,15 +44831,15 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 187 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || - parent.parent.kind === 189 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 188 /* ElementAccessExpression */ && + var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 202 /* BinaryExpression */ && - parent.parent.operatorToken.kind === 58 /* EqualsToken */ && + parent.parent.kind === 204 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 59 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 168 /* NumberLike */); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -42704,7 +44850,7 @@ var ts; return links.maybeTypePredicate; } function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97 /* SuperKeyword */) { + if (node.expression.kind !== 98 /* SuperKeyword */) { var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); @@ -42726,7 +44872,7 @@ var ts; if (flowAnalysisDisabled) { return errorType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 33492479 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) { return declaredType; } var sharedFlowStart = sharedFlowCount; @@ -42736,14 +44882,14 @@ var ts; // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. - var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent && reference.parent.kind === 211 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 32768 /* Never */) { + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { return declaredType; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42809,9 +44955,9 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.container; if (container && container !== flowContainer && - reference.kind !== 187 /* PropertyAccessExpression */ && - reference.kind !== 188 /* ElementAccessExpression */ && - reference.kind !== 99 /* ThisKeyword */) { + reference.kind !== 189 /* PropertyAccessExpression */ && + reference.kind !== 190 /* ElementAccessExpression */ && + reference.kind !== 100 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -42846,11 +44992,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + if (declaredType.flags & 1048576 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42859,15 +45005,27 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } + // for (const _ in ref) acts as a nonnull on ref + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } // Assignment doesn't affect reference return undefined; } function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 189 /* CallExpression */ ? + var expr = node.kind === 191 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -42875,15 +45033,16 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -42897,7 +45056,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { return flowType; } // If we have an antecedent type (meaning we're reachable in some way), we first @@ -42914,19 +45073,25 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 32768 /* Never */ ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43040,8 +45205,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 262144 /* Union */) || - expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + if (!(computedType.flags & 1048576 /* Union */) || + expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { return false; } var access = expr; @@ -43062,10 +45227,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); + return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } if (isMatchingReferenceDiscriminant(expr, declaredType)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } if (containsMatchingReferenceDiscriminant(reference, expr)) { return declaredType; @@ -43083,7 +45248,7 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if ((type.flags & (262144 /* Union */ | 131072 /* Object */)) || (type.flags & 65536 /* TypeParameter */ && type.isThisType)) { + if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); } @@ -43091,19 +45256,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -43122,15 +45287,15 @@ var ts; return declaredType; } break; - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 92 /* InKeyword */: + case 93 /* InKeyword */: var target = getReferenceCandidate(expr.right); if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; - case 26 /* CommaToken */: + case 27 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } return type; @@ -43139,28 +45304,28 @@ var ts; if (type.flags & 1 /* Any */) { return type; } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 24576 /* Nullable */) { + if (valueType.flags & 98304 /* Nullable */) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; + var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */; var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - valueType.flags & 16384 /* Null */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : + valueType.flags & 65536 /* Null */ ? + assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : + assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 16909315 /* NotUnionOrUnit */) { + if (type.flags & 67637251 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 32768 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -43172,40 +45337,47 @@ var ts; // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { return declaredType; } return type; } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 15794176 /* Instantiable */) { + if (type.flags & 63176704 /* Instantiable */) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43216,27 +45388,115 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 32768 /* Never */ ? neverType : + var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 /* Any */ ? type : globalFunctionType; + case "object": + return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjusted clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { return declaredType; } return type; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43253,22 +45513,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43276,9 +45526,9 @@ var ts; } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 32768 /* Never */)) { + if (!(assignableType.flags & 131072 /* Never */)) { return assignableType; } } @@ -43318,7 +45568,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 188 /* ElementAccessExpression */ || invokedExpression.kind === 187 /* PropertyAccessExpression */) { + if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -43335,20 +45585,20 @@ var ts; // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 200 /* PrefixUnaryExpression */: - if (expr.operator === 51 /* ExclamationToken */) { + case 202 /* PrefixUnaryExpression */: + if (expr.operator === 52 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -43362,7 +45612,7 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 71 /* Identifier */) { + if (location.kind === 72 /* Identifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } @@ -43383,17 +45633,17 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 243 /* ModuleBlock */ || - node.kind === 277 /* SourceFile */ || - node.kind === 152 /* PropertyDeclaration */; + node.kind === 245 /* ModuleBlock */ || + node.kind === 279 /* SourceFile */ || + node.kind === 154 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43401,13 +45651,13 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 149 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) { symbol.isAssigned = true; } } @@ -43422,21 +45672,21 @@ var ts; /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 149 /* Parameter */ && + declaration.kind === 151 /* Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 8192 /* Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 8192 /* Undefined */); - return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 187 /* PropertyAccessExpression */ || - parent.kind === 189 /* CallExpression */ && parent.expression === node || - parent.kind === 188 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 184 /* BindingElement */ && parent.name === node && !!parent.initializer; + return parent.kind === 189 /* PropertyAccessExpression */ || + parent.kind === 191 /* CallExpression */ && parent.expression === node || + parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { - return type.flags & 14745600 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 24576 /* Nullable */); + return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */); } function getConstraintForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, @@ -43449,7 +45699,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43467,7 +45717,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 195 /* ArrowFunction */) { + if (container.kind === 197 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { @@ -43488,28 +45738,28 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 238 /* ClassDeclaration */ + if (declaration.kind === 240 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); } } - else if (declaration.kind === 207 /* ClassExpression */) { + else if (declaration.kind === 209 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 277 /* SourceFile */) { + while (container.kind !== 279 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43522,12 +45772,17 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } return errorType; } } @@ -43551,7 +45806,7 @@ var ts; // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 149 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -43560,8 +45815,8 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 194 /* FunctionExpression */ || - flowContainer.kind === 195 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ || + flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -43570,9 +45825,9 @@ var ts; // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || - isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || - node.parent.kind === 211 /* NonNullExpression */ || - declaration.kind === 235 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) || + node.parent.kind === 213 /* NonNullExpression */ || + declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 4194304 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -43581,7 +45836,7 @@ var ts; // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (type === autoType || type === autoArrayType) { + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); @@ -43590,7 +45845,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -43600,10 +45855,13 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 272 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -43624,26 +45882,46 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + 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 === 223 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && + if (container.kind === 225 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 193 /* ParenthesizedExpression */) { + while (current.parent.kind === 195 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -43651,9 +45929,9 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 200 /* PrefixUnaryExpression */ || current.parent.kind === 201 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) { var expr = current.parent; - isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; + isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */; } if (!isAssigned) { return false; @@ -43664,7 +45942,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 152 /* PropertyDeclaration */ || container.kind === 155 /* Constructor */) { + if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -43732,37 +46010,37 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 155 /* Constructor */) { + if (container.kind === 157 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 195 /* ArrowFunction */) { + if (container.kind === 197 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } switch (container.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* 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 241 /* EnumDeclaration */: + case 243 /* 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 155 /* Constructor */: + case 157 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: if (ts.hasModifier(container, 32 /* Static */)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -43773,39 +46051,43 @@ var ts; var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ? + var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } } return type || anyType; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43820,16 +46102,68 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 196 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 156 /* MethodDeclaration */ && + container.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 196 /* FunctionExpression */ && + container.parent.kind === 275 /* PropertyAssignment */ && + container.parent.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === 196 /* FunctionExpression */ && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -43843,15 +46177,15 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 149 /* Parameter */; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 189 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 195 /* ArrowFunction */) { + while (container && container.kind === 197 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -43864,14 +46198,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 147 /* ComputedPropertyName */; }); - if (current && current.kind === 147 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; }); + if (current && current.kind === 149 /* 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 === 186 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -43879,7 +46213,7 @@ var ts; } return errorType; } - if (!isCallExpression && container.kind === 155 /* Constructor */) { + if (!isCallExpression && container.kind === 157 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { @@ -43911,16 +46245,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // 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: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43932,20 +46268,21 @@ var ts; // // 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); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = 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 === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. + if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -43959,7 +46296,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 186 /* ObjectLiteralExpression */) { + if (container.parent.kind === 188 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -43980,7 +46317,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 155 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 157 /* 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 errorType; @@ -43995,7 +46332,7 @@ 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 === 155 /* Constructor */; + return container.kind === 157 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -44003,21 +46340,21 @@ var 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\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) { if (ts.hasModifier(container, 32 /* Static */)) { - return container.kind === 154 /* MethodDeclaration */ || - container.kind === 153 /* MethodSignature */ || - container.kind === 156 /* GetAccessor */ || - container.kind === 157 /* SetAccessor */; + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */; } else { - return container.kind === 154 /* MethodDeclaration */ || - container.kind === 153 /* MethodSignature */ || - container.kind === 156 /* GetAccessor */ || - container.kind === 157 /* SetAccessor */ || - container.kind === 152 /* PropertyDeclaration */ || - container.kind === 151 /* PropertySignature */ || - container.kind === 155 /* Constructor */; + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */ || + container.kind === 154 /* PropertyDeclaration */ || + container.kind === 153 /* PropertySignature */ || + container.kind === 157 /* Constructor */; } } } @@ -44025,10 +46362,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 154 /* MethodDeclaration */ || - func.kind === 156 /* GetAccessor */ || - func.kind === 157 /* SetAccessor */) && func.parent.kind === 186 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 194 /* FunctionExpression */ && func.parent.kind === 273 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 156 /* MethodDeclaration */ || + func.kind === 158 /* GetAccessor */ || + func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -44036,11 +46373,11 @@ var ts; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 524288 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 195 /* ArrowFunction */) { + if (func.kind === 197 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -44052,7 +46389,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44067,7 +46404,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 273 /* PropertyAssignment */) { + if (literal.parent.kind !== 275 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -44081,9 +46418,9 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = func.parent; - if (parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) { var target = parent.left; - if (target.kind === 187 /* PropertyAccessExpression */ || target.kind === 188 /* ElementAccessExpression */) { + if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) { var expression = target.expression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { @@ -44109,7 +46446,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44143,7 +46480,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 149 /* Parameter */) { + if (declaration.kind === 151 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -44155,7 +46492,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 184 /* BindingElement */) { + if (parentDeclaration.kind !== 186 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -44176,9 +46513,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44225,7 +46574,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,10 +46582,13 @@ var ts; // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 191 /* TaggedTemplateExpression */) { + if (template.parent.kind === 193 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -44245,26 +46597,33 @@ var ts; var binaryExpression = node.parent; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { - case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; - case 54 /* BarBarToken */: + case 59 /* EqualsToken */: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; - case 53 /* AmpersandAmpersandToken */: - case 26 /* CommaToken */: + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; default: return undefined; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44282,26 +46641,57 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return ts.Debug.fail("Does not apply"); default: return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - if (t.flags & 917504 /* StructuredType */) { + if (t.flags & 3670016 /* StructuredType */) { var prop = getPropertyOfType(t, name); if (prop) { return getTypeOfSymbol(prop); @@ -44312,6 +46702,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44319,10 +46711,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44342,8 +46730,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44359,7 +46747,6 @@ var ts; // type of T. function getContextualTypeForElementExpression(arrayContextualType, index) { return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) - || getIndexTypeOfContextualType(arrayContextualType, 1 /* Number */) || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); } // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. @@ -44401,54 +46788,44 @@ var ts; // recursive (and possibly infinite) invocations of getContextualType. function isPossiblyDiscriminantValue(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 71 /* Identifier */: + case 9 /* BigIntLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 72 /* Identifier */: + case 141 /* UndefinedKeyword */: return true; - case 187 /* PropertyAccessExpression */: - case 193 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 195 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 270 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44477,52 +46854,54 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 186 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 195 /* ArrowFunction */: - case 228 /* ReturnStatement */: + case 197 /* ArrowFunction */: + case 230 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 201 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); + case 191 /* CallExpression */: + case 192 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 185 /* ArrayLiteralExpression */: { + case 187 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 214 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 204 /* TemplateExpression */); + case 216 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 193 /* ParenthesizedExpression */: { + case 195 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent); } return undefined; @@ -44532,67 +46911,16 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; } - var valueType = checkExpression(node.tagName); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); + return getContextualTypeForArgumentAtIndex(node, 0); } - function getJsxSignaturesParameterTypes(valueType, isJs, context) { - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (valueType.flags & 4 /* String */) { - return anyType; - } - else if (valueType.flags & 64 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = valueType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - } - return anyType; - } - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(valueType, 1 /* Construct */); - var ctor = true; - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, 0 /* Call */); - ctor = false; - if (signatures.length === 0) { - // We found no signatures at all, which is an error - return errorType; - } - } - var links = getNodeLinks(context); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(valueType); - var cachedResolved = links.resolvedSignatures.get(cacheKey); - if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { - signatures = cachedResolved; - } - else if (!cachedResolved) { - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); - } - return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); @@ -44607,22 +46935,40 @@ var ts; var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } return attributesType; } - function getJsxPropsTypeFromClassType(sig, isJs, context, reportErrors) { + function getJsxPropsTypeFromClassType(sig, context) { var ns = getJsxNamespaceAt(context); var forcedLookupLocation = getJsxElementPropertiesName(ns); var attributesType = forcedLookupLocation === undefined @@ -44635,7 +46981,7 @@ var ts; : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); if (!attributesType) { // There is no property named 'props' on this instance type - if (reportErrors && !!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); } return emptyObjectType; @@ -44653,7 +46999,7 @@ var ts; var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); var hostClassType = getReturnTypeOfSignature(sig); apparentAttributesType = intersectTypes(typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) : intrinsicClassAttribs, apparentAttributesType); } var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); @@ -44689,7 +47035,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 194 /* FunctionExpression */ || node.kind === 195 /* ArrowFunction */; + return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -44708,7 +47054,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -44717,13 +47063,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 262144 /* Union */)) { + if (!(type.flags & 1048576 /* Union */)) { return getContextualCallSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44756,10 +47102,10 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 184 /* BindingElement */ && !!node.initializer) || - (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + return (node.kind === 186 /* BindingElement */ && !!node.initializer) || + (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +47114,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elementCount; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 206 /* SpreadElement */) { + if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -44781,7 +47127,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44790,47 +47136,59 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } - if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { + if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) { hasNonEndingSpreadElement = true; } } if (!hasNonEndingSpreadElement) { - var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206 /* SpreadElement */; + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - 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 (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + 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 (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) { + if (e.kind !== 210 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44839,12 +47197,12 @@ var ts; } function isNumericName(name) { switch (name.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return isNumericComputedName(name); - case 71 /* Identifier */: + case 72 /* Identifier */: return isNumericLiteralName(name.escapedText); case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return isNumericLiteralName(name.text); default: return false; @@ -44853,7 +47211,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAssignableToKind(checkComputedPropertyName(name), 168 /* NumberLike */); + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -44888,8 +47246,8 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (links.resolvedType.flags & 24576 /* Nullable */ || - !isTypeAssignableToKind(links.resolvedType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */) && + if (links.resolvedType.flags & 98304 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -44909,6 +47267,17 @@ var ts; var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + } function checkObjectLiteral(node, checkMode) { var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking @@ -44916,13 +47285,13 @@ var ts; var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 33554432 /* FreshLiteral */; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44932,15 +47301,15 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 147 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 273 /* PropertyAssignment */ || - memberDecl.kind === 274 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 275 /* PropertyAssignment */ || + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : - memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -44951,7 +47320,7 @@ var ts; } } typeFlags |= type.flags; - var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? + var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : @@ -44962,8 +47331,8 @@ 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 === 273 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 274 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -44988,12 +47357,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 275 /* SpreadAssignment */) { + else if (memberDecl.kind === 277 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -45005,7 +47374,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); offset = i + 1; continue; } @@ -45015,10 +47384,10 @@ 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 === 156 /* GetAccessor */ || memberDecl.kind === 157 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (computedNameType && !(computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */)) { + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { if (isTypeAssignableTo(computedNameType, numberType)) { hasComputedNumberProperty = true; @@ -45052,7 +47421,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); } return spread; } @@ -45061,9 +47430,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; - result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); - result.objectFlags |= 128 /* ObjectLiteral */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; + result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -45073,20 +47441,17 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 24576 /* Nullable */)) { - propagatedFlags |= (result.flags & 939524096 /* PropagatingFlags */); - } + propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; return result; } } function isValidSpreadType(type) { - return !!(type.flags & (3 /* AnyOrUnknown */ | 16777216 /* NonPrimitive */) || - getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 131072 /* Object */ && !isGenericMappedType(type) || - type.flags & 786432 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); } function checkJsxSelfClosingElementDeferred(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node, 0 /* Normal */); + checkJsxOpeningLikeElementOrOpeningFragment(node); } function checkJsxSelfClosingElement(node, _checkMode) { checkNodeDeferred(node); @@ -45094,7 +47459,7 @@ var ts; } function checkJsxElementDeferred(node) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, 0 /* Normal */); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -45102,18 +47467,20 @@ var ts; else { checkExpression(node.closingElement.tagName); } + checkJsxChildren(node); } function checkJsxElement(node, _checkMode) { checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } - function checkJsxFragment(node, checkMode) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { error(node, compilerOptions.jsxFactory ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } + checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } /** @@ -45127,7 +47494,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) { - return tagName.kind === 71 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); + return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); } function checkJsxAttribute(node, checkMode) { return node.initializer @@ -45146,16 +47513,19 @@ var ts; function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); - var spread = emptyObjectType; + var spread = emptyJsxObjectType; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45170,9 +47540,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45180,7 +47550,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45189,11 +47559,11 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 258 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -45204,32 +47574,35 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); } } if (hasSpreadAnyType) { return anyType; } - if (typeToIntersect && spread !== emptyObjectType) { + if (typeToIntersect && spread !== emptyJsxObjectType) { return getIntersectionType([typeToIntersect, spread]); } - return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable * @param attributesTable a symbol table of attributes property */ function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; - result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; return result; } } @@ -45239,7 +47612,7 @@ var ts; var child = _a[_i]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. - if (child.kind === 10 /* JsxText */) { + if (child.kind === 11 /* JsxText */) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); } @@ -45261,7 +47634,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45302,57 +47675,6 @@ var ts; } return links.resolvedSymbol; } - function instantiateJsxSignatures(node, signatures) { - var instantiatedSignatures = []; - var candidateForTypeArgumentError; - var hasTypeArgumentError = !!node.typeArguments; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); - if (typeArgumentInstantiated) { - hasTypeArgumentError = false; - instantiatedSignatures.push(typeArgumentInstantiated); - } - else { - if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - candidateForTypeArgumentError = signature; - } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - } - else { - instantiatedSignatures.push(signature); - } - } - if (node.typeArguments && hasTypeArgumentError) { - if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); - } - // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine - else if (node.typeArguments.length !== 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); - } - } - return instantiatedSignatures; - } - function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { - if (reportErrors === void 0) { reportErrors = false; } - if (!node.typeArguments) { - return; - } - if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - return; - } - var args = checkTypeArguments(signature, node.typeArguments, reportErrors); - if (!args) { - return; - } - return getSignatureInstantiation(signature, args, isJavascript); - } function getJsxNamespaceAt(location) { var links = location && getNodeLinks(location); if (links && links.jsxNamespace) { @@ -45386,7 +47708,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45410,7 +47732,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45423,217 +47745,78 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - return undefined; + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; } - if (propsType.flags & 524288 /* Intersection */) { - var propsApparentType = []; - for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { - var t = _a[_i]; - propsApparentType.push(getApparentType(t)); + else if (elementType.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; } - return getIntersectionType(propsApparentType); - } - return getApparentType(propsType); - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return only attributes type of successfully resolved call signature. - * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) - * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); - if (callSignature !== unknownSignature) { - var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); - var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; } } - return undefined; - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return all attributes type of resolved call signature including candidate signatures. - * This function assumes that the caller handled other possible element type of the JSX element. - * This function is a behavior used by language service when looking up completion in JSX element. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - var candidate = candidatesOutArray_1[_i]; - var callReturnType = getReturnTypeOfSignature(candidate); - // TODO: GH#18217: callReturnType should always be defined... - var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - var shouldBeCandidate = true; - for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217 - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - // If we can't find any matching, just return everything. - if (!result) { - result = allMatchingAttributesType; - } - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { - var links = getNodeLinks(openingLikeElement); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(elementType); - if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { - return; - } - else if (links.resolvedSignatures.get(cacheKey)) { - return links.resolvedSignatures.get(cacheKey); - } - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + var apparentElemType = getApparentType(elementType); // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(elementType, 1 /* Construct */); + var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); if (signatures.length === 0) { // No construct signatures, try call signatures - signatures = getSignaturesOfType(elementType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - if (reportErrors) { - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - } + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0 /* Component */) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { // Mixed + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { return; } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - // Instantiate in context of source type - var results = instantiateJsxSignatures(openingLikeElement, signatures); - links.resolvedSignatures.set(cacheKey, results); - return results; - } - /** - * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. - * For instance: - * declare function Foo(attr: { p1: string}): JSX.Element; - * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" - * - * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. - * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component - * - * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement - * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature - * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present - * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) - * @return attributes type if able to resolve the type of node - * anyType if there is no type ElementAttributesProperty or there is an error - * emptyObjectType if there is no "prop" in the element instance type - */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType.flags & 262144 /* Union */) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), 2 /* Subtype */); - } - // Shortcircuit any - if (isTypeAny(elementType)) { - return elementType; - } - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - else if (elementType.flags & 4 /* String */) { - return anyType; - } - else if (elementType.flags & 64 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - // If we need to report an error, we already done so here. So just return any to prevent any more error downstream - return anyType; - } - // Get the element instance type (the result of newing or invoking this tag) - var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); - if (!ts.length(instantiatedSignatures)) { - return errorType; - } - var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */); - // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. - // Otherwise get only attributes type from the signature picked by choose-overload logic. - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -45657,53 +47840,6 @@ var ts; } return links.resolvedJsxElementAttributesType; } - /** - * Get attributes type of the given custom opening-like JSX element. - * This function is intended to be called from a caller that handles intrinsic JSX element already. - * @param node a custom JSX opening-like element - * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component - */ - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); - } - /** - * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. - * This function is called by language service (see: completions-tryGetGlobalSymbols). - * @param node a JSX opening-like element to get attributes type for - */ - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - // Because in language service, the given JSX opening-like element may be incomplete and therefore, - // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); - } - } - /** - * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. - * @param node a JSXOpeningLikeElement node - * @return an attributes type of the given node - */ - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); - } - } - /** - * Given a JSX attribute, returns the symbol for the corresponds property - * of the element attributes type. Will return unknownSymbol for attributes - * that have no matching element attributes type property. - */ - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.escapedText); - return prop || unknownSymbol; - } function getJsxElementClassTypeAt(location) { var type = getJsxType(JsxNames.ElementClass, location); if (type === errorType) @@ -45737,7 +47873,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -45748,7 +47884,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45759,10 +47895,8 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } /** @@ -45779,7 +47913,7 @@ var ts; * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType */ function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 131072 /* Object */) { + if (targetType.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -45789,7 +47923,7 @@ var ts; return true; } } - else if (targetType.flags & 786432 /* UnionOrIntersection */) { + else if (targetType.flags & 3145728 /* UnionOrIntersection */) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -45797,55 +47931,12 @@ var ts; } } } - else if (targetType.flags & 4194304 /* Conditional */) { + else if (targetType.flags & 16777216 /* Conditional */) { return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); } return false; } - /** - * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. - * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" - * Check assignablity between given attributes property, "source attributes", and the "target attributes" - * @param openingLikeElement an opening-like JSX element to check its JSXAttributes - */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { - // The function involves following steps: - // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. - // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) - // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. - // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); - // sourceAttributesType is a type of an attributes properties. - // i.e
- // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); - // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties - var isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); - // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { - var attribute = _a[_i]; - if (!ts.isJsxAttribute(attribute)) { - continue; - } - var attrName = attribute.name; - var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); - // We break here so that errors won't be cascading - break; - } - } - } - else if (!isSourceAttributeTypeAssignableToTarget) { - checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); - } - } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -45869,10 +47960,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45885,7 +47976,7 @@ var ts; */ function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name; + var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); @@ -45917,7 +48008,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -45957,13 +48048,13 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { return true; } - if (type.flags & 65536 /* TypeParameter */) { + if (type.flags & 262144 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } @@ -45983,19 +48074,26 @@ var ts; function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + return getNonNullableType(type); + } + return type; + } function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { if (type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 24576 /* Nullable */; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 8192 /* Undefined */ ? kind & 16384 /* Null */ ? + error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); - return t.flags & (24576 /* Nullable */ | 32768 /* Never */) ? errorType : t; + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } @@ -46028,7 +48126,7 @@ var ts; return anyType; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } return errorType; } @@ -46039,12 +48137,12 @@ var ts; } else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); + markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } } @@ -46053,9 +48151,9 @@ var ts; // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 187 /* PropertyAccessExpression */ || + if (node.kind !== 189 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 262144 /* Union */)) { + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } // If strict null checks and strict property initialization checks are enabled, if we have @@ -46063,17 +48161,23 @@ var ts; // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && left.kind === 99 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 155 /* Constructor */ && flowContainer.parent === declaration.parent) { + if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) { assumeUninitialized = true; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -46092,8 +48196,8 @@ var ts; && !isPropertyDeclaredInAncestorClass(prop)) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 238 /* ClassDeclaration */ && - node.parent.kind !== 162 /* TypeReference */ && + else if (valueDeclaration.kind === 240 /* ClassDeclaration */ && + node.parent.kind !== 164 /* TypeReference */ && !(valueDeclaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -46105,9 +48209,9 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return true; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: @@ -46145,7 +48249,7 @@ var ts; function reportNonexistentProperty(propNode, containingType) { var errorInfo; var relatedInfo; - if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { + if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -46185,7 +48289,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46237,7 +48341,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -46254,16 +48358,16 @@ var ts; } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: - return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 146 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 148 /* QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 181 /* ImportType */: + case 183 /* ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -46290,20 +48394,20 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * 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 === 236 /* VariableDeclarationList */) { + if (initializer.kind === 238 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 71 /* Identifier */) { + else if (initializer.kind === 72 /* Identifier */) { return getResolvedSymbol(initializer); } return undefined; @@ -46320,13 +48424,13 @@ var ts; */ function isForInVariableForNumericPropertyNames(expr) { var e = ts.skipParentheses(expr); - if (e.kind === 71 /* Identifier */) { + if (e.kind === 72 /* Identifier */) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3 /* Variable */) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 224 /* ForInStatement */ && + if (node.kind === 226 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -46344,7 +48448,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 190 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 192 /* 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); @@ -46356,15 +48460,15 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) { error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46375,7 +48479,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 3072 /* ESSymbolLike */) === 0) { + if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -46402,8 +48506,7 @@ var ts; return true; } function callLikeExpressionMayHaveTypeArguments(node) { - // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) - return ts.isCallOrNewExpression(node); + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); } function resolveUntypedCall(node) { if (callLikeExpressionMayHaveTypeArguments(node)) { @@ -46411,10 +48514,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 191 /* TaggedTemplateExpression */) { + if (node.kind === 193 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 150 /* Decorator */) { + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -46441,8 +48547,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -46478,25 +48584,23 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 206 /* SpreadElement */ || arg.kind === 213 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call + var argCount; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". - return true; - } - if (node.kind === 191 /* TaggedTemplateExpression */) { - // 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 + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193 /* TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 204 /* TemplateExpression */) { + if (node.template.kind === 206 /* 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 lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -46507,35 +48611,53 @@ var ts; // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. var templateLiteral = node.template; - ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */); + ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + else if (node.kind === 152 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 190 /* NewExpression */); + ts.Debug.assert(node.kind === 192 /* NewExpression */); return getMinArgumentCount(signature) === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. - if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { return false; } // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = argCount >= getMinArgumentCount(signature); - return callIsIncomplete || hasEnoughArguments; + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; } function hasCorrectTypeArgumentArity(signature, typeArguments) { // If the user supplied type arguments, but the number of type arguments does not match @@ -46547,7 +48669,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -46558,7 +48680,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46567,16 +48689,11 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, node, context) { - // Skip context sensitive pass - var skipContextParamType = getTypeAtPosition(signature, 0); - var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); - inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); - // Standard pass - var paramType = getTypeAtPosition(signature, 0); - var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } @@ -46592,11 +48709,14 @@ var ts; inference.inferredType = undefined; } } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (node.kind !== 150 /* Decorator */) { + if (node.kind !== 152 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -46625,71 +48745,50 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; 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 !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. - return arg.kind === 213 /* SyntheticExpression */ ? + return arg.kind === 215 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; - var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 32764 /* Primitive */ | 1048576 /* Index */); + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */); var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46698,27 +48797,40 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2 /* Mixed */; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. * @param node a JSX opening-like element we are trying to figure its call signature @@ -46726,37 +48838,20 @@ var ts; * @param relation a relationship to check parameter and argument type * @param excludeArgument */ - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: - // 1. callIsIncomplete - // 2. attributes property has same number of properties as the parameter object type. - // We can figure that out by resolving attributes property and check number of properties in the resolved type - // If the call has correct arity, we will then check if the argument type and parameter type is assignable - var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete - if (callIsIncomplete) { - return true; - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, // can be specified by users through attributes property. - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 190 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -46769,346 +48864,142 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; 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 !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); - if (callee.kind === 187 /* PropertyAccessExpression */ || callee.kind === 188 /* ElementAccessExpression */) { + if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) { return callee.expression; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { - if (node.kind === 191 /* TaggedTemplateExpression */) { + if (node.kind === 193 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 - if (template.kind === 204 /* TemplateExpression */) { + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 152 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* 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); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* 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. + var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 1; + case 154 /* PropertyDeclaration */: + return 2; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 151 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47117,15 +49008,19 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; var minCount = getMinArgumentCount(sig); var maxCount = getParameterCount(sig); if (minCount < argCount && minCount > belowArgCount) belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47136,22 +49031,31 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -47159,14 +49063,15 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { - var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 150 /* Decorator */; + var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 152 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; var typeArguments; if (!isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -47174,40 +49079,26 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47235,7 +49126,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -47259,32 +49150,33 @@ var ts; // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, // skip the checkApplicableSignature check. - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". - return candidateForArgumentError; + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); - } - else if (candidateForArgumentArityError) { - diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); - } - else if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); - } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47304,60 +49196,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47377,7 +49289,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47388,7 +49300,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47427,17 +49339,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47456,7 +49378,7 @@ var ts; return maxParamsIndex; } function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { @@ -47490,11 +49412,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47506,16 +49428,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47528,8 +49457,8 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -47588,11 +49517,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47605,7 +49536,7 @@ var ts; return false; } var firstBase = baseTypes[0]; - if (firstBase.flags & 524288 /* Intersection */) { + if (firstBase.flags & 2097152 /* Intersection */) { var types = firstBase.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); var i = 0; @@ -47662,10 +49593,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47689,8 +49621,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47704,16 +49636,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 149 /* Parameter */: + case 151 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -47729,8 +49661,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47749,6 +49681,46 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node); + var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.type = result; + return createSignature(declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } /** * Sometimes, we have a decorator that could accept zero arguments, * but is receiving too many arguments as part of the decorator invocation. @@ -47758,52 +49730,22 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } - /** - * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. - * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName - * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) - * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. - * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function - * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); - if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); - } - return undefined; - } function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); - case 150 /* Decorator */: + case 152 /* Decorator */: return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: - // This code-path is called by language service - var exprTypes = checkExpression(node.tagName); - return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); - if (sfcResult && sfcResult !== unknownSignature) { - return sfcResult; - } - var sigs = getInstantiatedJsxSignatures(node, exprType); - if (candidatesOutArray && ts.length(sigs)) { - candidatesOutArray.push.apply(candidatesOutArray, sigs); - } - return ts.length(sigs) ? sigs[0] : unknownSignature; - }) || unknownSignature; + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -47837,34 +49779,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { - if (type.flags & 131072 /* Object */) { + function isJSConstructorType(type) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47877,22 +49823,19 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } var parent = node.parent; - while (parent && parent.kind === 187 /* PropertyAccessExpression */) { + while (parent && parent.kind === 189 /* PropertyAccessExpression */) { parent = parent.parent; } - if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) { var right = ts.getInitializerOfBinaryExpression(parent); return ts.isObjectLiteralExpression(right) && right; } @@ -47918,15 +49861,15 @@ var ts; if (!checkGrammarTypeArguments(node, node.typeArguments)) checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { return voidType; } - if (node.kind === 190 /* NewExpression */) { + if (node.kind === 192 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 155 /* Constructor */ && - declaration.kind !== 159 /* ConstructSignature */ && - declaration.kind !== 164 /* ConstructorType */ && + declaration.kind !== 157 /* Constructor */ && + declaration.kind !== 161 /* ConstructSignature */ && + declaration.kind !== 166 /* 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 @@ -47934,10 +49877,10 @@ var ts; // Note:JS inferred classes might come from a variable declaration instead of a function declaration. // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. var funcSymbol = checkExpression(node.expression).symbol; - if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { + if (!funcSymbol && node.expression.kind === 72 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47948,18 +49891,18 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property // as a fresh unique symbol literal type. - if (returnType.flags & 3072 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47985,7 +49928,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48000,7 +49943,7 @@ var ts; for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 8192 /* Undefined */ || specifierType.flags & 16384 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal @@ -48044,7 +49987,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48053,9 +49996,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 237 /* FunctionDeclaration */ + ? 239 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 235 /* VariableDeclaration */ + ? 237 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -48091,10 +50034,10 @@ var ts; } function checkMetaProperty(node) { checkGrammarMetaProperty(node); - if (node.keywordToken === 94 /* NewKeyword */) { + if (node.keywordToken === 95 /* NewKeyword */) { return checkNewTargetMetaProperty(node); } - if (node.keywordToken === 91 /* ImportKeyword */) { + if (node.keywordToken === 92 /* ImportKeyword */) { return checkImportMetaProperty(node); } return ts.Debug.assertNever(node.keywordToken); @@ -48105,7 +50048,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 155 /* Constructor */) { + else if (container.kind === 157 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -48169,14 +50112,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48185,17 +50125,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48219,15 +50149,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48235,6 +50156,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48287,7 +50219,7 @@ var ts; for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71 /* Identifier */) { + if (element.name.kind === 72 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } else { @@ -48301,7 +50233,7 @@ var ts; if (!links.type) { links.type = contextualType; var decl = parameter.valueDeclaration; - if (decl.name.kind !== 71 /* Identifier */) { + if (decl.name.kind !== 72 /* Identifier */) { // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType) { links.type = getTypeFromBindingPattern(decl.name); @@ -48320,6 +50252,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48341,7 +50283,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 216 /* Block */) { + if (func.body.kind !== 218 /* Block */) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any @@ -48437,10 +50379,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 199 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48455,7 +50448,7 @@ var ts; if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - if (ts.some(func.body.statements, function (statement) { return statement.kind === 230 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -48477,7 +50470,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -48490,7 +50483,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48498,11 +50491,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; - case 154 /* MethodDeclaration */: - return func.parent.kind === 186 /* ObjectLiteralExpression */; + case 156 /* MethodDeclaration */: + return func.parent.kind === 188 /* ObjectLiteralExpression */; default: return false; } @@ -48521,16 +50514,16 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 153 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 216 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 32768 /* Never */) { + if (returnType && returnType.flags & 131072 /* Never */) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -48559,7 +50552,8 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48569,14 +50563,16 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 194 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -48611,7 +50607,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48622,7 +50617,7 @@ var ts; getAwaitedType(type) || errorType : type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function @@ -48638,7 +50633,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 216 /* Block */) { + if (node.body.kind === 218 /* Block */) { checkSourceElement(node.body); } else { @@ -48661,34 +50656,66 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAssignableToKind(type, 168 /* NumberLike */)) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { error(operand, diagnostic); return false; } return true; } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } 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 + // Object.defineProperty assignments with writable false or no setter // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || - symbol.flags & 8 /* EnumMember */); + symbol.flags & 8 /* EnumMember */ || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); } 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 === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) && - expr.expression.kind === 99 /* ThisKeyword */) { + (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) && + expr.expression.kind === 100 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 155 /* Constructor */)) { + if (!(func && func.kind === 157 /* Constructor */)) { return true; } // If func.parent is a class and symbol is a (readonly) property of that class, or @@ -48701,13 +50728,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) { + if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return !!declaration && declaration.kind === 249 /* NamespaceImport */; + return !!declaration && declaration.kind === 251 /* NamespaceImport */; } } } @@ -48716,7 +50743,7 @@ var ts; function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); - if (node.kind !== 71 /* Identifier */ && node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { + if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -48725,7 +50752,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -48762,37 +50789,52 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operand.kind === 8 /* NumericLiteral */) { - if (node.operator === 38 /* MinusToken */) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - else if (node.operator === 37 /* PlusToken */) { - return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); - } + switch (node.operand.kind) { + case 8 /* NumericLiteral */: + switch (node.operator) { + case 39 /* MinusToken */: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38 /* PlusToken */: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9 /* BigIntLiteral */: + if (node.operator === 39 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } } switch (node.operator) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 3072 /* ESSymbolLike */)) { + if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } - return numberType; - case 51 /* ExclamationToken */: + if (node.operator === 38 /* PlusToken */) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52 /* ExclamationToken */: checkTruthinessExpression(node.operand); - var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); - return facts === 1048576 /* Truthy */ ? falseType : - facts === 2097152 /* Falsy */ ? trueType : + var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : + facts === 8388608 /* Falsy */ ? trueType : booleanType; - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } - return numberType; + return getUnaryResultType(operandType); } return errorType; } @@ -48801,11 +50843,20 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number return numberType; } // Return true if type might be of the given kind. A union or intersection type might be of a given @@ -48814,10 +50865,10 @@ var ts; if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { return true; } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48829,21 +50880,22 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (3 /* AnyOrUnknown */ | 4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */)) { + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { return false; } - return !!(kind & 168 /* NumberLike */) && isTypeAssignableTo(source, numberType) || - !!(kind & 68 /* StringLike */) && isTypeAssignableTo(source, stringType) || - !!(kind & 272 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || - !!(kind & 4096 /* Void */) && isTypeAssignableTo(source, voidType) || - !!(kind & 32768 /* Never */) && isTypeAssignableTo(source, neverType) || - !!(kind & 16384 /* Null */) && isTypeAssignableTo(source, nullType) || - !!(kind & 8192 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || - !!(kind & 1024 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || - !!(kind & 16777216 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { - return source.flags & 262144 /* Union */ ? + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : isTypeAssignableToKind(source, kind, strict); } @@ -48863,7 +50915,7 @@ var ts; // 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 (!isTypeAny(leftType) && - allTypesAssignableToKind(leftType, 32764 /* Primitive */)) { + allTypesAssignableToKind(leftType, 131068 /* 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 @@ -48882,10 +50934,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 168 /* NumberLike */ | 3072 /* ESSymbolLike */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + if (!isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -48895,8 +50947,8 @@ var ts; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; @@ -48904,9 +50956,9 @@ var ts; /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { if (rightIsThis === void 0) { rightIsThis = false; } - if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { + if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -48915,13 +50967,13 @@ var ts; var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 275 /* SpreadAssignment */) { + else if (property.kind === 277 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } @@ -48973,11 +51025,11 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 208 /* OmittedExpression */) { - if (element.kind !== 206 /* SpreadElement */) { + if (element.kind !== 210 /* OmittedExpression */) { + if (element.kind !== 208 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48998,13 +51050,13 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 202 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49015,14 +51067,14 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 8192 /* Undefined */)) { - sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); } @@ -49031,21 +51083,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 202 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 186 /* ObjectLiteralExpression */) { + if (target.kind === 188 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 185 /* ArrayLiteralExpression */) { + if (target.kind === 187 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 275 /* SpreadAssignment */ ? + var error = target.parent.kind === 277 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { @@ -49064,72 +51116,73 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 191 /* TaggedTemplateExpression */: - case 204 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 193 /* TaggedTemplateExpression */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 140 /* UndefinedKeyword */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: - case 195 /* ArrowFunction */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 197 /* TypeOfExpression */: - case 211 /* NonNullExpression */: - case 259 /* JsxSelfClosingElement */: - case 258 /* JsxElement */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 141 /* UndefinedKeyword */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 199 /* TypeOfExpression */: + case 213 /* NonNullExpression */: + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: return true; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { - case 51 /* ExclamationToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: + case 52 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: return true; } return false; // Some forms listed here for clarity - case 198 /* VoidExpression */: // Explicit opt-out - case 192 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 210 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 200 /* VoidExpression */: // Explicit opt-out + case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */); + if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */); } var leftType; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { leftType = checkTruthinessExpression(left, checkMode); } else { @@ -49137,28 +51190,28 @@ var ts; } var rightType = checkExpression(right, checkMode); switch (operator) { - case 39 /* AsteriskToken */: - case 40 /* AsteriskAsteriskToken */: - case 61 /* AsteriskEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 42 /* PercentToken */: - case 64 /* PercentEqualsToken */: - case 38 /* MinusToken */: - case 60 /* MinusEqualsToken */: - case 45 /* LessThanLessThanToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: + case 40 /* AsteriskToken */: + case 41 /* AsteriskAsteriskToken */: + case 62 /* AsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 43 /* PercentToken */: + case 65 /* PercentEqualsToken */: + case 39 /* MinusToken */: + case 61 /* MinusEqualsToken */: + case 46 /* LessThanLessThanToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -49167,36 +51220,61 @@ var ts; 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 & 272 /* BooleanLike */) && - (rightType.flags & 272 /* BooleanLike */) && + if ((leftType.flags & 528 /* BooleanLike */) && + (rightType.flags & 528 /* BooleanLike */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; } else { // otherwise just check each operand separately and report errors as normal - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType_1 = numberType; } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) { + switch (operator) { + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; } - return numberType; - case 37 /* PlusToken */: - case 59 /* PlusEqualsToken */: + case 38 /* PlusToken */: + case 60 /* PlusEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 68 /* StringLike */) && !isTypeAssignableToKind(rightType, 68 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeAssignableToKind(leftType, 168 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 168 /* NumberLike */, /*strict*/ true)) { + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) { // 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 (isTypeAssignableToKind(leftType, 68 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 68 /* StringLike */, /*strict*/ true)) { + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -49213,26 +51291,27 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 59 /* PlusEqualsToken */) { + if (operator === 60 /* PlusEqualsToken */) { checkAssignmentOperator(resultType); } return resultType; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: if (checkForDisallowedESSymbolOperand(operator)) { leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { reportOperatorError(); } } return booleanType; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -49243,29 +51322,38 @@ var ts; reportOperatorError(); } return booleanType; - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return checkInstanceOfExpression(left, right, leftType, rightType); - case 92 /* InKeyword */: + case 93 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); - case 53 /* AmpersandAmpersandToken */: - return getTypeFacts(leftType) & 1048576 /* Truthy */ ? + case 54 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 4194304 /* Truthy */ ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; - case 54 /* BarBarToken */: - return getTypeFacts(leftType) & 2097152 /* Falsy */ ? + case 55 /* BarBarToken */: + return getTypeFacts(leftType) & 8388608 /* Falsy */ ? getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; - case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + case 59 /* EqualsToken */: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || + declKind !== 2 /* ModuleExports */ && + declKind !== 6 /* Prototype */ && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1 /* Class */)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } return leftType; } else { checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); } - case 26 /* CommaToken */: + case 27 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -49273,15 +51361,14 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { - var rightType_1 = checkExpression(right, checkMode); - for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2 /* ModuleExports */) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49291,12 +51378,12 @@ var ts; } } function isEvalNode(node) { - return node.kind === 71 /* Identifier */ && node.escapedText === "eval"; + return node.kind === 72 /* Identifier */ && node.escapedText === "eval"; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 3072 /* ESSymbolLike */) ? left : - maybeTypeOfKind(rightType, 3072 /* ESSymbolLike */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -49306,15 +51393,15 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - return 54 /* BarBarToken */; - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - return 35 /* ExclamationEqualsEqualsToken */; - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: - return 53 /* AmpersandAmpersandToken */; + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + return 55 /* BarBarToken */; + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + return 36 /* ExclamationEqualsEqualsToken */; + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + return 54 /* AmpersandAmpersandToken */; default: return undefined; } @@ -49334,8 +51421,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49344,7 +51431,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49361,11 +51448,11 @@ var ts; } function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { switch (operatorToken.kind) { - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); } return undefined; @@ -49443,14 +51530,14 @@ var ts; // A place where we actually *are* concerned with the expressions' types are // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { - if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) { error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49486,25 +51573,21 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 192 /* TypeAssertionExpression */ || node.kind === 210 /* AsExpression */; + return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */; } function checkDeclarationInitializer(declaration) { var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { - if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304 /* Nullable */) { + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49512,34 +51595,36 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 786432 /* UnionOrIntersection */) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { var types = contextualType.types; return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } - if (contextualType.flags & 14745600 /* InstantiableNonPrimitive */) { + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { // If the contextual type is a type variable constrained to a primitive type, consider // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || - maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || - maybeTypeOfKind(constraint, 1024 /* ESSymbol */) && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (64 /* StringLiteral */ | 1048576 /* Index */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || - contextualType.flags & 128 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || - contextualType.flags & 256 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 256 /* BooleanLiteral */) || - contextualType.flags & 2048 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */)); + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || + contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49547,7 +51632,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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -49558,7 +51643,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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -49586,15 +51671,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49608,9 +51697,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49621,13 +51714,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; - if (node.kind === 146 /* QualifiedName */) { + if (node.kind === 148 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49635,10 +51728,10 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 165 /* TypeQuery */ && node.parent.exprName === node)); + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === 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_or_type_query); } @@ -49646,102 +51739,105 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return checkIdentifier(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return checkThisExpression(node); - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return checkSuperExpression(node); - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: return nullWideningType; - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101 /* TrueKeyword */: + case 9 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102 /* TrueKeyword */: return trueType; - case 86 /* FalseKeyword */: + case 87 /* FalseKeyword */: return falseType; - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return checkTemplateExpression(node); - case 12 /* RegularExpressionLiteral */: + case 13 /* RegularExpressionLiteral */: return globalRegExpType; - case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); - case 186 /* ObjectLiteralExpression */: + case 187 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 189 /* CallExpression */: - if (node.expression.kind === 91 /* ImportKeyword */) { + case 191 /* CallExpression */: + if (node.expression.kind === 92 /* ImportKeyword */) { return checkImportCallExpression(node); } /* falls through */ - case 190 /* NewExpression */: + case 192 /* NewExpression */: return checkCallExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return checkClassExpression(node); - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return checkAssertion(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return checkNonNullAssertion(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return checkMetaProperty(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return checkDeleteExpression(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return checkVoidExpression(node); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return checkAwaitExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 208 /* OmittedExpression */: + case 210 /* OmittedExpression */: return undefinedWideningType; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return checkYieldExpression(node); - case 213 /* SyntheticExpression */: + case 215 /* SyntheticExpression */: return node.type; - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return checkJsxElement(node, checkMode); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 262 /* JsxFragment */: - return checkJsxFragment(node, checkMode); - case 266 /* JsxAttributes */: + case 264 /* JsxFragment */: + return checkJsxFragment(node); + case 268 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -49770,9 +51866,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49782,7 +51875,7 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 155 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -49793,16 +51886,16 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { + if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 195 /* ArrowFunction */) { + if (func.kind === 197 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -49851,13 +51944,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 195 /* ArrowFunction */: - case 158 /* CallSignature */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 163 /* FunctionType */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 197 /* ArrowFunction */: + case 160 /* CallSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 165 /* FunctionType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -49871,11 +51964,11 @@ var ts; continue; } var name = element.name; - if (name.kind === 71 /* Identifier */ && name.escapedText === predicateVariableName) { + if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 183 /* ArrayBindingPattern */ || name.kind === 182 /* ObjectBindingPattern */) { + else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -49884,13 +51977,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 160 /* IndexSignature */) { + if (node.kind === 162 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 163 /* FunctionType */ || node.kind === 237 /* FunctionDeclaration */ || node.kind === 164 /* ConstructorType */ || - node.kind === 158 /* CallSignature */ || node.kind === 155 /* Constructor */ || - node.kind === 159 /* ConstructSignature */) { + else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ || + node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ || + node.kind === 161 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -49920,10 +52013,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 158 /* CallSignature */: + case 160 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -49953,7 +52046,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -49970,7 +52063,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 155 /* Constructor */) { + if (member.kind === 157 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -49985,16 +52078,16 @@ var ts; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (name && memberName) { switch (member.kind) { - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: addName(names, name, memberName, 1 /* Getter */); break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: addName(names, name, memberName, 2 /* Setter */); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: addName(names, name, memberName, 3 /* Property */); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: addName(names, name, memberName, 4 /* Method */); break; } @@ -50057,15 +52150,15 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151 /* PropertySignature */) { + if (member.kind === 153 /* PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: memberName = name.text; break; - case 71 /* Identifier */: + case 72 /* Identifier */: memberName = ts.idText(name); break; default: @@ -50082,7 +52175,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 239 /* InterfaceDeclaration */) { + if (node.kind === 241 /* 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 @@ -50102,7 +52195,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -50110,7 +52203,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -50137,7 +52230,7 @@ var ts; checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 154 /* MethodDeclaration */ && node.body) { + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -50162,7 +52255,7 @@ var ts; return; } function isInstancePropertyWithInitializer(n) { - return n.kind === 152 /* PropertyDeclaration */ && + return n.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } @@ -50192,7 +52285,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -50217,7 +52310,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -50227,13 +52320,13 @@ 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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(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 === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); @@ -50251,7 +52344,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -50268,7 +52361,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50299,7 +52392,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50347,7 +52440,7 @@ var ts; var seenOptionalElement = false; for (var i = 0; i < elementTypes.length; i++) { var e = elementTypes[i]; - if (e.kind === 170 /* RestType */) { + if (e.kind === 172 /* RestType */) { if (i !== elementTypes.length - 1) { grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); break; @@ -50356,7 +52449,7 @@ var ts; error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); } } - else if (e.kind === 169 /* OptionalType */) { + else if (e.kind === 171 /* OptionalType */) { seenOptionalElement = true; } else if (seenOptionalElement) { @@ -50371,14 +52464,14 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 2097152 /* IndexedAccess */)) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { return type; } // Check if the index type is assignable to 'keyof T' for the object type. var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 188 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -50386,7 +52479,7 @@ var ts; } // Check if we're indexing with a numeric type and if either object or index types // is a generic type with a constraint that has a numeric index signature. - if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -50400,8 +52493,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50418,7 +52511,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 173 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -50435,9 +52528,9 @@ var ts; var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 239 /* InterfaceDeclaration */ && - n.parent.kind !== 238 /* ClassDeclaration */ && - n.parent.kind !== 207 /* ClassExpression */ && + if (n.parent.kind !== 241 /* InterfaceDeclaration */ && + n.parent.kind !== 240 /* ClassDeclaration */ && + n.parent.kind !== 209 /* ClassExpression */ && n.flags & 4194304 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -50528,7 +52621,7 @@ var ts; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */) && + var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) && ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -50567,7 +52660,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = node.flags & 4194304 /* Ambient */; - var inAmbientContextOrInterface = node.parent.kind === 239 /* InterfaceDeclaration */ || node.parent.kind === 166 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -50578,7 +52671,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 === 237 /* FunctionDeclaration */ || node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */ || node.kind === 155 /* Constructor */) { + if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -50630,8 +52723,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var signature = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -50640,6 +52733,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50697,32 +52797,25 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return 2 /* ExportType */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values if (!ts.isEntityNameExpression(d.expression)) { return 1 /* ExportValue */; @@ -50730,17 +52823,17 @@ var ts; d = d.expression; /* falls through */ // The below options all declare an Alias, which is allowed to merge with other values within the importing module - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 248 /* ImportClause */: - var result_3 = 0 /* None */; + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 237 /* FunctionDeclaration */: - case 251 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 239 /* FunctionDeclaration */: + case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); @@ -50787,7 +52880,7 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -50818,7 +52911,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -50966,10 +53059,10 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { - if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { @@ -50989,7 +53082,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51008,24 +53101,24 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 149 /* Parameter */: + case 151 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -51046,7 +53139,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51071,50 +53164,55 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 172 /* IntersectionType */: - case 171 /* UnionType */: - var commonEntityName = void 0; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175 /* ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 131 /* NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); - if (!individualEntityName) { - // Individual is something like string number - // So it would be serialized to either that type or object - // Safe to return here - return undefined; - } - if (commonEntityName) { - // Note this is in sync with the transformation that happens for type node. - // Keep this in sync with serializeUnionOrIntersectionType - // Verify if they refer to same entity and is identifier - // return undefined if they dont match because we would emit object - if (!ts.isIdentifier(commonEntityName) || - !ts.isIdentifier(individualEntityName) || - commonEntityName.escapedText !== individualEntityName.escapedText) { - return undefined; - } - } - else { - commonEntityName = individualEntityName; - } - } - return commonEntityName; - case 175 /* ParenthesizedType */: + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; } } } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } function getParameterTypeNodeForDecoratorCheck(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; @@ -51134,14 +53232,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 149 /* Parameter */) { + if (node.kind === 151 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -51150,23 +53248,23 @@ var ts; } } break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 149 /* Parameter */: + case 151 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -51219,16 +53317,22 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); } } } } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } function checkJSDocAugmentsTag(node) { var classLike = ts.getJSDocHost(node); if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { @@ -51251,9 +53355,9 @@ var ts; } function getIdentifierFromEntityNameExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return node.name; default: return undefined; @@ -51266,7 +53370,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 && node.name.kind === 147 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -51295,7 +53399,7 @@ var ts; } } } - var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); @@ -51304,8 +53408,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51315,7 +53419,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51324,7 +53428,7 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. - if (produceDiagnostics) { + if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) { var sourceFile = ts.getSourceFileOfNode(node); var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); if (!potentiallyUnusedIdentifiers) { @@ -51340,44 +53444,44 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 239 /* InterfaceDeclaration */: - checkUnusedTypeParameters(node, addDiagnostic); - break; - case 277 /* SourceFile */: - case 242 /* ModuleDeclaration */: - case 216 /* Block */: - case 244 /* CaseBlock */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 279 /* SourceFile */: + case 244 /* ModuleDeclaration */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - if (node.body) { + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 240 /* TypeAliasDeclaration */: - case 174 /* InferType */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; + case 176 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; default: ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); } @@ -51392,77 +53496,73 @@ var ts; return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 154 /* MethodDeclaration */: - case 152 /* PropertyDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - if (member.kind === 157 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { - // Already would have reported an error on the getter. - break; - } - var symbol = getSymbolOfNode(member); - if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. break; - case 155 /* Constructor */: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } - break; - case 160 /* IndexSignature */: - case 215 /* SemicolonClassElement */: - // Can't be private - break; - default: - ts.Debug.fail(); - } + } + break; + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) + if (ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174 /* InferType */) { - var typeParameter = node.typeParameter; - if (isTypeParameterUnused(typeParameter)) { - addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } } - } - else { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - var seenParentsWithEveryUnused = new ts.NodeSet(); - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var typeParameter = typeParameters_2[_i]; - if (!isTypeParameterUnused(typeParameter)) - continue; - var name = ts.idText(typeParameter.name); - var parent = typeParameter.parent; - if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { - if (seenParentsWithEveryUnused.tryAdd(parent)) { - var range = ts.isJSDocTemplateTag(parent) - // Whole @template tag - ? ts.rangeOfNode(parent) - // Include the `<>` in the error message - : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; - var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; - var arg0 = only ? name : undefined; - addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); - } - } - else { - addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); - } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } @@ -51533,7 +53633,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 @@ -51551,7 +53651,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 235 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 236 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -51572,7 +53672,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -51584,24 +53684,24 @@ var ts; } function bindingNameText(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.idText(name); - case 183 /* ArrayBindingPattern */: - case 182 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 248 /* ImportClause */ || node.kind === 251 /* ImportSpecifier */ || node.kind === 249 /* NamespaceImport */; + return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 248 /* ImportClause */ ? decl : decl.kind === 249 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 216 /* Block */) { + if (node.kind === 218 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -51631,12 +53731,12 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 151 /* PropertySignature */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 153 /* MethodSignature */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { + if (node.kind === 154 /* PropertyDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 156 /* MethodDeclaration */ || + node.kind === 155 /* MethodSignature */ || + node.kind === 158 /* GetAccessor */ || + node.kind === 159 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -51645,7 +53745,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 149 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -51655,7 +53755,7 @@ var ts; function checkIfThisIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { - var isDeclaration_1 = node.kind !== 71 /* Identifier */; + var isDeclaration_1 = node.kind !== 72 /* Identifier */; if (isDeclaration_1) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -51670,7 +53770,7 @@ var ts; function checkIfNewTargetIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { - var isDeclaration_2 = node.kind !== 71 /* Identifier */; + var isDeclaration_2 = node.kind !== 72 /* Identifier */; if (isDeclaration_2) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } @@ -51696,7 +53796,7 @@ var ts; } // 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 === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 279 /* 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)); } @@ -51711,7 +53811,7 @@ var ts; } // 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 === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -51746,7 +53846,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 235 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -51758,17 +53858,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 236 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 217 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 219 /* 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 === 216 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 243 /* ModuleBlock */ || - container.kind === 242 /* ModuleDeclaration */ || - container.kind === 277 /* SourceFile */); + (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 245 /* ModuleBlock */ || + container.kind === 244 /* ModuleDeclaration */ || + container.kind === 279 /* 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 @@ -51783,7 +53883,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 !== 149 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -51794,14 +53894,14 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 187 /* PropertyAccessExpression */) { + if (n.kind === 189 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } - else if (n.kind === 71 /* Identifier */) { + else if (n.kind === 72 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51813,8 +53913,8 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 149 /* Parameter */ || - symbol.valueDeclaration.kind === 184 /* BindingElement */) { + if (symbol.valueDeclaration.kind === 151 /* Parameter */ || + symbol.valueDeclaration.kind === 186 /* BindingElement */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -51828,7 +53928,7 @@ var ts; return ts.isFunctionLike(current.parent) || // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - (current.parent.kind === 152 /* PropertyDeclaration */ && + (current.parent.kind === 154 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)); })) { @@ -51861,18 +53961,18 @@ 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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 184 /* BindingElement */) { - if (node.parent.kind === 182 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + if (node.kind === 186 /* BindingElement */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 147 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -51883,29 +53983,29 @@ var ts; var nameText = ts.getTextOfPropertyName(name); if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { - checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property); } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 183 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 149 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) { var initializerType = checkExpressionCached(node.initializer); if (strictNullChecks && node.name.elements.length === 0) { checkNonNullType(initializerType, node); @@ -51924,15 +54024,20 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); checkParameterInitializer(node); } } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } } else { // Node is a secondary declaration, check that type is identical to primary declaration and check that @@ -51940,21 +54045,20 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */) { + if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -51963,14 +54067,14 @@ var ts; } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 152 /* PropertyDeclaration */ || nextDeclaration.kind === 151 /* PropertySignature */ + var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 149 /* Parameter */ && right.kind === 235 /* VariableDeclaration */) || - (left.kind === 235 /* VariableDeclaration */ && right.kind === 149 /* Parameter */)) { + if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) || + (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -52009,7 +54113,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 218 /* EmptyStatement */) { + if (node.thenStatement.kind === 220 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -52028,7 +54132,7 @@ var ts; } function checkTruthinessExpression(node, checkMode) { var type = checkExpression(node, checkMode); - if (type.flags & 4096 /* Void */) { + if (type.flags & 16384 /* Void */) { error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); } return type; @@ -52036,12 +54140,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -52075,14 +54179,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 === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side - if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* 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. @@ -52108,13 +54212,13 @@ var ts; function checkForInStatement(node) { // Grammar checking checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* 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); @@ -52128,7 +54232,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 === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -52141,7 +54245,7 @@ var ts; } // 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 (rightType === neverType || !isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -52196,16 +54300,16 @@ var ts; // This allows us to find other non-string element types from an array unioned with // a string. if (allowStringInput) { - if (arrayType.flags & 262144 /* Union */) { + if (arrayType.flags & 1048576 /* Union */) { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the result of filter is a new array. var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 68 /* StringLike */); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } } - else if (arrayType.flags & 68 /* StringLike */) { + else if (arrayType.flags & 132 /* StringLike */) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -52218,7 +54322,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType.flags & 32768 /* Never */) { + if (arrayType.flags & 131072 /* Never */) { return stringType; } } @@ -52249,7 +54353,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); if (hasStringConstituent && arrayElementType) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 68 /* StringLike */) { + if (arrayElementType.flags & 132 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], 2 /* Subtype */); @@ -52314,13 +54418,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52347,9 +54455,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52457,7 +54567,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 4096 /* Void */ | 3 /* AnyOrUnknown */); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { // Grammar checking @@ -52473,7 +54583,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); var functionFlags = ts.getFunctionFlags(func); var isGenerator = functionFlags & 1 /* Generator */; - if (strictNullChecks || node.expression || returnType.flags & 32768 /* Never */) { + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (isGenerator) { // AsyncGenerator function or Generator function // A generator does not need its return expressions checked against its return type. @@ -52482,12 +54592,12 @@ var ts; // for generators. return; } - else if (func.kind === 157 /* SetAccessor */) { + else if (func.kind === 159 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 155 /* Constructor */) { + else if (func.kind === 157 /* Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -52508,7 +54618,7 @@ var ts; } } } - else if (func.kind !== 155 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -52537,7 +54647,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 270 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -52549,7 +54659,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 269 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 271 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -52578,7 +54688,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 231 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -52685,8 +54795,8 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 202 /* BinaryExpression */ || - name.kind === 147 /* ComputedPropertyName */ || + (propDeclaration.kind === 204 /* BinaryExpression */ || + name.kind === 149 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -52715,6 +54825,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -52890,18 +55001,21 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 2162688 /* TypeVariable */)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52929,7 +55043,7 @@ var ts; } } else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -52944,7 +55058,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52963,7 +55077,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -52989,7 +55103,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 238 /* ClassDeclaration */ || d.kind === 239 /* InterfaceDeclaration */; + return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -53028,7 +55142,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 || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { - if (derivedClassDecl.kind === 207 /* ClassExpression */) { + if (derivedClassDecl.kind === 209 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -53078,8 +55192,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -53110,7 +55224,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 8192 /* Undefined */)) { + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -53120,16 +55234,18 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 152 /* PropertyDeclaration */ && + return node.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 8192 /* Undefined */); + return !(getFalsyFlags(flowType) & 32768 /* Undefined */); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -53142,7 +55258,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -53247,60 +55363,60 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { - case 37 /* PlusToken */: return value_2; - case 38 /* MinusToken */: return -value_2; - case 52 /* TildeToken */: return ~value_2; + case 38 /* PlusToken */: return value_2; + case 39 /* MinusToken */: return -value_2; + case 53 /* TildeToken */: return ~value_2; } } break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { switch (expr.operatorToken.kind) { - case 49 /* BarToken */: return left | right; - case 48 /* AmpersandToken */: return left & right; - case 46 /* GreaterThanGreaterThanToken */: return left >> right; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; - case 45 /* LessThanLessThanToken */: return left << right; - case 50 /* CaretToken */: return left ^ right; - case 39 /* AsteriskToken */: return left * right; - case 41 /* SlashToken */: return left / right; - case 37 /* PlusToken */: return left + right; - case 38 /* MinusToken */: return left - right; - case 42 /* PercentToken */: return left % right; - case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right); + case 50 /* BarToken */: return left | right; + case 49 /* AmpersandToken */: return left & right; + case 47 /* GreaterThanGreaterThanToken */: return left >> right; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 46 /* LessThanLessThanToken */: return left << right; + case 51 /* CaretToken */: return left ^ right; + case 40 /* AsteriskToken */: return left * right; + case 42 /* SlashToken */: return left / right; + case 38 /* PlusToken */: return left + right; + case 39 /* MinusToken */: return left - right; + case 43 /* PercentToken */: return left % right; + case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right); } } - else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 37 /* PlusToken */) { + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) { return left + right; } break; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return expr.text; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return evaluate(expr.expression); - case 71 /* Identifier */: + case 72 /* Identifier */: var identifier = expr; if (isInfinityOrNaNString(identifier.escapedText)) { return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 188 /* ElementAccessExpression */: - case 187 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 187 /* PropertyAccessExpression */) { + if (ex.kind === 189 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -53331,10 +55447,10 @@ var ts; } } function isConstantMemberAccess(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 187 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 188 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && - node.argumentExpression.kind === 9 /* StringLiteral */; + return node.kind === 72 /* Identifier */ || + node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10 /* StringLiteral */; } function checkEnumDeclaration(node) { if (!produceDiagnostics) { @@ -53371,7 +55487,7 @@ var ts; 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 !== 241 /* EnumDeclaration */) { + if (declaration.kind !== 243 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -53394,8 +55510,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { var declaration = declarations_8[_i]; - if ((declaration.kind === 238 /* ClassDeclaration */ || - (declaration.kind === 237 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 240 /* ClassDeclaration */ || + (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304 /* Ambient */)) { return declaration; } @@ -53432,7 +55548,7 @@ var ts; return; } if (!checkGrammarDecoratorsAndModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { + if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } @@ -53458,7 +55574,7 @@ 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, 238 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -53508,23 +55624,23 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* 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 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 184 /* BindingElement */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -53535,12 +55651,12 @@ var ts; break; } // falls through - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 237 /* FunctionDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -53553,7 +55669,7 @@ var ts; var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { // symbol should not originate in augmentation - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -53561,17 +55677,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: do { node = node.left; - } while (node.kind !== 71 /* Identifier */); + } while (node.kind !== 72 /* Identifier */); return node; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: do { node = node.expression; - } while (node.kind !== 71 /* Identifier */); + } while (node.kind !== 72 /* Identifier */); return node; } } @@ -53585,9 +55701,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 253 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -53616,19 +55732,19 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 255 /* ExportSpecifier */ ? + var message = node.kind === 257 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && node.kind === 257 /* ExportSpecifier */ + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53654,7 +55770,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -53678,17 +55794,17 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53714,10 +55830,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 243 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; - if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -53734,7 +55850,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 277 /* SourceFile */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 242 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -53742,13 +55858,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53763,8 +55879,8 @@ 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 === 277 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -53777,9 +55893,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 71 /* Identifier */) { + if (node.expression.kind === 72 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53811,7 +55927,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53852,14 +55968,14 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 237 /* FunctionDeclaration */ && declaration.kind !== 154 /* MethodDeclaration */) || + return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -53870,163 +55986,163 @@ var ts; // 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 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return checkTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return checkParameter(node); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return checkPropertyDeclaration(node); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return checkSignatureDeclaration(node); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return checkMethodDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return checkConstructorDeclaration(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return checkAccessorDeclaration(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return checkTypeReferenceNode(node); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return checkTypePredicate(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return checkTypeQuery(node); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return checkTypeLiteral(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return checkArrayType(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return checkTupleType(node); - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 175 /* ParenthesizedType */: - case 169 /* OptionalType */: - case 170 /* RestType */: + case 177 /* ParenthesizedType */: + case 171 /* OptionalType */: + case 172 /* RestType */: return checkSourceElement(node.type); - case 176 /* ThisType */: + case 178 /* ThisType */: return checkThisType(node); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return checkTypeOperator(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return checkConditionalType(node); - case 174 /* InferType */: + case 176 /* InferType */: return checkInferType(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return checkImportType(node); - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 297 /* JSDocParameterTag */: + case 299 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 287 /* JSDocFunctionType */: - checkSignatureDeclaration(node); + case 289 /* JSDocFunctionType */: + checkJSDocFunctionType(node); // falls through - case 285 /* JSDocNonNullableType */: - case 284 /* JSDocNullableType */: - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: - case 290 /* JSDocTypeLiteral */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + case 292 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 281 /* JSDocTypeExpression */: + case 283 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return checkMappedType(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return checkBlock(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return checkVariableStatement(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return checkExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return checkIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return checkDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return checkWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return checkForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return checkForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return checkForOfStatement(node); - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return checkReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return checkWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return checkSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return checkLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return checkThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return checkTryStatement(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return checkBindingElement(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return checkClassDeclaration(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return checkImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return checkExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return checkExportAssignment(node); - case 218 /* EmptyStatement */: - case 234 /* DebuggerStatement */: + case 220 /* EmptyStatement */: + case 236 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return checkMissingDeclaration(node); } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54097,31 +56213,38 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: checkClassExpressionDeferred(node); break; - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 258 /* JsxElement */: + case 260 /* JsxElement */: checkJsxElementDeferred(node); break; } @@ -54157,9 +56280,9 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54170,7 +56293,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54252,13 +56374,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 242 /* ModuleDeclaration */: + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + // falls through + case 244 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -54266,17 +56392,17 @@ var ts; // falls through // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* 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 (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -54318,17 +56444,17 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 71 /* Identifier */ && + return name.kind === 72 /* Identifier */ && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 148 /* TypeParameter */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: + case 150 /* TypeParameter */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: return true; default: return false; @@ -54336,16 +56462,16 @@ var ts; } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 146 /* QualifiedName */) { + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 162 /* TypeReference */; + return node.parent.kind === 164 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 187 /* PropertyAccessExpression */) { + while (node.parent.kind === 189 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 209 /* ExpressionWithTypeArguments */; + return node.parent.kind === 211 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -54358,12 +56484,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54373,13 +56499,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 146 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 246 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 252 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -54388,7 +56514,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54405,7 +56531,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 181 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -54414,8 +56540,8 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 187 /* PropertyAccessExpression */ && + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -54423,17 +56549,17 @@ var ts; return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } } else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 246 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } @@ -54451,11 +56577,11 @@ 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 === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) { + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54467,11 +56593,11 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 297 /* JSDocParameterTag */) { + if (entityName.parent.kind === 299 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54480,19 +56606,19 @@ var ts; // Missing entity name. return undefined; } - if (entityName.kind === 71 /* Identifier */) { + if (entityName.kind === 72 /* Identifier */) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { + else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 187 /* PropertyAccessExpression */) { + if (entityName.kind === 189 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -54502,20 +56628,17 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 265 /* JsxAttribute */) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 161 /* TypePredicate */) { + if (entityName.parent.kind === 163 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -54526,17 +56649,20 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(parent); + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(parent.parent); } - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (parent.kind === 184 /* BindingElement */ && - grandParent.kind === 182 /* ObjectBindingPattern */ && + else if (parent.kind === 186 /* BindingElement */ && + grandParent.kind === 184 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -54546,11 +56672,11 @@ var ts; } } switch (node.kind) { - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -54562,29 +56688,32 @@ var ts; return checkExpression(node).symbol; } // falls through - case 176 /* ThisType */: + case 178 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return checkExpression(node).symbol; - case 123 /* ConstructorKeyword */: + case 124 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 155 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } // falls through case 8 /* NumericLiteral */: // index access @@ -54594,19 +56723,22 @@ var ts; ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); - case 79 /* DefaultKeyword */: - case 89 /* FunctionKeyword */: - case 36 /* EqualsGreaterThanToken */: + case 80 /* DefaultKeyword */: + case 90 /* FunctionKeyword */: + case 37 /* EqualsGreaterThanToken */: + case 76 /* ClassKeyword */: return getSymbolOfNode(node.parent); - case 181 /* ImportType */: + case 183 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85 /* ExportKeyword */: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + if (location && location.kind === 276 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54614,30 +56746,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54678,28 +56805,28 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 186 /* ObjectLiteralExpression */ || expr.kind === 185 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 225 /* ForOfStatement */) { + if (expr.parent.kind === 227 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 202 /* BinaryExpression */) { + if (expr.parent.kind === 204 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 273 /* PropertyAssignment */) { + if (expr.parent.kind === 275 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 185 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; @@ -54732,13 +56859,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return getLiteralType(name.text); + case 149 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54778,7 +56924,7 @@ var ts; if (!ts.isGeneratedIdentifier(nodeIn)) { var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -54799,13 +56945,13 @@ var ts; // 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 & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54834,7 +56980,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 277 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -54854,7 +57000,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54867,11 +57013,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54887,9 +57033,9 @@ var ts; // * 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 isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -54930,18 +57076,18 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return node.expression - && node.expression.kind === 71 /* Identifier */ + && node.expression.kind === 72 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -54949,7 +57095,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 277 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -54963,7 +57109,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54976,7 +57122,8 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && + target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55021,6 +57168,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55030,15 +57196,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 276 /* EnumMember */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 278 /* EnumMember */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 276 /* EnumMember */) { + if (node.kind === 278 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -55052,7 +57218,7 @@ var ts; return undefined; } function isFunctionType(type) { - return !!(type.flags & 131072 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeNameIn, location) { // ensure both `typeName` and `location` are parse tree nodes. @@ -55065,9 +57231,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55089,22 +57255,25 @@ var ts; else if (type.flags & 3 /* AnyOrUnknown */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 4096 /* Void */ | 24576 /* Nullable */ | 32768 /* Never */)) { + else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeAssignableToKind(type, 272 /* BooleanLike */)) { + else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeAssignableToKind(type, 168 /* NumberLike */)) { + else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 68 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 3072 /* ESSymbolLike */)) { + else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -55120,14 +57289,14 @@ var ts; function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; - if (type.flags & 2048 /* UniqueESSymbol */ && + if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } @@ -55139,7 +57308,7 @@ var ts; function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); @@ -55147,7 +57316,7 @@ var ts; function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } var type = getWidenedType(getRegularTypeOfExpression(expr)); return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); @@ -55169,7 +57338,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55184,18 +57353,19 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } - function createLiteralConstValue(node) { + function createLiteralConstValue(node, tracker) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node, tracker); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55238,6 +57408,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55266,12 +57438,12 @@ var ts; getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 157 /* SetAccessor */ ? 156 /* GetAccessor */ : 157 /* SetAccessor */; + var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 157 /* SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 156 /* GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -55279,10 +57451,15 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { - return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; + return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -55293,9 +57470,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55345,7 +57522,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 277 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -55360,12 +57537,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 242 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 277 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -55384,6 +57561,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55428,6 +57608,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55455,31 +57637,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55491,7 +57672,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55539,14 +57720,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 154 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 156 /* 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 === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */) { + else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* 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); @@ -55563,23 +57744,23 @@ var ts; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 132 /* ReadonlyKeyword */) { - if (node.kind === 151 /* PropertySignature */ || node.kind === 153 /* MethodSignature */) { + if (modifier.kind !== 133 /* ReadonlyKeyword */) { + if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 160 /* IndexSignature */) { + if (node.kind === 162 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 76 /* ConstKeyword */: - if (node.kind !== 241 /* EnumDeclaration */) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); + case 77 /* ConstKeyword */: + if (node.kind !== 243 /* EnumDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */)); } break; - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: + case 115 /* PublicKeyword */: + case 114 /* ProtectedKeyword */: + case 113 /* PrivateKeyword */: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); @@ -55593,11 +57774,11 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { - if (modifier.kind === 112 /* PrivateKeyword */) { + if (modifier.kind === 113 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -55606,7 +57787,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -55616,10 +57797,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -55628,18 +57809,18 @@ var ts; flags |= 32 /* Static */; lastStatic = modifier; break; - case 132 /* ReadonlyKeyword */: + case 133 /* ReadonlyKeyword */: if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */ && node.kind !== 160 /* IndexSignature */ && node.kind !== 149 /* Parameter */) { + else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; lastReadonly = modifier; break; - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: if (flags & 1 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -55652,52 +57833,52 @@ 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 === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; - case 79 /* DefaultKeyword */: - var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + case 80 /* DefaultKeyword */: + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; break; - case 124 /* DeclareKeyword */: + case 125 /* DeclareKeyword */: if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 243 /* ModuleBlock */) { + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; lastDeclare = modifier; break; - case 117 /* AbstractKeyword */: + case 118 /* AbstractKeyword */: if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 238 /* ClassDeclaration */) { - if (node.kind !== 154 /* MethodDeclaration */ && - node.kind !== 152 /* PropertyDeclaration */ && - node.kind !== 156 /* GetAccessor */ && - node.kind !== 157 /* SetAccessor */) { + if (node.kind !== 240 /* ClassDeclaration */) { + if (node.kind !== 156 /* MethodDeclaration */ && + node.kind !== 154 /* PropertyDeclaration */ && + node.kind !== 158 /* GetAccessor */ && + node.kind !== 159 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 238 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -55709,14 +57890,14 @@ var ts; } flags |= 128 /* Abstract */; break; - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -55724,7 +57905,7 @@ var ts; break; } } - if (node.kind === 155 /* Constructor */) { + if (node.kind === 157 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -55739,13 +57920,13 @@ var ts; } return false; } - else if ((node.kind === 247 /* ImportDeclaration */ || node.kind === 246 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -55766,38 +57947,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 242 /* ModuleDeclaration */: - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 149 /* Parameter */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 244 /* ModuleDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 151 /* Parameter */: return false; default: - if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return false; } switch (node.kind) { - case 237 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 238 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 239 /* InterfaceDeclaration */: - case 217 /* VariableStatement */: - case 240 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */); + case 240 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */); + case 241 /* InterfaceDeclaration */: + case 219 /* VariableStatement */: + case 242 /* TypeAliasDeclaration */: return true; - case 241 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); + case 243 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */); default: ts.Debug.fail(); return false; @@ -55809,10 +57990,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -55865,11 +58046,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -55909,12 +58111,12 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 137 /* StringKeyword */ && parameter.type.kind !== 134 /* NumberKeyword */) { + if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) { var type = getTypeFromTypeNode(parameter.type); if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); } - if (type.flags & 262144 /* Union */ && allTypesAssignableToKind(type, 64 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); @@ -55945,7 +58147,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 208 /* OmittedExpression */) { + if (arg.kind === 210 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -55975,7 +58177,7 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (heritageClause.token === 86 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -55988,7 +58190,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -56004,14 +58206,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (heritageClause.token === 86 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } // Grammar checking heritageClause inside class declaration @@ -56022,20 +58224,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 147 /* ComputedPropertyName */) { + if (node.kind !== 149 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 202 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 237 /* FunctionDeclaration */ || - node.kind === 194 /* FunctionExpression */ || - node.kind === 154 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 156 /* MethodDeclaration */); if (node.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -56047,6 +58249,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56058,15 +58263,15 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 /* SpreadAssignment */) { + if (prop.kind === 277 /* SpreadAssignment */) { continue; } var name = prop.name; - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 274 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 276 /* 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); @@ -56075,7 +58280,7 @@ var ts; if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 154 /* MethodDeclaration */) { + if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -56090,21 +58295,23 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 275 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { checkGrammarNumericLiteral(name); } // falls through - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: currentKind = 1 /* Property */; break; - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: currentKind = 2 /* GetAccessor */; break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: currentKind = 4 /* SetAccessor */; break; default: @@ -56141,7 +58348,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 267 /* JsxSpreadAttribute */) { + if (attr.kind === 269 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -56151,7 +58358,7 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 268 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -56160,12 +58367,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 225 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 236 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -56180,20 +58387,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* 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 === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* 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); @@ -56220,11 +58427,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 156 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 157 /* SetAccessor */) { + else if (kind === 159 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -56248,23 +58455,23 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } function checkGrammarTypeOperatorNode(node) { - if (node.operator === 141 /* UniqueKeyword */) { - if (node.type.kind !== 138 /* SymbolKeyword */) { - return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(138 /* SymbolKeyword */)); + if (node.operator === 142 /* UniqueKeyword */) { + if (node.type.kind !== 139 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */)); } var parent = ts.walkUpParenthesizedTypes(node.parent); switch (parent.kind) { - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: var decl = parent; - if (decl.name.kind !== 71 /* Identifier */) { + if (decl.name.kind !== 72 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); } if (!ts.isVariableDeclarationInVariableStatement(decl)) { @@ -56274,13 +58481,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: if (!ts.hasModifier(parent, 32 /* Static */) || !ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: if (!ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -56299,15 +58506,18 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 154 /* MethodDeclaration */) { - if (node.parent.kind === 186 /* ObjectLiteralExpression */) { + if (node.kind === 156 /* MethodDeclaration */) { + if (node.parent.kind === 188 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 120 /* AsyncKeyword */)) { + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56325,14 +58535,14 @@ var ts; if (node.flags & 4194304 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 154 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 156 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 239 /* InterfaceDeclaration */) { + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 166 /* TypeLiteral */) { + else if (node.parent.kind === 168 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -56343,11 +58553,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 226 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 228 /* 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); @@ -56355,8 +58565,8 @@ var ts; return false; } break; - case 230 /* SwitchStatement */: - if (node.kind === 227 /* BreakStatement */ && !node.label) { + case 232 /* SwitchStatement */: + if (node.kind === 229 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -56371,13 +58581,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 227 /* BreakStatement */ + var message = node.kind === 229 /* 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 === 227 /* BreakStatement */ + var message = node.kind === 229 /* 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); @@ -56400,30 +58610,45 @@ var ts; } } function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 /* BigIntLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 9 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { + if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56434,7 +58659,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 217 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && @@ -56451,7 +58676,7 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkESModuleMarker(name) { - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } @@ -56468,8 +58693,8 @@ var ts; return false; } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71 /* Identifier */) { - if (name.originalKeywordKind === 110 /* LetKeyword */) { + if (name.kind === 72 /* Identifier */) { + if (name.originalKeywordKind === 111 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -56496,15 +58721,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return false; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -56522,12 +58747,12 @@ var ts; function checkGrammarMetaProperty(node) { var escapedText = node.name.escapedText; switch (node.keywordToken) { - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: if (escapedText !== "target") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); } break; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: if (escapedText !== "meta") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); } @@ -56563,10 +58788,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56581,7 +58807,7 @@ var ts; return true; } } - else if (node.parent.kind === 239 /* InterfaceDeclaration */) { + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -56589,7 +58815,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 166 /* TypeLiteral */) { + else if (node.parent.kind === 168 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -56597,8 +58823,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -56618,13 +58844,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 239 /* InterfaceDeclaration */ || - node.kind === 240 /* TypeAliasDeclaration */ || - node.kind === 247 /* ImportDeclaration */ || - node.kind === 246 /* ImportEqualsDeclaration */ || - node.kind === 253 /* ExportDeclaration */ || - node.kind === 252 /* ExportAssignment */ || - node.kind === 245 /* NamespaceExportDeclaration */ || + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 242 /* TypeAliasDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 255 /* ExportDeclaration */ || + node.kind === 254 /* ExportAssignment */ || + node.kind === 247 /* NamespaceExportDeclaration */ || ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -56633,7 +58859,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 === 217 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -56660,7 +58886,7 @@ var ts; // 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 === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -56682,20 +58908,32 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 180 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 276 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */; + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */; var literal = (withMinus ? "-" : "") + "0o" + node.text; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } return false; } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6 /* ESNext */) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { @@ -56740,8 +58978,8 @@ var ts; /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); @@ -56749,14 +58987,14 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 248 /* ImportClause */: // For default import - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: // For rename import `x as y` + case 250 /* ImportClause */: // For default import + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: // For rename import `x as y` return true; - case 71 /* Identifier */: + case 72 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 251 /* ImportSpecifier */; + return decl.parent.kind === 253 /* ImportSpecifier */; default: return false; } @@ -56776,7 +59014,7 @@ var ts; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); function typeIsLiteralType(type) { - return !!(type.flags & 448 /* Literal */); + return !!(type.flags & 2944 /* Literal */); } })(ts || (ts = {})); var ts; @@ -56840,6 +59078,9 @@ var ts; if (typeof value === "number") { return createNumericLiteral(value + ""); } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } @@ -56859,14 +59100,20 @@ var ts; return node; } ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9 /* BigIntLiteral */); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; function createStringLiteral(text) { - var node = createSynthesizedNode(9 /* StringLiteral */); + var node = createSynthesizedNode(10 /* StringLiteral */); node.text = text; return node; } ts.createStringLiteral = createStringLiteral; function createRegularExpressionLiteral(text) { - var node = createSynthesizedNode(12 /* RegularExpressionLiteral */); + var node = createSynthesizedNode(13 /* RegularExpressionLiteral */); node.text = text; return node; } @@ -56877,7 +59124,7 @@ var ts; return node; } function createIdentifier(text, typeArguments) { - var node = createSynthesizedNode(71 /* Identifier */); + var node = createSynthesizedNode(72 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateFlags = 0 /* None */; @@ -56958,23 +59205,23 @@ var ts; ts.createToken = createToken; // Reserved words function createSuper() { - return createSynthesizedNode(97 /* SuperKeyword */); + return createSynthesizedNode(98 /* SuperKeyword */); } ts.createSuper = createSuper; function createThis() { - return createSynthesizedNode(99 /* ThisKeyword */); + return createSynthesizedNode(100 /* ThisKeyword */); } ts.createThis = createThis; function createNull() { - return createSynthesizedNode(95 /* NullKeyword */); + return createSynthesizedNode(96 /* NullKeyword */); } ts.createNull = createNull; function createTrue() { - return createSynthesizedNode(101 /* TrueKeyword */); + return createSynthesizedNode(102 /* TrueKeyword */); } ts.createTrue = createTrue; function createFalse() { - return createSynthesizedNode(86 /* FalseKeyword */); + return createSynthesizedNode(87 /* FalseKeyword */); } ts.createFalse = createFalse; // Modifiers @@ -56985,44 +59232,44 @@ var ts; function createModifiersFromModifierFlags(flags) { var result = []; if (flags & 1 /* Export */) { - result.push(createModifier(84 /* ExportKeyword */)); + result.push(createModifier(85 /* ExportKeyword */)); } if (flags & 2 /* Ambient */) { - result.push(createModifier(124 /* DeclareKeyword */)); + result.push(createModifier(125 /* DeclareKeyword */)); } if (flags & 512 /* Default */) { - result.push(createModifier(79 /* DefaultKeyword */)); + result.push(createModifier(80 /* DefaultKeyword */)); } if (flags & 2048 /* Const */) { - result.push(createModifier(76 /* ConstKeyword */)); + result.push(createModifier(77 /* ConstKeyword */)); } if (flags & 4 /* Public */) { - result.push(createModifier(114 /* PublicKeyword */)); + result.push(createModifier(115 /* PublicKeyword */)); } if (flags & 8 /* Private */) { - result.push(createModifier(112 /* PrivateKeyword */)); + result.push(createModifier(113 /* PrivateKeyword */)); } if (flags & 16 /* Protected */) { - result.push(createModifier(113 /* ProtectedKeyword */)); + result.push(createModifier(114 /* ProtectedKeyword */)); } if (flags & 128 /* Abstract */) { - result.push(createModifier(117 /* AbstractKeyword */)); + result.push(createModifier(118 /* AbstractKeyword */)); } if (flags & 32 /* Static */) { - result.push(createModifier(115 /* StaticKeyword */)); + result.push(createModifier(116 /* StaticKeyword */)); } if (flags & 64 /* Readonly */) { - result.push(createModifier(132 /* ReadonlyKeyword */)); + result.push(createModifier(133 /* ReadonlyKeyword */)); } if (flags & 256 /* Async */) { - result.push(createModifier(120 /* AsyncKeyword */)); + result.push(createModifier(121 /* AsyncKeyword */)); } return result; } ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; // Names function createQualifiedName(left, right) { - var node = createSynthesizedNode(146 /* QualifiedName */); + var node = createSynthesizedNode(148 /* QualifiedName */); node.left = left; node.right = asName(right); return node; @@ -57041,7 +59288,7 @@ var ts; : expression; } function createComputedPropertyName(expression) { - var node = createSynthesizedNode(147 /* ComputedPropertyName */); + var node = createSynthesizedNode(149 /* ComputedPropertyName */); node.expression = parenthesizeForComputedName(expression); return node; } @@ -57054,7 +59301,7 @@ var ts; ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(148 /* TypeParameter */); + var node = createSynthesizedNode(150 /* TypeParameter */); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -57070,7 +59317,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149 /* Parameter */); + var node = createSynthesizedNode(151 /* Parameter */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -57094,7 +59341,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(150 /* Decorator */); + var node = createSynthesizedNode(152 /* Decorator */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -57107,7 +59354,7 @@ var ts; ts.updateDecorator = updateDecorator; // Type Elements function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(151 /* PropertySignature */); + var node = createSynthesizedNode(153 /* PropertySignature */); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -57127,12 +59374,12 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createSynthesizedNode(152 /* PropertyDeclaration */); + var node = createSynthesizedNode(154 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); - node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined; - node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined; + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined; node.type = type; node.initializer = initializer; return node; @@ -57142,8 +59389,8 @@ var ts; return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name - || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined) - || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined) + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) @@ -57151,7 +59398,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(153 /* MethodSignature */, typeParameters, parameters, type); + var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -57168,7 +59415,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(154 /* MethodDeclaration */); + var node = createSynthesizedNode(156 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -57196,7 +59443,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(155 /* Constructor */); + var node = createSynthesizedNode(157 /* Constructor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -57216,7 +59463,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(156 /* GetAccessor */); + var node = createSynthesizedNode(158 /* GetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57239,7 +59486,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(157 /* SetAccessor */); + var node = createSynthesizedNode(159 /* SetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57260,7 +59507,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(158 /* CallSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -57268,7 +59515,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(159 /* ConstructSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -57276,7 +59523,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(160 /* IndexSignature */); + var node = createSynthesizedNode(162 /* IndexSignature */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -57316,7 +59563,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(161 /* TypePredicate */); + var node = createSynthesizedNode(163 /* TypePredicate */); node.parameterName = asName(parameterName); node.type = type; return node; @@ -57330,7 +59577,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(162 /* TypeReference */); + var node = createSynthesizedNode(164 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -57344,7 +59591,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(163 /* FunctionType */, typeParameters, parameters, type); + return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -57352,7 +59599,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(164 /* ConstructorType */, typeParameters, parameters, type); + return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -57360,7 +59607,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(165 /* TypeQuery */); + var node = createSynthesizedNode(167 /* TypeQuery */); node.exprName = exprName; return node; } @@ -57372,7 +59619,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(166 /* TypeLiteral */); + var node = createSynthesizedNode(168 /* TypeLiteral */); node.members = createNodeArray(members); return node; } @@ -57384,7 +59631,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(167 /* ArrayType */); + var node = createSynthesizedNode(169 /* ArrayType */); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -57396,7 +59643,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(168 /* TupleType */); + var node = createSynthesizedNode(170 /* TupleType */); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -57408,7 +59655,7 @@ var ts; } ts.updateTupleTypeNode = updateTupleTypeNode; function createOptionalTypeNode(type) { - var node = createSynthesizedNode(169 /* OptionalType */); + var node = createSynthesizedNode(171 /* OptionalType */); node.type = ts.parenthesizeArrayTypeMember(type); return node; } @@ -57420,7 +59667,7 @@ var ts; } ts.updateOptionalTypeNode = updateOptionalTypeNode; function createRestTypeNode(type) { - var node = createSynthesizedNode(170 /* RestType */); + var node = createSynthesizedNode(172 /* RestType */); node.type = type; return node; } @@ -57432,7 +59679,7 @@ var ts; } ts.updateRestTypeNode = updateRestTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(171 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(173 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -57440,7 +59687,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(172 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -57459,7 +59706,7 @@ var ts; : node; } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createSynthesizedNode(173 /* ConditionalType */); + var node = createSynthesizedNode(175 /* ConditionalType */); node.checkType = ts.parenthesizeConditionalTypeMember(checkType); node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); node.trueType = trueType; @@ -57477,7 +59724,7 @@ var ts; } ts.updateConditionalTypeNode = updateConditionalTypeNode; function createInferTypeNode(typeParameter) { - var node = createSynthesizedNode(174 /* InferType */); + var node = createSynthesizedNode(176 /* InferType */); node.typeParameter = typeParameter; return node; } @@ -57489,7 +59736,7 @@ var ts; } ts.updateInferTypeNode = updateInferTypeNode; function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { - var node = createSynthesizedNode(181 /* ImportType */); + var node = createSynthesizedNode(183 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = asNodeArray(typeArguments); @@ -57507,7 +59754,7 @@ var ts; } ts.updateImportTypeNode = updateImportTypeNode; function createParenthesizedType(type) { - var node = createSynthesizedNode(175 /* ParenthesizedType */); + var node = createSynthesizedNode(177 /* ParenthesizedType */); node.type = type; return node; } @@ -57519,12 +59766,12 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(176 /* ThisType */); + return createSynthesizedNode(178 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; function createTypeOperatorNode(operatorOrType, type) { - var node = createSynthesizedNode(177 /* TypeOperator */); - node.operator = typeof operatorOrType === "number" ? operatorOrType : 128 /* KeyOfKeyword */; + var node = createSynthesizedNode(179 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */; node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } @@ -57534,7 +59781,7 @@ var ts; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(178 /* IndexedAccessType */); + var node = createSynthesizedNode(180 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -57548,7 +59795,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(179 /* MappedType */); + var node = createSynthesizedNode(181 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -57566,7 +59813,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(180 /* LiteralType */); + var node = createSynthesizedNode(182 /* LiteralType */); node.literal = literal; return node; } @@ -57579,7 +59826,7 @@ var ts; ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(182 /* ObjectBindingPattern */); + var node = createSynthesizedNode(184 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -57591,7 +59838,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(183 /* ArrayBindingPattern */); + var node = createSynthesizedNode(185 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -57603,7 +59850,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(184 /* BindingElement */); + var node = createSynthesizedNode(186 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -57622,7 +59869,7 @@ var ts; ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(185 /* ArrayLiteralExpression */); + var node = createSynthesizedNode(187 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -57636,7 +59883,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(186 /* ObjectLiteralExpression */); + var node = createSynthesizedNode(188 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -57650,7 +59897,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(187 /* PropertyAccessExpression */); + var node = createSynthesizedNode(189 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); @@ -57667,7 +59914,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(188 /* ElementAccessExpression */); + var node = createSynthesizedNode(190 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -57681,7 +59928,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(189 /* CallExpression */); + var node = createSynthesizedNode(191 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -57697,7 +59944,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(190 /* NewExpression */); + var node = createSynthesizedNode(192 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -57713,7 +59960,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { - var node = createSynthesizedNode(191 /* TaggedTemplateExpression */); + var node = createSynthesizedNode(193 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); if (template) { node.typeArguments = asNodeArray(typeArgumentsOrTemplate); @@ -57736,7 +59983,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(192 /* TypeAssertionExpression */); + var node = createSynthesizedNode(194 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -57750,7 +59997,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(193 /* ParenthesizedExpression */); + var node = createSynthesizedNode(195 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -57762,7 +60009,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(194 /* FunctionExpression */); + var node = createSynthesizedNode(196 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -57786,12 +60033,12 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(195 /* ArrowFunction */); + var node = createSynthesizedNode(197 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(36 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */); node.body = ts.parenthesizeConciseBody(body); return node; } @@ -57808,7 +60055,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(196 /* DeleteExpression */); + var node = createSynthesizedNode(198 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57820,7 +60067,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(197 /* TypeOfExpression */); + var node = createSynthesizedNode(199 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57832,7 +60079,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(198 /* VoidExpression */); + var node = createSynthesizedNode(200 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57844,7 +60091,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(199 /* AwaitExpression */); + var node = createSynthesizedNode(201 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57856,7 +60103,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(200 /* PrefixUnaryExpression */); + var node = createSynthesizedNode(202 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -57869,7 +60116,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(201 /* PostfixUnaryExpression */); + var node = createSynthesizedNode(203 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -57882,7 +60129,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(202 /* BinaryExpression */); + var node = createSynthesizedNode(204 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -57899,11 +60146,11 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(203 /* ConditionalExpression */); + var node = createSynthesizedNode(205 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); - node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); - node.colonToken = whenFalse ? colonToken : createToken(56 /* ColonToken */); + node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */); node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); return node; } @@ -57919,7 +60166,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(204 /* TemplateExpression */); + var node = createSynthesizedNode(206 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -57933,33 +60180,33 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createTemplateHead(text) { - var node = createSynthesizedNode(14 /* TemplateHead */); + var node = createSynthesizedNode(15 /* TemplateHead */); node.text = text; return node; } ts.createTemplateHead = createTemplateHead; function createTemplateMiddle(text) { - var node = createSynthesizedNode(15 /* TemplateMiddle */); + var node = createSynthesizedNode(16 /* TemplateMiddle */); node.text = text; return node; } ts.createTemplateMiddle = createTemplateMiddle; function createTemplateTail(text) { - var node = createSynthesizedNode(16 /* TemplateTail */); + var node = createSynthesizedNode(17 /* TemplateTail */); node.text = text; return node; } ts.createTemplateTail = createTemplateTail; function createNoSubstitutionTemplateLiteral(text) { - var node = createSynthesizedNode(13 /* NoSubstitutionTemplateLiteral */); + var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */); node.text = text; return node; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(205 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + var node = createSynthesizedNode(207 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; } ts.createYield = createYield; @@ -57971,7 +60218,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(206 /* SpreadElement */); + var node = createSynthesizedNode(208 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -57983,7 +60230,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(207 /* ClassExpression */); + var node = createSynthesizedNode(209 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58004,11 +60251,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(208 /* OmittedExpression */); + return createSynthesizedNode(210 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(209 /* ExpressionWithTypeArguments */); + var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -58022,7 +60269,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(210 /* AsExpression */); + var node = createSynthesizedNode(212 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -58036,7 +60283,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(211 /* NonNullExpression */); + var node = createSynthesizedNode(213 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -58048,7 +60295,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(212 /* MetaProperty */); + var node = createSynthesizedNode(214 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -58062,7 +60309,7 @@ var ts; ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(214 /* TemplateSpan */); + var node = createSynthesizedNode(216 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -58076,12 +60323,12 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(215 /* SemicolonClassElement */); + return createSynthesizedNode(217 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(216 /* Block */); + var block = createSynthesizedNode(218 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -58095,7 +60342,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(217 /* VariableStatement */); + var node = createSynthesizedNode(219 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -58110,11 +60357,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(218 /* EmptyStatement */); + return createSynthesizedNode(220 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; function createExpressionStatement(expression) { - var node = createSynthesizedNode(219 /* ExpressionStatement */); + var node = createSynthesizedNode(221 /* ExpressionStatement */); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -58130,7 +60377,7 @@ var ts; /** @deprecated Use `updateExpressionStatement` instead. */ ts.updateStatement = updateExpressionStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(220 /* IfStatement */); + var node = createSynthesizedNode(222 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -58146,7 +60393,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(221 /* DoStatement */); + var node = createSynthesizedNode(223 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -58160,7 +60407,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(222 /* WhileStatement */); + var node = createSynthesizedNode(224 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -58174,7 +60421,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(223 /* ForStatement */); + var node = createSynthesizedNode(225 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -58192,7 +60439,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(224 /* ForInStatement */); + var node = createSynthesizedNode(226 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -58208,7 +60455,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(225 /* ForOfStatement */); + var node = createSynthesizedNode(227 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -58226,7 +60473,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(226 /* ContinueStatement */); + var node = createSynthesizedNode(228 /* ContinueStatement */); node.label = asName(label); return node; } @@ -58238,7 +60485,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(227 /* BreakStatement */); + var node = createSynthesizedNode(229 /* BreakStatement */); node.label = asName(label); return node; } @@ -58250,7 +60497,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(228 /* ReturnStatement */); + var node = createSynthesizedNode(230 /* ReturnStatement */); node.expression = expression; return node; } @@ -58262,7 +60509,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(229 /* WithStatement */); + var node = createSynthesizedNode(231 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -58276,7 +60523,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(230 /* SwitchStatement */); + var node = createSynthesizedNode(232 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -58290,7 +60537,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(231 /* LabeledStatement */); + var node = createSynthesizedNode(233 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -58304,7 +60551,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(232 /* ThrowStatement */); + var node = createSynthesizedNode(234 /* ThrowStatement */); node.expression = expression; return node; } @@ -58316,7 +60563,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(233 /* TryStatement */); + var node = createSynthesizedNode(235 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -58332,11 +60579,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(234 /* DebuggerStatement */); + return createSynthesizedNode(236 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(235 /* VariableDeclaration */); + var node = createSynthesizedNode(237 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -58353,7 +60600,7 @@ var ts; ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(236 /* VariableDeclarationList */); + var node = createSynthesizedNode(238 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; @@ -58366,7 +60613,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(237 /* FunctionDeclaration */); + var node = createSynthesizedNode(239 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -58392,7 +60639,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(238 /* ClassDeclaration */); + var node = createSynthesizedNode(240 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58414,7 +60661,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(239 /* InterfaceDeclaration */); + var node = createSynthesizedNode(241 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58436,7 +60683,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(240 /* TypeAliasDeclaration */); + var node = createSynthesizedNode(242 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58456,7 +60703,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(241 /* EnumDeclaration */); + var node = createSynthesizedNode(243 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58475,7 +60722,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(242 /* ModuleDeclaration */); + var node = createSynthesizedNode(244 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -58494,7 +60741,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(243 /* ModuleBlock */); + var node = createSynthesizedNode(245 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -58506,7 +60753,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(244 /* CaseBlock */); + var node = createSynthesizedNode(246 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -58518,7 +60765,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(245 /* NamespaceExportDeclaration */); + var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -58530,7 +60777,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(246 /* ImportEqualsDeclaration */); + var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58548,7 +60795,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(247 /* ImportDeclaration */); + var node = createSynthesizedNode(249 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -58566,7 +60813,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(248 /* ImportClause */); + var node = createSynthesizedNode(250 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -58580,7 +60827,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(249 /* NamespaceImport */); + var node = createSynthesizedNode(251 /* NamespaceImport */); node.name = name; return node; } @@ -58592,7 +60839,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(250 /* NamedImports */); + var node = createSynthesizedNode(252 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -58604,7 +60851,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(251 /* ImportSpecifier */); + var node = createSynthesizedNode(253 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -58618,11 +60865,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(252 /* ExportAssignment */); + var node = createSynthesizedNode(254 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -58635,7 +60882,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(253 /* ExportDeclaration */); + var node = createSynthesizedNode(255 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -58653,7 +60900,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(254 /* NamedExports */); + var node = createSynthesizedNode(256 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -58665,7 +60912,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(255 /* ExportSpecifier */); + var node = createSynthesizedNode(257 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -58680,7 +60927,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(257 /* ExternalModuleReference */); + var node = createSynthesizedNode(259 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -58691,9 +60938,57 @@ var ts; : node; } ts.updateExternalModuleReference = updateExternalModuleReference; + // JSDoc + /* @internal */ + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + /* @internal */ + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + /* @internal */ + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + /* @internal */ + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + /* @internal */ + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291 /* JSDocComment */); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + /* @internal */ + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(258 /* JsxElement */); + var node = createSynthesizedNode(260 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -58709,7 +61004,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); + var node = createSynthesizedNode(261 /* JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -58725,7 +61020,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(260 /* JsxOpeningElement */); + var node = createSynthesizedNode(262 /* JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -58741,7 +61036,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(261 /* JsxClosingElement */); + var node = createSynthesizedNode(263 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -58753,7 +61048,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxFragment(openingFragment, children, closingFragment) { - var node = createSynthesizedNode(262 /* JsxFragment */); + var node = createSynthesizedNode(264 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -58769,7 +61064,7 @@ var ts; } ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(265 /* JsxAttribute */); + var node = createSynthesizedNode(267 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -58783,7 +61078,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(266 /* JsxAttributes */); + var node = createSynthesizedNode(268 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -58795,7 +61090,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(267 /* JsxSpreadAttribute */); + var node = createSynthesizedNode(269 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -58807,7 +61102,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(268 /* JsxExpression */); + var node = createSynthesizedNode(270 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -58821,7 +61116,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(269 /* CaseClause */); + var node = createSynthesizedNode(271 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -58835,7 +61130,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(270 /* DefaultClause */); + var node = createSynthesizedNode(272 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -58847,7 +61142,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(271 /* HeritageClause */); + var node = createSynthesizedNode(273 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -58860,7 +61155,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(272 /* CatchClause */); + var node = createSynthesizedNode(274 /* CatchClause */); node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -58875,7 +61170,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(273 /* PropertyAssignment */); + var node = createSynthesizedNode(275 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = ts.parenthesizeExpressionForList(initializer); @@ -58890,7 +61185,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(274 /* ShorthandPropertyAssignment */); + var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -58904,7 +61199,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(275 /* SpreadAssignment */); + var node = createSynthesizedNode(277 /* SpreadAssignment */); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } @@ -58917,7 +61212,7 @@ var ts; ts.updateSpreadAssignment = updateSpreadAssignment; // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(276 /* EnumMember */); + var node = createSynthesizedNode(278 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -58938,7 +61233,7 @@ var ts; (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { - var updated = createSynthesizedNode(277 /* SourceFile */); + var updated = createSynthesizedNode(279 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -59022,7 +61317,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(305 /* NotEmittedStatement */); + var node = createSynthesizedNode(307 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -59034,7 +61329,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -59046,7 +61341,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(308 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -59061,7 +61356,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -59077,17 +61372,17 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 307 /* CommaListExpression */) { + if (node.kind === 309 /* CommaListExpression */) { return node.elements; } - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { return [node.left, node.right]; } } return node; } function createCommaList(elements) { - var node = createSynthesizedNode(307 /* CommaListExpression */); + var node = createSynthesizedNode(309 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -59100,14 +61395,14 @@ var ts; ts.updateCommaList = updateCommaList; function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = ts.createNode(278 /* Bundle */); + var node = ts.createNode(280 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; function createUnparsedSourceFile(text, mapPath, map) { - var node = ts.createNode(279 /* UnparsedSource */); + var node = ts.createNode(281 /* UnparsedSource */); node.text = text; node.sourceMapPath = mapPath; node.sourceMapText = map; @@ -59115,7 +61410,7 @@ var ts; } ts.createUnparsedSourceFile = createUnparsedSourceFile; function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { - var node = ts.createNode(280 /* InputFiles */); + var node = ts.createNode(282 /* InputFiles */); node.javascriptText = javascript; node.javascriptMapPath = javascriptMapPath; node.javascriptMapText = javascriptMapText; @@ -59157,47 +61452,47 @@ var ts; } ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { - return createBinary(left, 26 /* CommaToken */, right); + return createBinary(left, 27 /* CommaToken */, right); } ts.createComma = createComma; function createLessThan(left, right) { - return createBinary(left, 27 /* LessThanToken */, right); + return createBinary(left, 28 /* LessThanToken */, right); } ts.createLessThan = createLessThan; function createAssignment(left, right) { - return createBinary(left, 58 /* EqualsToken */, right); + return createBinary(left, 59 /* EqualsToken */, right); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 34 /* EqualsEqualsEqualsToken */, right); + return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 35 /* ExclamationEqualsEqualsToken */, right); + return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 37 /* PlusToken */, right); + return createBinary(left, 38 /* PlusToken */, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 38 /* MinusToken */, right); + return createBinary(left, 39 /* MinusToken */, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand) { - return createPostfix(operand, 43 /* PlusPlusToken */); + return createPostfix(operand, 44 /* PlusPlusToken */); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 53 /* AmpersandAmpersandToken */, right); + return createBinary(left, 54 /* AmpersandAmpersandToken */, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 54 /* BarBarToken */, right); + return createBinary(left, 55 /* BarBarToken */, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(51 /* ExclamationToken */, operand); + return createPrefix(52 /* ExclamationToken */, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { @@ -59258,7 +61553,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -59769,7 +62064,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 231 /* LabeledStatement */ + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -59781,19 +62076,20 @@ var ts; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = ts.skipParentheses(node); switch (target.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return cacheIdentifiers; - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: return false; - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -59808,7 +62104,7 @@ var ts; thisArg = ts.createThis(); target = callee; } - else if (callee.kind === 97 /* SuperKeyword */) { + else if (callee.kind === 98 /* SuperKeyword */) { thisArg = ts.createThis(); target = languageVersion < 2 /* ES2015 */ ? ts.setTextRange(ts.createIdentifier("_super"), callee) @@ -59820,7 +62116,7 @@ var ts; } else { switch (callee.kind) { - case 187 /* PropertyAccessExpression */: { + case 189 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -59833,7 +62129,7 @@ var ts; } break; } - case 188 /* ElementAccessExpression */: { + case 190 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -59890,14 +62186,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -59905,7 +62201,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_9 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -59916,7 +62212,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_9.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -59928,15 +62224,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_9.push(setter); + properties_8.push(setter); } - properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_9, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -60174,6 +62470,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60187,19 +62498,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -60220,7 +62519,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 193 /* ParenthesizedExpression */) { + if (skipped.kind === 195 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -60254,10 +62553,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -60269,7 +62568,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 205 /* YieldExpression */) { + && operand.kind === 207 /* YieldExpression */) { return false; } return true; @@ -60306,7 +62605,7 @@ var ts; // the same kind (recursively). // "a"+(1+2) => "a"+(1+2) // "a"+("b"+"c") => "a"+"b"+"c" - if (binaryOperator === 37 /* PlusToken */) { + if (binaryOperator === 38 /* PlusToken */) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -60341,10 +62640,10 @@ var ts; // // While addition is associative in mathematics, JavaScript's `+` is not // guaranteed to be associative as it is overloaded with string concatenation. - return binaryOperator === 39 /* AsteriskToken */ - || binaryOperator === 49 /* BarToken */ - || binaryOperator === 48 /* AmpersandToken */ - || binaryOperator === 50 /* CaretToken */; + return binaryOperator === 40 /* AsteriskToken */ + || binaryOperator === 50 /* BarToken */ + || binaryOperator === 49 /* AmpersandToken */ + || binaryOperator === 51 /* CaretToken */; } /** * This function determines whether an expression consists of a homogeneous set of @@ -60357,7 +62656,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -60372,7 +62671,7 @@ var ts; return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(203 /* ConditionalExpression */, 55 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { @@ -60407,8 +62706,8 @@ var ts; var needsParens = isCommaSequence(check); if (!needsParens) { switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: needsParens = true; } } @@ -60424,9 +62723,9 @@ var ts; function parenthesizeForNew(expression) { var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return ts.createParen(expression); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return !leftmostExpr.arguments ? ts.createParen(expression) : expression; @@ -60449,7 +62748,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 190 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -60487,7 +62786,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, 26 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -60498,29 +62797,29 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 194 /* FunctionExpression */ || kind === 195 /* ArrowFunction */) { + if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 186 /* ObjectLiteralExpression */ || leftmostExpressionKind === 194 /* FunctionExpression */) { + if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeConditionalTypeMember(member) { - return member.kind === 173 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; } ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return ts.createParenthesizedType(member); } return parenthesizeConditionalTypeMember(member); @@ -60528,9 +62827,9 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 165 /* TypeQuery */: - case 177 /* TypeOperator */: - case 174 /* InferType */: + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 176 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -60556,28 +62855,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: node = node.operand; continue; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: node = node.left; continue; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: node = node.condition; continue; - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: node = node.tag; continue; - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 210 /* AsExpression */: - case 188 /* ElementAccessExpression */: - case 187 /* PropertyAccessExpression */: - case 211 /* NonNullExpression */: - case 306 /* PartiallyEmittedExpression */: + case 212 /* AsExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 213 /* NonNullExpression */: + case 308 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -60585,15 +62884,15 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 186 /* ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) { return ts.setTextRange(ts.createParen(body), body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { - return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || - node.kind === 307 /* CommaListExpression */; + return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 309 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; @@ -60606,13 +62905,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 211 /* NonNullExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 213 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -60637,7 +62936,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 211 /* NonNullExpression */) { + while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) { node = node.expression; } return node; @@ -60645,11 +62944,11 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 193 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); - case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -60667,7 +62966,7 @@ var ts; * the containing expression is created/updated. */ function isIgnorableParen(node) { - return node.kind === 193 /* ParenthesizedExpression */ + return node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -60732,10 +63031,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 247 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 249 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 253 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -60751,7 +63050,7 @@ var ts; */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 - if (moduleName.kind === 9 /* StringLiteral */) { + if (moduleName.kind === 10 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) || ts.getSynthesizedClone(moduleName); @@ -60854,7 +63153,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -60866,11 +63165,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -60902,12 +63201,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 149 /* Parameter */: - case 184 /* BindingElement */: + case 151 /* Parameter */: + case 186 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 206 /* SpreadElement */: - case 275 /* SpreadAssignment */: + case 208 /* SpreadElement */: + case 277 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -60919,7 +63218,7 @@ var ts; */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 184 /* BindingElement */: + case 186 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -60931,7 +63230,7 @@ var ts; : propertyName; } break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -60943,7 +63242,7 @@ var ts; : propertyName; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -60958,7 +63257,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; - return kind === 9 /* StringLiteral */ + return kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */; } /** @@ -60966,13 +63265,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -61012,11 +63311,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 182 /* ObjectBindingPattern */: - case 186 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -61177,276 +63476,276 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */) || kind === 176 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) { return node; } switch (kind) { // Names - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 149 /* Parameter */: + case 151 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 150 /* Decorator */: + case 152 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); // Type elements - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 153 /* MethodSignature */: + case 155 /* MethodSignature */: return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 155 /* Constructor */: + case 157 /* Constructor */: return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 158 /* CallSignature */: + case 160 /* CallSignature */: return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 163 /* FunctionType */: + case 165 /* FunctionType */: return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 164 /* ConstructorType */: + case 166 /* ConstructorType */: return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); - case 168 /* TupleType */: + case 170 /* TupleType */: return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 170 /* RestType */: + case 172 /* RestType */: return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 171 /* UnionType */: + case 173 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); - case 174 /* InferType */: + case 176 /* InferType */: return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 181 /* ImportType */: + case 183 /* ImportType */: return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 179 /* MappedType */: + case 181 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); // Binding patterns - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); // Expression - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 210 /* AsExpression */: + case 212 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 216 /* Block */: + case 218 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 250 /* NamedImports */: + case 252 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 254 /* NamedExports */: + case 256 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 255 /* ExportSpecifier */: + case 257 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -61488,58 +63787,58 @@ var ts; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 161 /* TypePredicate */ && kind <= 180 /* LiteralType */)) { + if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 215 /* SemicolonClassElement */: - case 218 /* EmptyStatement */: - case 208 /* OmittedExpression */: - case 234 /* DebuggerStatement */: - case 305 /* NotEmittedStatement */: + case 217 /* SemicolonClassElement */: + case 220 /* EmptyStatement */: + case 210 /* OmittedExpression */: + case 236 /* DebuggerStatement */: + case 307 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 149 /* Parameter */: + case 151 /* Parameter */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 150 /* Decorator */: + case 152 /* Decorator */: result = reduceNode(node.expression, cbNode, result); break; // Type member - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61548,12 +63847,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 155 /* Constructor */: + case 157 /* Constructor */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61561,7 +63860,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61569,49 +63868,50 @@ var ts; result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 190 /* NewExpression */: + case 192 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNode(node.template, cbNode, result); break; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -61619,123 +63919,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 193 /* ParenthesizedExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 199 /* AwaitExpression */: - case 205 /* YieldExpression */: - case 206 /* SpreadElement */: - case 211 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 210 /* AsExpression */: + case 212 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; // Element - case 216 /* Block */: + case 218 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 221 /* DoStatement */: + case 223 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 222 /* WhileStatement */: - case 229 /* WithStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61744,7 +64044,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61752,139 +64052,140 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 250 /* NamedImports */: - case 254 /* NamedExports */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: result = reduceNode(node.openingFragment, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingFragment, cbNode, result); break; - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); // falls through - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 272 /* CatchClause */: + case 274 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 277 /* SourceFile */: + case 279 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -61957,7 +64258,7 @@ var ts; function aggregateTransformFlagsForSubtree(node) { // We do not transform ambient declarations or types, so there is no need to // recursively aggregate transform flags. - if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 209 /* ExpressionWithTypeArguments */)) { + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) { return 0 /* None */; } // Aggregate the transform flags of each child. @@ -62007,7 +64308,7 @@ var ts; }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, - __debugObjectFlags: { get: function () { return this.flags & 131072 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ @@ -62044,288 +64345,623 @@ var ts; /* @internal */ var ts; (function (ts) { - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + // Current source map file and its index in the sources list + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + // Last recorded and encoded mappings + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - // And failing that, check the disk - var text = host.readFile(path); // TODO: GH#18217 - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + // Then reencode all the updated mappings into the overall map + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } } - }; - cached.set(path, file); - return file; + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } + } + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + /** + * Tries to find the sourceMappingURL comment at the end of a file. + * @param text The source text of the file. + * @param lineStarts The line starts of the file. + */ + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + // empty + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + // Next entry is on same line - no action needed + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); } }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 /* comma */ || + mappings.charCodeAt(pos) === 59 /* semicolon */); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + // 6 digit number + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } } - ts.createSourceFileLikeCache = createSourceFileLikeCache; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - var sourcemaps; - (function (sourcemaps) { - sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; - function decode(host, mapPath, map, program, fallbackCache) { - if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } - var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; - var decodedMappings; - var generatedOrderedMappings; - var sourceOrderedMappings; - return { - getOriginalPosition: getOriginalPosition, - getGeneratedPosition: getGeneratedPosition - }; - function getGeneratedPosition(loc) { - var maps = getSourceOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { - return loc; - } - return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos - } - function getOriginalPosition(loc) { - var maps = getGeneratedOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos - } - function getSourceFileLike(fileName, location) { - // Lookup file in program, if provided - var path = ts.toPath(fileName, location, host.getCanonicalFileName); - var file = program && program.getSourceFile(path); - // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file - if (!file || file.resolvedPath !== path) { - // Otherwise check the cache (which may hit disk) - return fallbackCache.get(path); - } - return file; - } - function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { - var file = getSourceFileLike(fileName, directory); - if (!file) { - return -1; - } - return ts.getPositionOfLineAndCharacter(file, line, character); - } - function getDecodedMappings() { - return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host)); - } - function getSourceOrderedMappings() { - return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); - } - function getGeneratedOrderedMappings() { - return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); - } - function compareProcessedPositionSourcePositions(a, b) { - return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || - ts.compareValues(a.sourcePosition, b.sourcePosition); - } - function compareProcessedPositionEmittedPositions(a, b) { - return ts.compareValues(a.emittedPosition, b.emittedPosition); - } - function processPosition(position) { - var sourcePath = map.sources[position.sourceIndex]; - return { - emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), - sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), - sourcePath: sourcePath, - }; - } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : + value >= 26 && value < 52 ? 97 /* a */ + value - 26 : + value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : + value === 62 ? 43 /* plus */ : + value === 63 ? 47 /* slash */ : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : + ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : + ch === 43 /* plus */ ? 62 : + ch === 47 /* slash */ ? 63 : + -1; + } + 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; } - sourcemaps.decode = decode; - /*@internal*/ - function decodeMappings(map) { - var state = { - encodedText: map.mappings, - currentNameIndex: undefined, - sourceMapNamesLength: map.names ? map.names.length : undefined, - currentEmittedColumn: 0, - currentEmittedLine: 0, - currentSourceColumn: 0, - currentSourceLine: 0, - currentSourceIndex: 0, - decodingIndex: 0 - }; - function captureSpan() { - return { - emittedColumn: state.currentEmittedColumn, - emittedLine: state.currentEmittedLine, - sourceColumn: state.currentSourceColumn, - sourceIndex: state.currentSourceIndex, - sourceLine: state.currentSourceLine, - nameIndex: state.currentNameIndex - }; + 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 + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; } return { - get decodingIndex() { return state.decodingIndex; }, - get error() { return state.error; }, - get lastSpan() { return captureSpan(); }, - next: function () { - if (hasCompletedDecoding(state) || state.error) - return { done: true, value: undefined }; - if (!decodeSinglePosition(state)) - return { done: true, value: undefined }; - return { done: false, value: captureSpan() }; - } + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex }; } - sourcemaps.decodeMappings = decodeMappings; - function calculateDecodedMappings(map, processPosition, host) { - var decoder = decodeMappings(map); - var positions = ts.arrayFrom(decoder, processPosition); - if (decoder.error) { - if (host && host.log) { - host.log("Encountered error while decoding sourcemap: " + decoder.error); - } - return []; - } - return positions; - } - function hasCompletedDecoding(state) { - return state.decodingIndex === state.encodedText.length; - } - function decodeSinglePosition(state) { - while (state.decodingIndex < state.encodedText.length) { - var char = state.encodedText.charCodeAt(state.decodingIndex); - if (char === 59 /* semicolon */) { - // New line - state.currentEmittedLine++; - state.currentEmittedColumn = 0; - state.decodingIndex++; - continue; - } - if (char === 44 /* comma */) { - // Next entry is on same line - no action needed - state.decodingIndex++; - continue; - } - // Read the current position - // 1. Column offset from prev read jsColumn - state.currentEmittedColumn += base64VLQFormatDecode(); - // Incorrect emittedColumn dont support this map - if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { - return false; - } - // 2. Relative sourceIndex - state.currentSourceIndex += base64VLQFormatDecode(); - // Incorrect sourceIndex dont support this map - if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { - return false; - } - // Dont support reading mappings that dont have information about original source position - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { - return false; - } - // 3. Relative sourceLine 0 based - state.currentSourceLine += base64VLQFormatDecode(); - // Incorrect sourceLine dont support this map - if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { - return false; - } - // 4. Relative sourceColumn 0 based - state.currentSourceColumn += base64VLQFormatDecode(); - // Incorrect sourceColumn dont support this map - if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { - return false; - } - // 5. Check if there is name: - if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { - if (state.currentNameIndex === undefined) { - state.currentNameIndex = 0; + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); } - state.currentNameIndex += base64VLQFormatDecode(); - // Incorrect nameIndex dont support this map - // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap - // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { - // return; - // } - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { - return false; - } - // Entry should be complete - return true; - } - createErrorIfCondition(/*condition*/ true, "No encoded entry found"); - return false; - function createErrorIfCondition(condition, errormsg) { - if (state.error) { - // An error was already reported - return true; - } - if (condition) { - state.error = errormsg; - } - return condition; - } - function base64VLQFormatDecode() { - var moreDigits = true; - var shiftCount = 0; - var value = 0; - for (; moreDigits; state.decodingIndex++) { - if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return undefined; // TODO: GH#18217 - } - // 6 digit number - var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); - // If msb is set, we still have more bits to continue - moreDigits = (currentByte & 32) !== 0; - // least significant 5 bits are the next msbs in the final value. - value = value | ((currentByte & 31) << shiftCount); - shiftCount += 5; - } - // Least significant bit if 1 represents negative and rest of the msb is actual absolute value - if ((value & 1) === 0) { - // + number - value = value >> 1; + decodedMappings = ts.emptyArray; } else { - // - number - value = value >> 1; - value = -value; + decodedMappings = mappings; } - return value; } + return decodedMappings; } - function base64FormatDecode(char) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; } - function isSourceMappingSegmentEnd(encodedText, pos) { - return (pos === encodedText.length || - encodedText.charCodeAt(pos) === 44 /* comma */ || - encodedText.charCodeAt(pos) === 59 /* semicolon */); + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; } - })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; })(ts || (ts = {})); /* @internal */ var ts; @@ -62348,7 +64984,7 @@ var ts; function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 277 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -62394,7 +65030,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -62402,13 +65038,13 @@ var ts; externalImports.push(node); hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; - case 246 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { + case 248 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -62438,13 +65074,13 @@ var ts; } } break; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -62452,7 +65088,7 @@ var ts; } } break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default function() { } @@ -62472,7 +65108,7 @@ var ts; } } break; - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default class { } @@ -62824,8 +65460,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62891,7 +65527,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63088,8 +65724,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -63119,14 +65755,14 @@ var ts; var pendingExpressions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 278 /* Bundle */) { + if (node.kind === 280 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280 /* InputFiles */) { + if (prepend.kind === 282 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); } return prepend; @@ -63175,16 +65811,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 277 /* SourceFile */: - case 244 /* CaseBlock */: - case 243 /* ModuleBlock */: - case 216 /* Block */: + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 245 /* ModuleBlock */: + case 218 /* Block */: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 238 /* ClassDeclaration */: - case 237 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: if (ts.hasModifier(node, 2 /* Ambient */)) { break; } @@ -63196,7 +65832,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 238 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); } if (ts.isClassDeclaration(node)) { // XXX: should probably also cover interfaces and type aliases that can have type variables? @@ -63244,10 +65880,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -63268,13 +65904,13 @@ var ts; return node; } switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -63294,11 +65930,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 253 /* ExportDeclaration */ || - node.kind === 247 /* ImportDeclaration */ || - node.kind === 248 /* ImportClause */ || - (node.kind === 246 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 257 /* ExternalModuleReference */)) { + if (node.kind === 255 /* ExportDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 250 /* ImportClause */ || + (node.kind === 248 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 259 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -63328,19 +65964,19 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 152 /* PropertyDeclaration */: - case 160 /* IndexSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); @@ -63350,7 +65986,7 @@ var ts; if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { return undefined; } - else if (currentNamespace && node.kind === 84 /* ExportKeyword */) { + else if (currentNamespace && node.kind === 85 /* ExportKeyword */) { return undefined; } return node; @@ -63367,67 +66003,67 @@ var ts; return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 133 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 169 /* OptionalType */: - case 170 /* RestType */: - case 166 /* TypeLiteral */: - case 161 /* TypePredicate */: - case 148 /* TypeParameter */: - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 105 /* VoidKeyword */: - case 138 /* SymbolKeyword */: - case 164 /* ConstructorType */: - case 163 /* FunctionType */: - case 165 /* TypeQuery */: - case 162 /* TypeReference */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 173 /* ConditionalType */: - case 175 /* ParenthesizedType */: - case 176 /* ThisType */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 180 /* LiteralType */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 168 /* TypeLiteral */: + case 163 /* TypePredicate */: + case 150 /* TypeParameter */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 123 /* BooleanKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 132 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 139 /* SymbolKeyword */: + case 166 /* ConstructorType */: + case 165 /* FunctionType */: + case 167 /* TypeQuery */: + case 164 /* TypeReference */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 177 /* ParenthesizedType */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: // TypeScript type nodes are elided. - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: // TypeScript index signatures are elided. - case 150 /* Decorator */: + case 152 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 155 /* Constructor */: + case 157 /* Constructor */: return visitConstructor(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -63438,7 +66074,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -63449,35 +66085,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 149 /* Parameter */: + case 151 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -63487,35 +66123,35 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: @@ -63552,7 +66188,7 @@ var ts; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); - if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) facts |= 2 /* HasConstructorDecorators */; @@ -63621,7 +66257,7 @@ var ts; // return C; // }(); // - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18 /* CloseBraceToken */); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */); var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -63823,7 +66459,7 @@ var ts; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85 /* ExtendsKeyword */; })); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; })); var classExpression = ts.createClassExpression( /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, heritageClauses, members); @@ -63831,7 +66467,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63879,9 +66515,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -63997,7 +66635,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -64068,7 +66706,7 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 152 /* PropertyDeclaration */ + return member.kind === 154 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } @@ -64079,8 +66717,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -64096,8 +66734,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { - var property = properties_11[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var expression = transformInitializedProperty(property, receiver); ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -64208,12 +66846,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -64366,7 +67004,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 152 /* PropertyDeclaration */ + ? member.kind === 154 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? ts.createVoidZero() @@ -64467,13 +67105,13 @@ var ts; if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); } if (properties) { decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); @@ -64489,10 +67127,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 152 /* PropertyDeclaration */; + return kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 154 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -64502,7 +67140,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 154 /* MethodDeclaration */; + return node.kind === 156 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -64513,12 +67151,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return true; } return false; @@ -64535,15 +67173,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 152 /* PropertyDeclaration */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: return serializeTypeNode(node.type); - case 157 /* SetAccessor */: - case 156 /* GetAccessor */: + case 159 /* SetAccessor */: + case 158 /* GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 154 /* MethodDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 156 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -64580,7 +67218,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 156 /* GetAccessor */) { + if (container && node.kind === 158 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -64625,77 +67263,83 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: return ts.createVoidZero(); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return ts.createIdentifier("Function"); - case 167 /* ArrayType */: - case 168 /* TupleType */: + case 169 /* ArrayType */: + case 170 /* TupleType */: return ts.createIdentifier("Array"); - case 161 /* TypePredicate */: - case 122 /* BooleanKeyword */: + case 163 /* TypePredicate */: + case 123 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: return ts.createIdentifier("String"); - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 180 /* LiteralType */: + case 182 /* LiteralType */: switch (node.literal.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return ts.createIdentifier("String"); case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 9 /* BigIntLiteral */: + return getGlobalBigIntNameWithFallback(); + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: return ts.Debug.failBadSyntaxKind(node.literal); } - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: return ts.createIdentifier("Number"); - case 138 /* SymbolKeyword */: + case 146 /* BigIntKeyword */: + return getGlobalBigIntNameWithFallback(); + case 139 /* SymbolKeyword */: return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return serializeTypeReferenceNode(node); - case 172 /* IntersectionType */: - case 171 /* UnionType */: - return serializeUnionOrIntersectionType(node); - case 165 /* TypeQuery */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 166 /* TypeLiteral */: - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 176 /* ThisType */: - case 181 /* ImportType */: + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return serializeTypeList(node.types); + case 175 /* ConditionalType */: + return serializeTypeList([node.trueType, node.falseType]); + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 168 /* TypeLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 178 /* ThisType */: + case 183 /* ImportType */: break; default: return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } - function serializeUnionOrIntersectionType(node) { + function serializeTypeList(types) { // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175 /* ParenthesizedType */) { + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } - if (typeNode.kind === 131 /* NeverKeyword */) { + if (typeNode.kind === 132 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedIndividual = serializeTypeNode(typeNode); @@ -64731,6 +67375,10 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); @@ -64738,6 +67386,8 @@ var ts; return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); case ts.TypeReferenceSerializationKind.BooleanType: return ts.createIdentifier("Boolean"); case ts.TypeReferenceSerializationKind.NumberLikeType: @@ -64769,12 +67419,12 @@ var ts; * @param node The entity name to serialize. */ function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { // A -> typeof A !== undefined && A var copied = serializeEntityNameAsExpression(node); return createCheckedValue(copied, copied); } - if (node.left.kind === 71 /* Identifier */) { + if (node.left.kind === 72 /* Identifier */) { // A.B -> typeof A !== undefined && A.B return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); } @@ -64790,7 +67440,7 @@ var ts; */ function serializeEntityNameAsExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were // a source tree node for the purposes of the checker. var name = ts.getMutableClone(node); @@ -64798,7 +67448,7 @@ var ts; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. return name; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -64819,6 +67469,15 @@ var ts; function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 /* ESNext */ + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } /** * A simple inlinable expression is an expression which can be copied into multiple locations * without risk of repeating any sideeffects and whose value could not possibly change between @@ -64899,9 +67558,9 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 85 /* ExtendsKeyword */) { + if (node.token === 86 /* ExtendsKeyword */) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(85 /* ExtendsKeyword */, types), node); + return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); } return undefined; } @@ -65297,7 +67956,7 @@ var ts; var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); var valueExpression = transformEnumMemberDeclarationValue(member); var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); - var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? innerAssignment : ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); @@ -65378,12 +68037,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 277 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 241 /* EnumDeclaration */) { + if (node.kind === 243 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -65508,7 +68167,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 243 /* ModuleBlock */) { + if (body.kind === 245 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -65554,13 +68213,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 243 /* ModuleBlock */) { + if (body.kind !== 245 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -65601,7 +68260,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 249 /* NamespaceImport */) { + if (node.kind === 251 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -65795,7 +68454,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65814,7 +68473,7 @@ var ts; function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } function enableSubstitutionForClassAliases() { @@ -65822,7 +68481,7 @@ var ts; enabledSubstitutions |= 1 /* ClassAliases */; // We need to enable substitutions for identifiers. This allows us to // substitute class names inside of a class declaration. - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); // Keep track of class aliases. classAliases = []; } @@ -65832,17 +68491,17 @@ var ts; enabledSubstitutions |= 2 /* NamespaceExports */; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. - context.enableSubstitution(71 /* Identifier */); - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); + context.enableSubstitution(72 /* Identifier */); + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(242 /* ModuleDeclaration */); + context.enableEmitNotification(244 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 242 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 241 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */; } /** * Hook for node emit. @@ -65901,11 +68560,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -65917,7 +68576,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // 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. @@ -65943,9 +68602,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 277 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 242 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 241 /* EnumDeclaration */); + if (container && container.kind !== 279 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), /*location*/ node); @@ -66057,6 +68716,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66077,19 +68744,29 @@ var ts; return node; } switch (node.kind) { - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitAwaitExpression(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66097,27 +68774,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 216 /* Block */: - case 230 /* SwitchStatement */: - case 244 /* CaseBlock */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 233 /* TryStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 220 /* IfStatement */: - case 229 /* WithStatement */: - case 231 /* LabeledStatement */: + case 218 /* Block */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 231 /* WithStatement */: + case 233 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -66318,7 +68995,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 195 /* ArrowFunction */; + var isArrowFunction = node.kind === 197 /* 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 @@ -66331,23 +69008,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66365,6 +69052,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66391,15 +69080,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(189 /* CallExpression */); - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(238 /* ClassDeclaration */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); } } /** @@ -66422,6 +69113,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66439,24 +69138,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66475,24 +69174,68 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 /* ClassDeclaration */ - || kind === 155 /* Constructor */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66502,7 +69245,7 @@ var ts; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); var generatorFunc = ts.createFunctionExpression( - /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), /*name*/ undefined, /*typeParameters*/ undefined, /*parameters*/ [], @@ -66520,12 +69263,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66548,6 +69291,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66564,7 +69313,7 @@ var ts; return visitorWorker(node, /*noDestructuringValue*/ true); } function visitorNoAsyncModifier(node) { - if (node.kind === 120 /* AsyncKeyword */) { + if (node.kind === 121 /* AsyncKeyword */) { return undefined; } return node; @@ -66574,48 +69323,58 @@ var ts; return node; } switch (node.kind) { - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitAwaitExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return visitVoidExpression(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return visitConstructorDeclaration(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: return visitGetAccessorDeclaration(node); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitParameter(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitExpressionStatement(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66648,7 +69407,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 225 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); @@ -66660,7 +69419,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 275 /* SpreadAssignment */) { + if (e.kind === 277 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -66669,7 +69428,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 273 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */ ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -66680,14 +69439,14 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); // If the first element is a spread element, then the first argument to __assign is {}: // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 186 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -66712,10 +69471,10 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } - else if (node.operatorToken.kind === 26 /* CommaToken */) { + else if (node.operatorToken.kind === 27 /* CommaToken */) { return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); @@ -66727,7 +69486,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66744,7 +69503,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66841,7 +69600,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66938,25 +69697,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( - /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66980,7 +69751,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -67000,15 +69771,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(189 /* CallExpression */); - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(238 /* ClassDeclaration */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); } } /** @@ -67031,6 +69804,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67048,24 +69829,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67084,19 +69865,19 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 /* ClassDeclaration */ - || kind === 155 /* Constructor */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67197,13 +69978,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67211,15 +69992,15 @@ var ts; } function transformJsxChildToExpression(node) { switch (node.kind) { - case 10 /* JsxText */: + case 11 /* JsxText */: return visitJsxText(node); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitJsxExpression(node); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -67287,14 +70068,14 @@ var ts; if (node === undefined) { return ts.createTrue(); } - else if (node.kind === 9 /* StringLiteral */) { + else if (node.kind === 10 /* StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); return ts.setTextRange(literal, node); } - else if (node.kind === 268 /* JsxExpression */) { + else if (node.kind === 270 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } @@ -67388,7 +70169,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 258 /* JsxElement */) { + if (node.kind === 260 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -67694,7 +70475,7 @@ var ts; return node; } switch (node.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67702,9 +70483,9 @@ var ts; } function visitBinaryExpression(node) { switch (node.operatorToken.kind) { - case 62 /* AsteriskAsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: return visitExponentiationAssignmentExpression(node); - case 40 /* AsteriskAsteriskToken */: + case 41 /* AsteriskAsteriskToken */: return visitExponentiationExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67754,6 +70535,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67927,14 +70713,14 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 228 /* ReturnStatement */ + && node.kind === 230 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -67952,104 +70738,104 @@ var ts; return node; } function callExpressionVisitor(node) { - if (node.kind === 97 /* SuperKeyword */) { + if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); } return visitor(node); } function visitJavaScript(node) { switch (node.kind) { - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: return undefined; // elide static keyword - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return visitClassExpression(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitParameter(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 71 /* Identifier */: + case 72 /* Identifier */: return visitIdentifier(node); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitCaseBlock(node); - case 216 /* Block */: + case 218 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitExpressionStatement(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node, /*needsDestructuringValue*/ true); - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: return visitTemplateLiteral(node); - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return visitTemplateExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return visitSpreadElement(node); - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return visitThisKeyword(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return visitMetaProperty(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return visitAccessorDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -68136,14 +70922,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 227 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 227 /* BreakStatement */) { + if (node.kind === 229 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -68154,7 +70940,7 @@ var ts; } } else { - if (node.kind === 227 /* BreakStatement */) { + if (node.kind === 229 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -68173,10 +70959,10 @@ var ts; expr = copyExpr; } else { - expr = ts.createBinary(expr, 26 /* CommaToken */, copyExpr); + expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr); } } - returnExpression = ts.createBinary(expr, 26 /* CommaToken */, returnExpression); + returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression); } return ts.createReturn(returnExpression); } @@ -68310,7 +71096,7 @@ var ts; addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); // Create a synthetic text range for the return statement. - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18 /* CloseBraceToken */); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */); var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -68415,7 +71201,7 @@ var ts; } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); // The last statement expression was replaced. Skip it. if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { @@ -68454,11 +71240,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 228 /* ReturnStatement */) { + if (statement.kind === 230 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 220 /* IfStatement */) { + else if (statement.kind === 222 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -68466,7 +71252,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 216 /* Block */) { + else if (statement.kind === 218 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -68524,7 +71310,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -68532,10 +71318,10 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 202 /* BinaryExpression */ - || superCallExpression.left.kind !== 189 /* CallExpression */) { + if (superCallExpression.kind !== 204 /* BinaryExpression */ + || superCallExpression.left.kind !== 191 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } // Shift comments from the original super call to the return statement. @@ -68603,7 +71389,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68680,7 +71466,7 @@ var ts; * synthesized call to `super` */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 71 /* Identifier */ && !inConstructorWithSynthesizedSuper; + return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; } /** * Adds statements to the body of a function-like node if it contains a rest parameter. @@ -68732,7 +71518,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68751,25 +71537,25 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return statements; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = ts.createVoidZero(); break; - case 155 /* Constructor */: + case 157 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. - newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); break; default: return ts.Debug.failBadSyntaxKind(node); @@ -68797,20 +71583,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 155 /* Constructor */: + case 157 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -68920,7 +71706,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69002,7 +71788,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 237 /* FunctionDeclaration */ || node.kind === 194 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); @@ -69047,7 +71833,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 195 /* ArrowFunction */); + ts.Debug.assert(node.kind === 197 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -69085,7 +71871,7 @@ var ts; ts.setEmitFlags(block, 1 /* SingleLine */); } if (closeBraceLocation) { - ts.setTokenSourceMapRange(block, 18 /* CloseBraceToken */, closeBraceLocation); + ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -69115,9 +71901,9 @@ var ts; function visitExpressionStatement(node) { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); @@ -69136,9 +71922,9 @@ var ts; // expression. If we are in a state where we do not need the destructuring value, // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } @@ -69173,7 +71959,7 @@ var ts; assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); } else { - assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); @@ -69210,19 +71996,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69270,8 +72064,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69339,14 +72133,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -69526,11 +72320,11 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 147 /* ComputedPropertyName */) { + if (property.name.kind === 149 /* ComputedPropertyName */) { numInitialProperties = i; break; } @@ -69557,7 +72351,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69569,7 +72379,7 @@ var ts; } visit(node.name); function visit(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { state.hoistedLocalVariables.push(node); } else { @@ -69583,7 +72393,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69599,14 +72409,76 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 236 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 238 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -69616,165 +72488,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // 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 - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.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 = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.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'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 58 /* EqualsToken */, source); + return ts.createBinary(target, 59 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69782,38 +72765,38 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); } if (state.nonLocalJumps & 2 /* Break */) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69853,21 +72836,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69886,20 +72877,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -70007,10 +72998,10 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -70186,15 +73177,15 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || - node.expression.kind === 97 /* SuperKeyword */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70223,7 +73214,7 @@ var ts; resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { var actualThis = ts.createThis(); ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); var initializer = ts.createLogicalOr(resultingCall, actualThis); @@ -70241,7 +73232,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70288,7 +73279,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 185 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -70405,7 +73396,7 @@ var ts; // thus we need to remove those characters. // First template piece starts with "`", others with "}" // Last template piece ends with "`", others with "${" - var isLast = node.kind === 13 /* NoSubstitutionTemplateLiteral */ || node.kind === 16 /* TemplateTail */; + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; text = text.substring(1, text.length - (isLast ? 1 : 2)); // Newline normalization: // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's @@ -70503,7 +73494,7 @@ var ts; : ts.createFileLevelUniqueName("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") { + if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { if (hierarchyFacts & 8192 /* ComputedPropertyName */) { hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; } @@ -70540,7 +73531,7 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } /** @@ -70550,14 +73541,14 @@ var ts; function enableSubstitutionsForCapturedThis() { if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; - context.enableSubstitution(99 /* ThisKeyword */); - context.enableEmitNotification(155 /* Constructor */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(195 /* ArrowFunction */); - context.enableEmitNotification(194 /* FunctionExpression */); - context.enableEmitNotification(237 /* FunctionDeclaration */); + context.enableSubstitution(100 /* ThisKeyword */); + context.enableEmitNotification(157 /* Constructor */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(197 /* ArrowFunction */); + context.enableEmitNotification(196 /* FunctionExpression */); + context.enableEmitNotification(239 /* FunctionDeclaration */); } } /** @@ -70598,10 +73589,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 237 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -70614,9 +73605,9 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return substituteThisKeyword(node); } return node; @@ -70683,19 +73674,19 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 219 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 189 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 97 /* SuperKeyword */) { + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) { return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 206 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -70723,7 +73714,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -70748,15 +73739,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(260 /* JsxOpeningElement */); - context.enableEmitNotification(261 /* JsxClosingElement */); - context.enableEmitNotification(259 /* JsxSelfClosingElement */); + context.enableEmitNotification(262 /* JsxOpeningElement */); + context.enableEmitNotification(263 /* JsxClosingElement */); + context.enableEmitNotification(261 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(273 /* PropertyAssignment */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(275 /* PropertyAssignment */); return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -70775,9 +73766,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -70834,7 +73825,7 @@ var ts; */ function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { + if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -71109,13 +74100,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitWhileStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -71128,30 +74119,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return visitAccessorDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return visitBreakStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return visitContinueStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71166,21 +74157,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return visitConditionalExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -71193,9 +74184,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -71354,7 +74345,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71394,23 +74385,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 59 /* FirstCompoundAssignment */ - && kind <= 70 /* LastCompoundAssignment */; + return kind >= 60 /* FirstCompoundAssignment */ + && kind <= 71 /* LastCompoundAssignment */; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 59 /* PlusEqualsToken */: return 37 /* PlusToken */; - case 60 /* MinusEqualsToken */: return 38 /* MinusToken */; - case 61 /* AsteriskEqualsToken */: return 39 /* AsteriskToken */; - case 62 /* AsteriskAsteriskEqualsToken */: return 40 /* AsteriskAsteriskToken */; - case 63 /* SlashEqualsToken */: return 41 /* SlashToken */; - case 64 /* PercentEqualsToken */: return 42 /* PercentToken */; - case 65 /* LessThanLessThanEqualsToken */: return 45 /* LessThanLessThanToken */; - case 66 /* GreaterThanGreaterThanEqualsToken */: return 46 /* GreaterThanGreaterThanToken */; - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanGreaterThanToken */; - case 68 /* AmpersandEqualsToken */: return 48 /* AmpersandToken */; - case 69 /* BarEqualsToken */: return 49 /* BarToken */; - case 70 /* CaretEqualsToken */: return 50 /* CaretToken */; + case 60 /* PlusEqualsToken */: return 38 /* PlusToken */; + case 61 /* MinusEqualsToken */: return 39 /* MinusToken */; + case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */; + case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */; + case 64 /* SlashEqualsToken */: return 42 /* SlashToken */; + case 65 /* PercentEqualsToken */: return 43 /* PercentToken */; + case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */; + case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */; + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */; + case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */; + case 70 /* BarEqualsToken */: return 50 /* BarToken */; + case 71 /* CaretEqualsToken */: return 51 /* CaretToken */; } } /** @@ -71423,7 +74414,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -71435,7 +74426,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -71467,7 +74458,7 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 26 /* CommaToken */) { + else if (node.operatorToken.kind === 27 /* CommaToken */) { return visitCommaExpression(node); } // [source] @@ -71478,10 +74469,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71522,7 +74513,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { // Logical `&&` shortcuts when the left-hand operand is falsey. emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); } @@ -71553,7 +74544,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { visit(node.left); visit(node.right); } @@ -71742,10 +74733,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -71811,35 +74802,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 216 /* Block */: + case 218 /* Block */: return transformAndEmitBlock(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return transformAndEmitIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return transformAndEmitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return transformAndEmitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return transformAndEmitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -72269,7 +75260,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 270 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -72282,7 +75273,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 269 /* CaseClause */) { + if (clause.kind === 271 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -72412,7 +75403,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72444,10 +75435,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -72594,7 +75585,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = []; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } renamedCatchVariables.set(text, true); renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -73510,12 +76501,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -73529,7 +76520,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73583,6 +76577,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73613,22 +76608,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73837,23 +76834,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 308 /* MergeDeclarationMarker */: + case 310 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 309 /* EndOfDeclarationMarker */: + case 311 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -73862,7 +76859,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73880,24 +76877,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -73929,7 +76926,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74375,7 +77372,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -74430,10 +77427,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -74615,8 +77612,8 @@ var ts; function modifierVisitor(node) { // Elide module-specific modifiers. switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: return undefined; } return node; @@ -74632,7 +77629,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -74694,12 +77691,12 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return substituteBinaryExpression(node); - case 201 /* PostfixUnaryExpression */: - case 200 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -74720,7 +77717,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -74788,15 +77785,15 @@ var ts; // - We do not substitute identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only substitute identifiers that are exported at the top level. - if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 /* PostfixUnaryExpression */ - ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { @@ -74870,12 +77867,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -74894,7 +77891,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75096,7 +78093,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 253 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -75121,7 +78118,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 253 /* ExportDeclaration */) { + if (externalImport.kind !== 255 /* ExportDeclaration */) { continue; } if (!externalImport.exportClause) { @@ -75199,19 +78196,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -75261,15 +78258,15 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: // ExportDeclarations are elided as they are handled via // `appendExportsOfDeclaration`. return undefined; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -75445,7 +78442,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 277 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -75509,7 +78506,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -75571,10 +78568,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -75754,43 +78751,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitWhileStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return visitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitCaseBlock(node); - case 269 /* CaseClause */: + case 271 /* CaseClause */: return visitCaseClause(node); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return visitDefaultClause(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return visitTryStatement(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); - case 216 /* Block */: + case 218 /* Block */: return visitBlock(node); - case 308 /* MergeDeclarationMarker */: + case 310 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 309 /* EndOfDeclarationMarker */: + case 311 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -75973,13 +78970,13 @@ var ts; */ function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 202 /* BinaryExpression */) { + && node.kind === 204 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76038,7 +79035,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 277 /* SourceFile */; + return container !== undefined && container.kind === 279 /* SourceFile */; } else { return false; @@ -76054,8 +79051,8 @@ var ts; */ function modifierVisitor(node) { switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: return undefined; } return node; @@ -76071,7 +79068,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -76119,7 +79116,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -76153,12 +79150,12 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return substituteBinaryExpression(node); - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -76244,22 +79241,22 @@ var ts; // - We do not substitute identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only substitute identifiers that are exported at the top level. - if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 /* PostfixUnaryExpression */ + var expression = node.kind === 203 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 201 /* PostfixUnaryExpression */) { - expression = node.operator === 43 /* PlusPlusToken */ + if (node.kind === 203 /* PostfixUnaryExpression */) { + expression = node.operator === 44 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); } @@ -76280,7 +79277,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -76319,8 +79316,8 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(277 /* SourceFile */); - context.enableSubstitution(71 /* Identifier */); + context.enableEmitNotification(279 /* SourceFile */); + context.enableSubstitution(72 /* Identifier */); var currentSourceFile; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { @@ -76348,10 +79345,10 @@ var ts; } function visitor(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); } return node; @@ -76458,7 +79455,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* 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 : @@ -76487,7 +79484,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -76534,7 +79531,7 @@ var ts; return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { 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 : @@ -76543,8 +79540,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 152 /* PropertyDeclaration */ || node.kind === 151 /* PropertySignature */ || - (node.kind === 149 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -76553,7 +79550,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */ || node.kind === 149 /* Parameter */) { + else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -76578,7 +79575,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 157 /* SetAccessor */) { + if (node.kind === 159 /* SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.hasModifier(node, 32 /* Static */)) { @@ -76617,26 +79614,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named 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 158 /* CallSignature */: + case 160 /* CallSignature */: // Interfaces cannot have return types that cannot be named 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 160 /* IndexSignature */: + case 162 /* IndexSignature */: // Interfaces cannot have return types that cannot be named 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 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -76644,7 +79641,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* 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 : @@ -76658,7 +79655,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 237 /* FunctionDeclaration */: + case 239 /* 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 : @@ -76683,30 +79680,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 155 /* Constructor */: + case 157 /* 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 159 /* ConstructSignature */: - case 164 /* ConstructorType */: + case 161 /* ConstructSignature */: + case 166 /* ConstructorType */: // Interfaces cannot have parameter types that cannot be named 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 158 /* CallSignature */: + case 160 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named 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 160 /* IndexSignature */: + case 162 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -76714,7 +79711,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 240 /* 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 : @@ -76727,8 +79724,8 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 237 /* FunctionDeclaration */: - case 163 /* FunctionType */: + case 239 /* FunctionDeclaration */: + case 165 /* FunctionType */: 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 : @@ -76742,34 +79739,34 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 158 /* CallSignature */: + case 160 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node.parent, 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 === 238 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 240 /* 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 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -76784,9 +79781,9 @@ var ts; function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + if (node.parent.parent.kind === 240 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ? 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; } @@ -76821,11 +79818,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76851,7 +79848,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76862,6 +79859,7 @@ var ts; reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode @@ -76869,6 +79867,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76878,10 +79877,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76949,16 +79948,22 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } - if (node.kind === 278 /* Bundle */) { + if (node.kind === 280 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76970,23 +79975,25 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280 /* InputFiles */) { + if (prepend.kind === 282 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -77005,8 +80012,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77017,11 +80025,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77051,7 +80062,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77059,13 +80070,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77075,12 +80091,21 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { return name; } else { - if (name.kind === 183 /* ArrayBindingPattern */) { + if (name.kind === 185 /* ArrayBindingPattern */) { return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -77088,7 +80113,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 208 /* OmittedExpression */) { + if (elem.kind === 210 /* OmittedExpression */) { return elem; } return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -77101,7 +80126,7 @@ var ts; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } var newParam = ts.updateParameter(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -77113,7 +80138,7 @@ var ts; } function ensureNoInitializer(node) { if (shouldPrintWithInitializer(node)) { - return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe } return undefined; } @@ -77126,19 +80151,19 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 149 /* Parameter */ && + var shouldUseResolverType = node.kind === 151 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { return ts.visitNode(type, visitDeclarationSubtree); } if (!ts.getParseTreeNode(node)) { - return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */); } - if (node.kind === 157 /* SetAccessor */) { + if (node.kind === 159 /* SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } errorNameNode = node.name; var oldDiag; @@ -77146,12 +80171,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 149 /* Parameter */ - || node.kind === 152 /* PropertyDeclaration */ - || node.kind === 151 /* PropertySignature */) { + if (node.kind === 151 /* Parameter */ + || node.kind === 154 /* PropertyDeclaration */ + || node.kind === 153 /* PropertySignature */) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -77162,26 +80187,26 @@ var ts; if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } - return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */); + return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */); } } function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: return false; } return false; @@ -77235,7 +80260,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -77255,7 +80280,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 257 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return ts.updateImportEqualsDeclaration(decl, @@ -77282,7 +80307,7 @@ var ts; return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -77387,68 +80412,68 @@ var ts; checkEntityNameVisibility(input.exprName, enclosingDeclaration); } var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 /* TypeLiteral */ || input.kind === 179 /* MappedType */) && input.parent.kind !== 240 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */); if (shouldEnterSuppressNewDiagnosticsContextContext) { // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. suppressNewDiagnosticContexts = true; } if (isProcessedComponent(input)) { switch (input.kind) { - case 209 /* ExpressionWithTypeArguments */: { + case 211 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); } - case 162 /* TypeReference */: { + case 164 /* TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); } - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 155 /* Constructor */: { + case 157 /* Constructor */: { var isPrivate = ts.hasModifier(input, 8 /* Private */); // A constructor declaration may not have a type annotation - var ctor = ts.createSignatureDeclaration(155 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), // TODO: GH#18217 isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), /*type*/ undefined); ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); return cleanup(ctor); } - case 154 /* MethodDeclaration */: { - var sig = ts.createSignatureDeclaration(153 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + case 156 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); sig.name = input.name; sig.modifiers = ts.createNodeArray(ensureModifiers(input)); sig.questionToken = input.questionToken; return cleanup(sig); } - case 156 /* GetAccessor */: { + case 158 /* GetAccessor */: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 157 /* SetAccessor */: { + case 159 /* SetAccessor */: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return cleanup(ts.updateProperty(input, /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 153 /* MethodSignature */: { + case 155 /* MethodSignature */: { return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); } - case 158 /* CallSignature */: { + case 160 /* CallSignature */: { return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 160 /* IndexSignature */: { + case 162 /* IndexSignature */: { return cleanup(ts.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */))); } - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -77456,13 +80481,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); } - case 148 /* TypeParameter */: { + case 150 /* TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 173 /* ConditionalType */: { + case 175 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -77474,13 +80499,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 163 /* FunctionType */: { + case 165 /* FunctionType */: { return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 164 /* ConstructorType */: { + case 166 /* ConstructorType */: { return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 181 /* ImportType */: { + case 183 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -77509,7 +80534,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 154 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -77519,7 +80544,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 253 /* ExportDeclaration */: { + case 255 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; @@ -77528,13 +80553,13 @@ var ts; // Rewrite external module names if necessary return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 252 /* ExportAssignment */: { + case 254 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; } - if (input.expression.kind === 71 /* Identifier */) { + if (input.expression.kind === 72 /* Identifier */) { return input; } else { @@ -77544,7 +80569,7 @@ var ts; errorNode: input }); }; var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } @@ -77558,10 +80583,10 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 246 /* ImportEqualsDeclaration */: { + case 248 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 247 /* ImportDeclaration */: { + case 249 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -77582,24 +80607,39 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 240 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(ts.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 239 /* InterfaceDeclaration */: { + case 241 /* InterfaceDeclaration */: { return cleanup(ts.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 237 /* FunctionDeclaration */: { + case 239 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } - case 242 /* ModuleDeclaration */: { + case 244 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 243 /* ModuleBlock */) { + if (inner && inner.kind === 245 /* ModuleBlock */) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; @@ -77620,7 +80660,7 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 238 /* ClassDeclaration */: { + case 240 /* ClassDeclaration */: { var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -77631,7 +80671,7 @@ var ts; if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); - if (param.name.kind === 71 /* Identifier */) { + if (param.name.kind === 72 /* Identifier */) { return preserveJsDoc(ts.createProperty( /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } @@ -77661,7 +80701,7 @@ var ts; } var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); - if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 getSymbolAccessibilityDiagnostic = function () { return ({ @@ -77670,16 +80710,16 @@ var ts; typeName: input.name }); }; var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { - if (clause.token === 85 /* ExtendsKeyword */) { + if (clause.token === 86 /* ExtendsKeyword */) { var oldDiag_2 = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); getSymbolAccessibilityDiagnostic = oldDiag_2; return newClause; } - return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree)); })); return [statement, cleanup(ts.updateClassDeclaration(input, /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 @@ -77690,10 +80730,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { return cleanup(transformVariableStatement(input, isPrivate)); } - case 241 /* EnumDeclaration */: { + case 243 /* EnumDeclaration */: { return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -77712,7 +80752,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242 /* ModuleDeclaration */) { + if (input.kind === 244 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -77733,7 +80773,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 208 /* OmittedExpression */) { + if (e.kind === 210 /* OmittedExpression */) { return; } if (e.name) { @@ -77796,7 +80836,7 @@ var ts; function ensureModifierFlags(node, privateDeclaration) { var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 277 /* SourceFile */; + var parentIsFile = node.parent.kind === 279 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; @@ -77817,7 +80857,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77831,20 +80871,20 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; } function transformHeritageClauses(nodes) { return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { - return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */); + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */); })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); } } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 239 /* InterfaceDeclaration */) { + if (node.kind === 241 /* InterfaceDeclaration */) { return true; } return false; @@ -77869,7 +80909,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 156 /* GetAccessor */ + return accessor.kind === 158 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -77878,51 +80918,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: - case 217 /* VariableStatement */: - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 219 /* VariableStatement */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 159 /* ConstructSignature */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 160 /* IndexSignature */: - case 235 /* VariableDeclaration */: - case 148 /* TypeParameter */: - case 209 /* ExpressionWithTypeArguments */: - case 162 /* TypeReference */: - case 173 /* ConditionalType */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 181 /* ImportType */: + case 161 /* ConstructSignature */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 237 /* VariableDeclaration */: + case 150 /* TypeParameter */: + case 211 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 175 /* ConditionalType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 183 /* ImportType */: return true; } return false; @@ -77987,6 +81028,14 @@ var ts; return transformers; } ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -77998,7 +81047,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(310 /* Count */); + var enabledSyntaxKindFeatures = new Array(312 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -78006,8 +81055,8 @@ var ts; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; - var onSubstituteNode = function (_, node) { return node; }; - var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; var state = 0 /* Uninitialized */; var diagnostics = []; // The transformation context is provided to each transformer as part of transformer @@ -78256,825 +81305,11 @@ var ts; } ts.transformNodes = transformNodes; })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans - var defaultLastEncodedSourceMapSpan = { - emittedLine: 0, - emittedColumn: 0, - sourceLine: 0, - sourceColumn: 0, - sourceIndex: 0 - }; - function createSourceMapWriter(host, writer, compilerOptions) { - if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } - var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSource; - var currentSourceText; - var sourceMapDir; // The directory in which sourcemap will be - // 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; - var sourceMapDataList; - var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); - return { - initialize: initialize, - reset: reset, - setSourceFile: setSourceFile, - emitPos: emitPos, - emitNodeWithSourceMap: emitNodeWithSourceMap, - emitTokenWithSourceMap: emitTokenWithSourceMap, - getText: getText, - getSourceMappingURL: getSourceMappingURL, - }; - /** - * Skips trivia such as comments and white-space that can optionally overriden by the source map source - */ - function skipSourceTrivia(pos) { - return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); - } - /** - * Initialize the SourceMapWriter for a new output file. - * - * @param filePath The path to the generated output file. - * @param sourceMapFilePath The path to the output source map file. - * @param sourceFileOrBundle The input source file or bundle for the program. - */ - function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) { - return; - } - if (sourceMapData) { - reset(); - } - sourceMapDataList = outputSourceMapDataList; - currentSource = undefined; - currentSourceText = 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, - }; - // 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 (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file - // 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(sourceFileOrBundle.fileName, 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)); - } - } - /** - * Reset the SourceMapWriter to an empty state. - */ - function reset() { - if (disabled) { - return; - } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMapData); - } - currentSource = undefined; - sourceMapDir = undefined; - sourceMapSourceIndex = undefined; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = undefined; - lastEncodedNameIndex = undefined; - sourceMapData = undefined; - sourceMapDataList = undefined; - } - function captureSection() { - return { - version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent, - }; - } - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - ts.Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative"); - 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 = 0; - } - // 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; - } - /** - * Emits a mapping. - * - * If the position is synthetic (undefined or a negative value), no mapping will be - * created. - * - * @param pos The position. - */ - function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); - 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 - }; - } - 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; - } - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } - } - function isPossiblySourceMap(x) { - return typeof x === "object" && !!x.mappings && typeof x.mappings === "string" && !!x.sources; - } - /** - * Emits a node with possible leading and trailing source maps. - * - * @param hint A hint as to the intended usage of the node. - * @param node The node to emit. - * @param emitCallback The callback used to emit the node. - */ - function emitNodeWithSourceMap(hint, node, emitCallback) { - var _a; - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(hint, node); - } - if (node) { - if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { - var text = node.sourceMapText; - var parsed = void 0; - try { - parsed = JSON.parse(text); - } - catch (_b) { - // empty - } - if (!parsed || !isPossiblySourceMap(parsed)) { - return emitCallback(hint, node); - } - var offsetLine = writer.getLine(); - var firstLineColumnOffset = writer.getColumn(); - // First, decode the old component sourcemap - var originalMap = parsed; - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var resolvedPathCache = ts.createMap(); - var absolutePathCache = ts.createMap(); - var sourcemapIterator = ts.sourcemaps.decodeMappings(originalMap); - for (var _c = sourcemapIterator.next(), raw = _c.value, done = _c.done; !done; _a = sourcemapIterator.next(), raw = _a.value, done = _a.done, _a) { - var pathCacheKey = "" + raw.sourceIndex; - // Apply offsets to each position and fixup source entries - if (!resolvedPathCache.has(pathCacheKey)) { - var rawPath = originalMap.sources[raw.sourceIndex]; - var relativePath = originalMap.sourceRoot ? ts.combinePaths(originalMap.sourceRoot, rawPath) : rawPath; - var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath); - var resolvedPath_1 = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - resolvedPathCache.set(pathCacheKey, resolvedPath_1); - absolutePathCache.set(pathCacheKey, ts.getNormalizedAbsolutePath(resolvedPath_1, sourcesDirectoryPath)); - } - var resolvedPath = resolvedPathCache.get(pathCacheKey); - var absolutePath = absolutePathCache.get(pathCacheKey); - // tslint:disable-next-line:no-null-keyword - setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); // TODO: Lookup content for inlining? - var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath); - // Then reencode all the updated spans into the overall map - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = __assign({}, raw, { emittedLine: raw.emittedLine + offsetLine, emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, sourceIndex: newIndex }); - } - // And actually emit the text these sourcemaps are for - return emitCallback(hint, node); - } - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0 /* None */; - var range = emitNode && emitNode.sourceMapRange; - var _d = range || node, pos = _d.pos, end = _d.end; - var source = range && range.source; - var oldSource = currentSource; - if (source === oldSource) - source = undefined; - if (source) - setSourceFile(source); - if (node.kind !== 305 /* NotEmittedStatement */ - && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && pos >= 0) { - emitPos(skipSourceTrivia(pos)); - } - if (source) - setSourceFile(oldSource); - if (emitFlags & 64 /* NoNestedSourceMaps */) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - if (source) - setSourceFile(source); - if (node.kind !== 305 /* NotEmittedStatement */ - && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && end >= 0) { - emitPos(end); - } - if (source) - setSourceFile(oldSource); - } - } - /** - * Emits a token of a node with possible leading and trailing source maps. - * - * @param node The node containing the token. - * @param token The token to emit. - * @param tokenStartPos The start pos of the token. - * @param emitCallback The callback used to emit the token. - */ - function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(token, writer, tokenPos); - } - var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0 /* None */; - var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); - if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - tokenPos = emitCallback(token, writer, tokenPos); - if (range) - tokenPos = range.end; - if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - return tokenPos; - } - function isJsonSourceMapSource(sourceFile) { - return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); - } - /** - * Set the current source file. - * - * @param sourceFile The source file. - */ - function setSourceFile(sourceFile) { - if (disabled) { - return; - } - currentSource = sourceFile; - currentSourceText = currentSource.text; - if (isJsonSourceMapSource(sourceFile)) { - return; - } - setupSourceEntry(sourceFile.fileName, sourceFile.text); - } - function setupSourceEntry(fileName, content, source) { - if (!source) { - // 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; - source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(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(fileName); - if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(content); - } - } - } - /** - * Gets the text for the source map. - */ - function getText() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; // TODO: GH#18217 - } - encodeLastRecordedSourceMapSpan(); - return JSON.stringify(captureSection()); - } - /** - * Gets the SourceMappingURL for the source map. - */ - function getSourceMappingURL() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; // TODO: GH#18217 - } - if (compilerOptions.inlineSourceMap) { - // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.base64encode(ts.sys, 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 createCommentWriter(printerOptions, emitPos) { - var extendedDiagnostics = printerOptions.extendedDiagnostics; - var newLine = ts.getNewLineCharacter(printerOptions); - var writer; - var containerPos = -1; - var containerEnd = -1; - var declarationListContainerEnd = -1; - var currentSourceFile; - var currentText; - var currentLineMap; - var detachedCommentsInfo; - var hasWrittenComment = false; - var disabled = !!printerOptions.removeComments; - return { - reset: reset, - setWriter: setWriter, - setSourceFile: setSourceFile, - emitNodeWithComments: emitNodeWithComments, - emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, - emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, - }; - function emitNodeWithComments(hint, node, emitCallback) { - if (disabled) { - emitCallback(hint, node); - return; - } - if (node) { - hasWrittenComment = false; - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0; - var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; - if ((pos < 0 && end < 0) || (pos === end)) { - // Both pos and end are synthesized, so just emit the node without comments. - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - } - else { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithComment"); - } - var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */; - // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. - // It is expensive to walk entire tree just to set one kind of node to have no comments. - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; - var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 10 /* JsxText */; - // Emit leading comments if the position is not synthesized and the node - // has not opted out from emitting leading comments. - if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); - } - // Save current container state on the stack. - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { - // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. - containerPos = pos; - } - if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { - // As above. - containerEnd = end; - // To avoid invalid comment emit in a down-level binding pattern, we - // keep track of the last declaration list container's end - if (node.kind === 236 /* VariableDeclarationList */) { - declarationListContainerEnd = end; - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithComment"); - } - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithComment"); - } - // Restore previous container state. - containerPos = savedContainerPos; - containerEnd = savedContainerEnd; - declarationListContainerEnd = savedDeclarationListContainerEnd; - // Emit trailing comments if the position is not synthesized and the node - // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { - emitTrailingComments(end); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithComment"); - } - } - } - } - function emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback) { - var leadingComments = emitNode && emitNode.leadingComments; - if (ts.some(leadingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithSynthesizedComments"); - } - ts.forEach(leadingComments, emitLeadingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithSynthesizedComments"); - } - } - emitNodeWithNestedComments(hint, node, emitFlags, emitCallback); - var trailingComments = emitNode && emitNode.trailingComments; - if (ts.some(trailingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithSynthesizedComments"); - } - ts.forEach(trailingComments, emitTrailingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithSynthesizedComments"); - } - } - } - function emitLeadingSynthesizedComment(comment) { - if (comment.kind === 2 /* SingleLineCommentTrivia */) { - writer.writeLine(); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function emitTrailingSynthesizedComment(comment) { - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - } - function writeSynthesizedComment(comment) { - var text = formatSynthesizedComment(comment); - var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; - ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); - } - function formatSynthesizedComment(comment) { - return comment.kind === 3 /* MultiLineCommentTrivia */ - ? "/*" + comment.text + "*/" - : "//" + comment.text; - } - function emitNodeWithNestedComments(hint, node, emitFlags, emitCallback) { - if (emitFlags & 2048 /* NoNestedComments */) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - } - function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitBodyWithDetachedComments"); - } - var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = ts.getEmitFlags(node); - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; - if (!skipLeadingComments) { - emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); - } - if (emitFlags & 2048 /* NoNestedComments */ && !disabled) { - disabled = true; - emitCallback(node); - disabled = false; - } - else { - emitCallback(node); - } - if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); - } - if (!skipTrailingComments) { - emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); - if (hasWrittenComment && !writer.isAtStartOfLine()) { - writer.writeLine(); - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); - } - } - function emitLeadingComments(pos, isEmittedNode) { - hasWrittenComment = false; - if (isEmittedNode) { - forEachLeadingCommentToEmit(pos, emitLeadingComment); - } - else if (pos === 0) { - // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, - // unless it is a triple slash comment at the top of the file. - // For Example: - // /// - // declare var x; - // /// - // interface F {} - // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted - forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); - } - } - function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (isTripleSlashComment(commentPos, commentEnd)) { - emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); - } - } - function shouldWriteComment(text, pos) { - if (printerOptions.onlyPrintJsDocStyle) { - return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); - } - return true; - } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (!hasWrittenComment) { - ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); - hasWrittenComment = true; - } - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else if (kind === 3 /* MultiLineCommentTrivia */) { - writer.write(" "); - } - } - function emitLeadingCommentsOfPosition(pos) { - if (disabled || pos === -1) { - return; - } - emitLeadingComments(pos, /*isEmittedNode*/ true); - } - function emitTrailingComments(pos) { - forEachTrailingCommentToEmit(pos, emitTrailingComment); - } - function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - } - function emitTrailingCommentsOfPosition(pos, prefixSpace) { - if (disabled) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); - } - forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); - } - } - function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { - // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function forEachLeadingCommentToEmit(pos, cb) { - // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments - if (containerPos === -1 || pos !== containerPos) { - if (hasDetachedComments(pos)) { - forEachLeadingCommentWithoutDetachedComments(cb); - } - else { - ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - } - } - function forEachTrailingCommentToEmit(end, cb) { - // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments - if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { - ts.forEachTrailingCommentRange(currentText, end, cb); - } - } - function reset() { - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - detachedCommentsInfo = undefined; - } - function setWriter(output) { - writer = output; - } - function setSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = currentSourceFile.text; - currentLineMap = ts.getLineStarts(currentSourceFile); - detachedCommentsInfo = undefined; - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; - } - function forEachLeadingCommentWithoutDetachedComments(cb) { - // get the leading comments from detachedPos - var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - function emitDetachedCommentsAndUpdateCommentsInfo(range) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - } - /** - * Determine if the given comment is a triple-slash - * - * @return true if the comment is a triple-slash comment else false - */ - function isTripleSlashComment(commentPos, commentEnd) { - return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); - } - } - ts.createCommentWriter = createCommentWriter; -})(ts || (ts = {})); var ts; (function (ts) { var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ /** * Iterates over the source files that are expected to have an emit output. @@ -79112,21 +81347,26 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + if (sourceFile.kind === 280 /* Bundle */) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79149,7 +81389,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79169,22 +81409,16 @@ var ts; var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var newLine = host.getNewLine(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); var writer = ts.createTextWriter(newLine); - var sourceMap = ts.createSourceMapWriter(host, writer); - var declarationSourceMap = ts.createSourceMapWriter(host, writer, { - sourceMap: compilerOptions.declarationMap, - sourceRoot: compilerOptions.sourceRoot, - mapRoot: compilerOptions.mapRoot, - extendedDiagnostics: compilerOptions.extendedDiagnostics, - }); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; var exportedModulesFromDeclarationEmit; // Emit each output file - ts.performance.mark("beforePrint"); + enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); - ts.performance.measure("printTime", "beforePrint"); + exit(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -79198,56 +81432,66 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; // Create a printer to print the nodes - var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { + var printer = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, // transform hooks onEmitNode: transform.emitNodeWithNotification, substituteNode: transform.substituteNode, - // sourcemap hooks - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - // emitter hooks - onSetSourceFile: setSourceFile, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79261,14 +81505,20 @@ var ts; emitterDiagnostics.add(diagnostic); } } - var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true, noEmitHelpers: true }), { + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, - // sourcemap hooks - onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: declarationSourceMap.emitPos, - onSetSourceFile: setSourceFileForDeclarationSourceMaps, // transform hooks onEmitNode: declarationTransform.emitNodeWithNotification, substituteNode: declarationTransform.substituteNode, @@ -79277,8 +81527,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); - if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -79287,7 +81542,7 @@ var ts; } function collectLinkedAliases(node) { if (ts.isExportAssignment(node)) { - if (node.expression.kind === 71 /* Identifier */) { + if (node.expression.kind === 72 /* Identifier */) { resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); } return; @@ -79298,25 +81553,41 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { - var bundle = sourceFileOrBundle.kind === 278 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 277 /* SourceFile */ ? sourceFileOrBundle : undefined; + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } if (bundle) { - printer.writeBundle(bundle, writer, bundleInfo); + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); } else { - printer.writeFile(sourceFile, writer); + printer.writeFile(sourceFile, writer, sourceMapGenerator); } - writer.writeLine(); - var sourceMappingURL = mapRecorder.getSourceMappingURL(); - if (sourceMappingURL) { - writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } } - // Write the source map - if (sourceMapFilePath) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); + else { + writer.writeLine(); } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); @@ -79326,32 +81597,84 @@ var ts; ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); } // Reset state - mapRecorder.reset(); writer.clear(); bundleInfo = createDefaultBundleInfo(); } - function setSourceFile(node) { - sourceMap.setSourceFile(node); + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } - function setSourceFileForDeclarationSourceMaps(node) { - declarationSourceMap.setSourceFile(node); + function getSourceRoot(mapOptions) { + // 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 + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; } } ts.emitFiles = emitFiles; var PipelinePhase; (function (PipelinePhase) { PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; - PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; - PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; - PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); - var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); var currentSourceFile; var nodeIdToGeneratedName; // Map of generated names for specific nodes. var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. @@ -79361,19 +81684,23 @@ var ts; var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; - var ownWriter; + var ownWriter; // Reusable `EmitTextWriter` for basic printing. var write = writeBase; - var commitPendingSemicolon = ts.noop; - var writeSemicolon = writeSemicolonInternal; - var pendingSemicolon = false; - if (printerOptions.omitTrailingSemicolon) { - commitPendingSemicolon = commitPendingSemicolonInternal; - writeSemicolon = deferWriteSemicolon; - } - var syntheticParent = { pos: -1, end: -1 }; - var moduleKind = ts.getEmitModuleKind(printerOptions); - var bundledHelpers = ts.createMap(); var isOwnFileEmit; + // Source Maps + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + // Comments + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; reset(); return { // public API @@ -79400,9 +81727,9 @@ var ts; break; } switch (node.kind) { - case 277 /* SourceFile */: return printFile(node); - case 278 /* Bundle */: return printBundle(node); - case 279 /* UnparsedSource */: return printUnparsedSource(node); + case 279 /* SourceFile */: return printFile(node); + case 280 /* Bundle */: return printBundle(node); + case 281 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -79412,11 +81739,11 @@ var ts; return endPrint(); } function printBundle(bundle) { - writeBundle(bundle, beginPrint()); + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printFile(sourceFile) { - writeFile(sourceFile, beginPrint()); + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printUnparsedSource(unparsed) { @@ -79425,14 +81752,14 @@ var ts; } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(hint, node, sourceFile); reset(); writer = previousWriter; } function writeList(format, nodes, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); if (sourceFile) { setSourceFile(sourceFile); } @@ -79440,18 +81767,18 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output, bundleInfo) { + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { isOwnFileEmit = false; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { var prepend = _b[_a]; - print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); writeLine(); + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); } if (bundleInfo) { bundleInfo.originalOffset = writer.getTextPos(); @@ -79465,15 +81792,15 @@ var ts; } function writeUnparsedSource(unparsed, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); reset(); writer = previousWriter; } - function writeFile(sourceFile, output) { + function writeFile(sourceFile, output, sourceMapGenerator) { isOwnFileEmit = true; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(sourceFile); emitPrologueDirectivesIfNeeded(sourceFile); print(0 /* SourceFile */, sourceFile, sourceFile); @@ -79492,19 +81819,24 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - var pipelinePhase = getPipelinePhase(0 /* Notification */, hint); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; - comments.setSourceFile(sourceFile); - if (onSetSourceFile) { - onSetSourceFile(sourceFile); + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); } } - function setWriter(output) { - writer = output; // TODO: GH#18217 - comments.setWriter(output); + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; } function reset() { nodeIdToGeneratedName = []; @@ -79513,68 +81845,66 @@ var ts; tempFlagsStack = []; tempFlags = 0 /* Auto */; reservedNamesStack = []; - comments.reset(); - setWriter(/*output*/ undefined); + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } function emit(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(4 /* Unspecified */, node); } function emitIdentifierName(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(2 /* IdentifierName */, node); } function emitExpression(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(1 /* Expression */, node); } - function getPipelinePhase(phase, hint) { + function getPipelinePhase(phase, node) { switch (phase) { case 0 /* Notification */: - if (onEmitNode) { + if (onEmitNode !== ts.noEmitNotification) { return pipelineEmitWithNotification; } // falls through - case 1 /* Comments */: - if (emitNodeWithComments && hint !== 0 /* SourceFile */) { + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { return pipelineEmitWithComments; } - return pipelineEmitWithoutComments; - case 2 /* SourceMaps */: - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */) { + // falls through + case 3 /* SourceMaps */: + if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { return pipelineEmitWithSourceMap; } // falls through - case 3 /* Emit */: + case 4 /* Emit */: return pipelineEmitWithHint; default: - return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + return ts.Debug.assertNever(phase); } } - function getNextPipelinePhase(currentPhase, hint) { - return getPipelinePhase(currentPhase + 1, hint); + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); - } - function pipelineEmitWithComments(hint, node) { - ts.Debug.assertDefined(emitNodeWithComments); - ts.Debug.assert(hint !== 0 /* SourceFile */); - emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint)); - } - function pipelineEmitWithoutComments(hint, node) { - var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint); - pipelinePhase(hint, trySubstituteNode(hint, node)); - } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(hint !== 0 /* SourceFile */); - ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node); + onEmitNode(hint, node, pipelinePhase); } function pipelineEmitWithHint(hint, node) { if (hint === 0 /* SourceFile */) @@ -79583,254 +81913,285 @@ var ts; return emitIdentifier(ts.cast(node, ts.isIdentifier)); if (hint === 3 /* MappedTypeParameter */) return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } if (hint === 4 /* Unspecified */) { if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); switch (node.kind) { // Pseudo-literals - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: return emitLiteral(node); - case 279 /* UnparsedSource */: + case 281 /* UnparsedSource */: return emitUnparsedSource(node); // Identifiers - case 71 /* Identifier */: + case 72 /* Identifier */: return emitIdentifier(node); // Parse tree nodes // Names - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return emitQualifiedName(node); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return emitTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return emitParameter(node); - case 150 /* Decorator */: + case 152 /* Decorator */: return emitDecorator(node); // Type members - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return emitPropertySignature(node); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 153 /* MethodSignature */: + case 155 /* MethodSignature */: return emitMethodSignature(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return emitConstructor(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return emitAccessorDeclaration(node); - case 158 /* CallSignature */: + case 160 /* CallSignature */: return emitCallSignature(node); - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return emitConstructSignature(node); - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return emitIndexSignature(node); // Types - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return emitTypePredicate(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return emitTypeReference(node); - case 163 /* FunctionType */: + case 165 /* FunctionType */: return emitFunctionType(node); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return emitJSDocFunctionType(node); - case 164 /* ConstructorType */: + case 166 /* ConstructorType */: return emitConstructorType(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return emitTypeQuery(node); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return emitTypeLiteral(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return emitArrayType(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return emitTupleType(node); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return emitOptionalType(node); - case 171 /* UnionType */: + case 173 /* UnionType */: return emitUnionType(node); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return emitIntersectionType(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return emitConditionalType(node); - case 174 /* InferType */: + case 176 /* InferType */: return emitInferType(node); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return emitParenthesizedType(node); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 176 /* ThisType */: + case 178 /* ThisType */: return emitThisType(); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return emitTypeOperator(node); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return emitMappedType(node); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return emitLiteralType(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return emitImportTypeNode(node); - case 282 /* JSDocAllType */: - write("*"); + case 284 /* JSDocAllType */: + writePunctuation("*"); return; - case 283 /* JSDocUnknownType */: - write("?"); + case 285 /* JSDocUnknownType */: + writePunctuation("?"); return; - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return emitJSDocNullableType(node); - case 285 /* JSDocNonNullableType */: + case 287 /* JSDocNonNullableType */: return emitJSDocNonNullableType(node); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return emitJSDocOptionalType(node); - case 170 /* RestType */: - case 288 /* JSDocVariadicType */: + case 172 /* RestType */: + case 290 /* JSDocVariadicType */: return emitRestOrJSDocVariadicType(node); // Binding patterns - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return emitBindingElement(node); // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return emitTemplateSpan(node); - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 216 /* Block */: + case 218 /* Block */: return emitBlock(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return emitVariableStatement(node); - case 218 /* EmptyStatement */: - return emitEmptyStatement(); - case 219 /* ExpressionStatement */: + case 220 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 221 /* ExpressionStatement */: return emitExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return emitIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return emitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return emitWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return emitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return emitForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return emitForOfStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return emitContinueStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return emitBreakStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return emitReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return emitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return emitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return emitLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return emitThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return emitTryStatement(node); - case 234 /* DebuggerStatement */: + case 236 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return emitClassDeclaration(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return emitModuleBlock(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return emitCaseBlock(node); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return emitImportDeclaration(node); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return emitImportClause(node); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return emitNamespaceImport(node); - case 250 /* NamedImports */: + case 252 /* NamedImports */: return emitNamedImports(node); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return emitImportSpecifier(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return emitExportAssignment(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return emitExportDeclaration(node); - case 254 /* NamedExports */: + case 256 /* NamedExports */: return emitNamedExports(node); - case 255 /* ExportSpecifier */: + case 257 /* ExportSpecifier */: return emitExportSpecifier(node); - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return; // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) - case 10 /* JsxText */: + case 11 /* JsxText */: return emitJsxText(node); - case 260 /* JsxOpeningElement */: - case 263 /* JsxOpeningFragment */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 261 /* JsxClosingElement */: - case 264 /* JsxClosingFragment */: + case 263 /* JsxClosingElement */: + case 266 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return emitJsxAttribute(node); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return emitJsxAttributes(node); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: return emitCaseClause(node); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return emitDefaultClause(node); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return emitHeritageClause(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: return emitEnumMember(node); - // JSDoc nodes (ignored) + // JSDoc nodes (only used in codefixes currently) + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return emitJSDocSimpleTypedTag(node); + case 295 /* JSDocAugmentsTag */: + return emitJSDocAugmentsTag(node); + case 303 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 304 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 297 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 293 /* JSDocSignature */: + return emitJSDocSignature(node); + case 292 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 296 /* JSDocClassTag */: + case 294 /* JSDocTag */: + return emitJSDocSimpleTag(node); + case 291 /* JSDocComment */: + return emitJSDoc(node); // Transformation nodes (ignored) } if (ts.isExpression(node)) { hint = 1 /* Expression */; - node = trySubstituteNode(1 /* Expression */, node); + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } } else if (ts.isToken(node)) { return writeTokenNode(node, writePunctuation); @@ -79840,89 +82201,90 @@ var ts; switch (node.kind) { // Literals case 8 /* NumericLiteral */: - return emitNumericLiteral(node); - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return emitLiteral(node); // Identifiers - case 71 /* Identifier */: + case 72 /* Identifier */: return emitIdentifier(node); // Reserved words - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 101 /* TrueKeyword */: - case 99 /* ThisKeyword */: - case 91 /* ImportKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 102 /* TrueKeyword */: + case 100 /* ThisKeyword */: + case 92 /* ImportKeyword */: writeTokenNode(node, writeKeyword); return; // Expressions - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return emitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return emitNewExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return emitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return emitArrowFunction(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return emitDeleteExpression(node); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return emitVoidExpression(node); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return emitAwaitExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return emitBinaryExpression(node); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return emitConditionalExpression(node); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return emitTemplateExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return emitYieldExpression(node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return emitSpreadExpression(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return emitClassExpression(node); - case 208 /* OmittedExpression */: + case 210 /* OmittedExpression */: return; - case 210 /* AsExpression */: + case 212 /* AsExpression */: return emitAsExpression(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return emitNonNullExpression(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return emitMetaProperty(node); // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: return emitJsxElement(node); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return emitCommaList(node); } } @@ -79934,12 +82296,13 @@ var ts; writeSpace(); emit(node.constraint); } - function trySubstituteNode(hint, node) { - return node && substituteNode && substituteNode(hint, node) || node; + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); + pipelinePhase(hint, substituteNode(hint, node)); } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 278 /* Bundle */ ? node : undefined; + var bundle = node.kind === 280 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -79976,7 +82339,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79988,7 +82351,8 @@ var ts; // Literals/Pseudo-literals // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } // SyntaxKind.StringLiteral @@ -79998,9 +82362,9 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) - && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); } else { @@ -80018,7 +82382,7 @@ var ts; function emitIdentifier(node) { var writeText = node.symbol ? writeSymbol : write; writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); - emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments + emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names @@ -80029,7 +82393,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -80065,7 +82429,7 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 287 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { @@ -80087,7 +82451,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -80097,7 +82461,7 @@ var ts; emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); - writeSemicolon(); + writeTrailingSemicolon(); } function emitMethodSignature(node) { pushNameGenerationScope(node); @@ -80108,7 +82472,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -80127,7 +82491,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 156 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -80139,7 +82503,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -80151,7 +82515,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -80159,10 +82523,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // // Types @@ -80189,22 +82553,22 @@ var ts; popNameGenerationScope(node); } function emitJSDocFunctionType(node) { - write("function"); + writeKeyword("function"); emitParameters(node, node.parameters); - write(":"); + writePunctuation(":"); emit(node.type); } function emitJSDocNullableType(node) { - write("?"); + writePunctuation("?"); emit(node.type); } function emitJSDocNonNullableType(node) { - write("!"); + writePunctuation("!"); emit(node.type); } function emitJSDocOptionalType(node) { emit(node.type); - write("="); + writePunctuation("="); } function emitConstructorType(node) { pushNameGenerationScope(node); @@ -80225,8 +82589,8 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */; - emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); writePunctuation("}"); } function emitArrayType(node) { @@ -80235,23 +82599,23 @@ var ts; writePunctuation("]"); } function emitRestOrJSDocVariadicType(node) { - write("..."); + writePunctuation("..."); emit(node.type); } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 272 /* TupleTypeElements */); + emitList(node, node.elementTypes, 528 /* TupleTypeElements */); writePunctuation("]"); } function emitOptionalType(node) { emit(node.type); - write("?"); + writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 260 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */); } function emitIntersectionType(node) { - emitList(node, node.types, 264 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */); } function emitConditionalType(node) { emit(node.checkType); @@ -80304,25 +82668,25 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) { + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { writeKeyword("readonly"); } writeSpace(); } writePunctuation("["); - var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter); pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); - if (node.questionToken.kind !== 55 /* QuestionToken */) { + if (node.questionToken.kind !== 56 /* QuestionToken */) { writePunctuation("?"); } } writePunctuation(":"); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); if (emitFlags & 1 /* SingleLine */) { writeSpace(); } @@ -80355,12 +82719,12 @@ var ts; // function emitObjectBindingPattern(node) { writePunctuation("{"); - emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); writePunctuation("}"); } function emitArrayBindingPattern(node) { writePunctuation("["); - emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); writePunctuation("]"); } function emitBindingElement(node) { @@ -80378,8 +82742,8 @@ var ts; // function emitArrayLiteralExpression(node) { var elements = node.elements; - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -80387,9 +82751,9 @@ var ts; if (indentedFlag) { increaseIndent(); } - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */; - emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); } @@ -80400,20 +82764,20 @@ var ts; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = ts.createToken(23 /* DotToken */); + var dotToken = ts.createToken(24 /* DotToken */); dotToken.pos = dotRangeStart; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); - increaseIndentIf(indentBeforeDot); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); if (shouldEmitDotDot) { writePunctuation("."); } - emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node); - increaseIndentIf(indentAfterDot); + emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); } @@ -80423,9 +82787,9 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); + && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -80438,21 +82802,21 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); } function emitNewExpression(node) { - emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); @@ -80467,9 +82831,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node); + var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { generateNameIfNeeded(node.name); @@ -80488,22 +82852,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -80528,24 +82892,24 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 200 /* PrefixUnaryExpression */ - && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) - || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); + return operand.kind === 202 /* PrefixUnaryExpression */ + && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */)) + || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; + var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); - increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + increaseIndentIf(indentBeforeOperator, isCommaOperator); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, writeOperator); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - increaseIndentIf(indentAfterOperator, " "); + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); } @@ -80555,28 +82919,28 @@ var ts; var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); - increaseIndentIf(indentBeforeQuestion, " "); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); - increaseIndentIf(indentAfterQuestion, " "); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); - increaseIndentIf(indentBeforeColon, " "); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); - increaseIndentIf(indentAfterColon, " "); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); } function emitTemplateExpression(node) { emit(node.head); - emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - writePunctuation("..."); + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); emitExpression(node.expression); } function emitClassExpression(node) { @@ -80619,36 +82983,45 @@ var ts; emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); } function emitBlockStatements(node, forceSingleLine) { - emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); - var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; emitList(node, node.statements, format); - emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); + emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - writeSemicolon(); + writeTrailingSemicolon(); } - function emitEmptyStatement() { - writeSemicolon(); + function emitEmptyStatement(isEmbeddedStatement) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { - writeSemicolon(); + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); } } function emitIfStatement(node) { - var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 220 /* IfStatement */) { + emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -80658,14 +83031,14 @@ var ts; } } function emitWhileClause(node, startPos) { - var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node); + var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { - emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -80681,45 +83054,45 @@ var ts; emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.condition); - pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.incrementor); - emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(145 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 236 /* VariableDeclarationList */) { + if (node.kind === 238 /* VariableDeclarationList */) { emit(node); } else { @@ -80728,14 +83101,14 @@ var ts; } } function emitContinueStatement(node) { - emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitBreakStatement(node) { - emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { var node = ts.getParseTreeNode(contextNode); @@ -80761,40 +83134,40 @@ var ts; return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitWithStatement(node) { - var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node); + emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTryStatement(node) { - emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -80803,14 +83176,14 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); - writeSemicolon(); + writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); } // // Declarations @@ -80823,7 +83196,7 @@ var ts; function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); writeSpace(); - emitList(node, node.declarations, 272 /* VariableDeclarationList */); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { emitFunctionDeclarationOrExpression(node); @@ -80871,7 +83244,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -80923,7 +83296,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -80935,7 +83308,7 @@ var ts; emitHelpers(body); if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { decreaseIndent(); - emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); increaseIndent(); } else { @@ -80962,7 +83335,7 @@ var ts; emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65 /* ClassMembers */); + emitList(node, node.members, 129 /* ClassMembers */); writePunctuation("}"); if (indentedFlag) { decreaseIndent(); @@ -80975,10 +83348,10 @@ var ts; writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256 /* HeritageClauses */); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65 /* InterfaceMembers */); + emitList(node, node.members, 129 /* InterfaceMembers */); writePunctuation("}"); } function emitTypeAliasDeclaration(node) { @@ -80992,7 +83365,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -81001,7 +83374,7 @@ var ts; emit(node.name); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 81 /* EnumMembers */); + emitList(node, node.members, 145 /* EnumMembers */); writePunctuation("}"); } function emitModuleDeclaration(node) { @@ -81013,8 +83386,8 @@ var ts; emit(node.name); var body = node.body; if (!body) - return writeSemicolon(); - while (body.kind === 242 /* ModuleDeclaration */) { + return writeTrailingSemicolon(); + while (body.kind === 244 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); body = body.body; @@ -81029,23 +83402,23 @@ var ts; popNameGenerationScope(node); } function emitCaseBlock(node) { - emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node); - emitList(node, node.clauses, 65 /* CaseBlockClauses */); - emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node); + emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); - writeSemicolon(); + writeTrailingSemicolon(); } function emitModuleReference(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81054,29 +83427,29 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - emitTokenWithComment(143 /* FromKeyword */, node.importClause.end, writeKeyword, node); + emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); - writeSemicolon(); + writeTrailingSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); + var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node); writeSpace(); - emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node); + emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -81087,45 +83460,45 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node); + emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node); } else { - emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node); + emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitExportDeclaration(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node); + nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); var fromPos = node.exportClause ? node.exportClause.end : nextPos; - emitTokenWithComment(143 /* FromKeyword */, fromPos, writeKeyword, node); + emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamespaceExportDeclaration(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node); writeSpace(); emit(node.name); - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -81135,14 +83508,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -81161,7 +83534,7 @@ var ts; // function emitJsxElement(node) { emit(node.openingElement); - emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); emit(node.closingElement); } function emitJsxSelfClosingElement(node) { @@ -81173,7 +83546,7 @@ var ts; } function emitJsxFragment(node) { emit(node.openingFragment); - emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { @@ -81188,7 +83561,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { @@ -81199,7 +83571,7 @@ var ts; writePunctuation(">"); } function emitJsxAttributes(node) { - emitList(node, node.properties, 131328 /* JsxElementAttributes */); + emitList(node, node.properties, 262656 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); @@ -81219,7 +83591,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81230,13 +83602,13 @@ var ts; // Clauses // function emitCaseClause(node) { - emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node); + var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node); emitCaseOrDefaultClauseRest(node, node.statements, pos); } function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { @@ -81246,14 +83618,14 @@ var ts; ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); - var format = 81985 /* CaseOrDefaultClauseStatements */; + var format = 163969 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode); writeSpace(); - format &= ~(1 /* MultiLine */ | 64 /* Indented */); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); } else { - emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode); } emitList(parentNode, statements, format); } @@ -81261,15 +83633,15 @@ var ts; writeSpace(); writeTokenText(node.token, writeKeyword); writeSpace(); - emitList(node, node.types, 272 /* HeritageClauseTypes */); + emitList(node, node.types, 528 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -81306,7 +83678,7 @@ var ts; } function emitSpreadAssignment(node) { if (node.expression) { - writePunctuation("..."); + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); emitExpression(node.expression); } } @@ -81318,6 +83690,142 @@ var ts; emitInitializer(node.initializer, node.name.end, node); } // + // JSDoc + // + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // // Top-level nodes // function emitSourceFile(node) { @@ -81337,41 +83845,46 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.moduleName) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.amdDependencies) { for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { var dep = _b[_a]; if (dep.name) { - write("/// "); + writeComment("/// "); } else { - write("/// "); + writeComment("/// "); } writeLine(); } } for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { var directive = files_1[_c]; - write("/// "); + writeComment("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; - write("/// "); + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); writeLine(); } } @@ -81390,7 +83903,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 272 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -81430,13 +83943,14 @@ var ts; setSourceFile(sourceFile); emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); } + setSourceFile(undefined); } } function emitShebangIfNeeded(sourceFileOrBundle) { if (ts.isSourceFile(sourceFileOrBundle)) { var shebang = ts.getShebang(sourceFileOrBundle.text); if (shebang) { - write(shebang); + writeComment(shebang); writeLine(); return true; } @@ -81464,7 +83978,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328 /* Modifiers */); + emitList(node, modifiers, 262656 /* Modifiers */); writeSpace(); } } @@ -81478,7 +83992,7 @@ var ts; function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -81515,30 +84029,37 @@ var ts; else { writeLine(); increaseIndent(); - emit(node); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(5 /* EmbeddedStatement */, node); + } + else { + emit(node); + } decreaseIndent(); } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 24577 /* Decorators */); + emitList(parentNode, decorators, 49153 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26896 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures return emitTypeArguments(parentNode, parentNode.typeArguments); } - emitList(parentNode, typeParameters, 26896 /* TypeParameters */); + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1296 /* Parameters */); + emitList(parentNode, parameters, 2576 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81552,14 +84073,14 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); } else { emitParameters(parentNode, parameters); } } function emitParametersForIndexSignature(parentNode, parameters) { - emitList(parentNode, parameters, 4432 /* IndexSignatureParameters */); + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } function emitList(parentNode, children, format, start, count) { emitNodeList(emit, parentNode, children, format, start, count); @@ -81568,7 +84089,7 @@ var ts; emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 } function writeDelimiter(format) { - switch (format & 28 /* DelimitersMask */) { + switch (format & 60 /* DelimitersMask */) { case 0 /* None */: break; case 16 /* CommaDelimited */: @@ -81578,6 +84099,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8 /* AmpersandDelimited */: writeSpace(); writePunctuation("&"); @@ -81588,11 +84114,11 @@ var ts; if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; - if (isUndefined && format & 8192 /* OptionalIfUndefined */) { + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { return; } var isEmpty = children === undefined || start >= children.length || count === 0; - if (isEmpty && format & 16384 /* OptionalIfEmpty */) { + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); } @@ -81601,7 +84127,7 @@ var ts; } return; } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { // TODO: GH#18217 @@ -81616,23 +84142,23 @@ var ts; if (format & 1 /* MultiLine */) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { + else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { writeSpace(); } } else { // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; + var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 writeLine(); shouldEmitInterveningComments = false; } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 256 /* SpaceBetweenBraces */) { writeSpace(); } // Increase the indent, if requested. - if (format & 64 /* Indented */) { + if (format & 128 /* Indented */) { increaseIndent(); } // Emit each child. @@ -81641,14 +84167,19 @@ var ts; for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. - if (previousSibling) { + if (format & 32 /* AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { // i.e // function commentedParameters( // /* Parameter a */ // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -81656,14 +84187,14 @@ var ts; if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new // line, we should increase the indent. - if ((format & (3 /* LinesMask */ | 64 /* Indented */)) === 0 /* SingleLine */) { + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { increaseIndent(); shouldDecreaseIndentAfterEmit = true; } writeLine(); shouldEmitInterveningComments = false; } - else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { + else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { writeSpace(); } } @@ -81685,7 +84216,7 @@ var ts; previousSibling = child; } // Write a trailing comma, if requested. - var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; + var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { writePunctuation(","); } @@ -81695,25 +84226,25 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. - if (format & 64 /* Indented */) { + if (format & 128 /* Indented */) { decreaseIndent(); } // Write the closing line terminator or closing whitespace. if (shouldWriteClosingLineTerminator(parentNode, children, format)) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 256 /* SpaceBetweenBraces */) { writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { if (isEmpty && !isUndefined) { // TODO: GH#18217 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists @@ -81721,73 +84252,55 @@ var ts; writePunctuation(getClosingBracket(format)); } } - function commitPendingSemicolonInternal() { - if (pendingSemicolon) { - writeSemicolonInternal(); - pendingSemicolon = false; - } - } + // Writers function writeLiteral(s) { - commitPendingSemicolon(); writer.writeLiteral(s); } function writeStringLiteral(s) { - commitPendingSemicolon(); writer.writeStringLiteral(s); } function writeBase(s) { - commitPendingSemicolon(); writer.write(s); } function writeSymbol(s, sym) { - commitPendingSemicolon(); writer.writeSymbol(s, sym); } function writePunctuation(s) { - commitPendingSemicolon(); writer.writePunctuation(s); } - function deferWriteSemicolon() { - pendingSemicolon = true; - } - function writeSemicolonInternal() { - writer.writePunctuation(";"); + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); } function writeKeyword(s) { - commitPendingSemicolon(); writer.writeKeyword(s); } function writeOperator(s) { - commitPendingSemicolon(); writer.writeOperator(s); } function writeParameter(s) { - commitPendingSemicolon(); writer.writeParameter(s); } + function writeComment(s) { + writer.writeComment(s); + } function writeSpace() { - commitPendingSemicolon(); writer.writeSpace(" "); } function writeProperty(s) { - commitPendingSemicolon(); writer.writeProperty(s); } function writeLine() { - commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { - commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { - commitPendingSemicolon(); writer.decreaseIndent(); } function writeToken(token, pos, writer, contextNode) { - return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) : writeTokenText(token, writer, pos); } function writeTokenNode(node, writer) { @@ -81815,23 +84328,23 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = ts.guessIndentation(lines); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var lineText = lines_2[_a]; + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); - writeLine(); + writer.rawWrite(newLine); } } } - function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + function increaseIndentIf(value, writeSpaceIfNotIndenting) { if (value) { increaseIndent(); writeLine(); } - else if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); + else if (writeSpaceIfNotIndenting) { + writeSpace(); } } // Helper function to decrease the indent if we previously indented. Allows multiple @@ -81851,7 +84364,7 @@ var ts; return true; } if (format & 2 /* PreserveLines */) { - if (format & 32768 /* PreferNewLine */) { + if (format & 65536 /* PreferNewLine */) { return true; } var firstChild = children[0]; @@ -81890,10 +84403,10 @@ var ts; } function shouldWriteClosingLineTerminator(parentNode, children, format) { if (format & 1 /* MultiLine */) { - return (format & 65536 /* NoTrailingNewLine */) === 0; + return (format & 131072 /* NoTrailingNewLine */) === 0; } else if (format & 2 /* PreserveLines */) { - if (format & 32768 /* PreferNewLine */) { + if (format & 65536 /* PreferNewLine */) { return true; } var lastChild = ts.lastOrUndefined(children); @@ -81915,11 +84428,11 @@ var ts; if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { - return (format & 32768 /* PreferNewLine */) !== 0; + return (format & 65536 /* PreferNewLine */) !== 0; } return startsOnNewLine; } - return (format & 32768 /* PreferNewLine */) !== 0; + return (format & 65536 /* PreferNewLine */) !== 0; } function needsIndentation(parent, node1, node2) { parent = skipSynthesizedParentheses(parent); @@ -81939,7 +84452,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -81951,7 +84464,7 @@ var ts; else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } - else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); } else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { @@ -81959,19 +84472,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { - if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82004,81 +84517,81 @@ var ts; if (!node) return; switch (node.kind) { - case 216 /* Block */: + case 218 /* Block */: ts.forEach(node.statements, generateNames); break; - case 231 /* LabeledStatement */: - case 229 /* WithStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 233 /* LabeledStatement */: + case 231 /* WithStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: generateNames(node.statement); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 272 /* CatchClause */: + case 274 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: generateNames(node.declarationList); break; - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: generateNames(node.importClause); break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -82087,12 +84600,12 @@ var ts; if (!node) return; switch (node.kind) { - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: generateNameIfNeeded(node.name); break; } @@ -82150,7 +84663,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82229,7 +84742,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82272,23 +84785,23 @@ var ts; */ function generateNameForNode(node, flags) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 252 /* ExportAssignment */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 254 /* ExportAssignment */: return generateNameForExportDefault(); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return generateNameForClassExpression(); - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0 /* Auto */); @@ -82329,21 +84842,396 @@ var ts; // otherwise, return the original node for the source; return node; } + // Comments + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 238 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + // Source Maps + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, + /*nameIndex*/ undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } } ts.createPrinter = createPrinter; function createBracketsMap() { var brackets = []; - brackets[512 /* Braces */] = ["{", "}"]; - brackets[1024 /* Parenthesis */] = ["(", ")"]; - brackets[2048 /* AngleBrackets */] = ["<", ">"]; - brackets[4096 /* SquareBrackets */] = ["[", "]"]; + brackets[1024 /* Braces */] = ["{", "}"]; + brackets[2048 /* Parenthesis */] = ["(", ")"]; + brackets[4096 /* AngleBrackets */] = ["<", ">"]; + brackets[8192 /* SquareBrackets */] = ["[", "]"]; return brackets; } function getOpeningBracket(format) { - return brackets[format & 7680 /* BracketsMask */][0]; + return brackets[format & 15360 /* BracketsMask */][0]; } function getClosingBracket(format) { - return brackets[format & 7680 /* BracketsMask */][1]; + return brackets[format & 15360 /* BracketsMask */][1]; } // Flags enum to track count of temp variables and a few dedicated names var TempFlags; @@ -82743,17 +85631,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82769,7 +85664,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82779,7 +85674,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82787,8 +85682,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82799,8 +85694,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82811,11 +85706,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82827,36 +85722,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(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); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82864,8 +85756,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82891,7 +85783,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82979,8 +85871,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82995,11 +85887,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83034,7 +85926,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -83047,7 +85939,7 @@ var ts; result = cache.get(name); } else { - cache.set(name, result = loader(name, containingFile)); + cache.set(name, result = loader(name, containingFile, redirectedReference)); } resolutions.push(result); } @@ -83057,7 +85949,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83066,6 +85958,11 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + var seenResolvedRefs; + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83086,9 +85983,39 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || + return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolution(sourceFile.path); } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + // If child project references are upto date, this project reference is uptodate + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { @@ -83097,21 +86024,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83134,7 +86057,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var modifiedFilePaths; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -83162,16 +86085,15 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; - var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; @@ -83183,16 +86105,16 @@ var ts; } else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217 - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; } else { - var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217 - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). @@ -83208,30 +86130,34 @@ var ts; // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files - var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; if (projectReferences) { - for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { - var ref = projectReferences_1[_i]; - var parsedRef = parseProjectReferenceConfigFile(ref); - resolvedProjectReferences.push(parsedRef); - if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); - processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); } } } ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); @@ -83245,7 +86171,7 @@ var ts; // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. - if (!skipDefaultLib) { + if (rootNames.length && !skipDefaultLib) { // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file var defaultLibraryFileName = getDefaultLibraryFileName(); @@ -83270,10 +86196,18 @@ var ts; var oldSourceFiles = oldProgram.getSourceFiles(); for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { var oldSourceFile = oldSourceFiles_1[_a]; - if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { - host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); } // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; @@ -83312,7 +86246,12 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83346,9 +86285,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83375,13 +86314,13 @@ var ts; } return classifiableNames; } - function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, // the best we can do is fallback to the default logic. - return resolveModuleNamesWorker(moduleNames, containingFile); + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); } - var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { // `file` was created for the new program. // @@ -83391,13 +86330,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83444,7 +86383,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -83455,7 +86394,7 @@ var ts; } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) : ts.emptyArray; // Combine results of resolutions and predicted results if (!result) { @@ -83481,9 +86420,9 @@ var ts; return result; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83491,24 +86430,35 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); - if (!firstUnmodifiedFile) { + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { return false; } if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); } return true; } } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + // If array of references is changed, we cant resue old program + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return 0 /* Not */; @@ -83529,36 +86479,14 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); - if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } - for (var i = 0; i < projectReferences.length; i++) { - var oldRef = oldRefs[i]; - if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); - if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { - // Resolved project reference has gone missing or changed - return oldProgram.structureIsReused = 0 /* Not */; - } - } - else { - // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { - return oldProgram.structureIsReused = 0 /* Not */; - } - } - } + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0 /* Not */; } - else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; - var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2 /* Completely */; // If the missing file paths are now present, it can change the progam structure, @@ -83577,7 +86505,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83604,8 +86532,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; - filePaths.push(newSourceFile.path); + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { // If there are 2 different source files for the same package name and at least one of them changes, @@ -83666,15 +86597,23 @@ var ts; if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } - modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } // try to verify results of module resolution - for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { - var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { @@ -83686,8 +86625,9 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -83707,28 +86647,29 @@ var ts; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping - for (var i = 0; i < newSourceFiles.length; i++) { - filesByName.set(filePaths[i], newSourceFiles[i]); + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); // Set the file as found during node modules search if it was found that way in old progra, - if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { - sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { - var modifiedFile = modifiedSourceFiles_2[_c]; + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83739,11 +86680,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83753,12 +86695,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83815,7 +86758,7 @@ var ts; // get any preEmit diagnostics, not just the ones 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) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83881,9 +86824,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83972,7 +86915,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -83982,22 +86925,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } // falls through - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 235 /* VariableDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 237 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -84005,41 +86948,41 @@ var ts; } } switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: var heritageClause = node; - if (heritageClause.token === 108 /* ImplementsKeyword */) { + if (heritageClause.token === 109 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 210 /* AsExpression */: + case 212 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; @@ -84052,51 +86995,51 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, 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)); } switch (parent.kind) { - case 238 /* ClassDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 240 /* ClassDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } // falls through - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 217 /* VariableStatement */); + return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */); } break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 115 /* StaticKeyword */) { + if (modifier.kind !== 116 /* StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } return; } break; - case 149 /* Parameter */: + case 151 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 209 /* ExpressionWithTypeArguments */: - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -84113,24 +87056,24 @@ var ts; for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { var modifier = modifiers_1[_i]; switch (modifier.kind) { - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: if (isConstValid) { continue; } // to report error, // falls through - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 124 /* DeclareKeyword */: - case 117 /* AbstractKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 125 /* DeclareKeyword */: + case 118 /* AbstractKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. - case 115 /* StaticKeyword */: - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 116 /* StaticKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: } } } @@ -84178,10 +87121,22 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; } function getGlobalDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; } function getConfigFileParsingDiagnostics() { return configFileParsingDiagnostics || ts.emptyArray; @@ -84193,15 +87148,15 @@ var ts; return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 71 /* Identifier */ - ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText - : b.kind === 9 /* StringLiteral */ && a.text === b.text; + return a.kind === 72 /* Identifier */ + ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 10 /* StringLiteral */ && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84223,12 +87178,9 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, /*inAmbientModule*/ false); - if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(node); - } } if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(file.endOfFileToken); + collectDynamicImportOrRequireCalls(file); } file.imports = imports || ts.emptyArray; file.moduleAugmentations = moduleAugmentations || ts.emptyArray; @@ -84276,24 +87228,37 @@ var ts; } } } - function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { - imports = ts.append(imports, node.arguments[0]); - } - // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. - else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { - imports = ts.append(imports, node.arguments[0]); - } - else if (ts.isLiteralImportTypeNode(node)) { - imports = ts.append(imports, node.argument.literal); - } - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } } } - function collectDynamicImportOrRequireCallsForEachChild(node) { - ts.forEachChild(node, collectDynamicImportOrRequireCalls); + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } } } function getLibFileFromReference(ref) { @@ -84309,7 +87274,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84365,11 +87330,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84384,6 +87352,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84449,9 +87418,9 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); - filesByName.set(path, dupFile); + addFileToFilesByName(dupFile, path, redirectedPath); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); return dupFile; @@ -84462,14 +87431,12 @@ var ts; sourceFileToPackageName.set(path, packageId.name); } } - filesByName.set(path, file); - if (redirectedPath) { - filesByName.set(redirectedPath, file); - } + addFileToFilesByName(file, path, redirectedPath); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84498,25 +87465,90 @@ var ts; } return file; } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { - return undefined; - } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); }); - return result; + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + // Visit project references first + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84526,7 +87558,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84544,6 +87576,8 @@ var ts; } var saveResolution = true; if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 @@ -84568,6 +87602,8 @@ var ts; processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; } else { fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 @@ -84612,8 +87648,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84622,7 +87657,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84642,7 +87677,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84662,61 +87697,61 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } return allFilesBelongToPath; } function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); return undefined; } - sourceFile.path = toPath(refPath); + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); - return { commandLine: commandLine, sourceFile: sourceFile }; - } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84744,41 +87779,18 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); } } - if (projectReferences) { - for (var i = 0; i < projectReferences.length; i++) { - var ref = projectReferences[i]; - var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; - if (resolvedRefOpts === undefined) { - createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); - continue; - } - if (!resolvedRefOpts.composite) { - createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - } - if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); - } - } - else { - createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); - } - } - } - } + verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84828,15 +87840,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84846,12 +87858,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -84863,7 +87875,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84876,9 +87888,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84889,19 +87901,19 @@ var ts; // 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; })) { + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -84959,6 +87971,35 @@ var ts; } } } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { var needCompilerDiagnostic = true; var pathsSyntax = getOptionPathsSyntax(); @@ -85009,10 +88050,10 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } - function createDiagnosticForReference(index, message, arg0, arg1) { - var referencesSyntax = getProjectReferencesSyntax(); + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); if (referencesSyntax && referencesSyntax.elements.length > index) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); } else { programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); @@ -85026,22 +88067,6 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } - function getProjectReferencesSyntax() { - if (_referencesArrayLiteralSyntax === undefined) { - _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile) { - var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217 - for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { - var prop = _a[_i]; - if (ts.isArrayLiteralExpression(prop.initializer)) { - _referencesArrayLiteralSyntax = prop.initializer; - break; - } - } - } - } - return _referencesArrayLiteralSyntax; - } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword @@ -85092,7 +88117,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85109,25 +88134,26 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85166,7 +88192,7 @@ var ts; var res = imports.map(function (i) { return i.text; }); for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9 /* StringLiteral */) { + if (aug.kind === 10 /* StringLiteral */) { res.push(aug.text); } // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. @@ -85197,7 +88223,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85207,6 +88233,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85230,7 +88262,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85241,11 +88273,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85351,6 +88417,11 @@ var ts; var latestSignature; if (sourceFile.isDeclarationFile) { latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } } else { var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); @@ -85416,7 +88487,7 @@ var ts; return getAllFileNames(state, programOfThisState); } // If this is non module emit, or its a global file, it depends on all the source files - if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { return getAllFileNames(state, programOfThisState); } // Get the references, traversing deep from the referenceMap @@ -85475,6 +88546,20 @@ var ts; } return true; } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } /** * Gets all files of the program excluding the default library file */ @@ -85515,7 +88600,7 @@ var ts; * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { - if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } var compilerOptions = programOfThisState.getCompilerOptions(); @@ -85565,8 +88650,9 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && - !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { @@ -85581,6 +88667,8 @@ var ts; // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -85598,6 +88686,13 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } // Unchanged file copy diagnostics var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { @@ -85681,18 +88776,31 @@ var ts; // If there are no more diagnostics from old cache, done return; } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } // If there was change in signature for the changed file, // then delete the semantic diagnostics for files that are affected by using exports of this module if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { return; } ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { return exportedModules && exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); })) { return; } @@ -85700,16 +88808,44 @@ var ts; ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); }); } /** * removes the semantic diagnostics of files referencing referencedPath and * returns true if there are no more semantic diagnostics from old state */ - function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { - return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); }); } /** @@ -85718,7 +88854,7 @@ var ts; */ function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -85765,7 +88901,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85778,7 +88914,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85952,16 +89095,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -85984,6 +89127,10 @@ var ts; /*@internal*/ var ts; (function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; ts.maxNumberOfFilesToIterateForInvalidation = 256; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; @@ -85997,11 +89144,11 @@ var ts; // The key in the map is source file's path. // The values are Map of resolutions with key being name lookedup. var resolvedModuleNames = ts.createMap(); - var perDirectoryResolvedModuleNames = ts.createMap(); - var nonRelaticeModuleNameCache = ts.createMap(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); var resolvedTypeReferenceDirectives = ts.createMap(); - var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -86025,6 +89172,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -86086,7 +89234,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -86102,15 +89250,15 @@ var ts; } }); } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { return primaryResult; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86121,10 +89269,11 @@ var ts; // Default return the result from the first pass return primaryResult; } - function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { var path = resolutionHost.toPath(containingFile); var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); var perDirectoryResolution = perDirectoryCache.get(dirPath); if (!perDirectoryResolution) { perDirectoryResolution = ts.createMap(); @@ -86133,22 +89282,28 @@ var ts; var resolvedModules = []; var compilerOptions = resolutionHost.getCompilationSettings(); var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; var seenNamesInFile = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { var name = names_2[_i]; var resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { var existingResolution = resolution; var resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { resolution = resolutionInDirectory; } else { - resolution = loader(name, containingFile, compilerOptions, resolutionHost); + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); @@ -86164,7 +89319,7 @@ var ts; } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217 + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); } // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { @@ -86192,12 +89347,14 @@ var ts; return oldResult.resolvedFileName === newResult.resolvedFileName; } } - function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { - return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, /*reusedNames*/ undefined, /*logChanges*/ false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); } function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); @@ -86240,15 +89397,10 @@ var ts; } return true; } - function filterFSRootDirectoriesToWatch(watchPath, dirPath) { - if (!canWatchDirectory(dirPath)) { - watchPath.ignore = true; - } - return watchPath; - } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86264,13 +89416,13 @@ var ts; } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // If directory path contains node module, get the most parent node_modules directory for watching - while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { + while (ts.pathContainsNodeModules(dirPath)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } // If the directory is node_modules use it to watch, always watch it recursively if (isNodeModulesDirectory(dirPath)) { - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -86288,7 +89440,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive }, dirPath); + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -86317,8 +89469,9 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, nonRecursive = _a.nonRecursive, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; // If the failed lookup location path is not one of the supported extensions, // store it in the custom path if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { @@ -86371,8 +89524,9 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { if (refCount === 1) { @@ -86420,6 +89574,22 @@ var ts; cache.delete(filePath); } } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + // If this file is input file for the referenced project, get it + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } function removeResolutionsOfFile(filePath) { removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); @@ -86481,6 +89651,9 @@ var ts; isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; } else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; // Some file or directory in the watching directory is created // Return early if it does not have any of the watching extension or not the custom failed lookup path var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); @@ -86521,8 +89694,8 @@ var ts; if (isInDirectoryPath(rootPath, typeRootPath)) { return rootPath; } - var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info @@ -86588,121 +89761,118 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86766,16 +89936,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86793,7 +89953,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86813,25 +89974,30 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86840,20 +90006,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86868,12 +90032,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86936,13 +90102,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86981,11 +90170,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86994,13 +90178,12 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } return false; } - /** @internal */ ts.screenStartingMessageCodes = [ ts.Diagnostics.Starting_compilation_in_watch_mode.code, ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, @@ -87041,10 +90224,27 @@ var ts; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87060,7 +90260,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87079,7 +90279,7 @@ var ts; } } if (reportSummary) { - reportSummary(diagnostics.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length); + reportSummary(getErrorCountForSummary(diagnostics)); } if (emitSkipped && diagnostics.length > 0) { // If the emitter didn't emit anything, then pass that value along. @@ -87094,6 +90294,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87106,7 +90325,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87120,17 +90339,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87146,15 +90358,7 @@ var ts; function emitFilesAndReportErrorUsingBuilder(builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - var reportSummary = function (errorCount) { - if (errorCount === 1) { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions); - } - else { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions); - } - }; - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); } } /** @@ -87179,18 +90383,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87213,9 +90418,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87228,7 +90434,8 @@ var ts; fileExists: function (path) { return host.fileExists(path); }, readFile: readFile, getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); @@ -87286,7 +90493,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87295,11 +90503,11 @@ var ts; /*logChangesWhenResolvingModule*/ false); // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names compilerHost.resolveModuleNames = host.resolveModuleNames ? - (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : - (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? - (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : - (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; synchronizeProgram(); // Update the wild card directory watch @@ -87324,9 +90532,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87351,7 +90559,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87473,8 +90681,8 @@ var ts; var hostSourceFile = sourceFilesCache.get(path); return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); } - function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { - var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); // If this is the source file thats in the cache and new program doesnt need it, // remove the cached entry. // Note we arent deleting entry if file became missing in new program or @@ -87488,8 +90696,10 @@ var ts; if (hostSourceFileInfo.fileWatcher) { hostSourceFileInfo.fileWatcher.close(); } - sourceFilesCache.delete(oldSourceFile.path); - resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } } } } @@ -87532,12 +90742,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87563,7 +90768,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87572,6 +90779,7 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { resolutionCache.invalidateResolutionOfFile(path); } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program scheduleProgramUpdate(); @@ -87612,6 +90820,8 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { @@ -87650,6 +90860,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87670,7 +90882,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87687,94 +90900,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87787,7 +90971,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87798,13 +90986,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87815,808 +91007,827 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects - }; - } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } - } - ts.performBuild = performBuild; /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88652,7 +91863,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88660,6 +91873,144 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.js.map "use strict"; var __assign = (this && this.__assign) || function () { @@ -88679,7 +92030,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -88716,12 +92067,6 @@ var ts; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); /* @internal */ ts.emptyOptions = {}; - var TextChange = /** @class */ (function () { - function TextChange() { - } - return TextChange; - }()); - ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { HighlightSpanKind["none"] = "none"; @@ -88735,6 +92080,32 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + function getDefaultFormatCodeSettings(newLineCharacter) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: newLineCharacter || "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + /* @internal */ + ts.testFormatSettings = getDefaultFormatCodeSettings("\n"); var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -88796,8 +92167,9 @@ var ts; TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; - TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; - TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; + TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral"; + TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral"; })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); var ScriptElementKind; (function (ScriptElementKind) { @@ -88880,6 +92252,12 @@ var ts; ScriptElementKindModifier["staticModifier"] = "static"; ScriptElementKindModifier["abstractModifier"] = "abstract"; ScriptElementKindModifier["optionalModifier"] = "optional"; + ScriptElementKindModifier["dtsModifier"] = ".d.ts"; + ScriptElementKindModifier["tsModifier"] = ".ts"; + ScriptElementKindModifier["tsxModifier"] = ".tsx"; + ScriptElementKindModifier["jsModifier"] = ".js"; + ScriptElementKindModifier["jsxModifier"] = ".jsx"; + ScriptElementKindModifier["jsonModifier"] = ".json"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); var ClassificationTypeNames; (function (ClassificationTypeNames) { @@ -88887,6 +92265,7 @@ var ts; ClassificationTypeNames["identifier"] = "identifier"; ClassificationTypeNames["keyword"] = "keyword"; ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["bigintLiteral"] = "bigint"; ClassificationTypeNames["operator"] = "operator"; ClassificationTypeNames["stringLiteral"] = "string"; ClassificationTypeNames["whiteSpace"] = "whitespace"; @@ -88933,6 +92312,7 @@ var ts; ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral"; })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); })(ts || (ts = {})); // These utilities are common to multiple language service features. @@ -88950,36 +92330,37 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 272 /* CatchClause */: - case 265 /* JsxAttribute */: + case 237 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 274 /* CatchClause */: + case 267 /* JsxAttribute */: return 1 /* Value */; - case 148 /* TypeParameter */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 166 /* TypeLiteral */: + case 150 /* TypeParameter */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 168 /* TypeLiteral */: return 2 /* Type */; - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 276 /* EnumMember */: - case 238 /* ClassDeclaration */: + case 278 /* EnumMember */: + case 240 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -88989,26 +92370,26 @@ var ts; else { return 4 /* Namespace */; } - case 241 /* EnumDeclaration */: - case 250 /* NamedImports */: - case 251 /* ImportSpecifier */: - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: - case 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 243 /* EnumDeclaration */: + case 252 /* NamedImports */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89040,11 +92421,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 146 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 246 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + var name = node.kind === 148 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 248 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 146 /* QualifiedName */) { + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -89056,27 +92437,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 146 /* QualifiedName */) { - while (root.parent && root.parent.kind === 146 /* QualifiedName */) { + if (root.parent.kind === 148 /* QualifiedName */) { + while (root.parent && root.parent.kind === 148 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 162 /* TypeReference */ && !isLastClause; + return root.parent.kind === 164 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 187 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 187 /* PropertyAccessExpression */) { + if (root.parent.kind === 189 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 189 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 209 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 271 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 211 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 273 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 238 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || - (decl.kind === 239 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); + return (decl.kind === 240 /* ClassDeclaration */ && root.parent.parent.token === 109 /* ImplementsKeyword */) || + (decl.kind === 241 /* InterfaceDeclaration */ && root.parent.parent.token === 86 /* ExtendsKeyword */); } return false; } @@ -89085,17 +92466,17 @@ var ts; node = node.parent; } switch (node.kind) { - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 176 /* ThisType */: + case 178 /* ThisType */: return true; } switch (node.parent.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return true; - case 181 /* ImportType */: + case 183 /* ImportType */: return !node.parent.isTypeOf; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; @@ -89122,7 +92503,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 231 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 233 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -89130,53 +92511,64 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { - return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; + return node.kind === 72 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; + return node.kind === 72 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; } ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; function isLabelName(node) { return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } ts.isLabelName = isLabelName; + function isTagName(node) { + return ts.isJSDocTag(node.parent) && node.parent.tagName === node; + } + ts.isTagName = isTagName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 242 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 244 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { - return node.kind === 71 /* Identifier */ && + return node.kind === 72 /* Identifier */ && ts.isFunctionLike(node.parent) && node.parent.name === node; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 273 /* PropertyAssignment */: - case 276 /* EnumMember */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 242 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 278 /* EnumMember */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 244 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return true; - case 180 /* LiteralType */: - return node.parent.parent.kind === 178 /* IndexedAccessType */; + case 182 /* LiteralType */: + return node.parent.parent.kind === 180 /* IndexedAccessType */; default: return false; } @@ -89200,17 +92592,17 @@ var ts; return undefined; } switch (node.kind) { - case 277 /* SourceFile */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: return node; } } @@ -89218,51 +92610,54 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return "class" /* classElement */; - case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 240 /* TypeAliasDeclaration */: - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 242 /* TypeAliasDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 241 /* EnumDeclaration */: return "enum" /* enumElement */; - case 235 /* VariableDeclaration */: + case 243 /* EnumDeclaration */: return "enum" /* enumElement */; + case 237 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return "function" /* functionElement */; - case 156 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 157 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 158 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 159 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return "method" /* memberFunctionElement */; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return "property" /* memberVariableElement */; - case 160 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 159 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 158 /* CallSignature */: return "call" /* callSignatureElement */; - case 155 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 148 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 276 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 149 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 246 /* ImportEqualsDeclaration */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: - case 249 /* NamespaceImport */: + case 162 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 161 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 160 /* CallSignature */: return "call" /* callSignatureElement */; + case 157 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 150 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 278 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 151 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + case 251 /* NamespaceImport */: return "alias" /* alias */; - case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: case 0 /* None */: return "" /* unknown */; case 1 /* ExportsProperty */: @@ -89283,7 +92678,7 @@ var ts; return "" /* unknown */; } } - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; @@ -89299,12 +92694,12 @@ var ts; ts.getNodeKind = getNodeKind; function isThis(node) { switch (node.kind) { - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: // case SyntaxKind.ThisType: TODO: GH#9267 return true; - case 71 /* Identifier */: + case 72 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 149 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 151 /* Parameter */; default: return false; } @@ -89369,42 +92764,42 @@ var ts; return false; } switch (n.kind) { - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 186 /* ObjectLiteralExpression */: - case 182 /* ObjectBindingPattern */: - case 166 /* TypeLiteral */: - case 216 /* Block */: - case 243 /* ModuleBlock */: - case 244 /* CaseBlock */: - case 250 /* NamedImports */: - case 254 /* NamedExports */: - return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile); - case 272 /* CatchClause */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 168 /* TypeLiteral */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 246 /* CaseBlock */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); + case 274 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 190 /* NewExpression */: + case 192 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 189 /* CallExpression */: - case 193 /* ParenthesizedExpression */: - case 175 /* ParenthesizedType */: - return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 191 /* CallExpression */: + case 195 /* ParenthesizedExpression */: + case 177 /* ParenthesizedType */: + return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 159 /* ConstructSignature */: - case 158 /* CallSignature */: - case 195 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 197 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -89413,66 +92808,66 @@ var ts; } // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. - return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); - case 242 /* ModuleDeclaration */: + return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); + case 244 /* ModuleDeclaration */: return !!n.body && isCompletedNode(n.body, sourceFile); - case 220 /* IfStatement */: + case 222 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile); - case 185 /* ArrayLiteralExpression */: - case 183 /* ArrayBindingPattern */: - case 188 /* ElementAccessExpression */: - case 147 /* ComputedPropertyName */: - case 168 /* TupleType */: - return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile); - case 160 /* IndexSignature */: + hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); + case 187 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 190 /* ElementAccessExpression */: + case 149 /* ComputedPropertyName */: + case 170 /* TupleType */: + return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); + case 162 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 221 /* DoStatement */: + case 223 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile) - ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile) + return hasChildOfKind(n, 107 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 197 /* TypeOfExpression */: - case 196 /* DeleteExpression */: - case 198 /* VoidExpression */: - case 205 /* YieldExpression */: - case 206 /* SpreadElement */: + case 199 /* TypeOfExpression */: + case 198 /* DeleteExpression */: + case 200 /* VoidExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 253 /* ExportDeclaration */: - case 247 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -89489,7 +92884,7 @@ var ts; if (lastChild.kind === expectedLastToken) { return true; } - else if (lastChild.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -89624,7 +93019,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -89642,8 +93037,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); 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, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_1 && findRightmostToken(candidate_1, sourceFile); } else { // candidate should be in this node @@ -89651,15 +93046,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -89715,25 +93108,25 @@ var ts; if (!token) { return false; } - if (token.kind === 10 /* JsxText */) { + if (token.kind === 11 /* JsxText */) { return true; } //
Hello |
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 10 /* JsxText */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) { return true; } //
{ |
or
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 268 /* JsxExpression */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 270 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 268 /* JsxExpression */) { + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 270 /* JsxExpression */) { return true; } //
|
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 261 /* JsxClosingElement */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 263 /* JsxClosingElement */) { return true; } return false; @@ -89747,6 +93140,20 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; + function isInJSXText(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (ts.isJsxText(token)) { + return true; + } + if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + if (token.kind === 28 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + return false; + } + ts.isInJSXText = isInJSXText; function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { var tokenKind = token.kind; var remainingMatchingTokens = 0; @@ -89793,7 +93200,7 @@ var ts; var nTypeArguments = 0; while (token) { switch (token.kind) { - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // Found the beginning of the generic argument expression token = findPrecedingToken(token.getFullStart(), sourceFile); if (!token || !ts.isIdentifier(token)) @@ -89803,53 +93210,54 @@ var ts; } remainingLessThanTokens--; break; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: remainingLessThanTokens = +3; break; - case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: remainingLessThanTokens = +2; break; - case 29 /* GreaterThanToken */: + case 30 /* GreaterThanToken */: remainingLessThanTokens++; break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); + token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile); if (!token) return undefined; break; - case 20 /* CloseParenToken */: + case 21 /* CloseParenToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); + token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile); if (!token) return undefined; break; - case 22 /* CloseBracketToken */: + case 23 /* CloseBracketToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); + token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile); if (!token) return undefined; break; // Valid tokens in a type name. Skip. - case 26 /* CommaToken */: + case 27 /* CommaToken */: nTypeArguments++; break; - case 36 /* EqualsGreaterThanToken */: - case 71 /* Identifier */: - case 9 /* StringLiteral */: + case 37 /* EqualsGreaterThanToken */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 103 /* TypeOfKeyword */: - case 85 /* ExtendsKeyword */: - case 128 /* KeyOfKeyword */: - case 23 /* DotToken */: - case 49 /* BarToken */: - case 55 /* QuestionToken */: - case 56 /* ColonToken */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 104 /* TypeOfKeyword */: + case 86 /* ExtendsKeyword */: + case 129 /* KeyOfKeyword */: + case 24 /* DotToken */: + case 50 /* BarToken */: + case 56 /* QuestionToken */: + case 57 /* ColonToken */: break; default: if (ts.isTypeNode(token)) { @@ -89881,7 +93289,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -89904,10 +93312,10 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 162 /* TypeReference */ || node.kind === 189 /* CallExpression */) { + if (node.kind === 164 /* TypeReference */ || node.kind === 191 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 238 /* ClassDeclaration */ || node.kind === 239 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 240 /* ClassDeclaration */ || node.kind === 241 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -89918,8 +93326,8 @@ var ts; } ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { - if (kind === 9 /* StringLiteral */ - || kind === 12 /* RegularExpressionLiteral */ + if (kind === 10 /* StringLiteral */ + || kind === 13 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; } @@ -89927,7 +93335,7 @@ var ts; } ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; function isPunctuation(kind) { - return 17 /* FirstPunctuation */ <= kind && kind <= 70 /* LastPunctuation */; + return 18 /* FirstPunctuation */ <= kind && kind <= 71 /* LastPunctuation */; } ts.isPunctuation = isPunctuation; function isInsideTemplateLiteral(node, position, sourceFile) { @@ -89937,9 +93345,9 @@ var ts; ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: return true; } return false; @@ -89952,18 +93360,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 185 /* ArrayLiteralExpression */ || - node.kind === 186 /* ObjectLiteralExpression */) { + if (node.kind === 187 /* ArrayLiteralExpression */ || + node.kind === 188 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 202 /* BinaryExpression */ && + if (node.parent.kind === 204 /* BinaryExpression */ && node.parent.left === node && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { + node.parent.operatorToken.kind === 59 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 225 /* ForOfStatement */ && + if (node.parent.kind === 227 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -89971,7 +93379,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 273 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 275 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -89995,7 +93403,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90003,7 +93411,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90015,21 +93423,22 @@ var ts; } ts.createTextChange = createTextChange; ts.typeKeywords = [ - 119 /* AnyKeyword */, - 122 /* BooleanKeyword */, - 86 /* FalseKeyword */, - 128 /* KeyOfKeyword */, - 131 /* NeverKeyword */, - 95 /* NullKeyword */, - 134 /* NumberKeyword */, - 135 /* ObjectKeyword */, - 137 /* StringKeyword */, - 138 /* SymbolKeyword */, - 101 /* TrueKeyword */, - 105 /* VoidKeyword */, - 140 /* UndefinedKeyword */, - 141 /* UniqueKeyword */, - 142 /* UnknownKeyword */, + 120 /* AnyKeyword */, + 146 /* BigIntKeyword */, + 123 /* BooleanKeyword */, + 87 /* FalseKeyword */, + 129 /* KeyOfKeyword */, + 132 /* NeverKeyword */, + 96 /* NullKeyword */, + 135 /* NumberKeyword */, + 136 /* ObjectKeyword */, + 138 /* StringKeyword */, + 139 /* SymbolKeyword */, + 102 /* TrueKeyword */, + 106 /* VoidKeyword */, + 141 /* UndefinedKeyword */, + 142 /* UniqueKeyword */, + 143 /* UnknownKeyword */, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); @@ -90065,7 +93474,7 @@ var ts; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { - return name.kind === 147 /* ComputedPropertyName */ + return name.kind === 149 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.getTextOfIdentifierOrLiteral(name); @@ -90141,19 +93550,20 @@ var ts; } return ts.firstDefined(symbol.declarations, function (decl) { var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined; + return name && name.kind === 72 /* Identifier */ ? name.escapedText : undefined; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { - // See GH#16922 - ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); - return propSymbol.target; - } - return propSymbol; + return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; /** @@ -90206,7 +93616,6 @@ var ts; return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); } ts.findModifier = findModifier; - /* @internal */ function insertImport(changes, sourceFile, importDecl) { var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); if (lastImportDeclaration) { @@ -90230,7 +93639,7 @@ var ts; /* @internal */ (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 149 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 151 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -90256,6 +93665,7 @@ var ts; writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, @@ -90264,7 +93674,7 @@ var ts; writeSymbol: writeSymbol, writeLine: writeLine, write: unknownWrite, - writeTextOfNode: unknownWrite, + writeComment: unknownWrite, getText: function () { return ""; }, getTextPos: function () { return 0; }, getColumn: function () { return 0; }, @@ -90415,7 +93825,6 @@ var ts; return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; - /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -90449,9 +93858,7 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { - return !!location.parent && - (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && - location.parent.propertyName === location; + return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; /** @@ -90497,6 +93904,13 @@ var ts; return position; } ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; + function getPrecedingNonSpaceCharacterPosition(text, position) { + while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) { + position -= 1; + } + return position + 1; + } + ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition; /** * Creates a deep, memberwise clone of a node with no source map location. * @@ -90514,7 +93928,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90522,11 +93936,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -90563,7 +93977,6 @@ var ts; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - /* @internal */ function suppressLeadingAndTrailingTrivia(node) { suppressLeadingTrivia(node); suppressTrailingTrivia(node); @@ -90572,7 +93985,6 @@ var ts; /** * Sets EmitFlags to suppress leading trivia on the node. */ - /* @internal */ function suppressLeadingTrivia(node) { addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); } @@ -90580,7 +93992,6 @@ var ts; /** * Sets EmitFlags to suppress trailing trivia on the node. */ - /* @internal */ function suppressTrailingTrivia(node) { addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } @@ -90594,7 +94005,6 @@ var ts; function getFirstChild(node) { return node.forEachChild(function (child) { return child; }); } - /* @internal */ function getUniqueName(baseName, sourceFile) { var nameText = baseName; for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { @@ -90608,7 +94018,6 @@ var ts; * to be on the reference, rather than the declaration, because it's closer to where the * user was before extracting it. */ - /* @internal */ function getRenameLocation(edits, renameFilename, name, preferLastLocation) { var delta = 0; var lastPos = -1; @@ -90662,6 +94071,72 @@ var ts; idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 192 /* NewExpression */: + return checker.getContextualType(parent); + case 204 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 271 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + ts.getContextualTypeFromParent = getContextualTypeFromParent; + function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } + } + ts.quote = quote; + function isEqualityOperatorKind(kind) { + switch (kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return true; + default: + return false; + } + } + ts.isEqualityOperatorKind = isEqualityOperatorKind; + function isStringLiteralOrTemplate(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + return true; + default: + return false; + } + } + ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate; + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + ts.hasIndexSignature = hasIndexSignature; + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } + ts.getSwitchedType = getSwitchedType; })(ts || (ts = {})); var ts; (function (ts) { @@ -90700,7 +94175,7 @@ var ts; text = prefix + text; var offset = prefix.length; if (pushTemplate) { - templateStack.push(14 /* TemplateHead */); + templateStack.push(15 /* TemplateHead */); } scanner.setText(text); var endOfLineState = 0 /* None */; @@ -90742,65 +94217,65 @@ var ts; } while (token !== 1 /* EndOfFileToken */); function handleToken() { switch (token) { - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 12 /* RegularExpressionLiteral */) { - token = 12 /* RegularExpressionLiteral */; + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + token = 13 /* RegularExpressionLiteral */; } break; - case 27 /* LessThanToken */: - if (lastNonTriviaToken === 71 /* Identifier */) { + case 28 /* LessThanToken */: + if (lastNonTriviaToken === 72 /* Identifier */) { // Could be the start of something generic. Keep track of that by bumping // up the current count of generic contexts we may be in. angleBracketStack++; } break; - case 29 /* GreaterThanToken */: + case 30 /* GreaterThanToken */: if (angleBracketStack > 0) { // If we think we're currently in something generic, then mark that that // generic entity is complete. angleBracketStack--; } break; - case 119 /* AnyKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: + case 120 /* AnyKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* 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, // causing a noisy experience for the user. - token = 71 /* Identifier */; + token = 72 /* Identifier */; } break; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: templateStack.push(token); break; - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { templateStack.push(token); } break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 14 /* TemplateHead */) { + if (lastTemplateStackToken === 15 /* TemplateHead */) { token = scanner.reScanTemplateToken(); // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. - if (token === 16 /* TemplateTail */) { + if (token === 17 /* TemplateTail */) { templateStack.pop(); } else { - ts.Debug.assertEqual(token, 15 /* TemplateMiddle */, "Should have been a template middle."); + ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle."); } } else { - ts.Debug.assertEqual(lastTemplateStackToken, 17 /* OpenBraceToken */, "Should have been an open brace"); + ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace"); templateStack.pop(); } } @@ -90809,15 +94284,15 @@ var ts; if (!ts.isKeyword(token)) { break; } - if (lastNonTriviaToken === 23 /* DotToken */) { - token = 71 /* Identifier */; + if (lastNonTriviaToken === 24 /* DotToken */) { + token = 72 /* Identifier */; } else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { // We have two keywords in a row. Only treat the second as a keyword if // it's a sequence that could legally occur in the language. Otherwise // treat it as an identifier. This way, if someone writes "private var" // we recognize that 'var' is actually an identifier here. - token = 71 /* Identifier */; + token = 72 /* Identifier */; } } } @@ -90831,22 +94306,23 @@ var ts; /// we have a series of divide operator. this list allows us to be more accurate by ruling out /// locations where a regexp cannot exist. var noRegexTable = ts.arrayToNumericMap([ - 71 /* Identifier */, - 9 /* StringLiteral */, + 72 /* Identifier */, + 10 /* StringLiteral */, 8 /* NumericLiteral */, - 12 /* RegularExpressionLiteral */, - 99 /* ThisKeyword */, - 43 /* PlusPlusToken */, - 44 /* MinusMinusToken */, - 20 /* CloseParenToken */, - 22 /* CloseBracketToken */, - 18 /* CloseBraceToken */, - 101 /* TrueKeyword */, - 86 /* FalseKeyword */, + 9 /* BigIntLiteral */, + 13 /* RegularExpressionLiteral */, + 100 /* ThisKeyword */, + 44 /* PlusPlusToken */, + 45 /* MinusMinusToken */, + 21 /* CloseParenToken */, + 23 /* CloseBracketToken */, + 19 /* CloseBraceToken */, + 102 /* TrueKeyword */, + 87 /* FalseKeyword */, ], function (token) { return token; }, function () { return true; }); function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { switch (token) { - case 9 /* StringLiteral */: { + case 10 /* StringLiteral */: { // Check to see if we finished up on a multiline string literal. if (!scanner.isUnterminated()) return undefined; @@ -90870,15 +94346,15 @@ var ts; return undefined; } switch (token) { - case 16 /* TemplateTail */: + case 17 /* TemplateTail */: return 5 /* InTemplateMiddleOrTail */; - case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; default: return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } - return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; } } function pushEncodedClassification(start, end, offset, classification, result) { @@ -90927,6 +94403,7 @@ var ts; case 1 /* comment */: return ts.TokenClass.Comment; case 3 /* keyword */: return ts.TokenClass.Keyword; case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral; case 5 /* operator */: return ts.TokenClass.Operator; case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; @@ -90953,10 +94430,10 @@ var ts; return true; } switch (keyword2) { - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 123 /* ConstructorKeyword */: - case 115 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 124 /* ConstructorKeyword */: + case 116 /* StaticKeyword */: return true; // Allow things like "public get", "public constructor" and "public static". default: return false; // Any other keyword following "public" is actually an identifier, not a real keyword. @@ -90989,43 +94466,43 @@ var ts; } function isBinaryExpressionOperatorToken(token) { switch (token) { - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 48 /* AmpersandToken */: - case 50 /* CaretToken */: - case 49 /* BarToken */: - case 53 /* AmpersandAmpersandToken */: - case 54 /* BarBarToken */: - case 69 /* BarEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 58 /* EqualsToken */: - case 26 /* CommaToken */: + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 49 /* AmpersandToken */: + case 51 /* CaretToken */: + case 50 /* BarToken */: + case 54 /* AmpersandAmpersandToken */: + case 55 /* BarBarToken */: + case 70 /* BarEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 59 /* EqualsToken */: + case 27 /* CommaToken */: return true; default: return false; @@ -91033,12 +94510,12 @@ var ts; } function isPrefixUnaryExpressionOperatorToken(token) { switch (token) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: return true; default: return false; @@ -91051,15 +94528,17 @@ var ts; else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { return 5 /* operator */; } - else if (token >= 17 /* FirstPunctuation */ && token <= 70 /* LastPunctuation */) { + else if (token >= 18 /* FirstPunctuation */ && token <= 71 /* LastPunctuation */) { return 10 /* punctuation */; } switch (token) { case 8 /* NumericLiteral */: return 4 /* numericLiteral */; - case 9 /* StringLiteral */: + case 9 /* BigIntLiteral */: + return 25 /* bigintLiteral */; + case 10 /* StringLiteral */: return 6 /* stringLiteral */; - case 12 /* RegularExpressionLiteral */: + case 13 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; case 7 /* ConflictMarkerTrivia */: case 3 /* MultiLineCommentTrivia */: @@ -91068,7 +94547,7 @@ var ts; case 5 /* WhitespaceTrivia */: case 4 /* NewLineTrivia */: return 8 /* whiteSpace */; - case 71 /* Identifier */: + case 72 /* Identifier */: default: if (ts.isTemplateLiteralKind(token)) { return 6 /* stringLiteral */; @@ -91093,10 +94572,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 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -91171,6 +94650,7 @@ var ts; case 2 /* identifier */: return "identifier" /* identifier */; case 3 /* keyword */: return "keyword" /* keyword */; case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */; case 5 /* operator */: return "operator" /* operator */; case 6 /* stringLiteral */: return "string" /* stringLiteral */; case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; @@ -91304,22 +94784,22 @@ var ts; if (tag.pos !== pos) { pushCommentRange(pos, tag.pos - pos); } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); // "@" + pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 297 /* JSDocParameterTag */: + case 299 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; break; - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; break; - case 298 /* JSDocReturnTag */: + case 300 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; break; @@ -91390,10 +94870,10 @@ var ts; return true; } var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 10 /* JsxText */ && classifiedElementName === undefined) { + if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) { return false; } - var tokenStart = node.kind === 10 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { @@ -91406,22 +94886,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -91438,7 +94918,7 @@ var ts; } // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. - if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { + if (tokenKind === 28 /* LessThanToken */ || tokenKind === 30 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { @@ -91448,19 +94928,19 @@ var ts; if (ts.isPunctuation(tokenKind)) { if (token) { var parent = token.parent; - if (tokenKind === 58 /* EqualsToken */) { + if (tokenKind === 59 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (parent.kind === 235 /* VariableDeclaration */ || - parent.kind === 152 /* PropertyDeclaration */ || - parent.kind === 149 /* Parameter */ || - parent.kind === 265 /* JsxAttribute */) { + if (parent.kind === 237 /* VariableDeclaration */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 151 /* Parameter */ || + parent.kind === 267 /* JsxAttribute */) { return 5 /* operator */; } } - if (parent.kind === 202 /* BinaryExpression */ || - parent.kind === 200 /* PrefixUnaryExpression */ || - parent.kind === 201 /* PostfixUnaryExpression */ || - parent.kind === 203 /* ConditionalExpression */) { + if (parent.kind === 204 /* BinaryExpression */ || + parent.kind === 202 /* PrefixUnaryExpression */ || + parent.kind === 203 /* PostfixUnaryExpression */ || + parent.kind === 205 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -91469,11 +94949,14 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 265 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + else if (tokenKind === 9 /* BigIntLiteral */) { + return 25 /* bigintLiteral */; } - else if (tokenKind === 12 /* RegularExpressionLiteral */) { + else if (tokenKind === 10 /* StringLiteral */) { + // TODO: GH#18217 + return token.parent.kind === 267 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + } + else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */; } @@ -91481,38 +94964,38 @@ var ts; // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } - else if (tokenKind === 10 /* JsxText */) { + else if (tokenKind === 11 /* JsxText */) { return 23 /* jsxText */; } - else if (tokenKind === 71 /* Identifier */) { + else if (tokenKind === 72 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 149 /* Parameter */: + case 151 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -91546,37 +95029,245 @@ var ts; (function (ts) { var Completions; (function (Completions) { - var PathCompletions; - (function (PathCompletions) { - function nameAndKind(name, kind) { - return { name: name, kind: kind }; + var StringCompletions; + (function (StringCompletions) { + function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + if (ts.isInReferenceComment(sourceFile, position)) { + var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host), sourceFile, checker, log, preferences); + } + } + StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + if (completion === undefined) { + return undefined; + } + switch (completion.kind) { + case 0 /* Paths */: + return convertPathCompletions(completion.paths); + case 1 /* Properties */: { + var entries = []; + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; + } + case 2 /* Types */: { + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; + } + default: + return ts.Debug.assertNever(completion); + } + } + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + if (!contextToken || !ts.isStringLiteralLike(contextToken)) + return undefined; + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); + } + StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function convertPathCompletions(pathCompletions) { + var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. + var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. + var entries = pathCompletions.map(function (_a) { + var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension; + return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span }); + }); + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function kindModifiersFromExtension(extension) { + switch (extension) { + case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */; + case ".js" /* Js */: return ".js" /* jsModifier */; + case ".json" /* Json */: return ".json" /* jsonModifier */; + case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */; + case ".ts" /* Ts */: return ".ts" /* tsModifier */; + case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */; + case undefined: return "" /* none */; + default: + return ts.Debug.assertNever(extension); + } + } + var StringLiteralCompletionKind; + (function (StringLiteralCompletionKind) { + StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; + })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + var parent = node.parent; + switch (parent.kind) { + case 182 /* LiteralType */: + switch (parent.parent.kind) { + case 164 /* TypeReference */: + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; + case 180 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); + case 183 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 173 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } + default: + return undefined; + } + case 275 /* PropertyAssignment */: + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); + } + return fromContextualType(); + case 190 /* ElementAccessExpression */: { + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return undefined; + } + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through (is `require("")` or `import("")`) + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 259 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + default: + return fromContextualType(); + } + function fromContextualType() { + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; + } + } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } + function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { + var isNewIdentifier = false; + var uniques = ts.createMap(); + var candidates = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + var types = ts.flatMap(candidates, function (candidate) { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + return; + var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); + return getStringLiteralTypes(type, uniques); + }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; + } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: ts.hasIndexSignature(type) }; + } + function getStringLiteralTypes(type, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } + if (!type) + return ts.emptyArray; + type = ts.skipConstraint(type); + return type.isUnion() + ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) + : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) + ? [type] + : ts.emptyArray; + } + function nameAndKind(name, kind, extension) { + return { name: name, kind: kind, extension: extension }; + } + function directoryResult(name) { + return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined); } function addReplacementSpans(text, textStart, names) { var span = getDirectoryFragmentTextSpan(text, textStart); return names.map(function (_a) { - var name = _a.name, kind = _a.kind; - return ({ name: name, kind: kind, span: span }); + var name = _a.name, kind = _a.kind, extension = _a.extension; + return ({ name: name, kind: kind, extension: extension, span: span }); }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); } - PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { - var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); - if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); - } - else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); - } + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + } + function getExtensionOptions(compilerOptions, includeExtensions) { + if (includeExtensions === void 0) { includeExtensions = false; } + return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; + } + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { + var extensionOptions = getExtensionOptions(compilerOptions); + if (compilerOptions.rootDirs) { + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); } } function getSupportedExtensionsForModuleResolution(compilerOptions) { @@ -91589,31 +95280,27 @@ var ts; * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option */ - function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { // Make all paths absolute/normalized if they are not already rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { - return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; + return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined; }); // TODO: GH#18217 // Now find a path for each potential directory that is to be merged with the one containing the script - return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); - var result = []; - for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { - var baseDirectory = baseDirectories_1[_i]; - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); - } - return result; + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); + return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); } /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) { + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { + var extensions = _a.extensions, includeExtensions = _a.includeExtensions; if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; @@ -91634,46 +95321,77 @@ var ts; var absolutePath = ts.resolvePath(scriptPath, fragment); var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - if (tryDirectoryExists(host, baseDirectory)) { - // Enumerate the available files if possible - var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); - if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - var foundFiles = ts.createMap(); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var filePath = files_1[_i]; - filePath = ts.normalizePath(filePath); - if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { - continue; - } - var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.has(foundFileName)) { - foundFiles.set(foundFileName, true); - } + if (!tryDirectoryExists(host, baseDirectory)) + return result; + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ + var foundFiles = ts.createMap(); // maps file to its extension + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var filePath = files_1[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { + continue; } - ts.forEachKey(foundFiles, function (foundFile) { - result.push(nameAndKind(foundFile, "script" /* scriptElement */)); - }); + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); } - // If possible, get folder completion as well - var directories = tryGetDirectories(host, baseDirectory); - if (directories) { - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var directory = directories_1[_a]; - var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - if (directoryName !== "@types") { - result.push(nameAndKind(directoryName, "directory" /* directory */)); - } + foundFiles.forEach(function (ext, foundFile) { + result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext)); + }); + } + // If possible, get folder completion as well + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var directory = directories_1[_b]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + if (directoryName !== "@types") { + result.push(directoryResult(directoryName)); + } + } + } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); } } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_1 = function (name, kind, extension) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind, extension)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; + _loop_1(name, kind, extension); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -91684,33 +95402,21 @@ var ts; function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; - var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); + var extensionOptions = getExtensionOptions(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_1 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_1(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); } } - var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; - result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); + var fragmentDirectory = getFragmentDirectory(fragment); + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; + result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined)); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. // (But do if we didn't find anything, e.g. 'package.json' missing.) @@ -91719,11 +95425,11 @@ var ts; var _loop_2 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; - result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; _loop_2(moduleName); } } @@ -91731,13 +95437,16 @@ var ts; ts.forEachAncestorDirectory(scriptPath, function (ancestor) { var nodeModules = ts.combinePaths(ancestor, "node_modules"); if (tryDirectoryExists(host, nodeModules)) { - getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result); } }); } } return result; } + function getFragmentDirectory(fragment) { + return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + } function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. @@ -91749,7 +95458,7 @@ var ts; return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); function justPathMappingName(name) { - return ts.startsWith(name, fragment) ? [{ name: name, kind: "directory" /* directory */ }] : ts.emptyArray; + return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; } } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { @@ -91777,15 +95486,20 @@ var ts; // that encodes the suffix, but we would have to escape the character "?" which readDirectory // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]).map(function (name) { return ({ name: name, kind: "script" /* scriptElement */ }); }); - var directories = tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }).map(function (name) { return ({ name: name, kind: "directory" /* directory */ }); }); - // Trim away prefix and suffix - return ts.mapDefined(ts.concatenate(matches, directories), function (_a) { - var name = _a.name, kind = _a.kind; - var normalizedMatch = ts.normalizePath(name); - var inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix); - return inner !== undefined ? { name: removeLeadingDirectorySeparator(ts.removeFileExtension(inner)), kind: kind } : undefined; + var matches = ts.mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var extension = ts.tryGetExtensionFromPath(match); + var name = trimPrefixAndSuffix(match); + return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension); }); + var directories = ts.mapDefined(tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { + var name = trimPrefixAndSuffix(dir); + return name === undefined ? undefined : directoryResult(name); + }); + return matches.concat(directories); + function trimPrefixAndSuffix(path) { + var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); + return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner); + } } function withoutStartAndEnd(s, start, end) { return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; @@ -91820,62 +95534,48 @@ var ts; } var prefix = match[1], kind = match[2], toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) - : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) - : undefined; - return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) + : ts.Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, names); } - PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; - function getCompletionEntriesFromTypings(host, options, scriptPath, result) { + function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options var seen = ts.createMap(); - if (options.types) { - for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); - pushResult(moduleName); - } + var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + getCompletionEntriesFromDirectories(root); } - else if (host.getDirectories) { - var typeRoots = void 0; - try { - typeRoots = ts.getEffectiveTypeRoots(options, host); - } - catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ } - if (typeRoots) { - for (var _c = 0, typeRoots_1 = typeRoots; _c < typeRoots_1.length; _c++) { - var root = typeRoots_1[_c]; - getCompletionEntriesFromDirectories(root); - } - } - // Also get all @types typings installed in visible node_modules directories - for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { - var packageJson = _e[_d]; - var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(typesDir); - } + // Also get all @types typings installed in visible node_modules directories + for (var _a = 0, _b = findPackageJsons(scriptPath, host); _a < _b.length; _a++) { + var packageJson = _b[_a]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); } return result; function getCompletionEntriesFromDirectories(directory) { - ts.Debug.assert(!!host.getDirectories); - if (tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); - pushResult(moduleName); + if (!tryDirectoryExists(host, directory)) + return; + for (var _i = 0, _a = tryGetDirectories(host, directory); _i < _a.length; _i++) { + var typeDirectoryName = _a[_i]; + var packageName = ts.unmangleScopedPackageName(typeDirectoryName); + if (options.types && !ts.contains(options.types, packageName)) + continue; + if (fragmentDirectory === undefined) { + if (!seen.has(packageName)) { + result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + seen.set(packageName, true); + } + } + else { + var baseDirectory = ts.combinePaths(directory, typeDirectoryName); + var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host)); + if (remainingFragment !== undefined) { + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result); } } - } - } - function pushResult(moduleName) { - if (!seen.has(moduleName)) { - result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); - seen.set(moduleName, true); } } } @@ -91890,6 +95590,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -91953,27 +95665,27 @@ var ts; return tryIOAndConsumeErrors(host, host.fileExists, path); } function tryDirectoryExists(host, path) { - try { - return ts.directoryProbablyExists(path, host); - } - catch ( /*ignore*/_a) { /*ignore*/ } - return false; + return tryAndIgnoreErrors(function () { return ts.directoryProbablyExists(path, host); }) || false; } function tryIOAndConsumeErrors(host, toApply) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } + return tryAndIgnoreErrors(function () { return toApply && toApply.apply(host, args); }); + } + function tryAndIgnoreErrors(cb) { try { - return toApply && toApply.apply(host, args); + return cb(); + } + catch (_a) { + return undefined; } - catch ( /*ignore*/_a) { /*ignore*/ } - return undefined; } function containsSlash(fragment) { return ts.stringContains(fragment, ts.directorySeparator); } - })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); + })(StringCompletions = Completions.StringCompletions || (Completions.StringCompletions = {})); })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -91997,11 +95709,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92012,20 +95725,15 @@ var ts; function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); - if (ts.isInReferenceComment(sourceFile, position)) { - var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries && convertPathCompletions(entries); - } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; - if (ts.isInString(sourceFile, position, contextToken)) { - return !contextToken || !ts.isStringLiteralLike(contextToken) - ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); + var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); + if (stringCompletions) { + return stringCompletions; } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) - && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { + && (contextToken.kind === 73 /* BreakKeyword */ || contextToken.kind === 78 /* ContinueKeyword */ || contextToken.kind === 72 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined); @@ -92048,35 +95756,6 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { - if (completion === undefined) { - return undefined; - } - switch (completion.kind) { - case 0 /* Paths */: - return convertPathCompletions(completion.paths); - case 1 /* Properties */: { - var entries = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; - } - case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; - } - default: - return ts.Debug.assertNever(completion); - } - } - function convertPathCompletions(pathCompletions) { - var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. - var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. - var entries = pathCompletions.map(function (_a) { - var name = _a.name, kind = _a.kind, span = _a.span; - return ({ name: name, kind: kind, kindModifiers: "" /* none */, sortText: "0", replacementSpan: span }); - }); - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - } function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } @@ -92090,7 +95769,7 @@ var ts; // The completion list at "1" will contain "div>" with type any // And at `
` (with a closing `>`), the completion list will contain "div". var tagName = location.parent.parent.openingElement.tagName; - var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile); + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 30 /* GreaterThanToken */, sourceFile); var entry = { name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), kind: "class" /* classElement */, @@ -92102,7 +95781,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92110,22 +95789,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92137,14 +95817,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92154,7 +95834,9 @@ var ts; } }); } - var completionNameForLiteral = JSON.stringify; + var completionNameForLiteral = function (literal) { + return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); + }; function createCompletionEntryForLiteral(literal) { return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" }; } @@ -92167,13 +95849,13 @@ var ts; var insertText; var replacementSpan; if (origin && origin.kind === 0 /* ThisType */) { - insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; + insertText = needsConvertPropertyAccess ? "this[" + ts.quote(name, preferences) + "]" : "this." + name; } // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { - insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]"; - var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); + insertText = needsConvertPropertyAccess ? "[" + ts.quote(name, preferences) + "]" : "[" + name + "]"; + var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); @@ -92208,18 +95890,6 @@ var ts; replacementSpan: replacementSpan, }; } - function quote(text, preferences) { - var quoted = JSON.stringify(text); - switch (preferences.quotePreference) { - case undefined: - case "double": - return quoted; - case "single": - return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; - default: - return ts.Debug.assertNever(preferences.quotePreference); - } - } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; @@ -92257,6 +95927,7 @@ var ts; log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniques; } + Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { var entries = getLabelStatementCompletions(node); if (entries.length) { @@ -92287,120 +95958,6 @@ var ts; } return entries; } - var StringLiteralCompletionKind; - (function (StringLiteralCompletionKind) { - StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; - StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; - StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; - })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); - function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { - case 180 /* LiteralType */: - switch (node.parent.parent.kind) { - case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; - case 178 /* IndexedAccessType */: - // Get all apparent property names - // i.e. interface Foo { - // foo: string; - // bar: string; - // } - // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); - case 181 /* ImportType */: - return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; - default: - return undefined; - } - case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); - } - return fromContextualType(); - case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; - if (node === argumentExpression) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); - } - return undefined; - } - case 189 /* CallExpression */: - case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { - var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); - } - // falls through (is `require("")` or `import("")`) - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 257 /* ExternalModuleReference */: - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - default: - return fromContextualType(); - } - function fromContextualType() { - // Get completion for string literal from string literal type - // i.e. var x: "hi" | "hello" = "/*completion position*/" - return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; - } - } - function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { - var isNewIdentifier = false; - var uniques = ts.createMap(); - var candidates = []; - checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); - var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) - return; - var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); - isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); - return getStringLiteralTypes(type, uniques); - }); - return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; - } - function stringLiteralCompletionsFromProperties(type) { - return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; - } - function getStringLiteralTypes(type, uniques) { - if (uniques === void 0) { uniques = ts.createMap(); } - if (!type) - return ts.emptyArray; - type = ts.skipConstraint(type); - return type.isUnion() - ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) - : type.isStringLiteral() && !(type.flags & 512 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) - ? [type] - : ts.emptyArray; - } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { var compilerOptions = program.getCompilerOptions(); var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); @@ -92439,10 +95996,7 @@ var ts; var name = entryId.name; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { - var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) - ? undefined - : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); - return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); @@ -92486,25 +96040,11 @@ var ts; }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } - function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { - switch (completion.kind) { - case 0 /* Paths */: { - var match = ts.find(completion.paths, function (p) { return p.name === name; }); - return match && createCompletionDetails(name, "" /* none */, match.kind, [ts.textPart(name)]); - } - case 1 /* Properties */: { - var match = ts.find(completion.symbols, function (s) { return s.name === name; }); - return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); - } - case 2 /* Types */: - return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; - default: - return ts.Debug.assertNever(completion); - } - } + Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; } + Completions.createCompletionDetails = createCompletionDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { @@ -92535,7 +96075,7 @@ var ts; CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; CompletionKind[CompletionKind["String"] = 4] = "String"; CompletionKind[CompletionKind["None"] = 5] = "None"; - })(CompletionKind || (CompletionKind = {})); + })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {})); function getRecommendedCompletion(previousToken, contextualType, checker) { // For a union, return the first one with a recommended completion. return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { @@ -92549,56 +96089,36 @@ var ts; function getContextualType(previousToken, position, sourceFile, checker) { var parent = previousToken.parent; switch (previousToken.kind) { - case 71 /* Identifier */: - return getContextualTypeFromParent(previousToken, checker); - case 58 /* EqualsToken */: + case 72 /* Identifier */: + return ts.getContextualTypeFromParent(previousToken, checker); + case 59 /* EqualsToken */: switch (parent.kind) { - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return checker.getContextualType(parent.initializer); // TODO: GH#18217 - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; } - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: return checker.getContextualType(parent); - case 73 /* CaseKeyword */: - return getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); - case 17 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 258 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + case 74 /* CaseKeyword */: + return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); + case 18 /* OpenBraceToken */: + return ts.isJsxExpression(parent) && parent.parent.kind !== 260 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo // At `,`, treat this as the next argument after the comma. - ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 26 /* CommaToken */ ? 1 : 0)) - : isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) + : ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) // completion at `x ===/**/` should be for the right side ? checker.getTypeAtLocation(parent.left) : checker.getContextualType(previousToken); } } - function getContextualTypeFromParent(node, checker) { - var parent = node.parent; - switch (parent.kind) { - case 190 /* NewExpression */: - return checker.getContextualType(parent); - case 202 /* BinaryExpression */: { - var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; - return isEqualityOperatorKind(operatorToken.kind) - ? checker.getTypeAtLocation(node === right ? left : right) - : checker.getContextualType(node); - } - case 269 /* CaseClause */: - return parent.expression === node ? getSwitchedType(parent, checker) : undefined; - default: - return checker.getContextualType(node); - } - } - function getSwitchedType(caseClause, checker) { - return checker.getTypeAtLocation(caseClause.parent.parent.expression); - } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); if (chain) @@ -92606,7 +96126,7 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 277 /* SourceFile */; }); + return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; }); } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { var typeChecker = program.getTypeChecker(); @@ -92657,11 +96177,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 281 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 303 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -92708,21 +96228,21 @@ var ts; return undefined; } var parent = contextToken.parent; - if (contextToken.kind === 23 /* DotToken */) { + if (contextToken.kind === 24 /* DotToken */) { isRightOfDot = true; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; break; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: node = parent.left; break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: node = parent.name; break; - case 181 /* ImportType */: - case 212 /* MetaProperty */: + case 183 /* ImportType */: + case 214 /* MetaProperty */: node = parent; break; default: @@ -92735,53 +96255,56 @@ var ts; // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 187 /* PropertyAccessExpression */) { + if (parent && parent.kind === 189 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } // Fix location if (currentToken.parent === location) { switch (currentToken.kind) { - case 29 /* GreaterThanToken */: - if (currentToken.parent.kind === 258 /* JsxElement */ || currentToken.parent.kind === 260 /* JsxOpeningElement */) { + case 30 /* GreaterThanToken */: + if (currentToken.parent.kind === 260 /* JsxElement */ || currentToken.parent.kind === 262 /* JsxOpeningElement */) { location = currentToken; } break; - case 41 /* SlashToken */: - if (currentToken.parent.kind === 259 /* JsxSelfClosingElement */) { + case 42 /* SlashToken */: + if (currentToken.parent.kind === 261 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 261 /* JsxClosingElement */: - if (contextToken.kind === 41 /* SlashToken */) { + case 263 /* JsxClosingElement */: + if (contextToken.kind === 42 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 259 /* JsxSelfClosingElement */: - case 258 /* JsxElement */: - case 260 /* JsxOpeningElement */: - if (contextToken.kind === 27 /* LessThanToken */) { + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + case 262 /* JsxOpeningElement */: + if (contextToken.kind === 28 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: switch (previousToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: isJsxInitializer = true; break; - case 71 /* Identifier */: + case 72 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 59 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -92803,6 +96326,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -92811,6 +96335,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -92827,11 +96352,11 @@ var ts; return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: - case 298 /* JSDocReturnTag */: - case 300 /* JSDocTypeTag */: - case 302 /* JSDocTypedefTag */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 304 /* JSDocTypedefTag */: return true; default: return false; @@ -92871,15 +96396,15 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 277 /* SourceFile */ && d.kind !== 242 /* ModuleDeclaration */ && d.kind !== 241 /* EnumDeclaration */; })) { + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; } } } - if (ts.isMetaProperty(node) && (node.keywordToken === 94 /* NewKeyword */ || node.keywordToken === 91 /* ImportKeyword */)) { - var completion = (node.keywordToken === 94 /* NewKeyword */) ? "target" : "meta"; + if (ts.isMetaProperty(node) && (node.keywordToken === 95 /* NewKeyword */ || node.keywordToken === 92 /* ImportKeyword */)) { + var completion = (node.keywordToken === 95 /* NewKeyword */) ? "target" : "meta"; symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); return; } @@ -92900,7 +96425,7 @@ var ts; else { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 181 /* ImportType */ ? node : node.parent, type, symbol)) { + if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 183 /* ImportType */ ? node : node.parent, type, symbol)) { addPropertySymbol(symbol); } } @@ -92948,24 +96473,22 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { var jsxContainer = tryGetContainingJsxElement(contextToken); // Cursor is inside a JSX self-closing element or opening element - var attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); if (!attrsType) return 0 /* Continue */; - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties); completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93002,10 +96525,11 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var isTypeOnly = isTypeOnlyCompletion(); + var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode); if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { @@ -93030,31 +96554,31 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 277 /* SourceFile */: - case 204 /* TemplateExpression */: - case 268 /* JsxExpression */: - case 216 /* Block */: + case 279 /* SourceFile */: + case 206 /* TemplateExpression */: + case 270 /* JsxExpression */: + case 218 /* Block */: return true; default: return ts.isStatement(scopeNode); } } function filterGlobalCompletion(symbols) { - var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); - if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + var isTypeOnly = isTypeOnlyCompletion(); + var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); + if (isTypeOnly) + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93069,52 +96593,49 @@ var ts; if (allowTypes) { // Its a type, but you can reach it by namespace.type as well var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); - if (symbolAllowedAsType || isTypeOnlyCompletion) { + if (symbolAllowedAsType || isTypeOnly) { return symbolAllowedAsType; } } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } + function isTypeOnlyCompletion() { + return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 103 /* TypeOfKeyword */ && - (contextToken.parent.kind === 165 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + contextToken.kind === 104 /* TypeOfKeyword */ && + (contextToken.parent.kind === 167 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { - case 56 /* ColonToken */: - return parentKind === 152 /* PropertyDeclaration */ || - parentKind === 151 /* PropertySignature */ || - parentKind === 149 /* Parameter */ || - parentKind === 235 /* VariableDeclaration */ || + case 57 /* ColonToken */: + return parentKind === 154 /* PropertyDeclaration */ || + parentKind === 153 /* PropertySignature */ || + parentKind === 151 /* Parameter */ || + parentKind === 237 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); - case 58 /* EqualsToken */: - return parentKind === 240 /* TypeAliasDeclaration */; - case 118 /* AsKeyword */: - return parentKind === 210 /* AsExpression */; + case 59 /* EqualsToken */: + return parentKind === 242 /* TypeAliasDeclaration */; + case 119 /* AsKeyword */: + return parentKind === 212 /* AsExpression */; } } return false; } - function symbolCanBeReferencedAtTypeLocation(symbol) { - symbol = symbol.exportSymbol || symbol; - // This is an alias, follow what it aliases - symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { - return true; - } - if (symbol.flags & 1536 /* Module */) { - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - // If the exported symbols contains type, - // symbol can be referenced at locations where type is allowed - return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); - } - return false; + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { + if (seenModules === void 0) { seenModules = ts.createMap(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); + return !!(sym.flags & 67897832 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { var tokenTextLowerCase = tokenText.toLowerCase(); @@ -93129,19 +96650,29 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details. // This is just to avoid adding duplicate completion entries. // - // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. - // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + // If `symbol.parent !== ...`, this is an `export * from "foo"` re-export. Those don't create new symbols. if (typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol - || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + || ts.some(symbol.declarations, function (d) { + // If `!!d.name.originalKeywordKind`, this is `export { _break as break };` -- skip this and prefer the keyword completion. + // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + return ts.isExportSpecifier(d) && (d.propertyName ? ts.isIdentifierANonContextualKeyword(d.name) : !!d.parent.parent.moduleSpecifier); + })) { continue; } - var isDefaultExport = symbol.name === "default" /* Default */; + var isDefaultExport = symbol.escapedName === "default" /* Default */; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } @@ -93195,15 +96726,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 10 /* JsxText */) { + if (contextToken.kind === 11 /* JsxText */) { return true; } - if (contextToken.kind === 29 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 260 /* JsxOpeningElement */) { + if (contextToken.kind === 30 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 262 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 261 /* JsxClosingElement */ || contextToken.parent.kind === 259 /* JsxSelfClosingElement */) { - return !!contextToken.parent.parent && contextToken.parent.parent.kind === 258 /* JsxElement */; + if (contextToken.parent.kind === 263 /* JsxClosingElement */ || contextToken.parent.kind === 261 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 260 /* JsxElement */; } } return false; @@ -93213,41 +96744,41 @@ var ts; var containingNodeKind = previousToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(previousToken)) { - case 26 /* CommaToken */: - return containingNodeKind === 189 /* CallExpression */ // func( a, | - || containingNodeKind === 155 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 190 /* NewExpression */ // new C(a, | - || containingNodeKind === 185 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 202 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 163 /* FunctionType */; // var x: (s: string, list| - case 19 /* OpenParenToken */: - return containingNodeKind === 189 /* CallExpression */ // func( | - || containingNodeKind === 155 /* Constructor */ // constructor( | - || containingNodeKind === 190 /* NewExpression */ // new C(a| - || containingNodeKind === 193 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 175 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ - case 21 /* OpenBracketToken */: - return containingNodeKind === 185 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 160 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 147 /* ComputedPropertyName */; // [ | /* this can become an index signature */ - case 129 /* ModuleKeyword */: // module | - case 130 /* NamespaceKeyword */: // namespace | + case 27 /* CommaToken */: + return containingNodeKind === 191 /* CallExpression */ // func( a, | + || containingNodeKind === 157 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 192 /* NewExpression */ // new C(a, | + || containingNodeKind === 187 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 204 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 165 /* FunctionType */; // var x: (s: string, list| + case 20 /* OpenParenToken */: + return containingNodeKind === 191 /* CallExpression */ // func( | + || containingNodeKind === 157 /* Constructor */ // constructor( | + || containingNodeKind === 192 /* NewExpression */ // new C(a| + || containingNodeKind === 195 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 177 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 22 /* OpenBracketToken */: + return containingNodeKind === 187 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 162 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 149 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 130 /* ModuleKeyword */: // module | + case 131 /* NamespaceKeyword */: // namespace | return true; - case 23 /* DotToken */: - return containingNodeKind === 242 /* ModuleDeclaration */; // module A.| - case 17 /* OpenBraceToken */: - return containingNodeKind === 238 /* ClassDeclaration */; // class A{ | - case 58 /* EqualsToken */: - return containingNodeKind === 235 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 202 /* BinaryExpression */; // x = a| - case 14 /* TemplateHead */: - return containingNodeKind === 204 /* TemplateExpression */; // `aa ${| - case 15 /* TemplateMiddle */: - return containingNodeKind === 214 /* TemplateSpan */; // `aa ${10} dd ${| - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - return containingNodeKind === 152 /* PropertyDeclaration */; // class A{ public | + case 24 /* DotToken */: + return containingNodeKind === 244 /* ModuleDeclaration */; // module A.| + case 18 /* OpenBraceToken */: + return containingNodeKind === 240 /* ClassDeclaration */; // class A{ | + case 59 /* EqualsToken */: + return containingNodeKind === 237 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 204 /* BinaryExpression */; // x = a| + case 15 /* TemplateHead */: + return containingNodeKind === 206 /* TemplateExpression */; // `aa ${| + case 16 /* TemplateMiddle */: + return containingNodeKind === 216 /* TemplateSpan */; // `aa ${10} dd ${| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */; // class A{ public | } } return false; @@ -93274,16 +96805,16 @@ var ts; completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 186 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 188 /* ObjectLiteralExpression */) { var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return 2 /* Fail */; - isNewIdentifierLocation = hasIndexSignature(typeForObject); + isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker); existingMembers = objectLikeContainer.properties; } else { - ts.Debug.assert(objectLikeContainer.kind === 182 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 184 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -93294,12 +96825,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 225 /* ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 149 /* Parameter */) { + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 227 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 151 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 154 /* MethodDeclaration */ || rootDeclaration.parent.kind === 157 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 156 /* MethodDeclaration */ || rootDeclaration.parent.kind === 159 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -93335,13 +96866,13 @@ var ts; */ function tryGetImportOrExportClauseCompletionSymbols() { // `import { |` or `import { a as 0, | }` - var namedImportsOrExports = contextToken && (contextToken.kind === 17 /* OpenBraceToken */ || contextToken.kind === 26 /* CommaToken */) + var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; if (!namedImportsOrExports) return 0 /* Continue */; // cursor is in an import clause // try to show exported member for imported module - var moduleSpecifier = (namedImportsOrExports.kind === 250 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifier = (namedImportsOrExports.kind === 252 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -93364,14 +96895,15 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 40 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; var classElement = contextToken.parent; var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; // If this is context token is not something we are editing now, consider if this would lead to be modifier - if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + if (contextToken.kind === 72 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { switch (contextToken.getText()) { case "private": classElementModifierFlags = classElementModifierFlags | 8 /* Private */; @@ -93398,14 +96930,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { - case 17 /* OpenBraceToken */: // const x = { | - case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; + case 18 /* OpenBraceToken */: // const x = { | + case 27 /* CommaToken */: // const x = { a: 0, | if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 40 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 72 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93422,8 +96959,8 @@ var ts; if (contextToken) { var parent = contextToken.parent; switch (contextToken.kind) { - case 19 /* OpenParenToken */: - case 26 /* CommaToken */: + case 20 /* OpenParenToken */: + case 27 /* CommaToken */: return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; default: if (isConstructorParameterCompletion(contextToken)) { @@ -93453,17 +96990,23 @@ var ts; if (contextToken) { var parent = contextToken.parent; switch (contextToken.kind) { - case 28 /* LessThanSlashToken */: - case 41 /* SlashToken */: - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: - case 266 /* JsxAttributes */: - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 259 /* JsxSelfClosingElement */ || parent.kind === 260 /* JsxOpeningElement */)) { + case 30 /* GreaterThanToken */: // End of a type argument list + case 29 /* LessThanSlashToken */: + case 42 /* SlashToken */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 268 /* JsxAttributes */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) { + if (contextToken.kind === 30 /* GreaterThanToken */) { + var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); + if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */)) + break; + } return parent; } - else if (parent.kind === 265 /* JsxAttribute */) { + else if (parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93474,8 +97017,8 @@ var ts; // 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 && ((parent.kind === 265 /* JsxAttribute */) || (parent.kind === 267 /* JsxSpreadAttribute */))) { + case 10 /* StringLiteral */: + if (parent && ((parent.kind === 267 /* JsxAttribute */) || (parent.kind === 269 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93483,10 +97026,10 @@ var ts; return parent.parent.parent; } break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: if (parent && - parent.kind === 268 /* JsxExpression */ && - parent.parent && parent.parent.kind === 265 /* JsxAttribute */) { + parent.kind === 270 /* JsxExpression */ && + parent.parent && parent.parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93494,7 +97037,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 267 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 269 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93513,67 +97056,66 @@ var ts; var parent = contextToken.parent; var containingNodeKind = parent.kind; switch (contextToken.kind) { - case 26 /* CommaToken */: - return containingNodeKind === 235 /* VariableDeclaration */ || - containingNodeKind === 236 /* VariableDeclarationList */ || - containingNodeKind === 217 /* VariableStatement */ || - containingNodeKind === 241 /* EnumDeclaration */ || // enum a { foo, | + case 27 /* CommaToken */: + return containingNodeKind === 237 /* VariableDeclaration */ || + containingNodeKind === 238 /* VariableDeclarationList */ || + containingNodeKind === 219 /* VariableStatement */ || + containingNodeKind === 243 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A= contextToken.pos); - case 23 /* DotToken */: - return containingNodeKind === 183 /* ArrayBindingPattern */; // var [.| - case 56 /* ColonToken */: - return containingNodeKind === 184 /* BindingElement */; // var {x :html| - case 21 /* OpenBracketToken */: - return containingNodeKind === 183 /* ArrayBindingPattern */; // var [x| - case 19 /* OpenParenToken */: - return containingNodeKind === 272 /* CatchClause */ || + case 24 /* DotToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [.| + case 57 /* ColonToken */: + return containingNodeKind === 186 /* BindingElement */; // var {x :html| + case 22 /* OpenBracketToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [x| + case 20 /* OpenParenToken */: + return containingNodeKind === 274 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); - case 17 /* OpenBraceToken */: - return containingNodeKind === 241 /* EnumDeclaration */; // enum a { | - case 27 /* LessThanToken */: - return containingNodeKind === 238 /* ClassDeclaration */ || // class A< | - containingNodeKind === 207 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 240 /* TypeAliasDeclaration */ || // type List< | + case 18 /* OpenBraceToken */: + return containingNodeKind === 243 /* EnumDeclaration */; // enum a { | + case 28 /* LessThanToken */: + return containingNodeKind === 240 /* ClassDeclaration */ || // class A< | + containingNodeKind === 209 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 242 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); - case 115 /* StaticKeyword */: - return containingNodeKind === 152 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); - case 24 /* DotDotDotToken */: - return containingNodeKind === 149 /* Parameter */ || - (!!parent.parent && parent.parent.kind === 183 /* ArrayBindingPattern */); // var [...z| - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - return containingNodeKind === 149 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); - case 118 /* AsKeyword */: - return containingNodeKind === 251 /* ImportSpecifier */ || - containingNodeKind === 255 /* ExportSpecifier */ || - containingNodeKind === 249 /* NamespaceImport */; - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 109 /* InterfaceKeyword */: - case 89 /* FunctionKeyword */: - case 104 /* VarKeyword */: - case 91 /* ImportKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 116 /* YieldKeyword */: - case 139 /* TypeKeyword */: // type htm| + case 116 /* StaticKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + case 25 /* DotDotDotToken */: + return containingNodeKind === 151 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 185 /* ArrayBindingPattern */); // var [...z| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 151 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + case 119 /* AsKeyword */: + return containingNodeKind === 253 /* ImportSpecifier */ || + containingNodeKind === 257 /* ExportSpecifier */ || + containingNodeKind === 251 /* NamespaceImport */; + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return !isFromObjectTypeDeclaration(contextToken); + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 110 /* InterfaceKeyword */: + case 90 /* FunctionKeyword */: + case 105 /* VarKeyword */: + case 92 /* ImportKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 117 /* YieldKeyword */: + case 140 /* TypeKeyword */: // type htm| return true; + case 40 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93593,22 +97135,23 @@ var ts; } // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 75 /* ClassKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 83 /* EnumKeyword */: - case 89 /* FunctionKeyword */: - case 109 /* InterfaceKeyword */: - case 110 /* LetKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 115 /* StaticKeyword */: - case 104 /* VarKeyword */: - case 116 /* YieldKeyword */: + case 118 /* AbstractKeyword */: + case 76 /* ClassKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 90 /* FunctionKeyword */: + case 110 /* InterfaceKeyword */: + case 111 /* LetKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 116 /* StaticKeyword */: + case 105 /* VarKeyword */: + case 117 /* YieldKeyword */: return true; + case 121 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -93617,7 +97160,7 @@ var ts; && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 155 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 157 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -93640,12 +97183,12 @@ 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 !== 273 /* PropertyAssignment */ && - m.kind !== 274 /* ShorthandPropertyAssignment */ && - m.kind !== 184 /* BindingElement */ && - m.kind !== 154 /* MethodDeclaration */ && - m.kind !== 156 /* GetAccessor */ && - m.kind !== 157 /* SetAccessor */) { + if (m.kind !== 275 /* PropertyAssignment */ && + m.kind !== 276 /* ShorthandPropertyAssignment */ && + m.kind !== 186 /* BindingElement */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -93655,7 +97198,7 @@ var ts; var existingName = void 0; if (ts.isBindingElement(m) && m.propertyName) { // include only identifiers in completion list - if (m.propertyName.kind === 71 /* Identifier */) { + if (m.propertyName.kind === 72 /* Identifier */) { existingName = m.propertyName.escapedText; } } @@ -93680,10 +97223,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 152 /* PropertyDeclaration */ && - m.kind !== 154 /* MethodDeclaration */ && - m.kind !== 156 /* GetAccessor */ && - m.kind !== 157 /* SetAccessor */) { + if (m.kind !== 154 /* PropertyDeclaration */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -93723,7 +97266,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 265 /* JsxAttribute */) { + if (attr.kind === 267 /* JsxAttribute */) { seenNames.set(attr.name.escapedText, true); } } @@ -93767,7 +97310,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 72 /* FirstKeyword */; i <= 145 /* LastKeyword */; i++) { + for (var i = 73 /* FirstKeyword */; i <= 147 /* LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -93782,17 +97325,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 121 /* AsyncKeyword */ || 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 125 /* DeclareKeyword */ || kind === 130 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 141 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -93800,37 +97345,26 @@ var ts; })); } function isInterfaceOrTypeLiteralCompletionKeyword(kind) { - return kind === 132 /* ReadonlyKeyword */; + return kind === 133 /* ReadonlyKeyword */; } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 117 /* AbstractKeyword */: - case 123 /* ConstructorKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 120 /* AsyncKeyword */: + case 118 /* AbstractKeyword */: + case 124 /* ConstructorKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 121 /* AsyncKeyword */: return true; default: return ts.isClassMemberModifier(kind); } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 121 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } - function isEqualityOperatorKind(kind) { - switch (kind) { - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - return true; - default: - return false; - } - } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { var jsdoc = ts.findAncestor(node, ts.isJSDoc); @@ -93840,7 +97374,7 @@ var ts; return contextualType.isUnion() ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. - return !(memberType.flags & 32764 /* Primitive */ || + return !(memberType.flags & 131068 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker) || checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); @@ -93863,31 +97397,31 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 304 /* SyntaxList */: + case 306 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); - if (cls && !ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile)) { + if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) { return cls; } } if (!contextToken) return undefined; switch (contextToken.kind) { - case 25 /* SemicolonToken */: // class c {getValue(): number; | } - case 18 /* CloseBraceToken */: // class c { method() { } | } + case 26 /* SemicolonToken */: // class c {getValue(): number; | } + case 19 /* CloseBraceToken */: // class c { method() { } | } // class c { method() { } b| } return isFromObjectTypeDeclaration(location) && location.parent.name === location ? location.parent.parent : ts.tryCast(location, ts.isObjectTypeDeclaration); - case 17 /* OpenBraceToken */: // class c { | - case 26 /* CommaToken */: // class c {getValue(): number, | } + case 18 /* OpenBraceToken */: // class c { | + case 27 /* CommaToken */: // class c {getValue(): number, | } return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); default: if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 40 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -93895,9 +97429,6 @@ var ts; function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); } - function hasIndexSignature(type) { - return !!type.getStringIndexType() || !!type.getNumberIndexType(); - } function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { case ".": @@ -93907,14 +97438,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 28 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 42 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -93923,17 +97454,6 @@ var ts; var left = _a.left; return ts.nodeIsMissing(left); } - function isStringLiteralOrTemplate(node) { - switch (node.kind) { - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 191 /* TaggedTemplateExpression */: - return true; - default: - return false; - } - } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -93986,40 +97506,40 @@ var ts; } function getHighlightSpans(node, sourceFile) { switch (node.kind) { - case 90 /* IfKeyword */: - case 82 /* ElseKeyword */: + case 91 /* IfKeyword */: + case 83 /* ElseKeyword */: return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; - case 96 /* ReturnKeyword */: + case 97 /* ReturnKeyword */: return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); - case 100 /* ThrowKeyword */: + case 101 /* ThrowKeyword */: return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); - case 102 /* TryKeyword */: - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: - var tryStatement = node.kind === 74 /* CatchKeyword */ ? node.parent.parent : node.parent; + case 103 /* TryKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + var tryStatement = node.kind === 75 /* CatchKeyword */ ? node.parent.parent : node.parent; return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); - case 98 /* SwitchKeyword */: + case 99 /* SwitchKeyword */: return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); - case 73 /* CaseKeyword */: - case 79 /* DefaultKeyword */: + case 74 /* CaseKeyword */: + case 80 /* DefaultKeyword */: return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); - case 72 /* BreakKeyword */: - case 77 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 78 /* ContinueKeyword */: return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); - case 88 /* ForKeyword */: - case 106 /* WhileKeyword */: - case 81 /* DoKeyword */: + case 89 /* ForKeyword */: + case 107 /* WhileKeyword */: + case 82 /* DoKeyword */: return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); - case 123 /* ConstructorKeyword */: - return getFromAllDeclarations(ts.isConstructorDeclaration, [123 /* ConstructorKeyword */]); - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]); - case 121 /* AwaitKeyword */: + case 124 /* ConstructorKeyword */: + return getFromAllDeclarations(ts.isConstructorDeclaration, [124 /* ConstructorKeyword */]); + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return getFromAllDeclarations(ts.isAccessor, [126 /* GetKeyword */, 137 /* SetKeyword */]); + case 122 /* AwaitKeyword */: return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: return highlightSpans(getAsyncAndAwaitOccurrences(node)); - case 116 /* YieldKeyword */: + case 117 /* YieldKeyword */: return highlightSpans(getYieldOccurrences(node)); default: return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) @@ -94062,7 +97582,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 277 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -94094,16 +97614,16 @@ var ts; function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 230 /* SwitchStatement */: - if (statement.kind === 226 /* ContinueStatement */) { + case 232 /* SwitchStatement */: + if (statement.kind === 228 /* ContinueStatement */) { return false; } // falls through - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. @@ -94119,11 +97639,11 @@ var ts; // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 243 /* ModuleBlock */: - case 277 /* SourceFile */: - case 216 /* Block */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 218 /* Block */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return declaration.members.concat([declaration]); @@ -94131,12 +97651,12 @@ var ts; else { return container.statements; } - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 237 /* FunctionDeclaration */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: var 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. @@ -94167,12 +97687,12 @@ var ts; } function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) { + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 89 /* ForKeyword */, 107 /* WhileKeyword */, 82 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 221 /* DoStatement */) { + if (loopNode.kind === 223 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) { + if (pushKeywordIf(keywords, loopTokens[i], 107 /* WhileKeyword */)) { break; } } @@ -94180,7 +97700,7 @@ var ts; } ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) { if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */, 77 /* ContinueKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */, 78 /* ContinueKeyword */); } }); return keywords; @@ -94189,13 +97709,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -94203,13 +97723,13 @@ var ts; } function getSwitchCaseDefaultOccurrences(switchStatement) { var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 98 /* SwitchKeyword */); + pushKeywordIf(keywords, switchStatement.getFirstToken(), 99 /* SwitchKeyword */); // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 73 /* CaseKeyword */, 79 /* DefaultKeyword */); + pushKeywordIf(keywords, clause.getFirstToken(), 74 /* CaseKeyword */, 80 /* DefaultKeyword */); ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) { if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */); } }); }); @@ -94217,13 +97737,13 @@ var ts; } function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 102 /* TryKeyword */); + pushKeywordIf(keywords, tryStatement.getFirstToken(), 103 /* TryKeyword */); if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 74 /* CatchKeyword */); + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 75 /* CatchKeyword */); } if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 87 /* FinallyKeyword */); + var finallyKeyword = ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 88 /* FinallyKeyword */); } return keywords; } @@ -94234,13 +97754,13 @@ var ts; } var keywords = []; ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - keywords.push(ts.findChildOfKind(throwStatement, 100 /* ThrowKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); }); // If the "owner" is a function, then we equate 'return' and 'throw' statements in their // ability to "jump out" of the function, and include occurrences for both. if (ts.isFunctionBlock(owner)) { ts.forEachReturnStatement(owner, function (returnStatement) { - keywords.push(ts.findChildOfKind(returnStatement, 96 /* ReturnKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); }); } return keywords; @@ -94252,11 +97772,11 @@ var ts; } var keywords = []; ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { - keywords.push(ts.findChildOfKind(returnStatement, 96 /* ReturnKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); }); // Include 'throw' statements that do not occur within a try block. ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - keywords.push(ts.findChildOfKind(throwStatement, 100 /* ThrowKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); }); return keywords; } @@ -94268,13 +97788,13 @@ var ts; var keywords = []; if (func.modifiers) { func.modifiers.forEach(function (modifier) { - pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */); + pushKeywordIf(keywords, modifier, 121 /* AsyncKeyword */); }); } ts.forEachChild(func, function (child) { traverseWithoutCrossingFunction(child, function (node) { if (ts.isAwaitExpression(node)) { - pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */); + pushKeywordIf(keywords, node.getFirstToken(), 122 /* AwaitKeyword */); } }); }); @@ -94289,7 +97809,7 @@ var ts; ts.forEachChild(func, function (child) { traverseWithoutCrossingFunction(child, function (node) { if (ts.isYieldExpression(node)) { - pushKeywordIf(keywords, node.getFirstToken(), 116 /* YieldKeyword */); + pushKeywordIf(keywords, node.getFirstToken(), 117 /* YieldKeyword */); } }); }); @@ -94308,7 +97828,7 @@ var ts; // We'd like to highlight else/ifs together if they are only separated by whitespace // (i.e. the keywords are separated by no comments, no newlines). for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 82 /* ElseKeyword */ && i < keywords.length - 1) { + if (keywords[i].kind === 83 /* ElseKeyword */ && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. var shouldCombineElseAndIf = true; @@ -94343,10 +97863,10 @@ var ts; // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. while (true) { var children = ifStatement.getChildren(sourceFile); - pushKeywordIf(keywords, children[0], 90 /* IfKeyword */); + pushKeywordIf(keywords, children[0], 91 /* IfKeyword */); // Generally the 'else' keyword is second-to-last, so we traverse backwards. for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 82 /* ElseKeyword */)) { + if (pushKeywordIf(keywords, children[i], 83 /* ElseKeyword */)) { break; } } @@ -94379,16 +97899,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } - function getBucketForCompilationSettings(key, createIfMissing) { - var bucket = buckets.get(key); - if (!bucket && createIfMissing) { - buckets.set(key, bucket = ts.createMap()); - } - return bucket; // TODO: GH#18217 - } function reportStats() { var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = buckets.get(name); @@ -94424,9 +97934,9 @@ var ts; return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); + var bucket = ts.getOrUpdate(buckets, key, ts.createMap); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94440,7 +97950,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94478,8 +97988,7 @@ var ts; return releaseDocumentWithKey(path, key); } function releaseDocumentWithKey(path, key) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); - ts.Debug.assert(bucket !== undefined); + var bucket = ts.Debug.assertDefined(buckets.get(key)); var entry = bucket.get(path); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); @@ -94507,6 +98016,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -94570,12 +98082,12 @@ var ts; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 235 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 237 /* VariableDeclaration */) { var name = parent.name; - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { directImports.push(name); break; } @@ -94584,22 +98096,22 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; - case 71 /* Identifier */: // for 'const x = require("y"); + case 72 /* Identifier */: // for 'const x = require("y"); break; // TODO: GH#23879 - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 251 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); @@ -94609,7 +98121,7 @@ var ts; directImports.push(direct); } break; - case 181 /* ImportType */: + case 183 /* ImportType */: directImports.push(direct); break; default: @@ -94626,7 +98138,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 277 /* SourceFile */ || sourceFileLike.kind === 242 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -94681,17 +98193,17 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 246 /* ImportEqualsDeclaration */) { + if (decl.kind === 248 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } return; } - if (decl.kind === 71 /* Identifier */) { + if (decl.kind === 72 /* Identifier */) { handleNamespaceImportLike(decl); return; } - if (decl.kind === 181 /* ImportType */) { + if (decl.kind === 183 /* ImportType */) { if (decl.qualifier) { if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { singleReferences.push(decl.qualifier); @@ -94703,20 +98215,20 @@ var ts; return; } // Ignore if there's a grammar error - if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) { + if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { return; } - if (decl.kind === 253 /* ExportDeclaration */) { + if (decl.kind === 255 /* ExportDeclaration */) { searchForNamedImport(decl.exportClause); return; } var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: handleNamespaceImportLike(namedBindings.name); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: // 'default' might be accessed as a named import `{ default as foo }`. if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { searchForNamedImport(namedBindings); @@ -94766,7 +98278,7 @@ var ts; } } else { - var localSymbol = element.kind === 255 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 257 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -94795,7 +98307,7 @@ var ts; for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { var referencingFile = sourceFiles_1[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 277 /* SourceFile */) { + if (searchSourceFile.kind === 279 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -94843,7 +98355,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 277 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -94858,15 +98370,15 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 253 /* ExportDeclaration */: - case 247 /* ImportDeclaration */: { + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 246 /* ImportEqualsDeclaration */: { + case 248 /* ImportEqualsDeclaration */: { var decl = statement; if (isExternalModuleImportEquals(decl)) { action(decl, decl.moduleReference.expression); @@ -94890,7 +98402,7 @@ var ts; var parent = node.parent; var grandParent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 187 /* PropertyAccessExpression */) { + if (parent.kind === 189 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) @@ -94910,7 +98422,7 @@ var ts; return undefined; } var lhsSymbol = checker.getSymbolAtLocation(exportNode.name); - return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false }; + return { kind: 0 /* Import */, symbol: lhsSymbol }; } else { return exportInfo(symbol, getExportKindForDeclaration(exportNode)); @@ -94943,7 +98455,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -94980,7 +98492,7 @@ var ts; // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { - return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); + return { kind: 0 /* Import */, symbol: importedSymbol }; } } function exportInfo(symbol, kind) { @@ -95012,10 +98524,10 @@ var ts; // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent, node) { - if (parent.kind === 235 /* VariableDeclaration */) { + if (parent.kind === 237 /* VariableDeclaration */) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 272 /* CatchClause */ ? undefined : p.parent.parent.kind === 217 /* VariableStatement */ ? p.parent.parent : undefined; + p.parent.kind === 274 /* CatchClause */ ? undefined : p.parent.parent.kind === 219 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -95024,19 +98536,17 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 246 /* ImportEqualsDeclaration */: - return parent.name === node && isExternalModuleImportEquals(parent) - ? { isNamedImport: false } - : undefined; - case 251 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + return parent.name === node && isExternalModuleImportEquals(parent); + case 253 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. - return parent.propertyName ? undefined : { isNamedImport: true }; - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: + return !parent.propertyName; + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: ts.Debug.assert(parent.name === node); - return { isNamedImport: false }; + return true; default: - return undefined; + return false; } } function getExportInfo(exportSymbol, exportKind, checker) { @@ -95065,21 +98575,21 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 277 /* SourceFile */) { + if (parent.kind === 279 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 243 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 245 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; + return node.kind === 244 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; } function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 257 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */; + return eq.moduleReference.kind === 259 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95088,8 +98598,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95114,18 +98641,18 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { var result_1 = []; FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); }); return result_1; } - else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" var symbol = checker.getSymbolAtLocation(node); @@ -95136,10 +98663,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95152,28 +98679,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_1 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_1, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_1 = def.node; return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_2 = def.node; var name_2 = ts.tokenToString(node_2.kind); return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_3 = def.node; var symbol = checker.getSymbolAtLocation(node_3); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")]; return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_4 = def.node; return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95187,28 +98714,67 @@ var ts; } function getDefinitionKindAndDisplayParts(symbol, checker, node) { var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); - var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node; + var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode, checker) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), - isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + isDefinition: node.kind === 80 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode, checker) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + var prefixColon = { prefixText: name + ": " }; + var suffixColon = { suffixText: ": " + name }; + return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon + : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : isShorthandAssignment ? suffixColon : prefixColon; + } + else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + // If the original symbol was using this alias, just rename the alias. + var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); + return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions; + } + else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name }; + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95223,16 +98789,16 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 186 /* ObjectLiteralExpression */) { + else if (node.kind === 188 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, - displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] }; } - else if (node.kind === 207 /* ClassExpression */) { + else if (node.kind === 209 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, - displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] }; } else { @@ -95240,17 +98806,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95258,7 +98824,7 @@ var ts; function getTextSpan(node, sourceFile) { var start = node.getStart(sourceFile); var end = node.getEnd(); - if (node.kind === 9 /* StringLiteral */) { + if (node.kind === 10 /* StringLiteral */) { start += 1; end -= 1; } @@ -95266,7 +98832,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 80 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 204 /* BinaryExpression */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 80 /* DefaultKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 257 /* ExportSpecifier */: + case 250 /* ImportClause */: // default import + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 241 /* InterfaceDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 267 /* JsxAttribute */: + case 244 /* ModuleDeclaration */: + case 247 /* NamespaceExportDeclaration */: + case 251 /* NamespaceImport */: + case 151 /* Parameter */: + case 276 /* ShorthandPropertyAssignment */: + case 242 /* TypeAliasDeclaration */: + case 150 /* TypeParameter */: + return true; + case 275 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return !!decl.body; + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 155 /* MethodSignature */: + case 153 /* PropertySignature */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95299,6 +98920,9 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } + if (symbol.escapedName === "export=" /* ExportEquals */) { + return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } var moduleReferences = ts.emptyArray; var moduleSourceFile = isModuleSymbol(symbol); var referencedNode = node; @@ -95330,11 +98954,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95343,12 +98967,12 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95356,7 +98980,23 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + var exported = symbol.exports.get("export=" /* ExportEquals */); + if (exported) { + for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { + var decl = _c[_b]; + var sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + // At `module.exports = ...`, reference node is `module` + var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) + ? decl.left.expression + : ts.isExportAssignment(decl) + ? ts.Debug.assertDefined(ts.findChildOfKind(decl, 85 /* ExportKeyword */, sourceFile)) + : ts.getNameOfDeclaration(decl) || decl; + references.push(FindAllReferences.nodeEntry(node)); + } + } + } + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95377,24 +99017,29 @@ var ts; if (ts.isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); } - if (node.kind === 97 /* SuperKeyword */) { + if (node.kind === 98 /* SuperKeyword */) { return getReferencesForSuperKeyword(node); } return undefined; } /** Core find-all-references algorithm for a normal symbol. */ - function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; // Compute the meaning from the location and the symbol it references var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - if (node && node.kind === 79 /* DefaultKeyword */) { + var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + if (exportSpecifier) { + // When renaming at an export specifier, rename the export and not the thing being exported. + getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); + } + else if (node && node.kind === 80 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -95414,9 +99059,9 @@ var ts; } function getSpecialSearchKind(node) { switch (node.kind) { - case 123 /* ConstructorKeyword */: + case 124 /* ConstructorKeyword */: return 1 /* Constructor */; - case 71 /* Identifier */: + case 72 /* Identifier */: if (ts.isClassLike(node.parent)) { ts.Debug.assert(node.parent.name === node); return 2 /* Class */; @@ -95427,15 +99072,11 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { var parent = node.parent; - if (ts.isExportSpecifier(parent)) { + if (ts.isExportSpecifier(parent) && !isForRename) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); } - if (ts.isImportSpecifier(parent) && parent.propertyName === node) { - // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. - return checker.getImmediateAliasedSymbol(symbol); - } // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. return ts.firstDefined(symbol.declarations, function (decl) { if (!decl.parent) { @@ -95525,15 +99166,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -95598,7 +99239,8 @@ var ts; var indirectUser = indirectUsers_2[_b]; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; - if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) { + // Import specifiers should be handled by importSearches + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { cb(node); } } @@ -95614,7 +99256,7 @@ var ts; if (!ts.isIdentifier(singleRef)) return false; // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */); } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { @@ -95636,19 +99278,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -95661,7 +99290,7 @@ 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 declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 194 /* FunctionExpression */ || valueDeclaration.kind === 207 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 196 /* FunctionExpression */ || valueDeclaration.kind === 209 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -95671,14 +99300,14 @@ var ts; if (flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 238 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 240 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -95700,7 +99329,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -95721,7 +99350,9 @@ var ts; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { - var symbol = checker.getSymbolAtLocation(definition); + var symbol = ts.isParameterPropertyDeclaration(definition.parent) + ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) + : checker.getSymbolAtLocation(definition); if (!symbol) return undefined; for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { @@ -95801,21 +99432,21 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node.text.length === searchSymbolName.length; - case 9 /* StringLiteral */: { + case 10 /* StringLiteral */: { var str = node; - return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && str.text.length === searchSymbolName.length; } case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; - case 79 /* DefaultKeyword */: + case 80 /* DefaultKeyword */: return "default".length === searchSymbolName.length; default: return false; @@ -95828,7 +99459,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -95879,7 +99510,7 @@ var ts; return; } if (ts.isExportSpecifier(parent)) { - ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */); + ts.Debug.assert(referenceLocation.kind === 72 /* Identifier */); getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); return; } @@ -95904,16 +99535,16 @@ var ts; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) { + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); - if (!search.includes(localSymbol)) { + if (!alwaysGetReferences && !search.includes(localSymbol)) { return; } if (!propertyName) { // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) - if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) { + if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) { addRef(); } } @@ -95924,7 +99555,7 @@ var ts; addRef(); } if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { - addReference(name, referenceSymbol, state); + addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state); } } else { @@ -95933,15 +99564,14 @@ var ts; } } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!(referenceLocation === propertyName && state.options.isForRename)) { - var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; - var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); - if (!exportInfo) - return ts.Debug.fail(); - searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); + if (!state.options.isForRename || alwaysGetReferences) { + var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; + var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); + var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. - if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) { + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (imported) searchForImportedSymbol(imported, state); @@ -95973,12 +99603,11 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0 /* Import */) { - if (!state.options.isForRename || importOrExport.isNamedImport) { + if (!state.options.isForRename) { searchForImportedSymbol(symbol, state); } } else { - // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching. searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); } } @@ -95998,12 +99627,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96013,7 +99643,7 @@ var ts; } var pusher = function () { return state.referenceAdder(search.symbol); }; if (ts.isClassLike(referenceLocation.parent)) { - ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); + ts.Debug.assert(referenceLocation.kind === 80 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. findOwnConstructorReferences(search.symbol, sourceFile, pusher()); } @@ -96039,7 +99669,7 @@ var ts; } if (member.body) { member.body.forEachChild(function cb(node) { - if (node.kind === 99 /* ThisKeyword */) { + if (node.kind === 100 /* ThisKeyword */) { addRef(node); } else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { @@ -96056,16 +99686,16 @@ var ts; function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 155 /* Constructor */ && !!ctrKeyword); + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 154 /* MethodDeclaration */) { + if (decl && decl.kind === 156 /* MethodDeclaration */) { var body = decl.body; if (body) { - forEachDescendantOfKind(body, 99 /* ThisKeyword */, function (thisKeyword) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { if (ts.isNewExpressionTarget(thisKeyword)) { addNode(thisKeyword); } @@ -96082,10 +99712,10 @@ var ts; } for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 155 /* Constructor */); + ts.Debug.assert(decl.kind === 157 /* Constructor */); var body = decl.body; if (body) { - forEachDescendantOfKind(body, 97 /* SuperKeyword */, function (node) { + forEachDescendantOfKind(body, 98 /* SuperKeyword */, function (node) { if (ts.isCallExpressionTarget(node)) { addNode(node); } @@ -96099,10 +99729,10 @@ var ts; addReference(refNode); return; } - if (refNode.kind !== 71 /* Identifier */) { + if (refNode.kind !== 72 /* Identifier */) { return; } - if (refNode.parent.kind === 274 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 276 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -96122,7 +99752,7 @@ var ts; } else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { var body = typeHavingNode.body; - if (body.kind === 216 /* Block */) { + if (body.kind === 218 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression) addIfImplementation(returnStatement.expression); @@ -96150,13 +99780,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 195 /* ArrowFunction */: - case 194 /* FunctionExpression */: - case 186 /* ObjectLiteralExpression */: - case 207 /* ClassExpression */: - case 185 /* ArrayLiteralExpression */: + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 187 /* ArrayLiteralExpression */: return true; default: return false; @@ -96209,13 +99839,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -96224,7 +99854,7 @@ var ts; } var sourceFile = searchSpaceNode.getSourceFile(); var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) { - if (node.kind !== 97 /* SuperKeyword */) { + if (node.kind !== 98 /* SuperKeyword */) { return; } var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); @@ -96233,41 +99863,41 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // falls through - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // falls through - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* 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. default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 277 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -96275,24 +99905,25 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: return searchSpaceNode.symbol === container.symbol; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; - case 277 /* SourceFile */: - return container.kind === 277 /* SourceFile */ && !ts.isExternalModule(container); + case 279 /* SourceFile */: + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96300,39 +99931,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // 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 - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96344,8 +99961,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // 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 + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96358,11 +99993,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96370,19 +100007,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96471,14 +100108,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96486,7 +100123,7 @@ var ts; function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); return function (path) { - var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 }); var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); return originalPath ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) @@ -96505,7 +100142,7 @@ var ts; var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); return combinePathsSafe(ts.getDirectoryPath(a1), rel); } - function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; if (!configFile) return; @@ -96523,7 +100160,8 @@ var ts; var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); // If there isn't some include for this, add a new one. - if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if (ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); } } @@ -96574,7 +100212,7 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); var _loop_3 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); @@ -96602,7 +100240,7 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; @@ -96632,16 +100270,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -96655,7 +100300,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -96697,7 +100342,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -96709,7 +100354,7 @@ var ts; else { var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; // For a 'super()' call, put the signature first, else put the variable first. - return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); + return node.kind === 98 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -96717,7 +100362,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; } @@ -96870,18 +100515,18 @@ var ts; // (2) when the aliased symbol is originating from an import. // function shouldSkipAlias(node, declaration) { - if (node.kind !== 71 /* Identifier */) { + if (node.kind !== 72 /* Identifier */) { return false; } if (node.parent === declaration) { return true; } switch (declaration.kind) { - case 248 /* ImportClause */: - case 246 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: return true; - case 251 /* ImportSpecifier */: - return declaration.parent.kind === 250 /* NamedImports */; + case 253 /* ImportSpecifier */: + return declaration.parent.kind === 252 /* NamedImports */; default: return false; } @@ -96891,7 +100536,7 @@ var ts; function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */)) { + if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 124 /* ConstructorKeyword */)) { var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } @@ -96963,6 +100608,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97075,11 +100730,11 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: return [declaration]; - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -97100,16 +100755,16 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return withNode(tag.class); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 303 /* JSDocPropertyTag */: - case 297 /* JSDocParameterTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -97173,7 +100828,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97206,7 +100861,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97269,7 +100924,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97286,7 +100941,7 @@ var ts; function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { return parameters.map(function (_a, i) { var name = _a.name, dotDotDotToken = _a.dotDotDotToken; - var paramName = name.kind === 71 /* Identifier */ ? name.text : "param" + i; + var paramName = name.kind === 72 /* Identifier */ ? name.text : "param" + i; var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; return indentationStr + " * @param " + type + paramName + newLine; }).join(""); @@ -97296,23 +100951,23 @@ var ts; } function getCommentOwnerInfoWorker(commentOwner) { switch (commentOwner.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 155 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return getCommentOwnerInfoWorker(commentOwner.initializer); - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 151 /* PropertySignature */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 240 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 153 /* PropertySignature */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 242 /* TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer @@ -97320,16 +100975,16 @@ var ts; : undefined; return { commentOwner: commentOwner, parameters: parameters_1 }; } - case 277 /* SourceFile */: + case 279 /* SourceFile */: return "quit"; - case 242 /* ModuleDeclaration */: + case 244 /* 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 { }'. - return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 202 /* BinaryExpression */: { + return commentOwner.parent.kind === 244 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 204 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97346,14 +101001,14 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 193 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 195 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return rightHandSide.parameters; - case 207 /* ClassExpression */: { + case 209 /* ClassExpression */: { var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); return ctr ? ctr.parameters : ts.emptyArray; } @@ -97415,9 +101070,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 248 /* ImportClause */: - case 251 /* ImportSpecifier */: - case 246 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -97427,7 +101082,7 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - return !!name && (pushLiteral(name, containers) || name.kind === 147 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + return !!name && (pushLiteral(name, containers) || name.kind === 149 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // @@ -97444,7 +101099,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + if (name && name.kind === 149 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } // Don't include the last portion. @@ -97613,7 +101268,7 @@ var ts; return; } switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -97625,21 +101280,21 @@ var ts; } } break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 155 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -97651,7 +101306,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings.kind === 251 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -97662,8 +101317,8 @@ var ts; } } break; - case 184 /* BindingElement */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); @@ -97684,12 +101339,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -97699,9 +101354,9 @@ var ts; } endNode(); break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -97709,19 +101364,19 @@ var ts; } endNode(); break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 255 /* ExportSpecifier */: - case 246 /* ImportEqualsDeclaration */: - case 160 /* IndexSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 240 /* TypeAliasDeclaration */: + case 257 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 162 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 242 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: { + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -97732,6 +101387,9 @@ var ts; case 4 /* ThisProperty */: case 5 /* Property */: case 0 /* None */: + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: break; default: ts.Debug.assertNever(special); @@ -97799,12 +101457,12 @@ var ts; return false; } switch (a.kind) { - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return areSameModule(a, b); default: return true; @@ -97820,7 +101478,7 @@ var ts; // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { // TODO: GH#18217 - return a.body.kind === b.body.kind && (a.body.kind !== 242 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 244 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { @@ -97850,7 +101508,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 242 /* ModuleDeclaration */) { + if (node.kind === 244 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -97858,16 +101516,16 @@ var ts; return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 207 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: return getFunctionOrClassName(node); default: return undefined; } } function getItemName(node, name) { - if (node.kind === 242 /* ModuleDeclaration */) { + if (node.kind === 244 /* ModuleDeclaration */) { return getModuleName(node); } if (name) { @@ -97877,16 +101535,16 @@ var ts; } } switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -97894,13 +101552,13 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the // navigation bar. return getFunctionOrClassName(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return "constructor"; - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return "new()"; - case 158 /* CallSignature */: + case 160 /* CallSignature */: return "()"; - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return "[]"; default: return ""; @@ -97924,25 +101582,25 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 241 /* EnumDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 277 /* SourceFile */: - case 240 /* TypeAliasDeclaration */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 242 /* TypeAliasDeclaration */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return true; - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 235 /* VariableDeclaration */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 237 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -97952,10 +101610,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 243 /* ModuleBlock */: - case 277 /* SourceFile */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: return true; default: return hasSomeImportantChild(item); @@ -97964,7 +101622,7 @@ var ts; function hasSomeImportantChild(item) { return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 235 /* VariableDeclaration */ && childKind !== 184 /* BindingElement */; + return childKind !== 237 /* VariableDeclaration */ && childKind !== 186 /* BindingElement */; }); } } @@ -98021,7 +101679,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -98035,47 +101693,68 @@ var ts; return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 147 /* ComputedPropertyName */; + return !member.name || member.name.kind === 149 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 277 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 235 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 195 /* ArrowFunction */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: return true; default: return false; @@ -98202,7 +101881,7 @@ var ts; ? specifier.text : undefined; } - /* @internal */ // Internal for testing + // Internal for testing /** * @param importGroup a list of ImportDeclarations, all with the same module name. */ @@ -98301,7 +101980,7 @@ var ts; } } OrganizeImports.coalesceImports = coalesceImports; - /* @internal */ // Internal for testing + // Internal for testing /** * @param exportGroup a list of ExportDeclarations, all with the same module name. */ @@ -98404,7 +102083,7 @@ var ts; } var lastImport = current - 1; if (lastImport !== firstImport) { - out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 92 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); } } function visitNonImportNode(n) { @@ -98511,31 +102190,31 @@ var ts; } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(n)) { - return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 195 /* ArrowFunction */); + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 197 /* ArrowFunction */); } // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { - case 221 /* DoStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 220 /* IfStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 272 /* CatchClause */: + case 223 /* DoStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 274 /* CatchClause */: return spanForNode(n.parent); - case 233 /* TryStatement */: + case 235 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { return spanForNode(n.parent); } else if (tryStatement.finallyBlock === n) { - return spanForNode(ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile)); + return spanForNode(ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile)); } // falls through default: @@ -98543,21 +102222,21 @@ var ts; // the span of the block, independent of any parent span. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return spanForNode(n.parent); - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 244 /* CaseBlock */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 246 /* CaseBlock */: return spanForNode(n); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 185 /* ArrayLiteralExpression */: - return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); - case 258 /* JsxElement */: + case 187 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); + case 260 /* JsxElement */: return spanForJSXElement(n); - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); } function spanForJSXElement(node) { @@ -98573,7 +102252,7 @@ var ts; return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } function spanForObjectOrArrayLiteral(node, open) { - if (open === void 0) { open = 17 /* OpenBraceToken */; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } // If the block has no leading keywords and is inside an array literal, // we only want to collapse the span of the block. // Otherwise, the collapsed section will include the end of the previous line. @@ -98582,9 +102261,9 @@ var ts; function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { if (autoCollapse === void 0) { autoCollapse = false; } if (useFullStart === void 0) { useFullStart = true; } - if (open === void 0) { open = 17 /* OpenBraceToken */; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } var openToken = ts.findChildOfKind(n, open, sourceFile); - var close = open === 17 /* OpenBraceToken */ ? 18 /* CloseBraceToken */ : 22 /* CloseBracketToken */; + var close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; var closeToken = ts.findChildOfKind(n, close, sourceFile); if (!openToken || !closeToken) { return undefined; @@ -98943,11 +102622,11 @@ var ts; characterSpans: breakIntoCharacterSpans(text) }; } - /* @internal */ function breakIntoCharacterSpans(identifier) { + function breakIntoCharacterSpans(identifier) { return breakIntoSpans(identifier, /*word:*/ false); } ts.breakIntoCharacterSpans = breakIntoCharacterSpans; - /* @internal */ function breakIntoWordSpans(identifier) { + function breakIntoWordSpans(identifier) { return breakIntoSpans(identifier, /*word:*/ true); } ts.breakIntoWordSpans = breakIntoWordSpans; @@ -99087,10 +102766,10 @@ var ts; function nextToken() { lastToken = currentToken; currentToken = ts.scanner.scan(); - if (currentToken === 17 /* OpenBraceToken */) { + if (currentToken === 18 /* OpenBraceToken */) { braceNesting++; } - else if (currentToken === 18 /* CloseBraceToken */) { + else if (currentToken === 19 /* CloseBraceToken */) { braceNesting--; } return currentToken; @@ -99120,12 +102799,12 @@ var ts; */ function tryConsumeDeclare() { var token = ts.scanner.getToken(); - if (token === 124 /* DeclareKeyword */) { + if (token === 125 /* DeclareKeyword */) { // declare module "mod" token = nextToken(); - if (token === 129 /* ModuleKeyword */) { + if (token === 130 /* ModuleKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { recordAmbientExternalModule(); } } @@ -99137,42 +102816,42 @@ var ts; * Returns true if at least one token was consumed from the stream */ function tryConsumeImport() { - if (lastToken === 23 /* DotToken */) { + if (lastToken === 24 /* DotToken */) { return false; } var token = ts.scanner.getToken(); - if (token === 91 /* ImportKeyword */) { + if (token === 92 /* ImportKeyword */) { token = nextToken(); - if (token === 19 /* OpenParenToken */) { + if (token === 20 /* OpenParenToken */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import("mod"); recordModuleName(); return true; } } - else if (token === 9 /* StringLiteral */) { + else if (token === 10 /* StringLiteral */) { // import "mod"; recordModuleName(); return true; } else { - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import d from "mod"; recordModuleName(); return true; } } - else if (token === 58 /* EqualsToken */) { + else if (token === 59 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } - else if (token === 26 /* CommaToken */) { + else if (token === 27 /* CommaToken */) { // consume comma and keep going token = nextToken(); } @@ -99181,18 +102860,18 @@ var ts; return true; } } - if (token === 17 /* OpenBraceToken */) { + if (token === 18 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure that it stops on EOF - while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import {a as A} from "mod"; // import d, {a, b as B} from "mod" recordModuleName(); @@ -99200,15 +102879,15 @@ var ts; } } } - else if (token === 39 /* AsteriskToken */) { + else if (token === 40 /* AsteriskToken */) { token = nextToken(); - if (token === 118 /* AsKeyword */) { + if (token === 119 /* AsKeyword */) { token = nextToken(); - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import * as NS from "mod" // import d, * as NS from "mod" recordModuleName(); @@ -99224,21 +102903,21 @@ var ts; } function tryConsumeExport() { var token = ts.scanner.getToken(); - if (token === 84 /* ExportKeyword */) { + if (token === 85 /* ExportKeyword */) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 17 /* OpenBraceToken */) { + if (token === 18 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure it stops on EOF - while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // export {a as A} from "mod"; // export {a, b as B} from "mod" recordModuleName(); @@ -99246,21 +102925,21 @@ var ts; } } } - else if (token === 39 /* AsteriskToken */) { + else if (token === 40 /* AsteriskToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // export * from "mod" recordModuleName(); } } } - else if (token === 91 /* ImportKeyword */) { + else if (token === 92 /* ImportKeyword */) { token = nextToken(); - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 58 /* EqualsToken */) { + if (token === 59 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } @@ -99273,11 +102952,11 @@ var ts; } function tryConsumeRequireCall(skipCurrentToken) { var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); - if (token === 133 /* RequireKeyword */) { + if (token === 134 /* RequireKeyword */) { token = nextToken(); - if (token === 19 /* OpenParenToken */) { + if (token === 20 /* OpenParenToken */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // require("mod"); recordModuleName(); } @@ -99288,16 +102967,16 @@ var ts; } function tryConsumeDefine() { var token = ts.scanner.getToken(); - if (token === 71 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + if (token === 72 /* Identifier */ && ts.scanner.getTokenValue() === "define") { token = nextToken(); - if (token !== 19 /* OpenParenToken */) { + if (token !== 20 /* OpenParenToken */) { return true; } token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // looks like define ("modname", ... - skip string literal and comma token = nextToken(); - if (token === 26 /* CommaToken */) { + if (token === 27 /* CommaToken */) { token = nextToken(); } else { @@ -99306,15 +102985,15 @@ var ts; } } // should be start of dependency list - if (token !== 21 /* OpenBracketToken */) { + if (token !== 22 /* OpenBracketToken */) { return true; } // skip open bracket token = nextToken(); // scan until ']' or EOF - while (token !== 22 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { // record string literals as module names - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { recordModuleName(); } token = nextToken(); @@ -99422,47 +103101,61 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; - if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + if (ts.isIdentifier(node) && node.originalKeywordKind === 80 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); var width = node.getWidth(sourceFile); - if (node.kind === 9 /* StringLiteral */) { + if (node.kind === 10 /* StringLiteral */) { // Exclude the quotes start += 1; width -= 2; @@ -99471,9 +103164,9 @@ var ts; } function nodeIsEligibleForRename(node) { switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 99 /* ThisKeyword */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: return true; case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); @@ -99508,22 +103201,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // 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. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99532,17 +103235,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99552,19 +103259,19 @@ var ts; return false; var invocationChildren = node.getChildren(sourceFile); switch (startingToken.kind) { - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return ts.contains(invocationChildren, startingToken); - case 26 /* CommaToken */: { + case 27 /* CommaToken */: { var containingList = ts.findContainingList(startingToken); return !!containingList && ts.contains(invocationChildren, containingList); } - case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + case 28 /* LessThanToken */: + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99581,9 +103288,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -99604,7 +103311,7 @@ var ts; return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; } function getArgumentOrParameterListAndIndex(node, sourceFile) { - if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { + if (node.kind === 28 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; @@ -99657,10 +103364,10 @@ var ts; } return undefined; } - else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) { + else if (ts.isTemplateHead(node) && parent.parent.kind === 193 /* TaggedTemplateExpression */) { var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 204 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 206 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } @@ -99723,24 +103430,24 @@ var ts; return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) { - if (startingToken.kind !== 19 /* OpenParenToken */ && startingToken.kind !== 26 /* CommaToken */) + if (startingToken.kind !== 20 /* OpenParenToken */ && startingToken.kind !== 27 /* CommaToken */) return undefined; var parent = startingToken.parent; switch (parent.kind) { - case 193 /* ParenthesizedExpression */: - case 154 /* MethodDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ParenthesizedExpression */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: var info = getArgumentOrParameterListInfo(startingToken, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var highestBinary = getHighestBinary(parent); var contextualType_1 = checker.getContextualType(highestBinary); - var argumentIndex_1 = startingToken.kind === 19 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; + var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; var argumentCount_1 = countBinaryExpressionParameters(highestBinary); return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) }; } @@ -99772,7 +103479,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 26 /* CommaToken */) { + if (child.kind !== 27 /* CommaToken */) { argumentIndex++; } } @@ -99791,8 +103498,8 @@ var ts; // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. var listChildren = argumentsList.getChildren(); - var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 26 /* CommaToken */; }); - if (listChildren.length > 0 && ts.last(listChildren).kind === 26 /* CommaToken */) { + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; }); + if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -99861,7 +103568,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 === 204 /* TemplateExpression */) { + if (template.kind === 206 /* TemplateExpression */) { var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -99869,7 +103576,7 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { var _loop_6 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. @@ -99879,7 +103586,7 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { var state_2 = _loop_6(n); if (typeof state_2 === "object") return state_2.value; @@ -99895,10 +103602,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } - var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -99909,11 +103619,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(28 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(30 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -99938,9 +103665,9 @@ var ts; var parameterParts = ts.mapToDisplayParts(function (writer) { var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); + printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer); }); - return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(27 /* LessThanToken */)], suffix: [ts.punctuationPart(29 /* GreaterThanToken */)].concat(parameterParts) }; + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { var isVariadic = candidateSignature.hasRestParameter; @@ -99948,11 +103675,11 @@ var ts; var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); - printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); + printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); - return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(19 /* OpenParenToken */)]), suffix: [ts.punctuationPart(20 /* CloseParenToken */)] }; + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] }; } function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { @@ -99967,60 +103694,53 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); /* @internal */ var ts; (function (ts) { - // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) - var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; - var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) { + function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var sourcemappedFileCache; - return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + var mappedFile = sourcemappedFileCache.get(toPath(fileName)); if (!mappedFile) { return; } - var starts = ts.getLineStarts(mappedFile); - for (var index = starts.length - 1; index >= 0; index--) { - var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); - var comment = sourceMapCommentRegExp.exec(lineText); - if (comment) { - return comment[1]; - } - // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file - else if (!lineText.match(whitespaceOrMapCommentRegExp)) { - break; - } - } + return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); } function convertDocumentToSourceMapper(file, contents, mapFileName) { - var maps; - try { - maps = JSON.parse(contents); - } - catch (_a) { - // swallow error - } - if (!maps || !maps.sources || !maps.file || !maps.mappings) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { // obviously invalid map - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } - return file.sourceMapper = ts.sourcemaps.decode({ - readFile: function (s) { return host.readFile(s); }, - fileExists: function (s) { return host.fileExists(s); }, + var program = getProgram(); + return file.sourceMapper = ts.createDocumentPositionMapper({ + getSourceFileLike: function (s) { + // Lookup file in program, if provided + var file = program && program.getSourceFileByPath(s); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (file === undefined || file.resolvedPath !== s) { + // Otherwise check the cache (which may hit disk) + return sourcemappedFileCache.get(s); + } + return file; + }, getCanonicalFileName: getCanonicalFileName, log: log, - }, mapFileName, maps, getProgram(), sourcemappedFileCache); + }, map, mapFileName); } function getSourceMapper(fileName, file) { if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } if (file.sourceMapper) { return file.sourceMapper; @@ -100049,20 +103769,24 @@ var ts; return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 } } - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } - function tryGetOriginalLocation(info) { + function tryGetSourcePosition(info) { if (!ts.isDeclarationFileName(info.fileName)) return undefined; var file = getFile(info.fileName); if (!file) return undefined; - var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); - return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); + return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; } - function tryGetGeneratedLocation(info) { + function tryGetGeneratedPosition(info) { var program = getProgram(); - var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + var options = program.getCompilerOptions(); + var outPath = options.outFile || options.out; + var declarationPath = outPath ? + ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : + ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); if (declarationPath === undefined) return undefined; var declarationFile = getFile(declarationPath); @@ -100072,18 +103796,45 @@ var ts; return newLoc === info ? undefined : newLoc; } function getFile(fileName) { - return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + var path = toPath(fileName); + var file = getProgram().getSourceFileByPath(path); + if (file && file.resolvedPath === path) { + return file; + } + return sourcemappedFileCache.get(path); } function toLineColumnOffset(fileName, position) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 + var file = getFile(fileName); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } function clearCache() { - sourcemappedFileCache = ts.createSourceFileLikeCache(host); + sourcemappedFileCache = createSourceFileLikeCache(host); } } ts.getSourceMapper = getSourceMapper; + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } })(ts || (ts = {})); /* @internal */ var ts; @@ -100091,13 +103842,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100119,8 +103870,8 @@ var ts; function check(node) { if (isJsFile) { switch (node.kind) { - case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + case 196 /* FunctionExpression */: + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_1 = decl.symbol; if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) { @@ -100129,7 +103880,7 @@ var ts; } } // falls through if no diagnostic was created - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: var symbol = node.symbol; if (symbol.members && (symbol.members.size > 0)) { diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); @@ -100162,15 +103913,15 @@ var ts; function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 - case 219 /* ExpressionStatement */: { + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 221 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100183,66 +103934,74 @@ var ts; } function importNameForConvertToDefaultImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 249 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 251 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node.name; default: return undefined; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { - return; + if (!ts.isAsyncFunction(node) && + node.body && + ts.isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker)) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } + } + function returnsPromise(node, checker) { + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; - if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { - return; - } - // collect all the return statements - // check that a property access expression exists in there and that it is a handler - var returnStatements = getReturnStatementsWithPromiseHandlers(node); - if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); - } + return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - /** @internal */ - function getReturnStatementsWithPromiseHandlers(node) { - var returnStatements = []; - if (ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - else { - visit(node); - } - function visit(child) { - if (ts.isFunctionLike(child)) { - return; - } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } - } - ts.forEachChild(child, visit); - } - return returnStatements; + function hasReturnStatementWithPromiseHandler(body) { + return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); } - ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + function isReturnStatementWithFixablePromiseHandler(node) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + } + ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + ts.isFixablePromiseHandler = isFixablePromiseHandler; function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100258,7 +104017,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -100295,7 +104054,7 @@ var ts; if (typeChecker.isArgumentsSymbol(symbol)) { return "local var" /* localVariableElement */; } - if (location.kind === 99 /* ThisKeyword */ && ts.isExpression(location)) { + if (location.kind === 100 /* ThisKeyword */ && ts.isExpression(location)) { return "parameter" /* parameterElement */; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); @@ -100346,11 +104105,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 260 /* JsxOpeningElement */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 265 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + return location.kind === 72 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 267 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -100375,13 +104134,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 100 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 100 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(100 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100390,7 +104152,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 187 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 189 /* 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)) { @@ -100411,7 +104173,7 @@ var ts; if (callExpressionLike) { var candidateSignatures = []; signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 - var useConstructSignatures = callExpressionLike.kind === 190 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 192 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 98 /* 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 @@ -100429,7 +104191,7 @@ var ts; pushSymbolKind(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addFullSymbolName(symbol); @@ -100446,14 +104208,14 @@ var ts; case "parameter" /* parameterElement */: case "local var" /* localVariableElement */: // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(56 /* ColonToken */)); + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); displayParts.push(ts.spacePart()); if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); @@ -100466,29 +104228,29 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 155 /* Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 124 /* ConstructorKeyword */ && location.parent.kind === 157 /* Constructor */)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { - return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + return declaration === (location.kind === 124 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 155 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 157 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 155 /* Constructor */) { + if (functionDeclaration_1.kind === 157 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 158 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 160 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -100498,7 +104260,7 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 209 /* 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 @@ -100506,7 +104268,7 @@ var ts; } else { // Class declaration has name which is not local. - displayParts.push(ts.keywordPart(75 /* ClassKeyword */)); + displayParts.push(ts.keywordPart(76 /* ClassKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -100514,45 +104276,45 @@ var ts; } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); + displayParts.push(ts.keywordPart(110 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { - displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); + displayParts.push(ts.keywordPart(77 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } - displayParts.push(ts.keywordPart(83 /* EnumKeyword */)); + displayParts.push(ts.keywordPart(84 /* EnumKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 242 /* ModuleDeclaration */); - var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 130 /* NamespaceKeyword */ : 129 /* ModuleKeyword */)); + var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 131 /* NamespaceKeyword */ : 130 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); if (symbol.parent) { @@ -100563,7 +104325,7 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 148 /* TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 150 /* TypeParameter */); if (decl === undefined) return ts.Debug.fail(); var declaration = decl.parent; @@ -100571,21 +104333,21 @@ var ts; if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 - if (declaration.kind === 159 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + if (declaration.kind === 161 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 158 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 160 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 240 /* TypeAliasDeclaration */) { + else if (declaration.kind === 242 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path addInPrefix(); - displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -100597,11 +104359,11 @@ var ts; symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 276 /* EnumMember */) { + if (declaration.kind === 278 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } @@ -100627,41 +104389,41 @@ var ts; } } switch (symbol.declarations[0].kind) { - case 245 /* NamespaceExportDeclaration */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 247 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(130 /* NamespaceKeyword */)); + displayParts.push(ts.keywordPart(131 /* NamespaceKeyword */)); break; - case 252 /* ExportAssignment */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 254 /* ExportAssignment */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 59 /* EqualsToken */ : 80 /* DefaultKeyword */)); break; - case 255 /* ExportSpecifier */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 257 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); break; default: - displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); + displayParts.push(ts.keywordPart(92 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 246 /* ImportEqualsDeclaration */) { + if (declaration.kind === 248 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(133 /* RequireKeyword */)); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.keywordPart(134 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); } else { var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(internalAliasSymbol, enclosingDeclaration); } @@ -100675,7 +104437,7 @@ var ts; if (type) { if (isThisExpression) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); + displayParts.push(ts.keywordPart(100 /* ThisKeyword */)); } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); @@ -100686,7 +104448,7 @@ var ts; symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || isThisExpression) { - displayParts.push(ts.punctuationPart(56 /* ColonToken */)); + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); displayParts.push(ts.spacePart()); // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { @@ -100724,10 +104486,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 277 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 202 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -100749,7 +104511,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -100770,7 +104532,7 @@ var ts; } function addInPrefix() { displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(92 /* InKeyword */)); + displayParts.push(ts.keywordPart(93 /* InKeyword */)); displayParts.push(ts.spacePart()); } function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { @@ -100780,7 +104542,7 @@ var ts; var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); if (symbol.flags & 16777216 /* Optional */) { - displayParts.push(ts.punctuationPart(55 /* QuestionToken */)); + displayParts.push(ts.punctuationPart(56 /* QuestionToken */)); } } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { @@ -100803,9 +104565,9 @@ var ts; displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); return; } } @@ -100814,20 +104576,21 @@ var ts; ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); - displayParts.push(ts.operatorPart(37 /* PlusToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(38 /* PlusToken */)); displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); displayParts.push(ts.spacePart()); displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); - getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -100839,16 +104602,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 194 /* FunctionExpression */) { + if (declaration.kind === 196 /* FunctionExpression */) { return true; } - if (declaration.kind !== 235 /* VariableDeclaration */ && declaration.kind !== 237 /* FunctionDeclaration */) { + if (declaration.kind !== 237 /* VariableDeclaration */ && declaration.kind !== 239 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 277 /* SourceFile */ || parent.kind === 243 /* ModuleBlock */) { + if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) { return false; } } @@ -100888,6 +104651,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101007,16 +104771,11 @@ var ts; this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { - ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); - ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); - ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); - ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); - ts.Debug.assert(commonParent !== undefined, "commonParent is null"); - this.currentTokenSpan = currentRange; - this.currentTokenParent = currentTokenParent; - this.nextTokenSpan = nextRange; - this.nextTokenParent = nextTokenParent; - this.contextNode = commonParent; + this.currentTokenSpan = ts.Debug.assertDefined(currentRange); + this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent); + this.nextTokenSpan = ts.Debug.assertDefined(nextRange); + this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent); + this.contextNode = ts.Debug.assertDefined(commonParent); // drop cached results this.contextNodeAllOnSameLine = undefined; this.nextNodeAllOnSameLine = undefined; @@ -101062,8 +104821,8 @@ var ts; return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 17 /* OpenBraceToken */, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 18 /* CloseBraceToken */, this.sourceFile); + var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile); if (openBrace && closeBrace) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; @@ -101145,11 +104904,11 @@ var ts; } function shouldRescanGreaterThanToken(node) { switch (node.kind) { - case 31 /* GreaterThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 46 /* GreaterThanGreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: return true; } return false; @@ -101157,28 +104916,28 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 265 /* JsxAttribute */: - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 267 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. - return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; + return ts.isKeyword(node.kind) || node.kind === 72 /* Identifier */; } } return false; } function shouldRescanJsxText(node) { - return node.kind === 10 /* JsxText */; + return node.kind === 11 /* JsxText */; } function shouldRescanSlashToken(container) { - return container.kind === 12 /* RegularExpressionLiteral */; + return container.kind === 13 /* RegularExpressionLiteral */; } function shouldRescanTemplateToken(container) { - return container.kind === 15 /* TemplateMiddle */ || - container.kind === 16 /* TemplateTail */; + return container.kind === 16 /* TemplateMiddle */ || + container.kind === 17 /* TemplateTail */; } function startsWithSlashToken(t) { - return t === 41 /* SlashToken */ || t === 63 /* SlashEqualsToken */; + return t === 42 /* SlashToken */ || t === 64 /* SlashEqualsToken */; } function readTokenInfo(n) { ts.Debug.assert(isOnToken()); @@ -101248,7 +105007,7 @@ var ts; lastScanAction = 0 /* Scan */; switch (expectedScanAction) { case 1 /* RescanGreaterThanToken */: - if (token === 29 /* GreaterThanToken */) { + if (token === 30 /* GreaterThanToken */) { lastScanAction = 1 /* RescanGreaterThanToken */; var newToken = scanner.reScanGreaterToken(); ts.Debug.assert(n.kind === newToken); @@ -101264,7 +105023,7 @@ var ts; } break; case 3 /* RescanTemplateToken */: - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { lastScanAction = 3 /* RescanTemplateToken */; return scanner.reScanTemplateToken(); } @@ -101337,7 +105096,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 145 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 147 /* LastToken */; token++) { allTokens.push(token); } function anyTokenExcept() { @@ -101349,255 +105108,255 @@ var ts; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); - var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 145 /* LastKeyword */); - var binaryOperators = tokenRangeFromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 145 /* OfKeyword */, 118 /* AsKeyword */, 127 /* IsKeyword */]; - var unaryPrefixOperators = [43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]; + var keywords = tokenRangeFromRange(73 /* FirstKeyword */, 147 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(28 /* FirstBinaryOperator */, 71 /* LastBinaryOperator */); + var binaryKeywordOperators = [93 /* InKeyword */, 94 /* InstanceOfKeyword */, 147 /* OfKeyword */, 119 /* AsKeyword */, 128 /* IsKeyword */]; + var unaryPrefixOperators = [44 /* PlusPlusToken */, 45 /* MinusMinusToken */, 53 /* TildeToken */, 52 /* ExclamationToken */]; var unaryPrefixExpressions = [ - 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, - 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 72 /* Identifier */, 20 /* OpenParenToken */, + 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */ ]; - var unaryPreincrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; - var unaryPostincrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; - var unaryPredecrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; - var unaryPostdecrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; + var unaryPreincrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostincrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var unaryPredecrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostdecrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; - var typeNames = [71 /* Identifier */].concat(ts.typeKeywords); + var typeNames = [72 /* Identifier */].concat(ts.typeKeywords); // Place a space before open brace in a function declaration // TypeScript: Function can have return types, which can be made of tons of different token kinds var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) - var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([72 /* Identifier */, 3 /* MultiLineCommentTrivia */, 76 /* ClassKeyword */, 85 /* ExportKeyword */, 92 /* ImportKeyword */]); // Place a space before open brace in a control flow construct - var controlOpenBraceLeftTokenRange = tokenRangeFrom([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); + var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 82 /* DoKeyword */, 103 /* TryKeyword */, 88 /* FinallyKeyword */, 83 /* ElseKeyword */]); // These rules are higher in priority than user-configurable var highPriorityCommonRules = [ // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), - rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), - rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), - rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NotSpaceBeforeColon", anyToken, 57 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), + rule("SpaceAfterColon", 57 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 56 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // insert space after '?' only when it is used in conditional operator - rule("SpaceAfterQuestionMarkInConditionalOperator", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + rule("SpaceAfterQuestionMarkInConditionalOperator", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), // in other cases there should be no space between '?' and next token - rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), + rule("NoSpaceAfterQuestionMark", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 92 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), - rule("NoSpaceAfterUnaryPreincrementOperator", 43 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterUnaryPredecrementOperator", 44 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 44 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 45 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 45 /* MinusMinusToken */, [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 - rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterPostincrementWhenFollowedByAdd", 44 /* PlusPlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 38 /* PlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 38 /* PlusToken */, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 45 /* MinusMinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 39 /* MinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 39 /* MinusToken */, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // For functions and control block place } on a new line [multi-line rule] - rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), // Space/new line after }. - rule("SpaceAfterCloseBrace", 18 /* CloseBraceToken */, anyTokenExcept(20 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, 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 // Also should not apply to }) - rule("SpaceBetweenCloseBraceAndElse", 18 /* CloseBraceToken */, 82 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenCloseBraceAndWhile", 18 /* CloseBraceToken */, 106 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 83 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 107 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' - rule("SpaceAfterConditionalClosingParen", 20 /* CloseParenToken */, 21 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), - rule("NoSpaceBetweenFunctionKeywordAndStar", 89 /* FunctionKeyword */, 39 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), - rule("SpaceAfterStarInGeneratorDeclaration", 39 /* AsteriskToken */, [71 /* Identifier */, 19 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), - rule("SpaceAfterFunctionInFuncDecl", 89 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 90 /* FunctionKeyword */, 40 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 40 /* AsteriskToken */, [72 /* Identifier */, 20 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 90 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), // Insert new line after { and before } in multi-line contexts. - rule("NewLineAfterOpenBraceInBlockContext", 17 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: // get x() {} // set x(val) {} - rule("SpaceAfterGetSetInMember", [125 /* GetKeyword */, 136 /* SetKeyword */], 71 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceBetweenYieldKeywordAndStar", 116 /* YieldKeyword */, 39 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), - rule("SpaceBetweenYieldOrYieldStarAndOperand", [116 /* YieldKeyword */, 39 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), - rule("NoSpaceBetweenReturnAndSemicolon", 96 /* ReturnKeyword */, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterCertainKeywords", [104 /* VarKeyword */, 100 /* ThrowKeyword */, 94 /* NewKeyword */, 80 /* DeleteKeyword */, 96 /* ReturnKeyword */, 103 /* TypeOfKeyword */, 121 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceAfterLetConstInVariableDeclaration", [110 /* LetKeyword */, 76 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), - rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), + rule("SpaceAfterGetSetInMember", [126 /* GetKeyword */, 137 /* SetKeyword */], 72 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 117 /* YieldKeyword */, 40 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [117 /* YieldKeyword */, 40 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 97 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [105 /* VarKeyword */, 101 /* ThrowKeyword */, 95 /* NewKeyword */, 81 /* DeleteKeyword */, 97 /* ReturnKeyword */, 104 /* TypeOfKeyword */, 122 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [111 /* LetKeyword */, 77 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterVoidOperator", 105 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 106 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), // Async-await - rule("SpaceBetweenAsyncAndOpenParen", 120 /* AsyncKeyword */, 19 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 120 /* AsyncKeyword */, 89 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndOpenParen", 121 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 121 /* AsyncKeyword */, 90 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), // Template string - rule("NoSpaceBetweenTagAndTemplateString", [71 /* Identifier */, 20 /* CloseParenToken */], [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenTagAndTemplateString", [72 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // JSX opening elements - rule("SpaceBeforeJsxAttribute", anyToken, 71 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 41 /* SlashToken */, 29 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 58 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterEqualInJsxAttribute", 58 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeJsxAttribute", anyToken, 72 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 42 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 42 /* SlashToken */, 30 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 59 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 59 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), // TypeScript-specific rules // Use of module as a function call. e.g.: import m2 = module("m2"); - rule("NoSpaceAfterModuleImport", [129 /* ModuleKeyword */, 133 /* RequireKeyword */], 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterModuleImport", [130 /* ModuleKeyword */, 134 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Add a space around certain TypeScript keywords rule("SpaceAfterCertainTypeScriptKeywords", [ - 117 /* AbstractKeyword */, - 75 /* ClassKeyword */, - 124 /* DeclareKeyword */, - 79 /* DefaultKeyword */, - 83 /* EnumKeyword */, - 84 /* ExportKeyword */, - 85 /* ExtendsKeyword */, - 125 /* GetKeyword */, - 108 /* ImplementsKeyword */, - 91 /* ImportKeyword */, - 109 /* InterfaceKeyword */, - 129 /* ModuleKeyword */, - 130 /* NamespaceKeyword */, - 112 /* PrivateKeyword */, - 114 /* PublicKeyword */, - 113 /* ProtectedKeyword */, - 132 /* ReadonlyKeyword */, - 136 /* SetKeyword */, - 115 /* StaticKeyword */, - 139 /* TypeKeyword */, - 143 /* FromKeyword */, - 128 /* KeyOfKeyword */, - 126 /* InferKeyword */, + 118 /* AbstractKeyword */, + 76 /* ClassKeyword */, + 125 /* DeclareKeyword */, + 80 /* DefaultKeyword */, + 84 /* EnumKeyword */, + 85 /* ExportKeyword */, + 86 /* ExtendsKeyword */, + 126 /* GetKeyword */, + 109 /* ImplementsKeyword */, + 92 /* ImportKeyword */, + 110 /* InterfaceKeyword */, + 130 /* ModuleKeyword */, + 131 /* NamespaceKeyword */, + 113 /* PrivateKeyword */, + 115 /* PublicKeyword */, + 114 /* ProtectedKeyword */, + 133 /* ReadonlyKeyword */, + 137 /* SetKeyword */, + 116 /* StaticKeyword */, + 140 /* TypeKeyword */, + 144 /* FromKeyword */, + 129 /* KeyOfKeyword */, + 127 /* InferKeyword */, ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 143 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [86 /* ExtendsKeyword */, 109 /* ImplementsKeyword */, 144 /* FromKeyword */], [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" { - rule("SpaceAfterModuleName", 9 /* StringLiteral */, 17 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), + rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), // Lambda expressions - rule("SpaceBeforeArrow", anyToken, 36 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceAfterArrow", 36 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeArrow", anyToken, 37 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 37 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Optional parameters and let args - rule("NoSpaceAfterEllipsis", 24 /* DotDotDotToken */, 71 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOptionalParameters", 55 /* QuestionToken */, [20 /* CloseParenToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 72 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 56 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // Remove spaces in empty interface literals. e.g.: x: {} - rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), // generics and type assertions - rule("NoSpaceBeforeOpenAngularBracket", typeNames, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceBetweenCloseParenAndAngularBracket", 20 /* CloseParenToken */, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterOpenAngularBracket", 27 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 28 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 30 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 30 /* GreaterThanToken */, [20 /* OpenParenToken */, 22 /* OpenBracketToken */, 30 /* GreaterThanToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), // decorators - rule("SpaceBeforeAt", [20 /* CloseParenToken */, 71 /* Identifier */], 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeAt", [21 /* CloseParenToken */, 72 /* Identifier */], 58 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 58 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after @ in decorator rule("SpaceAfterDecorator", anyToken, [ - 117 /* AbstractKeyword */, - 71 /* Identifier */, - 84 /* ExportKeyword */, - 79 /* DefaultKeyword */, - 75 /* ClassKeyword */, - 115 /* StaticKeyword */, - 114 /* PublicKeyword */, - 112 /* PrivateKeyword */, - 113 /* ProtectedKeyword */, - 125 /* GetKeyword */, - 136 /* SetKeyword */, - 21 /* OpenBracketToken */, - 39 /* AsteriskToken */, + 118 /* AbstractKeyword */, + 72 /* Identifier */, + 85 /* ExportKeyword */, + 80 /* DefaultKeyword */, + 76 /* ClassKeyword */, + 116 /* StaticKeyword */, + 115 /* PublicKeyword */, + 113 /* PrivateKeyword */, + 114 /* ProtectedKeyword */, + 126 /* GetKeyword */, + 137 /* SetKeyword */, + 22 /* OpenBracketToken */, + 40 /* AsteriskToken */, ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), - rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 51 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterNewKeywordOnConstructorSignature", 94 /* NewKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 52 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 95 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), ]; // These rules are applied after high priority var userConfigurableRules = [ // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses - rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), - rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), + rule("SpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), // Insert space after function keyword for anonymous functions - rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), + rule("SpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), // Insert space after keywords in control flow statements - rule("SpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), - rule("NoSpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), + rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), // Insert space after opening and before closing nonempty parenthesis - rule("SpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenOpenParens", 19 /* OpenParenToken */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenParens", 19 /* OpenParenToken */, 20 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing nonempty brackets - rule("SpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenBrackets", 21 /* OpenBracketToken */, 22 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - rule("SpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), - rule("SpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), - rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), - rule("NoSpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing template string braces - rule("SpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // No space after { and before } in JSX expression - rule("SpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), - rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), - rule("NoSpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), // Insert space after semicolon in for statement - rule("SpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), - rule("NoSpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), // Insert space before and after binary operators rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), - rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), // Open Brace braces after control block - rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), // Open Brace braces after function // TypeScript: Function can have return types, which can be made of tons of different token kinds - rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), // Open Brace braces after TypeScript module/class/interface - rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), - rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), - rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), - rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), - rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), ]; // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. var lowPriorityCommonRules = [ // Space after keyword but not before ; or : or ? - rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // No space before and after indexer `x[]` - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), - rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(121 /* AsyncKeyword */, 74 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Remove extra space between for and await - rule("SpaceBetweenForAndAwaitKeyword", 88 /* ForKeyword */, 121 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenForAndAwaitKeyword", 89 /* ForKeyword */, 122 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), // 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] - rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), + rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 82 /* DoKeyword */, 83 /* ElseKeyword */, 74 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterTryFinally", [103 /* TryKeyword */, 88 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), ]; return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); } @@ -101641,45 +105400,45 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 223 /* ForStatement */; + return context.contextNode.kind === 225 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 202 /* BinaryExpression */: - case 203 /* ConditionalExpression */: - case 173 /* ConditionalType */: - case 210 /* AsExpression */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 161 /* TypePredicate */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 175 /* ConditionalType */: + case 212 /* AsExpression */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 163 /* TypePredicate */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 184 /* BindingElement */: + case 186 /* BindingElement */: // equals in type X = ... - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: // equal in p = 0; - case 149 /* Parameter */: - case 276 /* EnumMember */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; + case 151 /* Parameter */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] - case 148 /* TypeParameter */: - return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; + case 150 /* TypeParameter */: + return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 225 /* ForOfStatement */: - return context.currentTokenSpan.kind === 145 /* OfKeyword */ || context.nextTokenSpan.kind === 145 /* OfKeyword */; + case 227 /* ForOfStatement */: + return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */; } return false; } @@ -101691,22 +105450,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 152 /* PropertyDeclaration */ || - contextKind === 151 /* PropertySignature */ || - contextKind === 149 /* Parameter */ || - contextKind === 235 /* VariableDeclaration */ || + return contextKind === 154 /* PropertyDeclaration */ || + contextKind === 153 /* PropertySignature */ || + contextKind === 151 /* Parameter */ || + contextKind === 237 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 203 /* ConditionalExpression */ || - context.contextNode.kind === 173 /* ConditionalType */; + return context.contextNode.kind === 205 /* ConditionalExpression */ || + context.contextNode.kind === 175 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 182 /* ObjectBindingPattern */ || - context.contextNode.kind === 179 /* MappedType */ || + return context.contextNode.kind === 184 /* ObjectBindingPattern */ || + context.contextNode.kind === 181 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -101732,31 +105491,31 @@ var ts; return true; } switch (node.kind) { - case 216 /* Block */: - case 244 /* CaseBlock */: - case 186 /* ObjectLiteralExpression */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 188 /* ObjectLiteralExpression */: + case 245 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // case SyntaxKind.MethodSignature: - case 158 /* CallSignature */: - case 194 /* FunctionExpression */: - case 155 /* Constructor */: - case 195 /* ArrowFunction */: + case 160 /* CallSignature */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 197 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 239 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 241 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -101765,40 +105524,40 @@ var ts; return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 237 /* FunctionDeclaration */ || context.contextNode.kind === 194 /* FunctionExpression */; + return context.contextNode.kind === 239 /* FunctionDeclaration */ || context.contextNode.kind === 196 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 166 /* TypeLiteral */: - case 242 /* ModuleDeclaration */: - case 253 /* ExportDeclaration */: - case 254 /* NamedExports */: - case 247 /* ImportDeclaration */: - case 250 /* NamedImports */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 168 /* TypeLiteral */: + case 244 /* ModuleDeclaration */: + case 255 /* ExportDeclaration */: + case 256 /* NamedExports */: + case 249 /* ImportDeclaration */: + case 252 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 272 /* CatchClause */: - case 243 /* ModuleBlock */: - case 230 /* SwitchStatement */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 274 /* CatchClause */: + case 245 /* ModuleBlock */: + case 232 /* SwitchStatement */: return true; - case 216 /* Block */: { + case 218 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 195 /* ArrowFunction */ && blockParent.kind !== 194 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 197 /* ArrowFunction */ && blockParent.kind !== 196 /* FunctionExpression */) { return true; } } @@ -101807,64 +105566,64 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 220 /* IfStatement */: - case 230 /* SwitchStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: - case 233 /* TryStatement */: - case 221 /* DoStatement */: - case 229 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 231 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 272 /* CatchClause */: + case 274 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 186 /* ObjectLiteralExpression */; + return context.contextNode.kind === 188 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 189 /* CallExpression */; + return context.contextNode.kind === 191 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 190 /* NewExpression */; + return context.contextNode.kind === 192 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); } function isPreviousTokenNotComma(context) { - return context.currentTokenSpan.kind !== 26 /* CommaToken */; + return context.currentTokenSpan.kind !== 27 /* CommaToken */; } function isNextTokenNotCloseBracket(context) { - return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; + return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 195 /* ArrowFunction */; + return context.contextNode.kind === 197 /* ArrowFunction */; } function isImportTypeContext(context) { - return context.contextNode.kind === 181 /* ImportType */; + return context.contextNode.kind === 183 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; + return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 258 /* JsxElement */ && context.contextNode.kind !== 262 /* JsxFragment */; + return context.contextNode.kind !== 260 /* JsxElement */ && context.contextNode.kind !== 264 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 268 /* JsxExpression */ || context.contextNode.kind === 267 /* JsxSpreadAttribute */; + return context.contextNode.kind === 270 /* JsxExpression */ || context.contextNode.kind === 269 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 265 /* JsxAttribute */; + return context.nextTokenParent.kind === 267 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 265 /* JsxAttribute */; + return context.contextNode.kind === 267 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 259 /* JsxSelfClosingElement */; + return context.contextNode.kind === 261 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -101879,45 +105638,45 @@ var ts; while (ts.isExpressionNode(node)) { node = node.parent; } - return node.kind === 150 /* Decorator */; + return node.kind === 152 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 236 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 238 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 242 /* ModuleDeclaration */; + return context.contextNode.kind === 244 /* ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 166 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 168 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 159 /* ConstructSignature */; + return context.contextNode.kind === 161 /* ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { - if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { + if (token.kind !== 28 /* LessThanToken */ && token.kind !== 30 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 162 /* TypeReference */: - case 192 /* TypeAssertionExpression */: - case 240 /* TypeAliasDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 209 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 194 /* TypeAssertionExpression */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -101928,16 +105687,16 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 192 /* TypeAssertionExpression */; + return context.contextNode.kind === 194 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 198 /* VoidExpression */; + return context.currentTokenSpan.kind === 106 /* VoidKeyword */ && context.currentTokenParent.kind === 200 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 205 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 207 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 211 /* NonNullExpression */; + return context.contextNode.kind === 213 /* NonNullExpression */; } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -101988,12 +105747,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 145 /* LastKeyword */ && column <= 145 /* LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 147 /* LastKeyword */ && column <= 147 /* LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 145 /* LastToken */ + 1; + var mapRowLength = 147 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; @@ -102082,12 +105841,12 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, formatContext) { - var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25 /* SemicolonToken */, sourceFile); + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; function formatOnOpeningCurly(position, sourceFile, formatContext) { - var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17 /* OpenBraceToken */, sourceFile); + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile); if (!openingCurly) { return []; } @@ -102113,7 +105872,7 @@ var ts; } formatting.formatOnOpeningCurly = formatOnOpeningCurly; function formatOnClosingCurly(position, sourceFile, formatContext) { - var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18 /* CloseBraceToken */, sourceFile); + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; @@ -102171,17 +105930,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 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: var body = parent.body; - return !!body && body.kind === 243 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 277 /* SourceFile */: - case 216 /* Block */: - case 243 /* ModuleBlock */: + return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 279 /* SourceFile */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -102294,7 +106053,6 @@ var ts; } return 0; } - /* @internal */ function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { var range = { pos: 0, end: sourceFileLike.text.length }; return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors @@ -102324,7 +106082,7 @@ var ts; var previousParent; var previousRangeStartLine; var lastIndentedLine; - var indentationOnLastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -102338,7 +106096,7 @@ var ts; if (!formattingScanner.isOnToken()) { var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); // TODO: GH#18217 + indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); trimTrailingWhitespacesForRemainingRange(); } } @@ -102383,7 +106141,7 @@ var ts; }; } else if (inheritedIndentation === -1 /* Unknown */) { - if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) { + if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) { // the is used for chaining methods formatting // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; @@ -102404,19 +106162,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 238 /* ClassDeclaration */: return 75 /* ClassKeyword */; - case 239 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; - case 237 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; - case 241 /* EnumDeclaration */: return 241 /* EnumDeclaration */; - case 156 /* GetAccessor */: return 125 /* GetKeyword */; - case 157 /* SetAccessor */: return 136 /* SetKeyword */; - case 154 /* MethodDeclaration */: + case 240 /* ClassDeclaration */: return 76 /* ClassKeyword */; + case 241 /* InterfaceDeclaration */: return 110 /* InterfaceKeyword */; + case 239 /* FunctionDeclaration */: return 90 /* FunctionKeyword */; + case 243 /* EnumDeclaration */: return 243 /* EnumDeclaration */; + case 158 /* GetAccessor */: return 126 /* GetKeyword */; + case 159 /* SetAccessor */: return 137 /* SetKeyword */; + case 156 /* MethodDeclaration */: if (node.asteriskToken) { - return 39 /* AsteriskToken */; + return 40 /* AsteriskToken */; } // falls through - case 152 /* PropertyDeclaration */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: var name = ts.getNameOfDeclaration(node); if (name) { return name.kind; @@ -102431,15 +106189,25 @@ var ts; // .. { // // comment // } - case 18 /* CloseBraceToken */: - case 22 /* CloseBracketToken */: - case 20 /* CloseParenToken */: + case 19 /* CloseBraceToken */: + case 23 /* CloseBracketToken */: + case 21 /* CloseParenToken */: return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind, container) { - return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; + // if list end token is LessThanToken '>' then its delta should be explicitly suppressed + // so that LessThanToken as a binary operator can still be indented. + // foo.then + // < + // number, + // string, + // >(); + // vs + // var a = xValue + // > yValue; + getIndentationForToken: function (line, kind, container, suppressDelta) { + return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, getDelta: getDelta, @@ -102453,26 +106221,25 @@ var ts; function shouldAddDelta(line, kind, container) { switch (kind) { // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 17 /* OpenBraceToken */: - case 18 /* CloseBraceToken */: - case 19 /* OpenParenToken */: - case 20 /* CloseParenToken */: - case 82 /* ElseKeyword */: - case 106 /* WhileKeyword */: - case 57 /* AtToken */: + case 18 /* OpenBraceToken */: + case 19 /* CloseBraceToken */: + case 21 /* CloseParenToken */: + case 83 /* ElseKeyword */: + case 107 /* WhileKeyword */: + case 58 /* AtToken */: return false; - case 41 /* SlashToken */: - case 29 /* GreaterThanToken */: + case 42 /* SlashToken */: + case 30 /* GreaterThanToken */: switch (container.kind) { - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: return false; } break; - case 21 /* OpenBracketToken */: - case 22 /* CloseBracketToken */: - if (container.kind !== 179 /* MappedType */) { + case 22 /* OpenBracketToken */: + case 23 /* CloseBracketToken */: + if (container.kind !== 181 /* MappedType */) { return false; } break; @@ -102557,22 +106324,22 @@ var ts; return inheritedIndentation; } // JSX text shouldn't affect indenting - if (ts.isToken(child) && child.kind !== 10 /* JsxText */) { + if (ts.isToken(child) && child.kind !== 11 /* JsxText */) { // 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, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 150 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 152 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); - if (child.kind === 10 /* JsxText */) { + if (child.kind === 11 /* JsxText */) { var range = { pos: child.getStart(), end: child.getEnd() }; indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); } childContextNode = node; - if (isFirstListItem && parent.kind === 185 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 187 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -102593,9 +106360,20 @@ var ts; else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + var indentationOnListStartToken = void 0; + if (indentationOnLastIndentedLine !== -1 /* Unknown */) { + // scanner just processed list start token so consider last indentation as list indentation + // function foo(): { // last indentation was 0, list item will be indented based on this value + // foo: number; + // }: {}; + indentationOnListStartToken = indentationOnLastIndentedLine; + } + else { + var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile); + indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options); + } + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217 } else { // consume any tokens that precede the list as child elements of 'node' using its indentation scope @@ -102611,21 +106389,21 @@ var ts; var listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); - if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true); } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -102657,32 +106435,12 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : -1 /* Unknown */; var indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); - for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { - var triviaItem = _a[_i]; - var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); - switch (triviaItem.kind) { - case 3 /* MultiLineCommentTrivia */: - if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); - } - indentNextTokenOrTrivia = false; - break; - case 2 /* SingleLineCommentTrivia */: - if (indentNextTokenOrTrivia && triviaInRange) { - insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); - } - indentNextTokenOrTrivia = false; - break; - case 4 /* NewLineTrivia */: - indentNextTokenOrTrivia = true; - break; - } - } + var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); }); } // indent token only if is it is in target range and does not overlap with any error ranges if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { @@ -102695,16 +106453,39 @@ var ts; childContextNode = parent; } } - function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) { for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { var triviaItem = trivia_1[_i]; + var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); + switch (triviaItem.kind) { + case 3 /* MultiLineCommentTrivia */: + if (triviaInRange) { + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + } + indentNextTokenOrTrivia = false; + break; + case 2 /* SingleLineCommentTrivia */: + if (indentNextTokenOrTrivia && triviaInRange) { + indentSingleLine(triviaItem); + } + indentNextTokenOrTrivia = false; + break; + case 4 /* NewLineTrivia */: + indentNextTokenOrTrivia = true; + break; + } + } + return indentNextTokenOrTrivia; + } + function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) { + var triviaItem = trivia_2[_i]; if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); } } } - // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAction = 0 /* None */; @@ -102876,7 +106657,10 @@ var ts; * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - var startPosition = previousRange ? previousRange.end : originalRange.pos; + if (!previousRange) { + return; + } + var startPosition = previousRange.end; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); @@ -102976,41 +106760,46 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 195 /* ArrowFunction */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 197 /* ArrowFunction */: if (node.typeParameters === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } else if (node.parameters === list) { - return 19 /* OpenParenToken */; + return 20 /* OpenParenToken */; } break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: if (node.typeArguments === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } else if (node.arguments === list) { - return 19 /* OpenParenToken */; + return 20 /* OpenParenToken */; } break; - case 162 /* TypeReference */: + case 164 /* TypeReference */: if (node.typeArguments === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } + break; + case 168 /* TypeLiteral */: + return 18 /* OpenBraceToken */; } return 0 /* Unknown */; } function getCloseTokenForOpenToken(kind) { switch (kind) { - case 19 /* OpenParenToken */: - return 20 /* CloseParenToken */; - case 27 /* LessThanToken */: - return 29 /* GreaterThanToken */; + case 20 /* OpenParenToken */: + return 21 /* CloseParenToken */; + case 28 /* LessThanToken */: + return 30 /* GreaterThanToken */; + case 18 /* OpenBraceToken */: + return 19 /* CloseBraceToken */; } return 0 /* Unknown */; } @@ -103115,13 +106904,18 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 202 /* BinaryExpression */) { + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 204 /* 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 */) { return actualIndentation; } } + var containerList = getListByPosition(position, precedingToken.parent, sourceFile); + // use list position if the preceding token is before any list items + if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) { + return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217 + } return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); } SmartIndenter.getIndentation = getIndentation; @@ -103132,12 +106926,12 @@ var ts; if (previousLine <= commentStartLine) { return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); } - var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); - var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; if (column === 0) { return column; } - var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; } function getBlockIndent(sourceFile, position, options) { @@ -103170,14 +106964,13 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 } // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); + // do not consider parent-child line sharing yet: + // function foo(a + // | preceding node 'a' does share line with its parent but indentation is expected + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } - actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); - if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; // TODO: GH#18217 - } previous = current; current = current.parent; } @@ -103204,23 +106997,17 @@ var ts; var start = current.getStart(sourceFile); useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; } - if (useActualIndentation) { - // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); - if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + indentationDelta; - } - } var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { - // try to fetch actual indentation for current node from source text - var actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); + // check if current node is a list item - if yes, take indentation from it + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } - actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + // try to fetch actual indentation for current node from source text + actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -103271,7 +107058,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.isStatementButNotDeclaration(current)) && - (parent.kind === 277 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -103288,11 +107075,11 @@ var ts; if (!nextToken) { return 0 /* Unknown */; } - if (nextToken.kind === 17 /* OpenBraceToken */) { + if (nextToken.kind === 18 /* OpenBraceToken */) { // open braces are always indented at the parent level return 1 /* OpenBrace */; } - else if (nextToken.kind === 18 /* CloseBraceToken */) { + else if (nextToken.kind === 19 /* CloseBraceToken */) { // close braces are indented at the parent level if they are located on the same line with cursor // this means that if new line will be added at $ position, this case will be indented // class A { @@ -103319,8 +107106,8 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 220 /* IfStatement */ && parent.elseStatement === child) { - var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile); + if (parent.kind === 222 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 83 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; @@ -103328,103 +107115,87 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; - function getListIfStartEndIsInListRange(list, start, end) { - return list && ts.rangeContainsStartEnd(list, start, end) ? list : undefined; - } function getContainingList(node, sourceFile) { - if (node.parent) { - var end = node.end; - switch (node.parent.kind) { - case 162 /* TypeReference */: - return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); - case 186 /* ObjectLiteralExpression */: - return node.parent.properties; - case 185 /* ArrayLiteralExpression */: - return node.parent.elements; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 155 /* Constructor */: - case 164 /* ConstructorType */: - case 159 /* ConstructSignature */: { - var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || - getListIfStartEndIsInListRange(node.parent.parameters, start, end); - } - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: { - var typeParameters = node.parent.typeParameters; - return getListIfStartEndIsInListRange(typeParameters, node.getStart(sourceFile), end); - } - case 190 /* NewExpression */: - case 189 /* CallExpression */: { - var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || - getListIfStartEndIsInListRange(node.parent.arguments, start, end); - } - case 236 /* VariableDeclarationList */: - return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); - case 250 /* NamedImports */: - case 254 /* NamedExports */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); - } - } - return undefined; + return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile); } SmartIndenter.getContainingList = getContainingList; - function getActualIndentationForListItem(node, sourceFile, options) { + function getListByPosition(pos, node, sourceFile) { + return node && getListByRange(pos, pos, node, sourceFile); + } + function getListByRange(start, end, node, sourceFile) { + switch (node.kind) { + case 164 /* TypeReference */: + return getList(node.typeArguments); + case 188 /* ObjectLiteralExpression */: + return getList(node.properties); + case 187 /* ArrayLiteralExpression */: + return getList(node.elements); + case 168 /* TypeLiteral */: + return getList(node.members); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return getList(node.typeParameters) || getList(node.parameters); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + return getList(node.typeParameters); + case 192 /* NewExpression */: + case 191 /* CallExpression */: + return getList(node.typeArguments) || getList(node.arguments); + case 238 /* VariableDeclarationList */: + return getList(node.declarations); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return getList(node.elements); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return getList(node.elements); + } + function getList(list) { + return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined; + } + } + function getVisualListRange(node, list, sourceFile) { + var children = node.getChildren(sourceFile); + for (var i = 1; i < children.length - 1; i++) { + if (children[i].pos === list.pos && children[i].end === list.end) { + return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) }; + } + } + return list; + } + function getActualIndentationForListStartLine(list, sourceFile, options) { + if (!list) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); + } + function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { + if (node.parent && node.parent.kind === 238 /* VariableDeclarationList */) { + // VariableDeclarationList has no wrapping tokens + return -1 /* Unknown */; + } var containingList = getContainingList(node, sourceFile); if (containingList) { var index = containingList.indexOf(node); if (index !== -1) { - return deriveActualIndentationFromList(containingList, index, sourceFile, options); - } - } - return -1 /* Unknown */; - } - function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { - // actual indentation should not be used when: - // - node is close parenthesis - this is the end of the expression - if (node.kind === 20 /* CloseParenToken */) { - return -1 /* Unknown */; - } - if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { - var fullCallOrNewExpression = node.parent.expression; - var startingExpression = getStartingExpression(fullCallOrNewExpression); - if (fullCallOrNewExpression === startingExpression) { - return -1 /* Unknown */; - } - var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); - var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); - if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { - return -1 /* Unknown */; - } - return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); - } - return -1 /* Unknown */; - function getStartingExpression(node) { - while (true) { - switch (node.kind) { - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - node = node.expression; - break; - default: - return node; + var result = deriveActualIndentationFromList(containingList, index, sourceFile, options); + if (result !== -1 /* Unknown */) { + return result; } } + return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217 } + return -1 /* Unknown */; } function deriveActualIndentationFromList(list, index, sourceFile, options) { ts.Debug.assert(index >= 0 && index < list.length); @@ -103433,7 +107204,7 @@ var ts; // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for (var i = index - 1; i >= 0; i--) { - if (list[i].kind === 26 /* CommaToken */) { + if (list[i].kind === 27 /* CommaToken */) { continue; } // skip list items that ends on the same line with the current list element @@ -103482,83 +107253,83 @@ var ts; function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 219 /* ExpressionStatement */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 185 /* ArrayLiteralExpression */: - case 216 /* Block */: - case 243 /* ModuleBlock */: - case 186 /* ObjectLiteralExpression */: - case 166 /* TypeLiteral */: - case 179 /* MappedType */: - case 168 /* TupleType */: - case 244 /* CaseBlock */: - case 270 /* DefaultClause */: - case 269 /* CaseClause */: - case 193 /* ParenthesizedExpression */: - case 187 /* PropertyAccessExpression */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 217 /* VariableStatement */: - case 252 /* ExportAssignment */: - case 228 /* ReturnStatement */: - case 203 /* ConditionalExpression */: - case 183 /* ArrayBindingPattern */: - case 182 /* ObjectBindingPattern */: - case 260 /* JsxOpeningElement */: - case 263 /* JsxOpeningFragment */: - case 259 /* JsxSelfClosingElement */: - case 268 /* JsxExpression */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 149 /* Parameter */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 175 /* ParenthesizedType */: - case 191 /* TaggedTemplateExpression */: - case 199 /* AwaitExpression */: - case 254 /* NamedExports */: - case 250 /* NamedImports */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 152 /* PropertyDeclaration */: + case 221 /* ExpressionStatement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 187 /* ArrayLiteralExpression */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 181 /* MappedType */: + case 170 /* TupleType */: + case 246 /* CaseBlock */: + case 272 /* DefaultClause */: + case 271 /* CaseClause */: + case 195 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 219 /* VariableStatement */: + case 254 /* ExportAssignment */: + case 230 /* ReturnStatement */: + case 205 /* ConditionalExpression */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + case 261 /* JsxSelfClosingElement */: + case 270 /* JsxExpression */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 151 /* Parameter */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 177 /* ParenthesizedType */: + case 193 /* TaggedTemplateExpression */: + case 201 /* AwaitExpression */: + case 256 /* NamedExports */: + case 252 /* NamedImports */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 154 /* PropertyDeclaration */: return true; - case 235 /* VariableDeclaration */: - case 273 /* PropertyAssignment */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 186 /* ObjectLiteralExpression */) { // TODO: GH#18217 + case 237 /* VariableDeclaration */: + case 275 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 188 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } return true; - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 220 /* IfStatement */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 195 /* ArrowFunction */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return childKind !== 216 /* Block */; - case 253 /* ExportDeclaration */: - return childKind !== 254 /* NamedExports */; - case 247 /* ImportDeclaration */: - return childKind !== 248 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 250 /* NamedImports */); - case 258 /* JsxElement */: - return childKind !== 261 /* JsxClosingElement */; - case 262 /* JsxFragment */: - return childKind !== 264 /* JsxClosingFragment */; - case 172 /* IntersectionType */: - case 171 /* UnionType */: - if (childKind === 166 /* TypeLiteral */) { + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return childKind !== 218 /* Block */; + case 255 /* ExportDeclaration */: + return childKind !== 256 /* NamedExports */; + case 249 /* ImportDeclaration */: + return childKind !== 250 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 252 /* NamedImports */); + case 260 /* JsxElement */: + return childKind !== 263 /* JsxClosingElement */; + case 264 /* JsxFragment */: + return childKind !== 266 /* JsxClosingFragment */; + case 174 /* IntersectionType */: + case 173 /* UnionType */: + if (childKind === 168 /* TypeLiteral */) { return false; } // falls through @@ -103569,11 +107340,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: - return parent.kind !== 216 /* Block */; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return parent.kind !== 218 /* Block */; default: return false; } @@ -103701,7 +107472,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 186 /* ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 188 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -103730,7 +107501,6 @@ var ts; }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); - return this; }; ChangeTracker.prototype.delete = function (sourceFile, node) { this.deletedNodes.push({ sourceFile: sourceFile, node: node }); @@ -103743,7 +107513,6 @@ var ts; var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - return this; }; ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { if (options === void 0) { options = {}; } @@ -103754,11 +107523,10 @@ var ts; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); - return this; }; ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } @@ -103767,31 +107535,33 @@ var ts; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); - return this; }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + }; + ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) { + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); - return next && next.kind === 26 /* CommaToken */ ? next : undefined; + return next && next.kind === 27 /* CommaToken */ ? next : undefined; }; ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); - return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); + this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -103806,7 +107576,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -103821,17 +107599,32 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) { + var fnStart = node.getStart(sourceFile); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsdoc = _a[_i]; + this.deleteRange(sourceFile, { + pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + }); + } + } + var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); + var indent = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { var endNode; if (ts.isFunctionLike(node)) { - endNode = ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile); + endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) return; // Function missing parentheses, give up @@ -103840,13 +107633,13 @@ var ts; } } else { - endNode = node.kind !== 235 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + endNode = node.kind !== 237 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter - var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); }; ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { @@ -103887,30 +107680,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -103933,7 +107733,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -103945,18 +107745,18 @@ var ts; }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - case 235 /* VariableDeclaration */: - case 9 /* StringLiteral */: - case 71 /* Identifier */: + case 237 /* VariableDeclaration */: + case 10 /* StringLiteral */: + case 72 /* Identifier */: return { prefix: ", " }; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return { suffix: "," + this.newLineCharacter }; - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: return { prefix: " " }; - case 149 /* Parameter */: + case 151 /* Parameter */: return {}; default: ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it @@ -103965,28 +107765,28 @@ var ts; }; ChangeTracker.prototype.insertName = function (sourceFile, node, name) { ts.Debug.assert(!node.name); - if (node.kind === 195 /* ArrowFunction */) { - var arrow = ts.findChildOfKind(node, 36 /* EqualsGreaterThanToken */, sourceFile); - var lparen = ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile); + if (node.kind === 197 /* ArrowFunction */) { + var arrow = ts.findChildOfKind(node, 37 /* EqualsGreaterThanToken */, sourceFile); + var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); if (lparen) { // `() => {}` --> `function f() {}` - this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(89 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(90 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); deleteNode(this, sourceFile, arrow); } else { // `x => {}` -> `function f(x) {}` this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` - this.replaceRange(sourceFile, arrow, ts.createToken(20 /* CloseParenToken */)); + this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */)); } - if (node.body.kind !== 216 /* Block */) { + if (node.body.kind !== 218 /* Block */) { // `() => 0` => `function f() { return 0; }` - this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(17 /* OpenBraceToken */), ts.createToken(96 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); - this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(25 /* SemicolonToken */), ts.createToken(18 /* CloseBraceToken */)], { joiner: " " }); + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(97 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); + this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " }); } } else { - var pos = ts.findChildOfKind(node, node.kind === 194 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end; + var pos = ts.findChildOfKind(node, node.kind === 196 /* FunctionExpression */ ? 90 /* FunctionKeyword */ : 76 /* ClassKeyword */, sourceFile).end; this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } }; @@ -104002,11 +107802,11 @@ var ts; if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } if (!containingList) { ts.Debug.fail("node is not a list element"); - return this; + return; } var index = ts.indexOfNode(containingList, after); if (index < 0) { - return this; + return; } var end = after.getEnd(); if (index !== containingList.length - 1) { @@ -104058,7 +107858,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104074,12 +107874,12 @@ var ts; // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise // i.e. var x = 1 // this is x // | new element will be inserted at this position - separator = 26 /* CommaToken */; + separator = 27 /* CommaToken */; } else { // element has more than one element, pick separator from the list var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile); - separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 26 /* CommaToken */; + separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */; // determine if list is multiline by checking lines of after element and element that precedes it. var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile); multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition; @@ -104090,7 +107890,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104098,28 +107898,27 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } - return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; - var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. var _loop_8 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { @@ -104172,9 +107971,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { - return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; + function getClassOrObjectBraceEnds(cls, sourceFile) { + return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104200,14 +108006,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes) + newLineCharacter; + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104245,9 +108055,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -104329,6 +108140,9 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeComment = function (s) { + this.writer.writeComment(s); + }; Writer.prototype.writeKeyword = function (s) { this.writer.writeKeyword(s); this.setLastNonTriviaPosition(s, /*force*/ false); @@ -104341,6 +108155,10 @@ var ts; this.writer.writePunctuation(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeTrailingSemicolon = function (s) { + this.writer.writeTrailingSemicolon(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; Writer.prototype.writeParameter = function (s) { this.writer.writeParameter(s); this.setLastNonTriviaPosition(s, /*force*/ false); @@ -104361,9 +108179,6 @@ var ts; this.writer.writeSymbol(s, sym); this.setLastNonTriviaPosition(s, /*force*/ false); }; - Writer.prototype.writeTextOfNode = function (text, node) { - this.writer.writeTextOfNode(text, node); - }; Writer.prototype.writeLine = function () { this.writer.writeLine(); }; @@ -104405,10 +108220,25 @@ var ts; }; return Writer; }()); - function getInsertionPositionAtSourceFileTop(_a) { - var text = _a.text; - var shebang = ts.getShebang(text); + function getInsertionPositionAtSourceFileTop(sourceFile) { + var lastPrologue; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + if (ts.isPrologueDirective(node)) { + lastPrologue = node; + } + else { + break; + } + } var position = 0; + var text = sourceFile.text; + if (lastPrologue) { + position = lastPrologue.end; + advancePastLineBreak(); + return position; + } + var shebang = ts.getShebang(text); if (shebang !== undefined) { position = shebang.length; advancePastLineBreak(); @@ -104424,8 +108254,8 @@ var ts; ranges = ranges.slice(1); } // As well as any triple slash references - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; + for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) { + var range = ranges_1[_b]; if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { position = range.end; advancePastLineBreak(); @@ -104447,45 +108277,40 @@ var ts; } } function isValidLocationToAddComment(sourceFile, position) { - return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position); } textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; function needSemicolonBetween(a, b) { - return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 147 /* ComputedPropertyName */ + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 149 /* ComputedPropertyName */ || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` } var deleteDeclaration; (function (deleteDeclaration_1) { function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { switch (node.kind) { - case 149 /* Parameter */: { + case 151 /* Parameter */: { var oldFunction = node.parent; - if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + if (ts.isArrowFunction(oldFunction) && + oldFunction.parameters.length === 1 && + !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the // case if the parameter is simply removed (e.g. in `x => 1`). - var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, - /*parameters*/ undefined, // TODO: GH#18217 - oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); - // Drop leading and trailing trivia of the new function because we're only going - // to replace the span (vs the full span) of the old function - the old leading - // and trailing trivia will remain. - ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction); + changes.replaceNodeWithText(sourceFile, node, "()"); } else { deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; } - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: deleteNode(changes, sourceFile, node, // For first import, leave header comment in place node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: var pattern = node.parent; - var preserveComma = pattern.kind === 183 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + var preserveComma = pattern.kind === 185 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); if (preserveComma) { deleteNode(changes, sourceFile, node); } @@ -104493,13 +108318,13 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { deleteImportBinding(changes, sourceFile, namedImports); @@ -104508,7 +108333,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; default: @@ -104519,7 +108344,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } else { - deleteNode(changes, sourceFile, node, node.kind === 25 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); } } } @@ -104533,7 +108358,7 @@ var ts; // import |d,| * as ns from './file' var start = importClause.name.getStart(sourceFile); var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { + if (nextToken && nextToken.kind === 27 /* CommaToken */) { // shift first non-whitespace position after comma to the start position of the node var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); changes.deleteRange(sourceFile, { pos: start, end: end }); @@ -104555,15 +108380,15 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(node, 247 /* ImportDeclaration */); + var importDecl = ts.getAncestor(node, 249 /* ImportDeclaration */); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { var parent = node.parent; - if (parent.kind === 272 /* CatchClause */) { + if (parent.kind === 274 /* CatchClause */) { // TODO: There's currently no unused diagnostic for this, could be a suggestion - changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 19 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 20 /* CloseParenToken */, sourceFile)); + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); return; } if (parent.declarations.length !== 1) { @@ -104572,14 +108397,14 @@ var ts; } var gp = parent.parent; switch (gp.kind) { - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: deleteNode(changes, sourceFile, parent); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: deleteNode(changes, sourceFile, gp); break; default: @@ -104724,6 +108549,32 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addConvertToUnknownForNonOverlappingTypes"; + var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var assertion = ts.Debug.assertDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); })); + var replacement = ts.isAsExpression(assertion) + ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(143 /* UnknownKeyword */)) + : ts.createTypeAssertion(ts.createKeywordTypeNode(143 /* UnknownKeyword */), assertion.expression); + changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -104749,6 +108600,40 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addNameToNamelessParameter"; + var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(token)) { + return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.formatSyntaxKind(token.kind)); + } + var param = token.parent; + if (!ts.isParameter(param)) { + return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.formatSyntaxKind(token.kind)); + } + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); + ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); + var replacement = ts.createParameter( + /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer); + changeTracker.replaceNode(sourceFile, token, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -104791,9 +108676,9 @@ var ts; if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } - var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile); if (needParens) - changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(19 /* OpenParenToken */)); + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */)); for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { var param = _a[_i]; if (!param.type) { @@ -104803,7 +108688,7 @@ var ts; } } if (needParens) - changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(20 /* CloseParenToken */)); + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */)); if (!decl.type) { var returnType = ts.getJSDocReturnType(decl); if (returnType) @@ -104818,26 +108703,26 @@ var ts; } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 235 /* VariableDeclaration */ || - node.kind === 151 /* PropertySignature */ || - node.kind === 152 /* PropertyDeclaration */; + node.kind === 237 /* VariableDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 154 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 285 /* JSDocNonNullableType */: + case 287 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return transformJSDocFunctionType(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return transformJSDocTypeReference(node); default: var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 @@ -104859,9 +108744,9 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 288 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); - var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; + var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); } function transformJSDocTypeReference(node) { @@ -104899,8 +108784,8 @@ var ts; var index = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s", - /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []), + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "number" : "string", []), /*initializer*/ undefined); var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); ts.setEmitFlags(indexSignature, 1 /* SingleLine */); @@ -104910,6 +108795,784 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var token = ts.getTokenAtPosition(sourceFile, start); + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var markSeen = ts.nodeSeenTracker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + }); + }, + }); + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; + default: + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode) { + switch (errorCode) { + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 72 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 100 /* ThisKeyword */) { + return undefined; + } + var parent = token.parent; + errorCode = mapSuggestionDiagnostic(errorCode); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags + var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ ""); + addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + } + return parent; + } + return undefined; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + return symbol.valueDeclaration; + } + return undefined; + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + return param; + } + return undefined; + // Get Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: + case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + return containingFunction; + } + return undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + return undefined; + default: + return ts.Debug.fail(String(errorCode)); + } + } + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + } + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + return true; + case 196 /* FunctionExpression */: + var parent = declaration.parent; + return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) || !!declaration.name; + } + return false; + } + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return; + } + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } + } + } + } + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } + } + } + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) { + var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; + if (!parent) { + return; + } + var typeExpression = ts.createJSDocTypeExpression(typeNode); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } + } + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + var paramTags = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + // only infer parameters that have (1) no type and (2) an accessible inferred type + if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name)) + return; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + var name = ts.getSynthesizedClone(param.name); + ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), ""); + }); + addJSDocTags(changes, sourceFile, signature, paramTags); + } + function addJSDocTags(changes, sourceFile, parent, newTags) { + var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags))); + changes.insertJsdocCommentBefore(sourceFile, parent, tag); + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 299 /* JSDocParameterTag */: { + var oldParam = oldTag; + var newParam = newTag; + return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + : undefined; + } + case 300 /* JSDocReturnTag */: + return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); + } + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } + }); + return typeIsAccessible ? res : undefined; + } + function getReferences(token, program, cancellationToken) { + // Position shouldn't matter since token is not a SourceFile. + return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + }); + } + function inferTypeForVariableFromUsage(token, program, cancellationToken) { + var references = getReferences(token, program, cancellationToken); + var checker = program.getTypeChecker(); + var types = InferFromReference.inferTypesFromReferences(references, checker, cancellationToken); + return InferFromReference.unifyFromContext(types, checker); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + var searchToken; + switch (containingFunction.kind) { + case 157 /* Constructor */: + searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); + break; + case 196 /* FunctionExpression */: + var parent = containingFunction.parent; + searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + searchToken = containingFunction.name; + break; + } + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypesFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return inferFromContext(usageContext, checker); + } + InferFromReference.inferTypesFromReferences = inferTypesFromReferences; + function inferTypeForParametersFromReferences(references, declaration, program, cancellationToken) { + var checker = program.getTypeChecker(); + if (references.length === 0) { + return undefined; + } + if (!declaration.parameters) { + return undefined; + } + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []); + return declaration.parameters.map(function (parameter, parameterIndex) { + var types = []; + var isRest = ts.isRestParameter(parameter); + var isOptional = false; + for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { + var callContext = callContexts_1[_i]; + if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); + types.push(checker.getUndefinedType()); + } + else if (isRest) { + for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + } + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + if (ts.isIdentifier(parameter.name)) { + var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken); + types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); + } + var type = unifyFromContext(types, checker); + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; + }); + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 203 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 202 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 204 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 189 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 190 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + case 237 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + usageContext.isNumber = true; + break; + case 38 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + // case SyntaxKind.ExclamationToken: + // no inferences here; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 41 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + // ShiftOperator + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 49 /* AmpersandToken */: + case 50 /* BarToken */: + case 51 /* CaretToken */: + // CompoundAssignmentOperator + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 70 /* BarEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 39 /* MinusToken */: + // RelationalOperator + case 28 /* LessThanToken */: + case 31 /* LessThanEqualsToken */: + case 30 /* GreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 60 /* PlusEqualsToken */: + case 38 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 296 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 132 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 59 /* EqualsToken */: + case 33 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 93 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 55 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 237 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + case 94 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 191 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent.argumentExpression); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 296 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function removeLowPriorityInferences(inferences, priorities) { + var toRemove = []; + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var i = inferences_1[_i]; + for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) { + var _b = priorities_1[_a], high = _b.high, low = _b.low; + if (high(i)) { + ts.Debug.assert(!low(i)); + toRemove.push(low); + } + } + } + return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); }); + } + function unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + // 1. string or number individually override string | number + // 2. non-any, non-void overrides any or void + // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types + var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); + var priorities = [ + { + high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); }, + low: function (t) { return t === stringNumber; } + }, + { + high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); }, + low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); } + }, + { + high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); }, + low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); } + } + ]; + var good = removeLowPriorityInferences(inferences, priorities); + var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + if (anons.length) { + good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + good.push(unifyAnonymousTypes(anons, checker)); + } + return checker.getWidenedType(checker.getUnionType(good)); + } + InferFromReference.unifyFromContext = unifyFromContext; + function unifyAnonymousTypes(anons, checker) { + if (anons.length === 1) { + return anons[0]; + } + var calls = []; + var constructs = []; + var stringIndices = []; + var numberIndices = []; + var stringIndexReadonly = false; + var numberIndexReadonly = false; + var props = ts.createMultiMap(); + for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) { + var anon = anons_1[_i]; + for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { + var p = _b[_a]; + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); + constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } + } + var members = ts.mapEntries(props, function (name, types) { + var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; + var s = checker.createSymbol(4 /* Property */ | isOptional, name); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + function inferFromContext(usageContext, checker) { + var types = []; + if (usageContext.isNumber) { + types.push(checker.getNumberType()); + } + if (usageContext.isString) { + types.push(checker.getStringType()); + } + if (usageContext.isNumberOrString) { + types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); + } + types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 + var types_1 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + types_1.push(checker.createPromiseType(types_1.length ? checker.getUnionType(types_1, 2 /* Subtype */) : checker.getAnyType())); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker))); + } + if (usageContext.numberIndexContext) { + types.push(checker.createArrayType(recur(usageContext.numberIndexContext))); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { + var members_1 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = recur(context); + members_1.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); + } + types.push(checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 + } + return types; + function recur(innerContext) { + return unifyFromContext(inferFromContext(innerContext, checker), checker); + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = unifyFromContext(inferFromContext(callContext.returnType, checker), checker, checker.getVoidType()); + // TODO: GH#18217 + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return !!usageContext && !!usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -104934,12 +109597,12 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: precedingNode = ctorDeclaration; changes.delete(sourceFile, ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: precedingNode = ctorDeclaration.parent.parent; newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { @@ -104971,7 +109634,7 @@ var ts; // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); + var memberElement = createClassElement(member, [ts.createToken(116 /* StaticKeyword */)]); if (memberElement) { memberElements.push(memberElement); } @@ -104994,7 +109657,7 @@ var ts; return; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 219 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 221 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentBinaryExpression.right) { @@ -105002,27 +109665,27 @@ var ts; /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 194 /* FunctionExpression */: { + case 196 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); ts.copyComments(assignmentBinaryExpression, method, sourceFile); return method; } - case 195 /* ArrowFunction */: { + case 197 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 216 /* Block */) { + if (arrowFunctionBody.kind === 218 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] else { bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); } - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); ts.copyComments(assignmentBinaryExpression, method, sourceFile); @@ -105030,7 +109693,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105043,17 +109706,17 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 194 /* FunctionExpression */) { + if (!initializer || initializer.kind !== 196 /* FunctionExpression */) { return undefined; } - if (node.name.kind !== 71 /* Identifier */) { + if (node.name.kind !== 72 /* Identifier */) { return undefined; } var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */); + var modifiers = getModifierKindFromSource(precedingNode, 85 /* ExportKeyword */); var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place @@ -105064,7 +109727,7 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); } - var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */); + var modifiers = getModifierKindFromSource(node, 85 /* ExportKeyword */); var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place @@ -105083,59 +109746,73 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); - var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 121 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } var _loop_10 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; _loop_10(statement); } } + function getReturnStatementsWithPromiseHandlers(body) { + var res = []; + ts.forEachReturnStatement(body, function (ret) { + if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + res.push(ret); + }); + return res; + } // Returns the identifiers that are never reassigned in the refactor function getConstIdentifiers(synthNamesMap) { var constIdentifiers = []; @@ -105180,7 +109857,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105194,6 +109871,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105207,19 +109885,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105227,6 +109911,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105249,9 +109934,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105261,23 +109944,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105286,7 +109978,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105301,17 +109994,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105327,6 +110021,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105338,14 +110037,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105354,100 +110050,134 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 96 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 72 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; - if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } + if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; - var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); + var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_1 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_1 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105468,12 +110198,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105481,20 +110205,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105543,10 +110265,10 @@ var ts; } var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); } @@ -105572,7 +110294,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -105592,29 +110314,29 @@ var ts; sourceFile.forEachChild(function recur(node) { if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { var parent = node.parent; - cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 59 /* EqualsToken */); } node.forEachChild(recur); }); } function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 219 /* ExpressionStatement */: { + case 221 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 189 /* CallExpression */: { + case 191 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var operatorToken = expression.operatorToken; - return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); + return operatorToken.kind === 59 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); } } } @@ -105654,8 +110376,8 @@ var ts; /** Converts `const name = require("moduleSpecifier").propertyName` */ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ @@ -105663,7 +110385,7 @@ var ts; makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } - case 71 /* Identifier */: + case 72 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; default: @@ -105689,7 +110411,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -105706,16 +110428,16 @@ var ts; function tryChangeModuleExportsObject(object) { var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. - case 274 /* ShorthandPropertyAssignment */: - case 275 /* SpreadAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 277 /* SpreadAssignment */: return undefined; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); - case 154 /* MethodDeclaration */: - return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); + case 156 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(85 /* ExportKeyword */)], prop); default: ts.Debug.assertNever(prop); } @@ -105764,23 +110486,23 @@ var ts; var name = left.name.text; if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) { // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. - changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(84 /* ExportKeyword */), { suffix: " " }); + changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(85 /* ExportKeyword */), { suffix: " " }); if (!right.name) changes.insertName(sourceFile, right, name); - var semi = ts.findChildOfKind(parent, 25 /* SemicolonToken */, sourceFile); + var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile); if (semi) changes.delete(sourceFile, semi); } else { // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` - changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 23 /* DotToken */, sourceFile), [ts.createToken(84 /* ExportKeyword */), ts.createToken(76 /* ConstKeyword */)], { joiner: " ", suffix: " " }); + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(85 /* ExportKeyword */), ts.createToken(77 /* ConstKeyword */)], { joiner: " ", suffix: " " }); } } // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node. function convertExportsDotXEquals_replaceNode(name, exported) { - var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + var modifiers = [ts.createToken(85 /* ExportKeyword */)]; switch (exported.kind) { - case 194 /* FunctionExpression */: { + case 196 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -105788,10 +110510,10 @@ var ts; } } // falls through - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported); default: @@ -105809,7 +110531,7 @@ var ts; */ function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: { + case 184 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined @@ -105820,7 +110542,7 @@ var ts; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 183 /* ArrayBindingPattern */: { + case 185 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; @@ -105831,7 +110553,7 @@ var ts; makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } - case 71 /* Identifier */: + case 72 /* Identifier */: return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); default: return ts.Debug.assertNever(name); @@ -105903,11 +110625,11 @@ var ts; function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return parent.name !== node; - case 184 /* BindingElement */: + case 186 /* BindingElement */: return parent.propertyName !== node; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -106175,33 +110897,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106239,21 +110968,21 @@ var ts; function tryAddToExistingImport(existingImports) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind !== 247 /* ImportDeclaration */) + if (declaration.kind !== 249 /* ImportDeclaration */) return undefined; var importClause = declaration.importClause; if (!importClause) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; - return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */) + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 252 /* NamedImports */) ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } : undefined; }); } function getNamespaceImportName(declaration) { - if (declaration.kind === 247 /* ImportDeclaration */) { + if (declaration.kind === 249 /* ImportDeclaration */) { var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 249 /* NamespaceImport */ ? namedBindings.name : undefined; + return namedBindings && namedBindings.kind === 251 /* NamespaceImport */ ? namedBindings.name : undefined; } else { return declaration.name; @@ -106262,24 +110991,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) + return (i.kind === 249 /* ImportDeclaration */ || i.kind === 248 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return ts.sort(choicesForEachExportingModule, function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106287,9 +111016,9 @@ var ts; } function newImportInfoFromExistingSpecifier(_a) { var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 247 /* ImportDeclaration */ + var expression = declaration.kind === 249 /* ImportDeclaration */ ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 257 /* ExternalModuleReference */ + : declaration.moduleReference.kind === 259 /* ExternalModuleReference */ ? declaration.moduleReference.expression : undefined; return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; @@ -106321,7 +111050,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106369,17 +111098,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106389,7 +111114,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106397,11 +111137,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -106606,12 +111346,12 @@ var ts; var checker = context.program.getTypeChecker(); var suggestion; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71 /* Identifier */); + ts.Debug.assert(node.kind === 72 /* Identifier */); var containingType = checker.getTypeAtLocation(node.parent.expression); suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); } else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71 /* Identifier */); + ts.Debug.assert(node.kind === 72 /* Identifier */); var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { @@ -106640,10 +111380,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -106666,6 +111406,9 @@ var ts; var errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code ]; var fixId = "addMissingMember"; codefix.registerCodeFix({ @@ -106682,7 +111425,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -106782,7 +111525,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -106792,14 +111535,14 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { - if (classDeclaration.kind === 207 /* ClassExpression */) { + if (classDeclaration.kind === 209 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -106825,13 +111568,17 @@ var ts; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 202 /* BinaryExpression */) { + if (token.parent.parent.kind === 204 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } - return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); + else { + var contextualType = checker.getContextualType(token.parent); + typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + } + return typeNode || ts.createKeywordTypeNode(120 /* AnyKeyword */); } function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); @@ -106840,7 +111587,7 @@ var ts; function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); var lastProp = getNodeToInsertPropertyAfter(classDeclaration); @@ -106864,7 +111611,7 @@ var ts; } function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. - var stringTypeNode = ts.createKeywordTypeNode(137 /* StringKeyword */); + var stringTypeNode = ts.createKeywordTypeNode(138 /* StringKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -106884,7 +111631,7 @@ var ts; } function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); - var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */); + var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); } @@ -106900,7 +111647,7 @@ var ts; */ var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { var type = checker.getTypeAtLocation(member); - return !!(type && type.flags & 68 /* StringLike */); + return !!(type && type.flags & 132 /* StringLike */); }); var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); @@ -106912,7 +111659,43 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixId = "addMissingNewOperator"; + var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return addMissingNewOperator(changes, context.sourceFile, diag); + }); }, + }); + function addMissingNewOperator(changes, sourceFile, span) { + var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression); + var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments); + changes.replaceNode(sourceFile, call, newExpression); + } + function findAncestorMatchingSpan(sourceFile, span) { + var token = ts.getTokenAtPosition(sourceFile, span.start); + var end = ts.textSpanEnd(span); + while (token.end < end) { + token = token.parent; + } + return token; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -106922,24 +111705,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -107037,7 +111930,7 @@ var ts; } function getNodes(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - if (token.kind !== 99 /* ThisKeyword */) + if (token.kind !== 100 /* ThisKeyword */) return undefined; var constructor = ts.getContainingFunction(token); var superCall = findSuperCall(constructor.body); @@ -107076,7 +111969,7 @@ var ts; }); function getNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */); + ts.Debug.assert(token.kind === 124 /* ConstructorKeyword */); return token.parent; } function doChange(changes, sourceFile, ctr) { @@ -107114,17 +112007,17 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); var heritageClauses = ts.getContainingClass(token).heritageClauses; var extendsToken = heritageClauses[0].getFirstToken(); - return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + return extendsToken.kind === 86 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; } function doChanges(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); + changes.replaceNode(sourceFile, extendsToken, ts.createToken(109 /* ImplementsKeyword */)); // If there is already an implements clause, replace the implements keyword with a comma. if (heritageClauses.length === 2 && - heritageClauses[0].token === 85 /* ExtendsKeyword */ && - heritageClauses[1].token === 108 /* ImplementsKeyword */) { + heritageClauses[0].token === 86 /* ExtendsKeyword */ && + heritageClauses[1].token === 109 /* ImplementsKeyword */) { var implementsToken = heritageClauses[1].getFirstToken(); var implementsFullStart = implementsToken.getFullStart(); - changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(26 /* CommaToken */)); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */)); // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. // (Trailing because leading might be indentation, which is more sensitive.) var text = sourceFile.text; @@ -107208,7 +112101,7 @@ var ts; if (ts.isJSDocTemplateTag(token)) { return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; } - if (token.kind === 27 /* LessThanToken */) { + if (token.kind === 28 /* LessThanToken */) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; } @@ -107228,7 +112121,7 @@ var ts; return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; } var result = []; - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); @@ -107260,7 +112153,7 @@ var ts; tryPrefixDeclaration(changes, diag.code, sourceFile, token); break; case fixIdDelete: { - if (token.kind === 126 /* InferKeyword */) + if (token.kind === 127 /* InferKeyword */) break; // Can't delete var importDecl = tryGetFullImport(token); if (importDecl) { @@ -107269,7 +112162,7 @@ var ts; else if (ts.isJSDocTemplateTag(token)) { changes.delete(sourceFile, token); } - else if (token.kind === 27 /* LessThanToken */) { + else if (token.kind === 28 /* LessThanToken */) { deleteTypeParameters(changes, sourceFile, token); } else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && @@ -107279,7 +112172,7 @@ var ts; break; } case fixIdInfer: - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { changeInferToUnknown(changes, sourceFile, token); } break; @@ -107290,7 +112183,7 @@ var ts; }, }); function changeInferToUnknown(changes, sourceFile, token) { - changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(142 /* UnknownKeyword */)); + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(143 /* UnknownKeyword */)); } function createDeleteFix(changes, diag) { return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); @@ -107300,13 +112193,13 @@ var ts; } // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(token) { - return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; + return token.kind === 92 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; } function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { - if (token.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) + if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) return false; var decl = token.parent.parent; - if (decl.kind === 149 /* Parameter */) { + if (decl.kind === 151 /* Parameter */) { tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); } else { @@ -107317,7 +112210,7 @@ var ts; function tryDeleteFullVariableStatement(sourceFile, token, changes) { var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { - changes.delete(sourceFile, declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList); + changes.delete(sourceFile, declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList); return true; } return false; @@ -107326,7 +112219,7 @@ var ts; // Don't offer to prefix a property. if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) return; - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; } if (ts.isIdentifier(token) && canPrefix(token)) { @@ -107335,14 +112228,14 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 149 /* Parameter */: - case 148 /* TypeParameter */: + case 151 /* Parameter */: + case 150 /* TypeParameter */: return true; - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: return true; } } @@ -107356,9 +112249,9 @@ var ts; } function deleteAssignments(changes, sourceFile, token, checker) { ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { - if (ref.parent.kind === 187 /* PropertyAccessExpression */) + if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent; - if (ref.parent.kind === 202 /* BinaryExpression */ && ref.parent.parent.kind === 219 /* ExpressionStatement */) { + if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) { changes.delete(sourceFile, ref.parent.parent); } }); @@ -107374,33 +112267,41 @@ var ts; } function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { if (mayDeleteParameter(p, checker, isFixAll)) { - changes.delete(sourceFile, p); - deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + if (p.modifiers && p.modifiers.length > 0 + && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + p.modifiers.forEach(function (modifier) { + changes.deleteModifier(sourceFile, modifier); + }); + } + else { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + } } } function mayDeleteParameter(p, checker, isFixAll) { var parent = p.parent; switch (parent.kind) { - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // Don't remove a parameter if this overrides something. var symbol = checker.getSymbolAtLocation(parent.name); if (ts.isMemberSymbolInBaseType(symbol, checker)) return false; // falls through - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: return true; - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. var parameters = parent.parameters; var index = parameters.indexOf(p); ts.Debug.assert(index !== -1); return isFixAll - ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 71 /* Identifier */ && !p.symbol.isReferenced; }) + ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 72 /* Identifier */ && !p.symbol.isReferenced; }) : index === parameters.length - 1; } - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: // Setter must have a parameter return false; default: @@ -107440,7 +112341,7 @@ var ts; var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { switch (container.kind) { - case 220 /* IfStatement */: + case 222 /* IfStatement */: if (container.elseStatement) { if (ts.isBlock(statement.parent)) { break; @@ -107451,8 +112352,8 @@ var ts; return; } // falls through - case 222 /* WhileStatement */: - case 223 /* ForStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: changes.delete(sourceFile, container); return; } @@ -107501,7 +112402,7 @@ var ts; var statementPos = labeledStatement.statement.getStart(sourceFile); // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos - : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 57 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); changes.deleteRange(sourceFile, { pos: pos, end: end }); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -107525,10 +112426,10 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 284 /* JSDocNullableType */) { + if (typeNode.kind === 286 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - actions.push(fix(checker.getNullableType(type, 8192 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); + actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; function fix(type, fixId, fixAllDescription) { @@ -107545,7 +112446,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 284 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type; + var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -107562,22 +112463,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 210 /* AsExpression */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 237 /* FunctionDeclaration */: - case 156 /* GetAccessor */: - case 160 /* IndexSignature */: - case 179 /* MappedType */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 157 /* SetAccessor */: - case 240 /* TypeAliasDeclaration */: - case 192 /* TypeAssertionExpression */: - case 235 /* VariableDeclaration */: + case 212 /* AsExpression */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 239 /* FunctionDeclaration */: + case 158 /* GetAccessor */: + case 162 /* IndexSignature */: + case 181 /* MappedType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 194 /* TypeAssertionExpression */: + case 237 /* VariableDeclaration */: return true; default: return false; @@ -107631,15 +112532,15 @@ var ts; } var insertBefore; switch (containingFunction.kind) { - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 90 /* FunctionKeyword */, sourceFile); break; - case 195 /* ArrowFunction */: - insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + case 197 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: return; @@ -107653,11 +112554,11 @@ var ts; var insertBefore = _a.insertBefore, returnType = _a.returnType; if (returnType) { var entityName = ts.getEntityNameFromTypeNode(returnType); - if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") { + if (!entityName || entityName.kind !== 72 /* Identifier */ || entityName.text !== "Promise") { changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); } } - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore); + changes.insertModifierBefore(sourceFile, 121 /* AsyncKeyword */, insertBefore); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -107676,7 +112577,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -107747,17 +112648,17 @@ var ts; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 151 /* PropertySignature */: - case 152 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 153 /* PropertySignature */: + case 154 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); out(ts.createProperty( - /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, + /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 153 /* MethodSignature */: - case 154 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 156 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -107797,43 +112698,40 @@ var ts; } } function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 154 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); if (!signatureDeclaration) { return undefined; } signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; signatureDeclaration.name = name; - signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; + signatureDeclaration.questionToken = optional ? ts.createToken(56 /* QuestionToken */) : undefined; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, - /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(39 /* AsteriskToken */) : undefined, methodName, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(40 /* AsteriskToken */) : undefined, methodName, /*questionToken*/ undefined, /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -107844,8 +112742,8 @@ var ts; /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || "arg" + i, - /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, - /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(119 /* AnyKeyword */), + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(120 /* AnyKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -107873,11 +112771,11 @@ var ts; var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { - var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); + var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(120 /* AnyKeyword */)); var restParameter = ts.createParameter( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", - /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, anyArrayType, + /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", + /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, anyArrayType, /*initializer*/ undefined); parameters.push(restParameter); } @@ -107888,7 +112786,7 @@ var ts; function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { return ts.createMethod( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); + /*asteriskToken*/ undefined, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); } function createStubbedMethodBody(preferences) { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), @@ -107897,10 +112795,10 @@ var ts; } function createVisibilityModifier(flags) { if (flags & 4 /* Public */) { - return ts.createToken(114 /* PublicKeyword */); + return ts.createToken(115 /* PublicKeyword */); } else if (flags & 16 /* Protected */) { - return ts.createToken(113 /* ProtectedKeyword */); + return ts.createToken(114 /* ProtectedKeyword */); } return undefined; } @@ -107908,561 +112806,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - var codefix; - (function (codefix) { - var fixId = "inferFromUsage"; - var errorCodes = [ - // Variable declarations - ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, - ]; - codefix.registerCodeFix({ - errorCodes: errorCodes, - getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } - var token = ts.getTokenAtPosition(sourceFile, start); - var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); - var name = declaration && ts.getNameOfDeclaration(declaration); - return !name || changes.length === 0 ? undefined - : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; - }, - fixIds: [fixId], - getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; - var markSeen = ts.nodeSeenTracker(); - return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); - }); - }, - }); - function getDiagnostic(errorCode, token) { - switch (errorCode) { - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return ts.Diagnostics.Infer_parameter_types_from_usage; - default: - return ts.Diagnostics.Infer_type_of_0_from_usage; - } - } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { - return undefined; - } - var parent = token.parent; - switch (errorCode) { - // Variable and Property declarations - case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: - case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); - return parent; - } - return undefined; - case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { - var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); - return symbol.valueDeclaration; - } - return undefined; - } - } - var containingFunction = ts.getContainingFunction(token); - if (containingFunction === undefined) { - return undefined; - } - switch (errorCode) { - // Parameter declarations - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); - return containingFunction; - } - // falls through - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (markSeen(containingFunction)) { - var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); - return param; - } - return undefined; - // Get Accessor declarations - case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: - case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); - return containingFunction; - } - return undefined; - // Set Accessor declarations - case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); - return containingFunction; - } - return undefined; - default: - return ts.Debug.fail(String(errorCode)); - } - } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { - if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); - } - } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - return true; - case 194 /* FunctionExpression */: - return !!declaration.name; - } - return false; - } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return; - } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; - } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); - } - }); - } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { - var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); - if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || - inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); - } - } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); - } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { - var typeIsAccessible = true; - var notAccessible = function () { typeIsAccessible = false; }; - var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { - trackSymbol: function (symbol, declaration, meaning) { - // TODO: GH#18217 - typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; - }, - reportInaccessibleThisError: notAccessible, - reportPrivateInBaseOfClassExpression: notAccessible, - reportInaccessibleUniqueSymbolError: notAccessible, - }); - return typeIsAccessible ? res : undefined; - } - function getReferences(token, program, cancellationToken) { - // Position shouldn't matter since token is not a SourceFile. - return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; - }); - } - function inferTypeForVariableFromUsage(token, program, cancellationToken) { - return InferFromReference.inferTypeFromReferences(getReferences(token, program, cancellationToken), program.getTypeChecker(), cancellationToken); - } - function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { - switch (containingFunction.kind) { - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - var isConstructor = containingFunction.kind === 155 /* Constructor */; - var searchToken = isConstructor ? - ts.findChildOfKind(containingFunction, 123 /* ConstructorKeyword */, sourceFile) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); - } - } - } - var InferFromReference; - (function (InferFromReference) { - function inferTypeFromReferences(references, checker, cancellationToken) { - var usageContext = {}; - for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { - var reference = references_1[_i]; - cancellationToken.throwIfCancellationRequested(); - inferTypeFromContext(reference, checker, usageContext); - } - return getTypeFromUsageContext(usageContext, checker); - } - InferFromReference.inferTypeFromReferences = inferTypeFromReferences; - function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { - if (references.length === 0) { - return undefined; - } - if (!declaration.parameters) { - return undefined; - } - var usageContext = {}; - for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { - var reference = references_2[_i]; - cancellationToken.throwIfCancellationRequested(); - inferTypeFromContext(reference, checker, usageContext); - } - var isConstructor = declaration.kind === 155 /* Constructor */; - var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; - return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { - var types = []; - var isRest = ts.isRestParameter(parameter); - for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { - var callContext = callContexts_1[_i]; - if (callContext.argumentTypes.length <= parameterIndex) { - continue; - } - if (isRest) { - for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); - } - } - else { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); - } - } - if (!types.length) { - return undefined; - } - var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; - }); - } - InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; - function inferTypeFromContext(node, checker, usageContext) { - while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { - node = node.parent; - } - switch (node.parent.kind) { - case 201 /* PostfixUnaryExpression */: - usageContext.isNumber = true; - break; - case 200 /* PrefixUnaryExpression */: - inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); - break; - case 202 /* BinaryExpression */: - inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); - break; - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); - break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: - if (node.parent.expression === node) { - inferTypeFromCallExpressionContext(node.parent, checker, usageContext); - } - else { - inferTypeFromContextualType(node, checker, usageContext); - } - break; - case 187 /* PropertyAccessExpression */: - inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); - break; - case 188 /* ElementAccessExpression */: - inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); - break; - case 235 /* VariableDeclaration */: { - var _a = node.parent, name = _a.name, initializer = _a.initializer; - if (node === name) { - if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. - addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); - } - break; - } - } - // falls through - default: - return inferTypeFromContextualType(node, checker, usageContext); - } - } - function inferTypeFromContextualType(node, checker, usageContext) { - if (ts.isExpressionNode(node)) { - addCandidateType(usageContext, checker.getContextualType(node)); - } - } - function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { - switch (node.operator) { - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - usageContext.isNumber = true; - break; - case 37 /* PlusToken */: - usageContext.isNumberOrString = true; - break; - // case SyntaxKind.ExclamationToken: - // no inferences here; - } - } - function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { - switch (parent.operatorToken.kind) { - // ExponentiationOperator - case 40 /* AsteriskAsteriskToken */: - // MultiplicativeOperator - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - // ShiftOperator - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - // BitwiseOperator - case 48 /* AmpersandToken */: - case 49 /* BarToken */: - case 50 /* CaretToken */: - // CompoundAssignmentOperator - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 69 /* BarEqualsToken */: - case 70 /* CaretEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - // AdditiveOperator - case 38 /* MinusToken */: - // RelationalOperator - case 27 /* LessThanToken */: - case 30 /* LessThanEqualsToken */: - case 29 /* GreaterThanToken */: - case 31 /* GreaterThanEqualsToken */: - var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (operandType.flags & 544 /* EnumLike */) { - addCandidateType(usageContext, operandType); - } - else { - usageContext.isNumber = true; - } - break; - case 59 /* PlusEqualsToken */: - case 37 /* PlusToken */: - var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (otherOperandType.flags & 544 /* EnumLike */) { - addCandidateType(usageContext, otherOperandType); - } - else if (otherOperandType.flags & 168 /* NumberLike */) { - usageContext.isNumber = true; - } - else if (otherOperandType.flags & 68 /* StringLike */) { - usageContext.isString = true; - } - else { - usageContext.isNumberOrString = true; - } - break; - // AssignmentOperators - case 58 /* EqualsToken */: - case 32 /* EqualsEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); - break; - case 92 /* InKeyword */: - if (node === parent.left) { - usageContext.isString = true; - } - break; - // LogicalOperator - case 54 /* BarBarToken */: - if (node === parent.left && - (node.parent.parent.kind === 235 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { - // var x = x || {}; - // TODO: use getFalsyflagsOfType - addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); - } - break; - case 53 /* AmpersandAmpersandToken */: - case 26 /* CommaToken */: - case 93 /* InstanceOfKeyword */: - // nothing to infer here - break; - } - } - function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { - addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); - } - function inferTypeFromCallExpressionContext(parent, checker, usageContext) { - var callContext = { - argumentTypes: [], - returnType: {} - }; - if (parent.arguments) { - for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); - } - } - inferTypeFromContext(parent, checker, callContext.returnType); - if (parent.kind === 189 /* CallExpression */) { - (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); - } - else { - (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); - } - } - function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { - var name = ts.escapeLeadingUnderscores(parent.name.text); - if (!usageContext.properties) { - usageContext.properties = ts.createUnderscoreEscapedMap(); - } - var propertyUsageContext = usageContext.properties.get(name) || {}; - inferTypeFromContext(parent, checker, propertyUsageContext); - usageContext.properties.set(name, propertyUsageContext); - } - function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { - if (node === parent.argumentExpression) { - usageContext.isNumberOrString = true; - return; - } - else { - var indexType = checker.getTypeAtLocation(parent.argumentExpression); - var indexUsageContext = {}; - inferTypeFromContext(parent, checker, indexUsageContext); - if (indexType.flags & 168 /* NumberLike */) { - usageContext.numberIndexContext = indexUsageContext; - } - else { - usageContext.stringIndexContext = indexUsageContext; - } - } - } - function getTypeFromUsageContext(usageContext, checker) { - if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { - return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); - } - else if (usageContext.isNumber) { - return checker.getNumberType(); - } - else if (usageContext.isString) { - return checker.getStringType(); - } - else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); - } - else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { - var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 - var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); - return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); - } - else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { - return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); - } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { - var members_1 = ts.createUnderscoreEscapedMap(); - var callSignatures = []; - var constructSignatures = []; - var stringIndexInfo = void 0; - var numberIndexInfo = void 0; - if (usageContext.properties) { - usageContext.properties.forEach(function (context, name) { - var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); - members_1.set(name, symbol); - }); - } - if (usageContext.callContexts) { - for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { - var callContext = _a[_i]; - callSignatures.push(getSignatureFromCallContext(callContext, checker)); - } - } - if (usageContext.constructContexts) { - for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { - var constructContext = _c[_b]; - constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); - } - } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } - if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } - return checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 - } - else { - return undefined; - } - } - function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { - var types = []; - if (callContexts) { - for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { - var callContext = callContexts_2[_i]; - if (callContext.argumentTypes.length > parameterIndex) { - if (isRestParameter) { - types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); - } - else { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); - } - } - } - } - if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRestParameter ? checker.createArrayType(type) : type; - } - return undefined; - } - function getSignatureFromCallContext(callContext, checker) { - var parameters = []; - for (var i = 0; i < callContext.argumentTypes.length; i++) { - var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); - symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); - parameters.push(symbol); - } - var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); - // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - } - function addCandidateType(context, type) { - if (type && !(type.flags & 1 /* Any */) && !(type.flags & 32768 /* Never */)) { - (context.candidateTypes || (context.candidateTypes = [])).push(type); - } - } - function hasCallContext(usageContext) { - return !!usageContext && !!usageContext.callContexts; - } - })(InferFromReference || (InferFromReference = {})); - })(codefix = ts.codefix || (ts.codefix = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var codefix; (function (codefix) { @@ -108495,7 +112838,7 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 189 /* CallExpression */ : 190 /* NewExpression */; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 191 /* CallExpression */ : 192 /* NewExpression */; var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); if (!node) { return []; @@ -108606,7 +112949,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { - var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(52 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, propertyDeclaration) { @@ -108614,7 +112957,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { - var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + var undefinedTypeNode = ts.createKeywordTypeNode(141 /* UndefinedKeyword */); var type = propertyDeclaration.type; // TODO: GH#18217 var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); @@ -108635,8 +112978,8 @@ var ts; return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 } function getDefaultValueFromType(checker, type) { - if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + if (type.flags & 512 /* BooleanLiteral */) { + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -108660,6 +113003,234 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, 0 /* ExportEquals */); + } + ts.generateTypesForModule = generateTypesForModule; + function generateTypesForGlobal(name, globalValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, 3 /* Global */); + } + ts.generateTypesForGlobal = generateTypesForGlobal; + function generateTypesForModuleOrGlobal(name, globalValue, formatSettings, outputKind) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, globalValue), formatSettings, outputKind); + } + /* @internal */ + function valueInfoToDeclarationFileText(valueInfo, formatSettings, outputKind) { + if (outputKind === void 0) { outputKind = 0 /* ExportEquals */; } + return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + OutputKind[OutputKind["Global"] = 3] = "Global"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(85 /* ExportKeyword */), ts.createModifier(80 /* DefaultKeyword */)] + : kind === 3 /* Global */ || kind === 0 /* ExportEquals */ ? [ts.createModifier(125 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(85 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members, hasNontrivialPrototype = info.hasNontrivialPrototype; + if (!hasNontrivialPrototype) { + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var protoOrInstanceMembers = ts.createMap(); + if (typeof fnAst === "object") + getConstructorFunctionInstanceProperties(fnAst, protoOrInstanceMembers); + for (var _i = 0, prototypeMembers_1 = prototypeMembers; _i < prototypeMembers_1.length; _i++) { + var p = prototypeMembers_1[_i]; + // ignore non-functions on the prototype + if (p.kind === 2 /* FunctionOrClass */) { + var m = tryGetMethod(p); + if (m) { + protoOrInstanceMembers.set(p.name, m); + } + } + } + var classStaticMembers = protoOrInstanceMembers.size !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(116 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(116 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + break; + default: + ts.Debug.assertNever(info); + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), ts.arrayFrom(protoOrInstanceMembers.values()))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + function toPropertyName(name) { + return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name); + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst, members) { + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { + var name_4 = node.left.name.text; + if (!ts.isJsPrivate(name_4)) { + ts.getOrUpdate(members, name_4, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_4, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + } + } + }); + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 200 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(106 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -108756,8 +113327,8 @@ var ts; }); function getImportTypeNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 91 /* ImportKeyword */); - ts.Debug.assert(token.parent.kind === 181 /* ImportType */); + ts.Debug.assert(token.kind === 92 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 183 /* ImportType */); return token.parent; } function doChange(changes, sourceFile, importType) { @@ -108809,7 +113380,7 @@ var ts; var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); var parameter = ts.first(indexSignature.parameters); var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); - var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(133 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ mappedIntersectionType ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); @@ -108829,7 +113400,7 @@ var ts; getAvailableActions: function (context) { var info = getInfo(context); if (!info) - return undefined; + return ts.emptyArray; var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; @@ -108856,16 +113427,16 @@ var ts; return undefined; } switch (exportNode.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: { var node = exportNode; return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { var vs = exportNode; // Must be `export const x = something;`. if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { @@ -108888,17 +113459,17 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 79 /* DefaultKeyword */))); + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 80 /* DefaultKeyword */))); } else { - var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* ExportKeyword */)); + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 85 /* ExportKeyword */)); switch (exportNode.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(79 /* DefaultKeyword */)); + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(80 /* DefaultKeyword */)); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { // We checked in `getInfo` that an initializer exists. @@ -108906,9 +113477,9 @@ var ts; break; } // falls through - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // `export type T = number;` -> `type T = number; export default T;` changes.deleteModifier(exportingSourceFile, exportKeyword); changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); @@ -108935,18 +113506,18 @@ var ts; function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { var parent = ref.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // `a.default` --> `a.foo` changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: { + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: { var spec = parent; // `default as foo` --> `foo`, `default as bar` --> `foo as bar` changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); break; } - case 248 /* ImportClause */: { + case 250 /* ImportClause */: { var clause = parent; ts.Debug.assert(clause.name === ref); var spec = makeImportSpecifier(exportName, ref.text); @@ -108955,7 +113526,7 @@ var ts; // `import foo from "./a";` --> `import { foo } from "./a";` changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); } - else if (namedBindings.kind === 249 /* NamespaceImport */) { + else if (namedBindings.kind === 251 /* NamespaceImport */) { // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; @@ -108976,36 +113547,33 @@ var ts; function changeNamedToDefaultImport(importingSourceFile, ref, changes) { var parent = ref.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // `a.foo` --> `a.default` changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: { - var spec = parent; - if (spec.kind === 251 /* ImportSpecifier */) { - // `import { foo } from "./a";` --> `import foo from "./a";` - // `import { foo as bar } from "./a";` --> `import bar from "./a";` - var defaultImport = ts.createIdentifier(spec.name.text); - if (spec.parent.elements.length === 1) { - changes.replaceNode(importingSourceFile, spec.parent, defaultImport); - } - else { - changes.delete(importingSourceFile, spec); - changes.insertNodeBefore(importingSourceFile, spec.parent, defaultImport); - } + case 253 /* ImportSpecifier */: { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(parent.name.text); + if (parent.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent.parent, defaultImport); } else { - // `export { foo } from "./a";` --> `export { default as foo } from "./a";` - // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` - // `export { foo as default } from "./a";` --> `export { default } from "./a";` - // (Because `export foo from "./a";` isn't valid syntax.) - changes.replaceNode(importingSourceFile, spec, makeExportSpecifier("default", spec.name.text)); + changes.delete(importingSourceFile, parent); + changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport); } break; } + case 257 /* ExportSpecifier */: { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text)); + break; + } default: - ts.Debug.failBadSyntaxKind(parent); + ts.Debug.assertNever(parent); } } function makeImportSpecifier(propertyName, name) { @@ -109028,9 +113596,9 @@ var ts; getAvailableActions: function (context) { var i = getImportToConvert(context); if (!i) - return undefined; - var description = i.kind === 249 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; - var actionName = i.kind === 249 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return ts.emptyArray; + var description = i.kind === 251 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 251 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; }, getEditsForAction: function (context, actionName) { @@ -109052,7 +113620,7 @@ var ts; } function doChange(sourceFile, program, changes, toConvert) { var checker = program.getTypeChecker(); - if (toConvert.kind === 249 /* NamespaceImport */) { + if (toConvert.kind === 251 /* NamespaceImport */) { doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { @@ -109160,12 +113728,12 @@ var ts; var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { - return undefined; + return ts.emptyArray; } var extractions = getPossibleExtractions(targetRange, context); if (extractions === undefined) { // No extractions possible - return undefined; + return ts.emptyArray; } var functionActions = []; var usedFunctionNames = ts.createMap(); @@ -109221,7 +113789,7 @@ var ts; actions: constantActions }); } - return infos.length ? infos : undefined; + return infos.length ? infos : ts.emptyArray; } extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ @@ -109395,20 +113963,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 152 /* PropertyDeclaration */) { + if (current.kind === 154 /* PropertyDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 149 /* Parameter */) { + else if (current.kind === 151 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 155 /* Constructor */) { + if (ctorOrMethod.kind === 157 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 154 /* MethodDeclaration */) { + else if (current.kind === 156 /* MethodDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -109451,7 +114019,7 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 235 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 237 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! @@ -109463,13 +114031,13 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 189 /* CallExpression */) { + if (node.parent.kind === 191 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { @@ -109484,8 +114052,8 @@ var ts; } if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); @@ -109497,20 +114065,20 @@ var ts; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 220 /* IfStatement */: + case 222 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 216 /* Block */: - if (node.parent && node.parent.kind === 233 /* TryStatement */ && node.parent.finallyBlock === node) { + case 218 /* Block */: + if (node.parent && node.parent.kind === 235 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 269 /* CaseClause */: + case 271 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -109522,11 +114090,11 @@ var ts; break; } switch (node.kind) { - case 176 /* ThisType */: - case 99 /* ThisKeyword */: + case 178 /* ThisType */: + case 100 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -109534,8 +114102,8 @@ var ts; seenLabels.pop(); break; } - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: { var label = node.label; if (label) { @@ -109545,20 +114113,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 227 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -109612,7 +114180,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 149 /* Parameter */) { + if (current.kind === 151 /* Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -109623,7 +114191,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 277 /* SourceFile */) { + if (current.kind === 279 /* SourceFile */) { return scopes; } } @@ -109713,32 +114281,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: return "constructor"; - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : "anonymous function"; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return "arrow function"; - case 154 /* MethodDeclaration */: - return "method '" + scope.name.getText(); - case 156 /* GetAccessor */: + case 156 /* MethodDeclaration */: + return "method '" + scope.name.getText() + "'"; + case 158 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: throw ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 238 /* ClassDeclaration */ + return scope.kind === 240 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 243 /* ModuleBlock */ + return scope.kind === 245 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -109757,7 +114325,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -109804,20 +114372,20 @@ var ts; var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files - var modifiers = isJS ? [] : [ts.createToken(112 /* PrivateKeyword */)]; + var modifiers = isJS ? [] : [ts.createToken(113 /* PrivateKeyword */)]; if (range.facts & RangeFacts.InStaticRegion) { - modifiers.push(ts.createToken(115 /* StaticKeyword */)); + modifiers.push(ts.createToken(116 /* StaticKeyword */)); } if (range.facts & RangeFacts.IsAsyncFunction) { - modifiers.push(ts.createToken(120 /* AsyncKeyword */)); + modifiers.push(ts.createToken(121 /* AsyncKeyword */)); } newFunction = ts.createMethod( - /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { newFunction = ts.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(121 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; @@ -109834,7 +114402,7 @@ var ts; var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference callArguments); if (range.facts & RangeFacts.IsGenerator) { - call = ts.createYield(ts.createToken(39 /* AsteriskToken */), call); + call = ts.createYield(ts.createToken(40 /* AsteriskToken */), call); } if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); @@ -109958,9 +114526,9 @@ var ts; while (ts.isParenthesizedTypeNode(withoutParens)) { withoutParens = withoutParens.type; } - return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 140 /* UndefinedKeyword */; }) + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 141 /* UndefinedKeyword */; }) ? clone - : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(140 /* UndefinedKeyword */)]); + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(141 /* UndefinedKeyword */)]); } } /** @@ -109973,7 +114541,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -109983,11 +114551,11 @@ var ts; if (ts.isClassLike(scope)) { ts.Debug.assert(!isJS); // See CannotExtractToJSClass var modifiers = []; - modifiers.push(ts.createToken(112 /* PrivateKeyword */)); + modifiers.push(ts.createToken(113 /* PrivateKeyword */)); if (rangeFacts & RangeFacts.InStaticRegion) { - modifiers.push(ts.createToken(115 /* StaticKeyword */)); + modifiers.push(ts.createToken(116 /* StaticKeyword */)); } - modifiers.push(ts.createToken(132 /* ReadonlyKeyword */)); + modifiers.push(ts.createToken(133 /* ReadonlyKeyword */)); var newVariable = ts.createProperty( /*decorators*/ undefined, modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); @@ -110016,7 +114584,7 @@ var ts; var localReference = ts.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 219 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 221 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.createVariableStatement( @@ -110035,7 +114603,7 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 219 /* ExpressionStatement */) { + if (node.parent.kind === 221 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. changeTracker.delete(context.file, node.parent); } @@ -110122,7 +114690,7 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 228 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + if (!ignoreReturns && node.kind === 230 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { @@ -110292,7 +114860,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { + else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -110300,14 +114868,14 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 237 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 239 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110616,30 +115184,30 @@ var ts; function isExtractableExpression(node) { var parent = node.parent; switch (parent.kind) { - case 276 /* EnumMember */: + case 278 /* EnumMember */: return false; } switch (node.kind) { - case 9 /* StringLiteral */: - return parent.kind !== 247 /* ImportDeclaration */ && - parent.kind !== 251 /* ImportSpecifier */; - case 206 /* SpreadElement */: - case 182 /* ObjectBindingPattern */: - case 184 /* BindingElement */: + case 10 /* StringLiteral */: + return parent.kind !== 249 /* ImportDeclaration */ && + parent.kind !== 253 /* ImportSpecifier */; + case 208 /* SpreadElement */: + case 184 /* ObjectBindingPattern */: + case 186 /* BindingElement */: return false; - case 71 /* Identifier */: - return parent.kind !== 184 /* BindingElement */ && - parent.kind !== 251 /* ImportSpecifier */ && - parent.kind !== 255 /* ExportSpecifier */; + case 72 /* Identifier */: + return parent.kind !== 186 /* BindingElement */ && + parent.kind !== 253 /* ImportSpecifier */ && + parent.kind !== 257 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 216 /* Block */: - case 277 /* SourceFile */: - case 243 /* ModuleBlock */: - case 269 /* CaseClause */: + case 218 /* Block */: + case 279 /* SourceFile */: + case 245 /* ModuleBlock */: + case 271 /* CaseClause */: return true; default: return false; @@ -110660,7 +115228,7 @@ var ts; refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!getConvertibleFieldAtPosition(context)) - return undefined; + return ts.emptyArray; return [{ name: actionName, description: actionDescription, @@ -110677,7 +115245,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -110688,10 +115256,10 @@ var ts; var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; var accessorModifiers = isInClassLike ? !modifierFlags || modifierFlags & 8 /* Private */ - ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) + ? getModifiers(isJS, isStatic, 115 /* PublicKeyword */) : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined; - var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined; + var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 113 /* PrivateKeyword */) : undefined; updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); ts.suppressLeadingAndTrailingTrivia(getAccessor); @@ -110700,7 +115268,7 @@ var ts; // readonly modifier only existed in classLikeDeclaration var constructor = ts.getFirstConstructorWithBody(container); if (constructor) { - updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); } } else { @@ -110729,7 +115297,7 @@ var ts; return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); } function getModifiers(isJS, isStatic, accessModifier) { - var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined); + var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(116 /* StaticKeyword */) : undefined); return modifiers && ts.createNodeArray(modifiers); } function startsWithUnderscore(name) { @@ -110752,8 +115320,8 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), - container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent, - originalName: declaration.name, + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name.text, declaration: declaration, fieldName: fieldName, accessorName: accessorName, @@ -110804,22 +115372,23 @@ var ts; ? changeTracker.insertNodeAfterComma(file, declaration, accessor) : changeTracker.insertNodeAfter(file, declaration, accessor); } - function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) { + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { if (!constructor.body) return; - var file = context.file, program = context.program, cancellationToken = context.cancellationToken; - var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; - }); - ts.forEach(referenceEntries, function (entry) { - var parent = entry.parent; - var accessorName = ts.createIdentifier(fieldName.text); - var node = ts.isBinaryExpression(parent) - ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken) - : ts.isPropertyAccessExpression(parent) - ? ts.updatePropertyAccess(parent, parent.expression, accessorName) - : ts.Debug.fail("Unexpected write access token"); - changeTracker.replaceNode(file, parent, node); + constructor.body.forEachChild(function recur(node) { + if (ts.isElementAccessExpression(node) && + node.expression.kind === 100 /* ThisKeyword */ && + ts.isStringLiteral(node.argumentExpression) && + node.argumentExpression.text === originalName && + ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName)); + } + if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName)); + } + if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(recur); + } }); } })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); @@ -110834,7 +115403,7 @@ var ts; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) - return undefined; + return ts.emptyArray; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; }, @@ -110896,11 +115465,11 @@ var ts; } function isPureImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return true; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return !ts.hasModifier(node, 1 /* Export */); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; @@ -110988,12 +115557,12 @@ var ts; } function getNamespaceLikeImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 249 /* NamespaceImport */ ? + case 249 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 251 /* NamespaceImport */ ? node.importClause.namedBindings.name : undefined; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node.name; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: return ts.Debug.assertNever(node); @@ -111024,20 +115593,20 @@ var ts; var newNamespaceId = ts.createIdentifier(newNamespaceName); var newModuleString = ts.createLiteral(newModuleSpecifier); switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); default: return ts.Debug.assertNever(node); } } function moduleSpecifierFromImport(i) { - return (i.kind === 247 /* ImportDeclaration */ ? i.moduleSpecifier - : i.kind === 246 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + return (i.kind === 249 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 248 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]); } function forEachImportInStatement(statement, cb) { @@ -111107,15 +115676,15 @@ var ts; } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { switch (importDecl.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); break; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: if (isUnused(importDecl.name)) { changes.delete(sourceFile, importDecl); } break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: @@ -111128,7 +115697,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 251 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -111140,7 +115709,7 @@ var ts; if (namedBindingsUnused) { changes.delete(sourceFile, namedBindings); } - else if (namedBindings.kind === 250 /* NamedImports */) { + else if (namedBindings.kind === 252 /* NamedImports */) { for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { var element = _b[_i]; if (isUnused(element.name)) @@ -111153,14 +115722,14 @@ var ts; function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { var name = varDecl.name; switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: if (isUnused(name)) { changes.delete(sourceFile, name); } break; - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: break; - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } @@ -111265,13 +115834,13 @@ var ts; // Below should all be utilities function isInImport(decl) { switch (decl.kind) { - case 246 /* ImportEqualsDeclaration */: - case 251 /* ImportSpecifier */: - case 248 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: return true; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return isVariableDeclarationInImport(decl); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); default: return false; @@ -111283,7 +115852,7 @@ var ts; } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 247 /* ImportDeclaration */: { + case 249 /* ImportDeclaration */: { var clause = i.importClause; if (!clause) return undefined; @@ -111293,9 +115862,9 @@ var ts; ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) : undefined; } - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return keep(i.name) ? i : undefined; - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { var name = filterBindingName(i.name, keep); return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } @@ -111304,7 +115873,7 @@ var ts; } } function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings.kind === 251 /* NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : undefined; } else { @@ -111314,11 +115883,11 @@ var ts; } function filterBindingName(name, keep) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return keep(name) ? name : undefined; - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return name; - case 182 /* ObjectBindingPattern */: { + case 184 /* ObjectBindingPattern */: { // We can't handle nested destructurings or property names well here, so just copy them all. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; @@ -111375,13 +115944,13 @@ var ts; } function isNonVariableTopLevelDeclaration(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return true; default: return false; @@ -111389,29 +115958,47 @@ var ts; } function forEachTopLevelDeclaration(statement, cb) { switch (statement.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return cb(statement); - case 217 /* VariableStatement */: - return ts.forEach(statement.declarationList.declarations, cb); - case 219 /* ExpressionStatement */: { + case 219 /* VariableStatement */: + return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); + case 221 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } } } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 72 /* Identifier */: + return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); + default: + return ts.Debug.assertNever(name); + } + } function nameOfTopLevelDeclaration(d) { - return d.kind === 219 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + return ts.isExpressionStatement(d) ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); } function getTopLevelDeclarationStatement(d) { - return ts.isVariableDeclaration(d) ? d.parent.parent : d; + switch (d.kind) { + case 237 /* VariableDeclaration */: + return d.parent.parent; + case 186 /* BindingElement */: + return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); + default: + return d; + } } function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { if (isExported(sourceFile, decl, useEs6Exports)) @@ -111438,25 +116025,25 @@ var ts; return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); } function addEs6Export(d) { - var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers); + var modifiers = ts.concatenate([ts.createModifier(85 /* ExportKeyword */)], d.modifiers); switch (d.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.updateVariableStatement(d, modifiers, d.declarationList); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(d); @@ -111467,18 +116054,18 @@ var ts; } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: return [decl.name.text]; // TODO: GH#18217 - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.emptyArray; - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(decl); @@ -111486,7 +116073,7 @@ var ts; } /** Creates `exports.x = x;` */ function createExportAssignment(name) { - return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name))); + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 59 /* EqualsToken */, ts.createIdentifier(name))); } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); @@ -111508,7 +116095,7 @@ var ts; var file = context.file, startPosition = context.startPosition; var info = getConvertibleArrowFunctionAtPosition(file, startPosition); if (!info) - return undefined; + return ts.emptyArray; return [{ name: refactorName, description: refactorDescription, @@ -111550,7 +116137,7 @@ var ts; return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); } function getConvertibleArrowFunctionAtPosition(file, startPosition) { var node = ts.getTokenAtPosition(file, startPosition); @@ -111586,7 +116173,7 @@ var ts; ts.servicesVersion = "0.8"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : - kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : + kind === 72 /* Identifier */ ? new IdentifierObject(72 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; node.flags = parent.flags & 12679168 /* ContextFlags */; @@ -111659,8 +116246,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 303 /* LastJSDocNode */; }); - return child.kind < 146 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; }); + return child.kind < 148 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -111671,7 +116258,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 146 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 148 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -111717,7 +116304,7 @@ var ts; var token = ts.scanner.scan(); var textPos = ts.scanner.getTextPos(); if (textPos <= end) { - if (token === 71 /* Identifier */) { + if (token === 72 /* Identifier */) { ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); } nodes.push(createNode(token, pos, textPos, parent)); @@ -111729,7 +116316,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(304 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { @@ -111861,7 +116448,7 @@ var ts; }); return IdentifierObject; }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 71 /* Identifier */; + IdentifierObject.prototype.kind = 72 /* Identifier */; var TypeObject = /** @class */ (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -111907,25 +116494,25 @@ var ts; return this.checker.getDefaultFromTypeParameter(this); }; TypeObject.prototype.isUnion = function () { - return !!(this.flags & 262144 /* Union */); + return !!(this.flags & 1048576 /* Union */); }; TypeObject.prototype.isIntersection = function () { - return !!(this.flags & 524288 /* Intersection */); + return !!(this.flags & 2097152 /* Intersection */); }; TypeObject.prototype.isUnionOrIntersection = function () { - return !!(this.flags & 786432 /* UnionOrIntersection */); + return !!(this.flags & 3145728 /* UnionOrIntersection */); }; TypeObject.prototype.isLiteral = function () { - return !!(this.flags & 192 /* StringOrNumberLiteral */); + return !!(this.flags & 384 /* StringOrNumberLiteral */); }; TypeObject.prototype.isStringLiteral = function () { - return !!(this.flags & 64 /* StringLiteral */); + return !!(this.flags & 128 /* StringLiteral */); }; TypeObject.prototype.isNumberLiteral = function () { - return !!(this.flags & 128 /* NumberLiteral */); + return !!(this.flags & 256 /* NumberLiteral */); }; TypeObject.prototype.isTypeParameter = function () { - return !!(this.flags & 65536 /* TypeParameter */); + return !!(this.flags & 262144 /* TypeParameter */); }; TypeObject.prototype.isClassOrInterface = function () { return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */); @@ -112062,10 +116649,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -112085,31 +116672,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 166 /* TypeLiteral */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 168 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 149 /* Parameter */: + case 151 /* Parameter */: // Only consider parameter properties if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // falls through - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: { + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -112120,19 +116707,19 @@ var ts; } } // falls through - case 276 /* EnumMember */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: addDeclaration(node); break; - case 253 /* ExportDeclaration */: + case 255 /* 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 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -112144,7 +116731,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -112153,8 +116740,8 @@ var ts; } } break; - case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112466,7 +117053,7 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; }); + var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -112496,8 +117083,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112534,6 +117122,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112542,11 +117134,11 @@ var ts; compilerHost.trace = function (message) { return host.trace(message); }; } if (host.resolveModuleNames) { - compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }; + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }; } if (host.resolveTypeReferenceDirectives) { - compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile) { - return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile); + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile, redirectedReference); }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); @@ -112555,7 +117147,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -112580,7 +117172,7 @@ var ts; // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -112670,7 +117262,7 @@ var ts; // 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); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -112737,15 +117329,15 @@ var ts; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { - case 71 /* Identifier */: - return !ts.isLabelName(node); - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + return !ts.isLabelName(node) && !ts.isTagName(node); + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` return !ts.isInComment(sourceFile, position); - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 97 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 98 /* SuperKeyword */: return true; default: return false; @@ -112783,7 +117375,7 @@ var ts; var normalizedFileName = ts.normalizePath(fileName); ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); synchronizeHostData(); - var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); }); + var sourceFilesToSearch = filesToSearch.map(getValidSourceFile); var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } @@ -112791,29 +117383,27 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position); - if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { + if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -112854,16 +117444,16 @@ var ts; return undefined; } switch (node.kind) { - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: - case 9 /* StringLiteral */: - case 86 /* FalseKeyword */: - case 101 /* TrueKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 71 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + case 10 /* StringLiteral */: + case 87 /* FalseKeyword */: + case 102 /* TrueKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 72 /* Identifier */: break; // Cant create the text span default: @@ -112879,7 +117469,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 === 242 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 244 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -112941,10 +117531,10 @@ var ts; return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken); } var braceMatching = ts.createMapFromTemplate((_a = {}, - _a[17 /* OpenBraceToken */] = 18 /* CloseBraceToken */, - _a[19 /* OpenParenToken */] = 20 /* CloseParenToken */, - _a[21 /* OpenBracketToken */] = 22 /* CloseBracketToken */, - _a[29 /* GreaterThanToken */] = 27 /* LessThanToken */, + _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */, + _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */, + _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */, + _a[30 /* GreaterThanToken */] = 28 /* LessThanToken */, _a)); braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); function getBraceMatchingAtPosition(fileName, position) { @@ -113020,19 +117610,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -113072,7 +117674,7 @@ var ts; var token = ts.findPrecedingToken(position, sourceFile); if (!token) return undefined; - var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent + var element = token.kind === 30 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent : ts.isJsxText(token) ? token.parent : undefined; if (element && isUnclosedTag(element)) { return { newText: "" }; @@ -113310,7 +117912,7 @@ var ts; function initializeNameTable(sourceFile) { var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); sourceFile.forEachChild(function walk(node) { - if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { + if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { var text = ts.getEscapedTextOfIdentifierOrLiteral(node); nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } @@ -113331,7 +117933,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 257 /* ExternalModuleReference */ || + node.parent.kind === 259 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -113346,15 +117948,15 @@ var ts; ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; function getContainingObjectLiteralElementWorker(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 147 /* ComputedPropertyName */) { + if (node.parent.kind === 149 /* ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 186 /* ObjectLiteralExpression */ || node.parent.parent.kind === 266 /* JsxAttributes */) && + (node.parent.parent.kind === 188 /* ObjectLiteralExpression */ || node.parent.parent.kind === 268 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -113396,7 +117998,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 188 /* ElementAccessExpression */ && + node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -113476,144 +118078,144 @@ var ts; if (node) { var parent = node.parent; switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 235 /* VariableDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return spanInVariableDeclaration(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return spanInParameterDeclaration(node); - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return spanInBlock(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return spanInBlock(node.block); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 221 /* DoStatement */: + case 223 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 234 /* DebuggerStatement */: + case 236 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 220 /* IfStatement */: + case 222 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return spanInForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 233 /* TryStatement */: + case 235 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 184 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 186 /* BindingElement */: // span on complete node return textSpan(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 150 /* Decorator */: + case 152 /* Decorator */: return spanInNodeArray(parent.decorators); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return undefined; // Tokens: - case 25 /* SemicolonToken */: + case 26 /* SemicolonToken */: case 1 /* EndOfFileToken */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return spanInPreviousNode(node); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return spanInOpenBraceToken(node); - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: return spanInCloseBraceToken(node); - case 22 /* CloseBracketToken */: + case 23 /* CloseBracketToken */: return spanInCloseBracketToken(node); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return spanInOpenParenToken(node); - case 20 /* CloseParenToken */: + case 21 /* CloseParenToken */: return spanInCloseParenToken(node); - case 56 /* ColonToken */: + case 57 /* ColonToken */: return spanInColonToken(node); - case 29 /* GreaterThanToken */: - case 27 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 28 /* LessThanToken */: return spanInGreaterThanOrLessThanToken(node); // Keywords: - case 106 /* WhileKeyword */: + case 107 /* WhileKeyword */: return spanInWhileKeyword(node); - case 82 /* ElseKeyword */: - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 83 /* ElseKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return spanInNextNode(node); - case 145 /* OfKeyword */: + case 147 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -113625,14 +118227,14 @@ var ts; // 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 === 71 /* Identifier */ || - node.kind === 206 /* SpreadElement */ || - node.kind === 273 /* PropertyAssignment */ || - node.kind === 274 /* ShorthandPropertyAssignment */) && + if ((node.kind === 72 /* Identifier */ || + node.kind === 208 /* SpreadElement */ || + node.kind === 275 /* PropertyAssignment */ || + node.kind === 276 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 202 /* BinaryExpression */) { + if (node.kind === 204 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -113641,35 +118243,35 @@ var ts; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); } - if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + if (operatorToken.kind === 59 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.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 (operatorToken.kind === 26 /* CommaToken */) { + if (operatorToken.kind === 27 /* CommaToken */) { return spanInNode(left); } } if (ts.isExpressionNode(node)) { switch (parent.kind) { - case 221 /* DoStatement */: + case 223 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 150 /* Decorator */: + case 152 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: return textSpan(node); - case 202 /* BinaryExpression */: - if (node.parent.operatorToken.kind === 26 /* CommaToken */) { + case 204 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 27 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -113678,21 +118280,21 @@ var ts; } } switch (node.parent.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -113700,7 +118302,7 @@ var ts; } break; } - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -113730,7 +118332,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 224 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 226 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } var parent = variableDeclaration.parent; @@ -113742,7 +118344,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - parent.parent.kind === 225 /* ForOfStatement */) { + parent.parent.kind === 227 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -113783,7 +118385,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 238 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */); + (functionDeclaration.parent.kind === 240 /* ClassDeclaration */ && functionDeclaration.kind !== 157 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -113806,26 +118408,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // falls through // Set on parent if on same line otherwise on first statement - case 222 /* WhileStatement */: - case 220 /* IfStatement */: - case 224 /* ForInStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 226 /* 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 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 227 /* 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(forLikeStatement) { - if (forLikeStatement.initializer.kind === 236 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 238 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -113850,21 +118452,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 184 /* BindingElement */) { + if (bindingPattern.parent.kind === 186 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 183 /* ArrayBindingPattern */ && node.kind !== 182 /* ObjectBindingPattern */); - var elements = node.kind === 185 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 185 /* ArrayBindingPattern */ && node.kind !== 184 /* ObjectBindingPattern */); + var elements = node.kind === 187 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -113872,18 +118474,18 @@ var ts; // 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 === 202 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 204 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -113891,25 +118493,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 241 /* EnumDeclaration */: - case 238 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 272 /* CatchClause */: + case 274 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -113917,7 +118519,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 182 /* ObjectBindingPattern */: + case 184 /* 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); @@ -113933,7 +118535,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 183 /* ArrayBindingPattern */: + case 185 /* 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); @@ -113948,12 +118550,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 221 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 189 /* CallExpression */ || - node.parent.kind === 190 /* NewExpression */) { + if (node.parent.kind === 223 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 191 /* CallExpression */ || + node.parent.kind === 192 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 193 /* ParenthesizedExpression */) { + if (node.parent.kind === 195 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -113962,21 +118564,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 193 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 195 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -113986,20 +118588,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 273 /* PropertyAssignment */ || - node.parent.kind === 149 /* Parameter */) { + node.parent.kind === 275 /* PropertyAssignment */ || + node.parent.kind === 151 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 192 /* TypeAssertionExpression */) { + if (node.parent.kind === 194 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 221 /* DoStatement */) { + if (node.parent.kind === 223 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -114007,7 +118609,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 225 /* ForOfStatement */) { + if (node.parent.kind === 227 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -114105,7 +118707,7 @@ var ts; var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; // TODO: GH#18217 + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -114115,7 +118717,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); }; } } @@ -114224,9 +118826,15 @@ var ts; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } + else { + this.directoryExists = undefined; // TODO: GH#18217 + } if ("realpath" in this.shimHost) { this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 } + else { + this.realpath = undefined; // TODO: GH#18217 + } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 @@ -114826,6 +119434,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -114854,7 +119463,6 @@ var ts; : undefined; } server.findArgument = findArgument; - /*@internal*/ function nowString() { // E.g. "12:34:56.789" var d = new Date(); @@ -114868,13 +119476,11 @@ var ts; (function (ts) { var JsTyping; (function (JsTyping) { - /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; - /* @internal */ JsTyping.nodeCoreModuleList = [ "assert", "async_hooks", @@ -114913,7 +119519,6 @@ var ts; "vm", "zlib" ]; - /* @internal */ JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); @@ -114946,7 +119551,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -115031,7 +119636,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -115160,71 +119765,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); //# sourceMappingURL=jsTyping.js.map "use strict"; var __assign = (this && this.__assign) || function () { @@ -115244,13 +119784,22 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; var ts; (function (ts) { var server; @@ -115297,30 +119846,6 @@ var ts; } Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; })(Errors = server.Errors || (server.Errors = {})); - function getDefaultFormatCodeSettings(host) { - return { - indentSize: 4, - tabSize: 4, - newLineCharacter: host.newLine || "\n", - convertTabsToSpaces: true, - indentStyle: ts.IndentStyle.Smart, - insertSpaceAfterConstructor: false, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceBeforeFunctionParenthesis: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - }; - } - server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; function toNormalizedPath(fileName) { return ts.normalizePath(fileName); } @@ -115439,26 +119964,13 @@ var ts; } } server.removeSorted = removeSorted; - function toSortedArray(arr, comparer) { - arr.sort(comparer); - return arr; - } - server.toSortedArray = toSortedArray; - function toDeduplicatedSortedArray(arr) { - arr.sort(); - ts.filterMutate(arr, isNonDuplicateInSortedArray); - return arr; - } - server.toDeduplicatedSortedArray = toDeduplicatedSortedArray; - function isNonDuplicateInSortedArray(value, index, array) { - return index === 0 || value !== array[index - 1]; - } + var indentStr = "\n "; function indent(str) { - return "\n " + str; + return indentStr + str.replace(/\n/g, indentStr); } server.indent = indent; function stringifyIndented(json) { - return "\n " + JSON.stringify(json); + return indentStr + JSON.stringify(json); } server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); @@ -115559,6 +120071,7 @@ var ts; CommandTypes["OrganizeImportsFull"] = "organizeImports-full"; CommandTypes["GetEditsForFileRename"] = "getEditsForFileRename"; CommandTypes["GetEditsForFileRenameFull"] = "getEditsForFileRename-full"; + CommandTypes["ConfigurePlugin"] = "configurePlugin"; })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {})); var IndentStyle; (function (IndentStyle) { @@ -115616,6 +120129,9 @@ var ts; this.host = host; this.fileName = fileName; this.info = info; + this.isOpen = false; + this.ownFileText = false; + this.pendingReloadFromDisk = false; this.version = initialVersion || { svc: 0, text: 0 }; } TextStorage.prototype.getVersion = function () { @@ -115633,6 +120149,7 @@ var ts; this.svc = undefined; this.text = newText; this.lineMap = undefined; + this.fileSize = undefined; this.version.text++; }; TextStorage.prototype.edit = function (start, end, newText) { @@ -115640,6 +120157,7 @@ var ts; this.ownFileText = false; this.text = undefined; this.lineMap = undefined; + this.fileSize = undefined; }; TextStorage.prototype.reload = function (newText) { ts.Debug.assert(newText !== undefined); @@ -115649,9 +120167,12 @@ var ts; this.ownFileText = false; return true; } + return false; }; TextStorage.prototype.reloadWithFileText = function (tempFileName) { - var reloaded = this.reload(this.getFileText(tempFileName)); + var _a = this.getFileTextAndSize(tempFileName), newText = _a.text, fileSize = _a.fileSize; + var reloaded = this.reload(newText); + this.fileSize = fileSize; this.ownFileText = !tempFileName || tempFileName === this.fileName; return reloaded; }; @@ -115664,6 +120185,15 @@ var ts; TextStorage.prototype.delayReloadFromFileIntoText = function () { this.pendingReloadFromDisk = true; }; + TextStorage.prototype.getTelemetryFileSize = function () { + return !!this.fileSize + ? this.fileSize + : !!this.text + ? this.text.length + : !!this.svc + ? this.svc.getSnapshot().getLength() + : this.getSnapshot().getLength(); + }; TextStorage.prototype.getSnapshot = function () { return this.useScriptVersionCacheIfValidOrOpen() ? this.svc.getSnapshot() @@ -115694,22 +120224,22 @@ var ts; } return this.svc.positionToLineOffset(position); }; - TextStorage.prototype.getFileText = function (tempFileName) { + TextStorage.prototype.getFileTextAndSize = function (tempFileName) { var _this = this; var text; var fileName = tempFileName || this.fileName; var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; - if (!ts.hasTypeScriptFileExtension(this.fileName)) { + if (!ts.hasTSFileExtension(this.fileName)) { var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > server.maxFileSize) { ts.Debug.assert(!!this.info.containingProjects.length); var service = this.info.containingProjects[0].projectService; service.logger.info("Skipped loading contents of large file " + fileName + " for info " + this.info.fileName + ": fileSize: " + fileSize); this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize); - return ""; + return { text: "", fileSize: fileSize }; } } - return getText(); + return { text: getText() }; }; TextStorage.prototype.switchToScriptVersionCache = function () { if (!this.svc || this.pendingReloadFromDisk) { @@ -115766,6 +120296,9 @@ var ts; ScriptInfo.prototype.getVersion = function () { return this.textStorage.version; }; + ScriptInfo.prototype.getTelemetryFileSize = function () { + return this.textStorage.getTelemetryFileSize(); + }; ScriptInfo.prototype.isDynamicOrHasMixedContent = function () { return this.hasMixedContent || this.isDynamic; }; @@ -115904,7 +120437,7 @@ var ts; ScriptInfo.prototype.setOptions = function (formatSettings, preferences) { if (formatSettings) { if (!this.formatSettings) { - this.formatSettings = server.getDefaultFormatCodeSettings(this.host); + this.formatSettings = ts.getDefaultFormatCodeSettings(this.host.newLine); ts.assign(this.formatSettings, formatSettings); } else { @@ -115983,6 +120516,7 @@ var ts; server.nullTypingsInstaller = { isKnownTypesPackageName: ts.returnFalse, installPackage: ts.notImplemented, + inspectValue: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -116042,6 +120576,9 @@ var ts; TypingsCache.prototype.installPackage = function (options) { return this.installer.installPackage(options); }; + TypingsCache.prototype.inspectValue = function (options) { + return this.installer.inspectValue(options); + }; TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -116064,7 +120601,7 @@ var ts; } }; TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typeAcquisition, unresolvedImports, newTypings) { - var typings = server.toSortedArray(newTypings); + var typings = ts.sort(newTypings); this.perProjectCache.set(projectName, { compilerOptions: compilerOptions, typeAcquisition: typeAcquisition, @@ -116093,27 +120630,45 @@ var ts; ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; ProjectKind[ProjectKind["External"] = 2] = "External"; })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); - function countEachFileTypes(infos) { - var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0, deferred: 0 }; + function countEachFileTypes(infos, includeSizes) { + if (includeSizes === void 0) { includeSizes = false; } + var result = { + js: 0, jsSize: 0, + jsx: 0, jsxSize: 0, + ts: 0, tsSize: 0, + tsx: 0, tsxSize: 0, + dts: 0, dtsSize: 0, + deferred: 0, deferredSize: 0, + }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; + var fileSize = includeSizes ? info.getTelemetryFileSize() : 0; switch (info.scriptKind) { case 1: result.js += 1; + result.jsSize += fileSize; break; case 2: result.jsx += 1; + result.jsxSize += fileSize; break; case 3: - ts.fileExtensionIs(info.fileName, ".d.ts") - ? result.dts += 1 - : result.ts += 1; + if (ts.fileExtensionIs(info.fileName, ".d.ts")) { + result.dts += 1; + result.dtsSize += fileSize; + } + else { + result.ts += 1; + result.tsSize += fileSize; + } break; case 4: result.tsx += 1; + result.tsxSize += fileSize; break; case 7: result.deferred += 1; + result.deferredSize += fileSize; break; } } @@ -116159,6 +120714,7 @@ var ts; this.lastReportedVersion = 0; this.projectProgramVersion = 0; this.projectStateVersion = 0; + this.isInitialLoadPending = ts.returnFalse; this.dirty = false; this.hasChangedAutomaticTypeDirectiveNames = false; this.typingFiles = server.emptyArray; @@ -116219,6 +120775,9 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + Project.prototype.inspectValue = function (options) { + return this.typingsCache.inspectValue(options); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -116239,7 +120798,7 @@ var ts; return this.projectStateVersion.toString(); }; Project.prototype.getProjectReferences = function () { - return server.emptyArray; + return undefined; }; Project.prototype.getScriptFileNames = function () { var _this = this; @@ -116299,18 +120858,21 @@ var ts; Project.prototype.readFile = function (fileName) { return this.projectService.host.readFile(fileName); }; + Project.prototype.writeFile = function (fileName, content) { + return this.projectService.host.writeFile(fileName, content); + }; Project.prototype.fileExists = function (file) { var path = this.toPath(file); return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); }; - Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { - return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); + Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }; Project.prototype.getResolvedModuleWithFailedLookupLocationsFromCache = function (moduleName, containingFile) { return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile); }; - Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); + Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile, redirectedReference) { + return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }; Project.prototype.directoryExists = function (path) { return this.directoryStructureHost.directoryExists(path); @@ -116427,11 +120989,11 @@ var ts; }; Project.prototype.getExternalFiles = function () { var _this = this; - return server.toSortedArray(ts.flatMap(this.plugins, function (plugin) { - if (typeof plugin.getExternalFiles !== "function") + return ts.sort(ts.flatMap(this.plugins, function (plugin) { + if (typeof plugin.module.getExternalFiles !== "function") return; try { - return plugin.getExternalFiles(_this); + return plugin.module.getExternalFiles(_this); } catch (e) { _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); @@ -116458,19 +121020,15 @@ var ts; var f = _a[_i]; this.detachScriptInfoIfNotRoot(f.fileName); } - var projectReferences = this.program.getProjectReferences(); - if (projectReferences) { - for (var _b = 0, projectReferences_1 = projectReferences; _b < projectReferences_1.length; _b++) { - var ref = projectReferences_1[_b]; - if (ref) { - this.detachScriptInfoFromProject(ref.sourceFile.fileName); - } + this.program.forEachResolvedProjectReference(function (ref) { + if (ref) { + _this.detachScriptInfoFromProject(ref.sourceFile.fileName); } - } + }); } ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); }); - for (var _c = 0, _d = this.rootFiles; _c < _d.length; _c++) { - var root = _d[_c]; + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; root.detachFromProject(this); } this.projectService.pendingEnsureProjectForOpenFiles = true; @@ -116520,7 +121078,7 @@ var ts; return this.rootFiles; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { - var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; }); return scriptInfo; }); @@ -116584,7 +121142,7 @@ var ts; return false; }; Project.prototype.containsScriptInfo = function (info) { - return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); + return this.isRoot(info) || (!!this.program && this.program.getSourceFileByPath(info.path) !== undefined); }; Project.prototype.containsFile = function (filename, requireOpen) { var info = this.projectService.getScriptInfoForNormalizedPath(filename); @@ -116633,38 +121191,10 @@ var ts; this.dirty = true; } }; - Project.prototype.extractUnresolvedImportsFromSourceFile = function (file, ambientModules) { - var cached = this.cachedUnresolvedImportsPerFile.get(file.path); - if (cached) { - return cached; - } - var unresolvedImports; - if (file.resolvedModules) { - file.resolvedModules.forEach(function (resolvedModule, name) { - if (!resolvedModule && !ts.isExternalModuleNameRelative(name) && !isAmbientlyDeclaredModule(name)) { - var trimmed = name.trim(); - var i = trimmed.indexOf("/"); - if (i !== -1 && trimmed.charCodeAt(0) === 64) { - i = trimmed.indexOf("/", i + 1); - } - if (i !== -1) { - trimmed = trimmed.substr(0, i); - } - (unresolvedImports || (unresolvedImports = [])).push(trimmed); - } - }); - } - this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || server.emptyArray); - return unresolvedImports || server.emptyArray; - function isAmbientlyDeclaredModule(name) { - return ambientModules.some(function (m) { return m === name; }); - } - }; Project.prototype.onFileAddedOrRemoved = function () { this.hasAddedorRemovedFiles = true; }; Project.prototype.updateGraph = function () { - var _a; this.resolutionCache.startRecordingFilesWithChangedResolutions(); var hasNewProgram = this.updateGraphWorker(); var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; @@ -116676,16 +121206,7 @@ var ts; } if (this.languageServiceEnabled) { if (hasNewProgram || changedFiles.length) { - var result = void 0; - var ambientModules = this.program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); - for (var _b = 0, _c = this.program.getSourceFiles(); _b < _c.length; _b++) { - var sourceFile = _c[_b]; - var unResolved = this.extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules); - if (unResolved !== server.emptyArray) { - (_a = (result || (result = []))).push.apply(_a, unResolved); - } - } - this.lastCachedUnresolvedImportsList = result ? server.toDeduplicatedSortedArray(result) : server.emptyArray; + this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile); } this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles); } @@ -116728,11 +121249,16 @@ var ts; if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var f = _a[_i]; - if (this.program.getSourceFileByPath(f.path)) { - continue; + var newFile = this.program.getSourceFileByPath(f.resolvedPath); + if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) { + this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path)); } - this.detachScriptInfoFromProject(f.fileName); } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !_this.program.getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + _this.detachScriptInfoFromProject(resolvedProjectReference.sourceFile.fileName); + } + }); } ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); }); if (this.languageServiceEnabled) { @@ -116749,11 +121275,13 @@ var ts; this.writeLog("Finishing updateGraphWorker: Project: " + this.getProjectName() + " Version: " + this.getProjectVersion() + " structureChanged: " + hasNewProgram + " Elapsed: " + elapsed + "ms"); return hasNewProgram; }; - Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName) { + Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName, noRemoveResolution) { var scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); if (scriptInfoToDetach) { scriptInfoToDetach.detachFromProject(this); - this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); + if (!noRemoveResolution) { + this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); + } } }; Project.prototype.addMissingFileWatcher = function (missingFilePath) { @@ -116771,7 +121299,7 @@ var ts; return fileWatcher; }; Project.prototype.isWatchedMissingFile = function (path) { - return this.missingFilesMap && this.missingFilesMap.has(path); + return !!this.missingFilesMap && this.missingFilesMap.has(path); }; Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { var scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName)); @@ -116797,6 +121325,11 @@ var ts; } return strBuilder; }; + Project.prototype.print = function (counter) { + this.writeLog("Project '" + this.projectName + "' (" + ProjectKind[this.projectKind] + ") " + (counter === undefined ? "" : counter)); + this.writeLog(this.filesToString(this.projectService.logger.hasLevel(server.LogLevel.verbose))); + this.writeLog("-----------------------------------------------"); + }; Project.prototype.setCompilerOptions = function (compilerOptions) { if (compilerOptions) { compilerOptions.allowNonTsExtensions = true; @@ -116812,7 +121345,9 @@ var ts; } }; Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - server.updateProjectIfDirty(this); + if (!this.isInitialLoadPending()) { + server.updateProjectIfDirty(this); + } var info = { projectName: this.getProjectName(), version: this.projectProgramVersion, @@ -116860,9 +121395,8 @@ var ts; ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); }; - Project.prototype.enableGlobalPlugins = function () { + Project.prototype.enableGlobalPlugins = function (options, pluginConfigOverrides) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -116875,7 +121409,7 @@ var ts; if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; this_1.projectService.logger.info("Loading global plugin " + globalPluginName); - this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths); + this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides); }; var this_1 = this; for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { @@ -116884,7 +121418,7 @@ var ts; } } }; - Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths) { + Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { var _this = this; this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); var log = function (message) { @@ -116894,15 +121428,18 @@ var ts; return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log); }); if (resolvedModule) { + var configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name); + if (configurationOverride) { + var pluginName = pluginConfigEntry.name; + pluginConfigEntry = configurationOverride; + pluginConfigEntry.name = pluginName; + } this.enableProxy(resolvedModule, pluginConfigEntry); } else { this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); } }; - Project.prototype.refreshDiagnostics = function () { - this.projectService.sendProjectsUpdatedInBackgroundEvent(); - }; Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) { try { if (typeof pluginModuleFactory !== "function") { @@ -116927,25 +121464,56 @@ var ts; } this.projectService.logger.info("Plugin validation succeded"); this.languageService = newLS; - this.plugins.push(pluginModule); + this.plugins.push({ name: configEntry.name, module: pluginModule }); } catch (e) { this.projectService.logger.info("Plugin activation failed: " + e); } }; + Project.prototype.onPluginConfigurationChanged = function (pluginName, configuration) { + this.plugins.filter(function (plugin) { return plugin.name === pluginName; }).forEach(function (plugin) { + if (plugin.module.onConfigurationChanged) { + plugin.module.onConfigurationChanged(configuration); + } + }); + }; + Project.prototype.refreshDiagnostics = function () { + this.projectService.sendProjectsUpdatedInBackgroundEvent(); + }; return Project; }()); server.Project = Project; + function getUnresolvedImports(program, cachedUnresolvedImportsPerFile) { + var ambientModules = program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); + return ts.sortAndDeduplicate(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + return extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile); + })); + } + function extractUnresolvedImportsFromSourceFile(file, ambientModules, cachedUnresolvedImportsPerFile) { + return ts.getOrUpdate(cachedUnresolvedImportsPerFile, file.path, function () { + if (!file.resolvedModules) + return server.emptyArray; + var unresolvedImports; + file.resolvedModules.forEach(function (resolvedModule, name) { + if ((!resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) && + !ts.isExternalModuleNameRelative(name) && + !ambientModules.some(function (m) { return m === name; })) { + unresolvedImports = ts.append(unresolvedImports, ts.parsePackageName(name).packageName); + } + }); + return unresolvedImports || server.emptyArray; + }); + } var InferredProject = (function (_super) { __extends(InferredProject, _super); - function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory) { + function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory, pluginConfigOverrides) { var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, undefined, compilerOptions, false, projectService.host, currentDirectory) || this; _this._isJsInferredProject = false; _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); if (!projectRootPath && !projectService.useSingleInferredProject) { _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory); } - _this.enableGlobalPlugins(); + _this.enableGlobalPlugins(_this.getCompilerOptions(), pluginConfigOverrides); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -116955,10 +121523,10 @@ var ts; } }; InferredProject.prototype.setCompilerOptions = function (options) { - var newOptions = options ? ts.cloneCompilerOptions(options) : this.getCompilationSettings(); - if (!newOptions) { + if (!options && !this.getCompilationSettings()) { return; } + var newOptions = ts.cloneCompilerOptions(options || this.getCompilationSettings()); if (this._isJsInferredProject && typeof newOptions.maxNodeModuleJsDepth !== "number") { newOptions.maxNodeModuleJsDepth = 2; } @@ -117017,27 +121585,37 @@ var ts; server.InferredProject = InferredProject; var ConfiguredProject = (function (_super) { __extends(ConfiguredProject, _super); - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { - var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; - _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectReferences = projectReferences; + function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, false, undefined, {}, false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; + _this.canConfigFileJsonReportNoInputFiles = false; _this.externalProjectRefCount = 0; + _this.isInitialLoadPending = ts.returnTrue; + _this.sendLoadingProjectFinish = false; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); - _this.enablePlugins(); return _this; } ConfiguredProject.prototype.updateGraph = function () { + this.isInitialLoadPending = ts.returnFalse; var reloadLevel = this.pendingReload; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + var result; switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: - return this.projectService.reloadFileNamesOfConfiguredProject(this); + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; case ts.ConfigFileProgramReloadLevel.Full: - this.projectService.reloadConfiguredProject(this); - return true; + var reason = ts.Debug.assertDefined(this.pendingReloadReason); + this.pendingReloadReason = undefined; + this.projectService.reloadConfiguredProject(this, reason); + result = true; + break; default: - return _super.prototype.updateGraph.call(this); + result = _super.prototype.updateGraph.call(this); } + this.projectService.sendProjectLoadingFinishEvent(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; }; ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { return this.directoryStructureHost; @@ -117046,18 +121624,17 @@ var ts; return server.asNormalizedPath(this.getProjectName()); }; ConfiguredProject.prototype.getProjectReferences = function () { - return this.projectReferences || server.emptyArray; + return this.projectReferences; }; ConfiguredProject.prototype.updateReferences = function (refs) { this.projectReferences = refs; }; - ConfiguredProject.prototype.getResolvedProjectReferences = function () { + ConfiguredProject.prototype.forEachResolvedProjectReference = function (cb) { var program = this.getCurrentProgram(); - return program && program.getProjectReferences(); + return program && program.forEachResolvedProjectReference(cb); }; - ConfiguredProject.prototype.enablePlugins = function () { + ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117071,10 +121648,10 @@ var ts; if (options.plugins) { for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { var pluginConfigEntry = _a[_i]; - this.enablePlugin(pluginConfigEntry, searchPaths); + this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); } } - this.enableGlobalPlugins(); + this.enableGlobalPlugins(options, pluginConfigOverrides); }; ConfiguredProject.prototype.getGlobalProjectErrors = function () { return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; @@ -117131,16 +121708,14 @@ var ts; } return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; + ConfiguredProject.prototype.hasExternalProjectRef = function () { + return !!this.externalProjectRefCount; + }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; }; - ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (hasFileNames) { - if (hasFileNames) { - ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); - } - else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { - this.projectErrors.push(ts.getErrorForNoInputFiles(this.configFileSpecs, this.getConfigFilePath())); - } + ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) { + ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); }; return ConfiguredProject; }(Project)); @@ -117154,6 +121729,12 @@ var ts; _this.excludedFiles = []; return _this; } + ExternalProject.prototype.updateGraph = function () { + var result = _super.prototype.updateGraph.call(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; @@ -117179,6 +121760,9 @@ var ts; server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; server.maxFileSize = 4 * 1024 * 1024; server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.ProjectLoadingStartEvent = "projectLoadingStart"; + server.ProjectLoadingFinishEvent = "projectLoadingFinish"; + server.SurveyReady = "surveyReady"; server.LargeFileReferencedEvent = "largeFileReferenced"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -117266,6 +121850,11 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; + function convertUserPreferences(preferences) { + var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]); + return userPreferences; + } + server.convertUserPreferences = convertUserPreferences; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -117308,6 +121897,7 @@ var ts; WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; WatchType["TypeRoots"] = "Type root directory"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; })(WatchType = server.WatchType || (server.WatchType = {})); var ConfigFileWatcherStatus; (function (ConfigFileWatcherStatus) { @@ -117325,14 +121915,23 @@ var ts; function getDetailWatchInfo(watchType, project) { return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== undefined; + } function updateProjectIfDirty(project) { return project.dirty && project.updateGraph(); } server.updateProjectIfDirty = updateProjectIfDirty; + function setProjectOptionsUsed(project) { + if (project.projectKind === server.ProjectKind.Configured) { + project.projectOptions = true; + } + } var ProjectService = (function () { function ProjectService(opts) { var _this = this; this.filenameToScriptInfo = ts.createMap(); + this.scriptInfoInNodeModulesWatchers = ts.createMap(); this.filenameToScriptInfoVersion = ts.createMap(); this.allJsFilesForOpenFileTelemetry = ts.createMap(); this.externalProjectToConfiguredProjectMap = ts.createMap(); @@ -117345,9 +121944,11 @@ var ts; this.projectToSizeMap = ts.createMap(); this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist = ts.createMap(); this.pendingProjectUpdates = ts.createMap(); + this.pendingEnsureProjectForOpenFiles = false; this.seenProjects = ts.createMap(); + this.seenSurveyProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -117360,7 +121961,7 @@ var ts; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; this.syntaxOnly = opts.syntaxOnly; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); if (this.host.realpath) { @@ -117381,7 +121982,7 @@ var ts; this.typingsInstaller.attach(this); this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { - formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), + formatCodeOptions: ts.getDefaultFormatCodeSettings(this.host.newLine), preferences: ts.emptyOptions, hostInfo: "Unknown host", extraFileExtensions: [] @@ -117440,14 +122041,14 @@ var ts; this.safelist = raw.typesMap; for (var key in raw.simpleMap) { if (raw.simpleMap.hasOwnProperty(key)) { - this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); } } } catch (e) { this.logger.info("Error loading types map: " + e); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist.clear(); } }; ProjectService.prototype.updateTypingsForProject = function (response) { @@ -117507,6 +122108,12 @@ var ts; }; this.eventHandler(event); }; + ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } }); + }; ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { if (!this.eventHandler) { return; @@ -117517,6 +122124,28 @@ var ts; }; this.eventHandler(event); }; + ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + var event = { + eventName: server.ProjectLoadingStartEvent, + data: { project: project, reason: reason } + }; + this.eventHandler(event); + }; + ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + project.sendLoadingProjectFinish = false; + var event = { + eventName: server.ProjectLoadingFinishEvent, + data: { project: project } + }; + this.eventHandler(event); + }; ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) { this.delayUpdateProjectGraph(project); this.delayEnsureProjectForOpenFiles(); @@ -117564,9 +122193,9 @@ var ts; return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); }; ProjectService.prototype.forEachProject = function (cb) { - this.inferredProjects.forEach(cb); - this.configuredProjects.forEach(cb); this.externalProjects.forEach(cb); + this.configuredProjects.forEach(cb); + this.inferredProjects.forEach(cb); }; ProjectService.prototype.forEachEnabledProject = function (cb) { this.forEachProject(function (project) { @@ -117588,7 +122217,7 @@ var ts; ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileName) { this.ensureProjectStructuresUptoDate(); var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - return scriptInfo ? scriptInfo.getDefaultProject() : server.Errors.ThrowNoProject(); + return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(fileName), server.Errors.ThrowNoProject()); }; ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { this.ensureProjectStructuresUptoDate(); @@ -117626,12 +122255,17 @@ var ts; if (!info) { this.logger.msg("Error: got watch notification for unknown file: " + fileName); } - else if (eventKind === ts.FileWatcherEventKind.Deleted) { - this.handleDeletedFile(info); - } - else if (!info.isScriptOpen()) { - info.delayReloadNonMixedContentFile(); - this.delayUpdateProjectGraphs(info.containingProjects); + else { + if (info.containingProjects) { + info.containingProjects.forEach(function (project) { return project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path); }); + } + if (eventKind === ts.FileWatcherEventKind.Deleted) { + this.handleDeletedFile(info); + } + else if (!info.isScriptOpen()) { + info.delayReloadNonMixedContentFile(); + this.delayUpdateProjectGraphs(info.containingProjects); + } } }; ProjectService.prototype.handleDeletedFile = function (info) { @@ -117648,6 +122282,8 @@ var ts; return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) { var fileOrDirectoryPath = _this.toPath(fileOrDirectory); project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; var configFilename = project.getConfigFilePath(); if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, project.getCompilationSettings(), _this.hostConfiguration.extraFileExtensions)) { _this.logger.info("Project: " + configFilename + " Detected file add/remove of non supported extension: " + fileOrDirectory); @@ -117673,6 +122309,7 @@ var ts; else { this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files"); project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = "Change in config file detected"; this.delayUpdateProjectGraph(project); this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, true); } @@ -117685,10 +122322,12 @@ var ts; this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false); }; ProjectService.prototype.removeProject = function (project) { - this.logger.info("remove project: " + project.getRootFiles().toString()); + var _this = this; + this.logger.info("`remove Project::"); + project.print(); project.close(); if (ts.Debug.shouldAssert(1)) { - this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project)); }); + this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project), "Found script Info still attached to project", function () { return project.projectName + ": ScriptInfos still attached: " + JSON.stringify(ts.mapDefined(ts.arrayFrom(_this.filenameToScriptInfo.values()), function (info) { return info.isAttached(project) ? info : undefined; })); }); }); } this.pendingProjectUpdates.delete(project.getProjectName()); switch (project.projectKind) { @@ -117977,20 +122616,9 @@ var ts; } var writeProjectFileNames = this.logger.hasLevel(server.LogLevel.verbose); this.logger.startGroup(); - var counter = 0; - var printProjects = function (projects, counter) { - for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { - var project = projects_3[_i]; - _this.logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); - _this.logger.info(project.filesToString(writeProjectFileNames)); - _this.logger.info("-----------------------------------------------"); - counter++; - } - return counter; - }; - counter = printProjects(this.externalProjects, counter); - counter = printProjects(ts.arrayFrom(this.configuredProjects.values()), counter); - printProjects(this.inferredProjects, counter); + var counter = printProjectsWithCounter(this.externalProjects, 0); + counter = printProjectsWithCounter(ts.arrayFrom(this.configuredProjects.values()), counter); + printProjectsWithCounter(this.inferredProjects, counter); this.logger.info("Open files: "); this.openFiles.forEach(function (projectRootPath, path) { var info = _this.getScriptInfoForPath(path); @@ -118011,33 +122639,6 @@ var ts; ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { return findProjectByName(projectFileName, this.externalProjects); }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { - configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); - var result = ts.parseJsonText(configFilename, configFileContent); - if (!result.endOfFileToken) { - result.endOfFileToken = { kind: 1 }; - } - var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); - if (parsedCommandLine.errors.length) { - errors.push.apply(errors, parsedCommandLine.errors); - } - ts.Debug.assert(!!parsedCommandLine.fileNames); - var projectOptions = { - files: parsedCommandLine.fileNames, - compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, - configHasFilesProperty: parsedCommandLine.raw.files !== undefined, - configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, - configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, - wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), - typeAcquisition: parsedCommandLine.typeAcquisition, - compileOnSave: parsedCommandLine.compileOnSave, - projectReferences: parsedCommandLine.projectReferences - }; - return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; - }; ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { return; @@ -118049,12 +122650,12 @@ var ts; for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var f = fileNames_1[_i]; var fileName = propertyReader.getFileName(f); - if (ts.hasTypeScriptFileExtension(fileName)) { + if (ts.hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); return fileName; } } @@ -118065,9 +122666,9 @@ var ts; return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); } function getTop5LargestFiles(_a) { - var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; + var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .filter(function (name) { return hasTypeScriptFileExtension(name); }) + .filter(function (name) { return hasTSFileExtension(name); }) .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) .sort(function (a, b) { return b.size - a.size; }) .slice(0, 5); @@ -118077,22 +122678,36 @@ var ts; var compilerOptions = convertCompilerOptions(options); var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); project.excludedFiles = excludedFiles; - this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); - this.sendProjectTelemetry(projectFileName, project); return project; }; - ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { - if (this.seenProjects.has(projectKey)) { + ProjectService.prototype.sendSurveyReady = function (project) { + if (this.seenSurveyProjects.has(project.projectName)) { return; } - this.seenProjects.set(projectKey, true); + if (project.getCompilerOptions().checkJs !== undefined) { + var name = "checkJs"; + this.logger.info("Survey " + name + " is ready"); + this.sendSurveyReadyEvent(name); + this.seenSurveyProjects.set(project.projectName, true); + } + }; + ProjectService.prototype.sendProjectTelemetry = function (project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); + return; + } + this.seenProjects.set(project.projectName, true); if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); return; } + var projectOptions = project.projectKind === server.ProjectKind.Configured ? project.projectOptions : undefined; + setProjectOptionsUsed(project); var data = { - projectId: this.host.createSHA256Hash(projectKey), - fileStats: server.countEachFileTypes(project.getScriptInfos()), + projectId: this.host.createSHA256Hash(project.projectName), + fileStats: server.countEachFileTypes(project.getScriptInfos(), true), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), extends: projectOptions && projectOptions.configHasExtendsProperty, @@ -118110,8 +122725,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; - return server.getBaseConfigFileName(configFilePath) || "other"; + return server.getBaseConfigFileName(project.getConfigFilePath()) || "other"; } function convertTypeAcquisition(_a) { var enable = _a.enable, include = _a.include, exclude = _a.exclude; @@ -118122,31 +122736,76 @@ var ts; }; } }; - ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { + ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) { this.updateNonInferredProjectFiles(project, files, propertyReader); project.setTypeAcquisition(typeAcquisition); - project.updateGraph(); }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); - var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); - project.configFileSpecs = configFileSpecs; + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program", project); - if (!lastFileExceededProgramSize) { - project.watchWildcards(projectOptions.wildcardDirectories); - } - project.setProjectErrors(configFileErrors); - var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); - this.sendProjectTelemetry(configFileName, project, projectOptions); return project; }; + ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; + return project; + }; + ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project, reason); + return project; + }; + ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) { + var project = this.createAndLoadConfiguredProject(configFileName, reason); + project.updateGraph(); + return project; + }; + ProjectService.prototype.loadConfiguredProject = function (project, reason) { + this.sendProjectLoadingStartEvent(project, reason); + var configFilename = ts.normalizePath(project.getConfigFilePath()); + var configFileContent = this.host.readFile(configFilename); + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 }; + } + var configFileErrors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + var compilerOptions = parsedCommandLine.options; + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + }; + } + project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(parsedCommandLine.raw); + project.setProjectErrors(configFileErrors); + project.updateReferences(parsedCommandLine.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + project.stopWatchingWildCards(); + } + else { + project.enableLanguageService(); + project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); + } + project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); + var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); + }; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = ts.createMap(); @@ -118194,40 +122853,28 @@ var ts; } project.markAsDirty(); }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { + ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } - this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { var configFileSpecs = project.configFileSpecs; var configFileName = project.getConfigFilePath(); var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); - project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); - this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); + project.updateErrorOnNoInputFiles(fileNamesResult); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); }; - ProjectService.prototype.reloadConfiguredProject = function (project) { + ProjectService.prototype.reloadConfiguredProject = function (project, reason) { var host = project.getCachedDirectoryStructureHost(); host.clearCache(); var configFileName = project.getConfigFilePath(); this.logger.info("Reloading configured project " + configFileName); - var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; - project.configFileSpecs = configFileSpecs; - project.setProjectErrors(configFileErrors); - project.updateReferences(projectOptions.projectReferences); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - if (lastFileExceededProgramSize) { - project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - } - else { - project.enableLanguageService(); - project.watchWildcards(projectOptions.wildcardDirectories); - } - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); + this.loadConfiguredProject(project, reason); + project.updateGraph(); this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { @@ -118292,7 +122939,7 @@ var ts; }; ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) { var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; - var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory); + var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides); if (isSingleInferredProject) { this.inferredProjects.unshift(project); } @@ -118315,6 +122962,13 @@ var ts; var configProject = this.configuredProjects.get(uncheckedFileName); return configProject && configProject.getCompilerOptions().configFile; }; + ProjectService.prototype.logErrorForScriptInfoNotFound = function (fileName) { + var names = ts.arrayFrom(this.filenameToScriptInfo.entries()).map(function (_a) { + var path = _a[0], scriptInfo = _a[1]; + return ({ path: path, fileName: scriptInfo.fileName }); + }); + this.logger.msg("Could not find file " + JSON.stringify(fileName) + ".\nAll files are: " + JSON.stringify(names), server.Msg.Err); + }; ProjectService.prototype.getSymlinkedProjects = function (info) { var projects; if (this.realpathToScriptInfos) { @@ -118354,10 +123008,79 @@ var ts; if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - var fileName = info.fileName; - info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); + var indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } } }; + ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) { + var _this = this; + var existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + var watchDir = dir + "/node_modules"; + var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + ts.Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + _this.refreshScriptInfosInDirectory(watchDir); + } + else { + var info = _this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + _this.refreshScriptInfo(info); + } + } + else if (!ts.hasExtension(fileOrDirectoryPath)) { + _this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, 1, "node_modules for closed script infos in them"); + var result = { + close: function () { + if (result.refCount === 1) { + watcher.close(); + _this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + }; + ProjectService.prototype.getModifiedTime = function (info) { + return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime(); + }; + ProjectService.prototype.refreshScriptInfo = function (info) { + var mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + }; + ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) { + var _this = this; + dir = dir + ts.directorySeparator; + this.filenameToScriptInfo.forEach(function (info) { + if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) { + _this.refreshScriptInfo(info); + } + }); + }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { if (info.fileWatcher) { info.fileWatcher.close(); @@ -118365,7 +123088,14 @@ var ts; } }; ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { - return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, false, undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + if (ts.isRootedDiskPath(fileName) || server.isDynamicFileName(fileName)) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, false, undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + } + var info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)); + if (info) { + return info; + } + return undefined; }; ProjectService.prototype.getOrCreateScriptInfoOpenedByClientForNormalizedPath = function (fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) { return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, true, fileContent, scriptKind, hasMixedContent); @@ -118380,7 +123110,7 @@ var ts; var info = this.getScriptInfoForPath(path); if (!info) { var isDynamic = server.isDynamicFileName(fileName); - ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info"; }); + ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory"; }); ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { @@ -118392,7 +123122,7 @@ var ts; if (!openedByClient) { this.watchClosedScriptInfo(info); } - else if (!ts.isRootedDiskPath(fileName) && currentDirectory !== this.currentDirectory) { + else if (!ts.isRootedDiskPath(fileName) && !isDynamic) { this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); } } @@ -118416,6 +123146,7 @@ var ts; return this.filenameToScriptInfo.get(fileName); }; ProjectService.prototype.setHostConfiguration = function (args) { + var _this = this; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { @@ -118433,7 +123164,17 @@ var ts; this.logger.info("Format host information updated"); } if (args.preferences) { + var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject; this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences); + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + this.configuredProjects.forEach(function (project) { + if (project.hasExternalProjectRef() && + project.pendingReload === ts.ConfigFileProgramReloadLevel.Full && + !_this.pendingProjectUpdates.has(project.getProjectName())) { + project.updateGraph(); + } + }); + } } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; @@ -118447,16 +123188,16 @@ var ts; }; ProjectService.prototype.reloadProjects = function () { this.logger.info("reload projects."); - this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue); + this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue, "User requested reload projects"); this.ensureProjectForOpenFiles(); }; ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, true, ignoreIfNotRootOfInferredProject ? function (isRootOfInferredProject) { return isRootOfInferredProject; } : - ts.returnTrue); + ts.returnTrue, "Change in config file detected"); this.delayEnsureProjectForOpenFiles(); }; - ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor) { + ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) { var _this = this; var updatedProjects = ts.createMap(); openFiles.forEach(function (openFileValue, path) { @@ -118467,18 +123208,15 @@ var ts; ts.Debug.assert(info.isScriptOpen()); var configFileName = _this.getConfigFileNameForFile(info); if (configFileName) { - var project = _this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - _this.createConfiguredProject(configFileName); - updatedProjects.set(configFileName, true); - } - else if (!updatedProjects.has(configFileName)) { + var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName); + if (!updatedProjects.has(configFileName)) { if (delayReload) { project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; _this.delayUpdateProjectGraph(project); } else { - _this.reloadConfiguredProject(project); + _this.reloadConfiguredProject(project, reason); } updatedProjects.set(configFileName, true); } @@ -118517,7 +123255,7 @@ var ts; return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); }; ProjectService.prototype.getOriginalLocationEnsuringConfiguredProject = function (project, location) { - var originalLocation = project.getSourceMapper().tryGetOriginalLocation(location); + var originalLocation = project.getSourceMapper().tryGetSourcePosition(location); if (!originalLocation) return undefined; var fileName = originalLocation.fileName; @@ -118527,7 +123265,8 @@ var ts; var configFileName = this.getConfigFileNameForFile(originalFileInfo); if (!configFileName) return undefined; - var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || + this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName); updateProjectIfDirty(configuredProject); addOriginalConfiguredProject(configuredProject); var originalScriptInfo = this.getScriptInfo(fileName); @@ -118567,7 +123306,7 @@ var ts; if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createConfiguredProject(configFileName); + project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open"); if (info.isOrphan()) { configFileName = undefined; } @@ -118614,18 +123353,14 @@ var ts; markOriginalProjectsAsUsed(project); } else { - var resolvedProjectReferences = project.getResolvedProjectReferences(); - if (resolvedProjectReferences) { - for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { - var ref = resolvedProjectReferences_1[_i]; - if (ref) { - var refProject = _this.configuredProjects.get(ref.sourceFile.path); - if (refProject && refProject.hasOpenRef()) { - toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); - } + project.forEachResolvedProjectReference(function (ref) { + if (ref) { + var refProject = _this.configuredProjects.get(ref.sourceFile.path); + if (refProject && refProject.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); } } - } + }); } }); toRemoveConfiguredProjects.forEach(function (project) { return _this.removeProject(project); }); @@ -118730,8 +123465,8 @@ var ts; ts.forEachKey(this.externalProjectToConfiguredProjectMap, function (externalProjectName) { projectsToClose.set(externalProjectName, true); }); - for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { - var externalProject = projects_4[_i]; + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var externalProject = projects_3[_i]; this.openExternalProject(externalProject); projectsToClose.delete(externalProject.projectFileName); } @@ -118825,11 +123560,11 @@ var ts; if (ts.fileExtensionIs(baseName, "js")) { var inferredTypingName = ts.removeFileExtension(baseName); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - if (this_3.legacySafelist[cleanedTypingName]) { + var typeName = this_3.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); excludedFiles.push(normalizedNames[i]); exclude = true; - var typeName = this_3.legacySafelist[cleanedTypingName]; if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); } @@ -118895,7 +123630,8 @@ var ts; else { externalProject.enableLanguageService(); } - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + externalProject.updateGraph(); return; } this.closeExternalProject(proj.projectFileName); @@ -118935,7 +123671,9 @@ var ts; var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { - project = this.createConfiguredProject(tsconfigFile); + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? + this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { project.addExternalProjectReference(); @@ -118944,7 +123682,8 @@ var ts; } else { this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); } }; ProjectService.prototype.hasDeferredExtension = function () { @@ -118956,6 +123695,11 @@ var ts; } return false; }; + ProjectService.prototype.configurePlugin = function (args) { + this.forEachEnabledProject(function (project) { return project.onPluginConfigurationChanged(args.pluginName, args.configuration); }); + this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || ts.createMap(); + this.currentPluginConfigOverrides.set(args.pluginName, args.configuration); + }; ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; return ProjectService; }()); @@ -118964,6 +123708,14 @@ var ts; return config.kind !== undefined; } server.isConfigFile = isConfigFile; + function printProjectsWithCounter(projects, counter) { + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var project = projects_4[_i]; + project.print(counter); + counter++; + } + return counter; + } })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -119137,17 +123889,15 @@ var ts; }; } server.toEvent = toEvent; - function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { - var outputs = ts.flatMap(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); + function combineProjectOutput(defaultValue, getValue, projects, action) { + var outputs = ts.flatMapToMutable(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); if (!ts.isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach(function (projects, path) { var value = getValue(path); outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); }); } - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); + return ts.deduplicate(outputs, ts.equateValues); } function combineProjectOutputFromEveryProject(projectService, action, areEqual) { var outputs = []; @@ -119157,9 +123907,9 @@ var ts; }); return outputs; } - function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, projectService, action, getLocation, resultsEqual) { + function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, action, getLocation, resultsEqual) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, undefined, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, undefined, function (_a, tryAddToTodo) { var project = _a.project; for (var _i = 0, _b = action(project); _i < _b.length; _i++) { var output = _b[_i]; @@ -119170,11 +123920,11 @@ var ts; }, undefined); return outputs; } - function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, projectService, findInStrings, findInComments) { + function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, tryAddToTodo) { var project = _a.project, location = _a.location; - for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.position, findInStrings, findInComments) || server.emptyArray; _i < _b.length; _i++) { + for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments) || server.emptyArray; _i < _b.length; _i++) { var output = _b[_i]; if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { outputs.push(output); @@ -119184,28 +123934,30 @@ var ts; return outputs; } function getDefinitionLocation(defaultProject, initialLocation) { - var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.position); + var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos); var info = infos && ts.firstOrUndefined(infos); - return info && { fileName: info.fileName, position: info.textSpan.start }; + return info && { fileName: info.fileName, pos: info.textSpan.start }; } - function combineProjectOutputForReferences(projects, defaultProject, initialLocation, projectService) { + function combineProjectOutputForReferences(projects, defaultProject, initialLocation) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, getMappedLocation) { var project = _a.project, location = _a.location; var _loop_8 = function (outputReferencedSymbol) { - var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, outputReferencedSymbol.definition); }); + var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); if (!symbolToAddTo) { - symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + symbolToAddTo = { definition: definition, references: [] }; outputs.push(symbolToAddTo); } for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { var ref = _a[_i]; - if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { symbolToAddTo.references.push(ref); } } }; - for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.position) || server.emptyArray; _i < _b.length; _i++) { + for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _b.length; _i++) { var outputReferencedSymbol = _b[_i]; _loop_8(outputReferencedSymbol); } @@ -119226,11 +123978,12 @@ var ts; }); } } - function combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, cb, getDefinition) { + function combineProjectOutputWorker(projects, defaultProject, initialLocation, cb, getDefinition) { + var projectService = defaultProject.projectService; var toDo; var seenProjects = ts.createMap(); forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) { - var location = (initialLocation ? { fileName: path, position: initialLocation.position } : undefined); + var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined); toDo = callbackProjectAndLocation({ project: project, location: location }, projectService, toDo, seenProjects, cb); }); if (getDefinition) { @@ -119251,7 +124004,7 @@ var ts; function getDefinitionInProject(definition, definingProject, project) { if (!definition || project.containsFile(server.toNormalizedPath(definition.fileName))) return definition; - var mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedLocation(definition); + var mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(definition); return mappedDefinition && project.containsFile(server.toNormalizedPath(mappedDefinition.fileName)) ? mappedDefinition : undefined; } function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) { @@ -119261,7 +124014,7 @@ var ts; seenProjects.set(projectAndLocation.project.projectName, true); var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); if (!originalLocation) - return false; + return undefined; var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); toDo = toDo || []; for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { @@ -119277,7 +124030,7 @@ var ts; } }); } - return true; + return originalLocation; }); return toDo; } @@ -119287,10 +124040,10 @@ var ts; } function documentSpanLocation(_a) { var fileName = _a.fileName, textSpan = _a.textSpan; - return { fileName: fileName, position: textSpan.start }; + return { fileName: fileName, pos: textSpan.start }; } function getMappedLocation(location, projectService, project) { - var mapsTo = project.getSourceMapper().tryGetOriginalLocation(location); + var mapsTo = project.getSourceMapper().tryGetSourcePosition(location); return mapsTo && projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined; } var Session = (function () { @@ -119596,6 +124349,10 @@ var ts; _a[server.CommandNames.GetEditsForFileRenameFull] = function (request) { return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, false)); }, + _a[server.CommandNames.ConfigurePlugin] = function (request) { + _this.configurePlugin(request.arguments); + return _this.notRequired(); + }, _a)); this.host = opts.host; this.cancellationToken = opts.cancellationToken; @@ -119632,6 +124389,7 @@ var ts; globalPlugins: opts.globalPlugins, pluginProbeLocations: opts.pluginProbeLocations, allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, syntaxOnly: opts.syntaxOnly, }; this.projectService = new server.ProjectService(settings); @@ -119646,21 +124404,33 @@ var ts; var openFiles = event.data.openFiles; this.projectsUpdatedInBackgroundEvent(openFiles); break; + case server.ProjectLoadingStartEvent: + var _a = event.data, project = _a.project, reason = _a.reason; + this.event({ projectName: project.getProjectName(), reason: reason }, server.ProjectLoadingStartEvent); + break; + case server.ProjectLoadingFinishEvent: + var finishProject = event.data.project; + this.event({ projectName: finishProject.getProjectName() }, server.ProjectLoadingFinishEvent); + break; case server.LargeFileReferencedEvent: - var _a = event.data, file = _a.file, fileSize = _a.fileSize, maxFileSize_1 = _a.maxFileSize; - this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, "largeFileReferenced"); + var _b = event.data, file = _b.file, fileSize = _b.fileSize, maxFileSize_1 = _b.maxFileSize; + this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, server.LargeFileReferencedEvent); break; case server.ConfigFileDiagEvent: - var _b = event.data, triggerFile = _b.triggerFile, configFile = _b.configFileName, diagnostics = _b.diagnostics; + var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics; var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); this.event({ triggerFile: triggerFile, configFile: configFile, diagnostics: bakedDiags - }, "configFileDiag"); + }, server.ConfigFileDiagEvent); + break; + case server.SurveyReady: + var surveyId = event.data.surveyId; + this.event({ surveyId: surveyId }, server.SurveyReady); break; case server.ProjectLanguageServiceStateEvent: { - var eventName = "projectLanguageServiceState"; + var eventName = server.ProjectLanguageServiceStateEvent; this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled @@ -119687,10 +124457,13 @@ var ts; } this.event({ openFiles: openFiles - }, "projectsUpdatedInBackground"); + }, server.ProjectsUpdatedInBackgroundEvent); } }; Session.prototype.logError = function (err, cmd) { + this.logErrorWorker(err, cmd); + }; + Session.prototype.logErrorWorker = function (err, cmd, fileRequest) { var msg = "Exception on executing command " + cmd; if (err.message) { msg += ":\n" + server.indent(err.message); @@ -119698,6 +124471,17 @@ var ts; msg += "\n" + server.indent(err.stack); } } + if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) { + try { + var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + var text = ts.getSnapshotText(scriptInfo.getSnapshot()); + msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + } + } + catch (_b) { } + } this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { @@ -119724,7 +124508,27 @@ var ts; success: success, }; if (success) { - res.body = info; + var metadata = void 0; + if (ts.isArray(info)) { + res.body = info; + metadata = info.metadata; + delete info.metadata; + } + else if (typeof info === "object") { + if (info.metadata) { + var _a = info, infoMetadata = _a.metadata, body = __rest(_a, ["metadata"]); + res.body = body; + metadata = infoMetadata; + } + else { + res.body = info; + } + } + else { + res.body = info; + } + if (metadata) + res.metadata = metadata; } else { ts.Debug.assert(info === undefined); @@ -119902,7 +124706,7 @@ var ts; kind: info.kind, name: info.name, textSpan: { - start: newLoc.position, + start: newLoc.pos, length: info.textSpan.length }, originalFileName: info.fileName, @@ -119974,7 +124778,7 @@ var ts; kind: info.kind, displayParts: info.displayParts, textSpan: { - start: newLoc.position, + start: newLoc.pos, length: info.textSpan.length }, originalFileName: info.fileName, @@ -120107,13 +124911,17 @@ var ts; this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : this.projectService.getScriptInfo(args.file); if (!scriptInfo) { - return ignoreNoProjectError ? server.emptyArray : server.Errors.ThrowNoProject(); + if (ignoreNoProjectError) + return server.emptyArray; + this.projectService.logErrorForScriptInfoNotFound(args.file); + return server.Errors.ThrowNoProject(); } projects = scriptInfo.containingProjects; symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); } projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); }); if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { + this.projectService.logErrorForScriptInfoNotFound(args.file); return server.Errors.ThrowNoProject(); } return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; @@ -120132,25 +124940,32 @@ var ts; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); - var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, position: position }, this.projectService, !!args.findInStrings, !!args.findInComments); + var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments); if (!simplifiedResult) return locations; var defaultProject = this.getDefaultProject(args); - var renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; - Session.mapRenameInfo = function (_a) { - var canRename = _a.canRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers; - return { canRename: canRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers }; + Session.prototype.mapRenameInfo = function (info, scriptInfo) { + if (info.canRename) { + var canRename = info.canRename, fileToRename = info.fileToRename, displayName = info.displayName, fullDisplayName = info.fullDisplayName, kind = info.kind, kindModifiers = info.kindModifiers, triggerSpan = info.triggerSpan; + return ts.identity({ canRename: canRename, fileToRename: fileToRename, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }); + } + else { + return info; + } }; Session.prototype.toSpanGroups = function (locations) { var map = ts.createMap(); for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { - var _a = locations_1[_i], fileName = _a.fileName, textSpan = _a.textSpan; + var _a = locations_1[_i]; + var fileName = _a.fileName, textSpan = _a.textSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "originalTextSpan", "originalFileName"]); var group_1 = map.get(fileName); if (!group_1) map.set(fileName, group_1 = { file: fileName, locs: [] }); - group_1.locs.push(this.toLocationTextSpan(textSpan, ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)))); + var scriptInfo = ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)); + group_1.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText)); } return ts.arrayFrom(map.values()); }; @@ -120159,7 +124974,7 @@ var ts; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); var position = this.getPositionInFile(args, file); - var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, position: position }, this.projectService); + var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }); if (simplifiedResult) { var defaultProject = this.getDefaultProject(args); var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); @@ -120368,7 +125183,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); if (completions === undefined) return undefined; if (kind === "completions-full") @@ -120381,8 +125196,11 @@ var ts; return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; } }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); - if (kind === "completions") + if (kind === "completions") { + if (completions.metadata) + entries.metadata = completions.metadata; return entries; + } var res = __assign({}, completions, { entries: entries }); return res; }; @@ -120590,7 +125408,7 @@ var ts; return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file); } else { - return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), this.projectService, function (project) { + return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), function (project) { return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, undefined, project.isNonTsProject()); }, documentSpanLocation, navigateToItemIsEqualTo); } @@ -120619,7 +125437,7 @@ var ts; Session.prototype.isLocation = function (locationOrSpan) { return locationOrSpan.line !== undefined; }; - Session.prototype.extractPositionAndRange = function (args, scriptInfo) { + Session.prototype.extractPositionOrRange = function (args, scriptInfo) { var position; var textRange; if (this.isLocation(args)) { @@ -120629,7 +125447,7 @@ var ts; var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; textRange = { pos: startPosition, end: endPosition }; } - return { position: position, textRange: textRange }; + return ts.Debug.assertDefined(position === undefined ? textRange : position); function getPosition(loc) { return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); } @@ -120637,14 +125455,12 @@ var ts; Session.prototype.getApplicableRefactors = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; - return project.getLanguageService().getApplicableRefactors(file, position || textRange, this.getPreferences(file)); + return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); }; Session.prototype.getEditsForRefactor = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; - var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), position || textRange, args.refactor, args.action, this.getPreferences(file)); + var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, this.getPreferences(file)); if (result === undefined) { return { edits: [] @@ -120708,8 +125524,8 @@ var ts; var commands = args.command; for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; - var project = this.getFileAndProject(command).project; - project.getLanguageService().applyCodeActionCommand(command).then(function (_result) { }, function (_error) { }); + var _b = this.getFileAndProject(command), file = _b.file, project = _b.project; + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { }); } return {}; }; @@ -120743,8 +125559,17 @@ var ts; var _this = this; return textChanges.map(function (change) { return _this.mapTextChangeToCodeEdit(change); }); }; - Session.prototype.mapTextChangeToCodeEdit = function (change) { - return mapTextChangesToCodeEdits(change, this.projectService.getScriptInfoOrConfig(change.fileName)); + Session.prototype.mapTextChangeToCodeEdit = function (textChanges) { + var scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges.fileName); + if (!!textChanges.isNewFile === !!scriptInfo) { + if (!scriptInfo) { + this.projectService.logErrorForScriptInfoNotFound(textChanges.fileName); + } + ts.Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo })); + } + return scriptInfo + ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, scriptInfo); }) } + : convertNewFileTextChangeToCodeEdit(textChanges); }; Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { return { @@ -120807,6 +125632,9 @@ var ts; var checkList = sortedFiles.map(function (fileName) { return ({ fileName: fileName, project: project }); }); this.updateErrorCheck(next, checkList, delay, false); }; + Session.prototype.configurePlugin = function (args) { + this.projectService.configurePlugin(args); + }; Session.prototype.getCanonicalFileName = function (fileName) { var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); return ts.normalizePath(name); @@ -120864,8 +125692,10 @@ var ts; } } var request; + var relevantFile; try { request = JSON.parse(message); + relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; if (this.logger.hasLevel(server.LogLevel.requestTime)) { var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); @@ -120888,7 +125718,7 @@ var ts; this.doOutput({ canceled: true }, request.command, request.seq, true); return; } - this.logError(err, message); + this.logErrorWorker(err, message, relevantFile); this.doOutput(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, false, "Error processing request. " + err.message + "\n" + err.stack); } }; @@ -120910,12 +125740,6 @@ var ts; function toFileSpan(fileName, textSpan, scriptInfo) { return { file: fileName, start: scriptInfo.positionToLineOffset(textSpan.start), end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) }; } - function mapTextChangesToCodeEdits(textChanges, scriptInfo) { - ts.Debug.assert(!!textChanges.isNewFile === !scriptInfo, "Expected isNewFile for (only) new files", function () { return JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo }); }); - return scriptInfo - ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, scriptInfo); }) } - : convertNewFileTextChangeToCodeEdit(textChanges); - } function convertTextChangeToCodeEdit(change, scriptInfo) { return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, ts.textSpanEnd(change.span)), newText: change.newText }; } @@ -121824,6 +126648,8 @@ var ts; this.activeRequestCount = 0; this.requestQueue = []; this.requestMap = ts.createMap(); // Maps operation ID to newest requestQueue entry with that ID + /** We will lazily request the types registry on the first call to `isKnownTypesPackageName` and store it in `typesRegistryCache`. */ + this.requestedRegistry = false; } NodeTypingsInstaller.prototype.isKnownTypesPackageName = function (name) { // We want to avoid looking this up in the registry as that is expensive. So first check that it's actually an NPM package. @@ -121840,13 +126666,18 @@ var ts; }; NodeTypingsInstaller.prototype.installPackage = function (options) { var _this = this; - var rq = __assign({ kind: "installPackage" }, options); - this.send(rq); + this.send(__assign({ kind: "installPackage" }, options)); ts.Debug.assert(this.packageInstalledPromise === undefined); return new Promise(function (resolve, reject) { _this.packageInstalledPromise = { resolve: resolve, reject: reject }; }); }; + NodeTypingsInstaller.prototype.inspectValue = function (options) { + var _this = this; + this.send({ kind: "inspectValue", options: options }); + ts.Debug.assert(this.inspectValuePromise === undefined); + return new Promise(function (resolve) { _this.inspectValuePromise = { resolve: resolve }; }); + }; NodeTypingsInstaller.prototype.attach = function (projectService) { var _this = this; this.projectService = projectService; @@ -121945,6 +126776,10 @@ var ts; this.event(response, "setTypings"); break; } + case server.ActionValueInspected: + this.inspectValuePromise.resolve(response.result); + this.inspectValuePromise = undefined; + break; case server.EventInitializationFailed: { var body = { @@ -122071,6 +126906,7 @@ var ts; globalPlugins: globalPlugins, pluginProbeLocations: pluginProbeLocations, allowLocalPluginLoads: allowLocalPluginLoads, + typesMapLocation: typesMapLocation, }) || this; _this.eventPort = eventPort; if (_this.canUseEvents && _this.eventPort) { @@ -122190,13 +127026,16 @@ var ts; var cmdLineLogFileName = server.findArgument("--logFile"); var cmdLineVerbosity = getLogLevel(server.findArgument("--logVerbosity")); var envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); - var logFileName = cmdLineLogFileName + var unsubstitutedLogFileName = cmdLineLogFileName ? ts.stripQuotes(cmdLineLogFileName) : envLogOptions.logToFile ? envLogOptions.file || (__dirname + "/.log" + process.pid.toString()) : undefined; + var substitutedLogFileName = unsubstitutedLogFileName + ? unsubstitutedLogFileName.replace("PID", process.pid.toString()) + : undefined; var logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel; - return new Logger(logFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217 + return new Logger(substitutedLogFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217 } // This places log file in the directory containing editorServices.js // TODO: check that this location is writable @@ -122414,7 +127253,7 @@ var ts; } sys.require = function (initialDir, moduleName) { try { - return { module: require(ts.resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; + return { module: require(ts.resolveJSModule(moduleName, initialDir, sys)), error: undefined }; } catch (error) { return { module: undefined, error: error }; @@ -122442,7 +127281,7 @@ var ts; } ts.setStackTraceLimit(); var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); // TODO: GH#18217 - var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(sys.getExecutingFilePath(), "../typesMap.json"); + var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(ts.getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); var npmLocation = server.findArgument(server.Arguments.NpmLocation); function parseStringArray(argName) { var arg = server.findArgument(argName); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index a16288c6c27..2b78178587e 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ const version: string; } @@ -27,6 +27,9 @@ declare namespace ts { interface MapLike { [index: string]: T; } + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } interface SortedArray extends Array { " __sortedArrayBrand": any; } @@ -69,7 +72,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -81,337 +85,339 @@ declare namespace ts { ShebangTrivia = 6, ConflictMarkerTrivia = 7, NumericLiteral = 8, - StringLiteral = 9, - JsxText = 10, - JsxTextAllWhiteSpaces = 11, - RegularExpressionLiteral = 12, - NoSubstitutionTemplateLiteral = 13, - TemplateHead = 14, - TemplateMiddle = 15, - TemplateTail = 16, - OpenBraceToken = 17, - CloseBraceToken = 18, - OpenParenToken = 19, - CloseParenToken = 20, - OpenBracketToken = 21, - CloseBracketToken = 22, - DotToken = 23, - DotDotDotToken = 24, - SemicolonToken = 25, - CommaToken = 26, - LessThanToken = 27, - LessThanSlashToken = 28, - GreaterThanToken = 29, - LessThanEqualsToken = 30, - GreaterThanEqualsToken = 31, - EqualsEqualsToken = 32, - ExclamationEqualsToken = 33, - EqualsEqualsEqualsToken = 34, - ExclamationEqualsEqualsToken = 35, - EqualsGreaterThanToken = 36, - PlusToken = 37, - MinusToken = 38, - AsteriskToken = 39, - AsteriskAsteriskToken = 40, - SlashToken = 41, - PercentToken = 42, - PlusPlusToken = 43, - MinusMinusToken = 44, - LessThanLessThanToken = 45, - GreaterThanGreaterThanToken = 46, - GreaterThanGreaterThanGreaterThanToken = 47, - AmpersandToken = 48, - BarToken = 49, - CaretToken = 50, - ExclamationToken = 51, - TildeToken = 52, - AmpersandAmpersandToken = 53, - BarBarToken = 54, - QuestionToken = 55, - ColonToken = 56, - AtToken = 57, - EqualsToken = 58, - PlusEqualsToken = 59, - MinusEqualsToken = 60, - AsteriskEqualsToken = 61, - AsteriskAsteriskEqualsToken = 62, - SlashEqualsToken = 63, - PercentEqualsToken = 64, - LessThanLessThanEqualsToken = 65, - GreaterThanGreaterThanEqualsToken = 66, - GreaterThanGreaterThanGreaterThanEqualsToken = 67, - AmpersandEqualsToken = 68, - BarEqualsToken = 69, - CaretEqualsToken = 70, - Identifier = 71, - BreakKeyword = 72, - CaseKeyword = 73, - CatchKeyword = 74, - ClassKeyword = 75, - ConstKeyword = 76, - ContinueKeyword = 77, - DebuggerKeyword = 78, - DefaultKeyword = 79, - DeleteKeyword = 80, - DoKeyword = 81, - ElseKeyword = 82, - EnumKeyword = 83, - ExportKeyword = 84, - ExtendsKeyword = 85, - FalseKeyword = 86, - FinallyKeyword = 87, - ForKeyword = 88, - FunctionKeyword = 89, - IfKeyword = 90, - ImportKeyword = 91, - InKeyword = 92, - InstanceOfKeyword = 93, - NewKeyword = 94, - NullKeyword = 95, - ReturnKeyword = 96, - SuperKeyword = 97, - SwitchKeyword = 98, - ThisKeyword = 99, - ThrowKeyword = 100, - TrueKeyword = 101, - TryKeyword = 102, - TypeOfKeyword = 103, - VarKeyword = 104, - VoidKeyword = 105, - WhileKeyword = 106, - WithKeyword = 107, - ImplementsKeyword = 108, - InterfaceKeyword = 109, - LetKeyword = 110, - PackageKeyword = 111, - PrivateKeyword = 112, - ProtectedKeyword = 113, - PublicKeyword = 114, - StaticKeyword = 115, - YieldKeyword = 116, - AbstractKeyword = 117, - AsKeyword = 118, - AnyKeyword = 119, - AsyncKeyword = 120, - AwaitKeyword = 121, - BooleanKeyword = 122, - ConstructorKeyword = 123, - DeclareKeyword = 124, - GetKeyword = 125, - InferKeyword = 126, - IsKeyword = 127, - KeyOfKeyword = 128, - ModuleKeyword = 129, - NamespaceKeyword = 130, - NeverKeyword = 131, - ReadonlyKeyword = 132, - RequireKeyword = 133, - NumberKeyword = 134, - ObjectKeyword = 135, - SetKeyword = 136, - StringKeyword = 137, - SymbolKeyword = 138, - TypeKeyword = 139, - UndefinedKeyword = 140, - UniqueKeyword = 141, - UnknownKeyword = 142, - FromKeyword = 143, - GlobalKeyword = 144, - OfKeyword = 145, - QualifiedName = 146, - ComputedPropertyName = 147, - TypeParameter = 148, - Parameter = 149, - Decorator = 150, - PropertySignature = 151, - PropertyDeclaration = 152, - MethodSignature = 153, - MethodDeclaration = 154, - Constructor = 155, - GetAccessor = 156, - SetAccessor = 157, - CallSignature = 158, - ConstructSignature = 159, - IndexSignature = 160, - TypePredicate = 161, - TypeReference = 162, - FunctionType = 163, - ConstructorType = 164, - TypeQuery = 165, - TypeLiteral = 166, - ArrayType = 167, - TupleType = 168, - OptionalType = 169, - RestType = 170, - UnionType = 171, - IntersectionType = 172, - ConditionalType = 173, - InferType = 174, - ParenthesizedType = 175, - ThisType = 176, - TypeOperator = 177, - IndexedAccessType = 178, - MappedType = 179, - LiteralType = 180, - ImportType = 181, - ObjectBindingPattern = 182, - ArrayBindingPattern = 183, - BindingElement = 184, - ArrayLiteralExpression = 185, - ObjectLiteralExpression = 186, - PropertyAccessExpression = 187, - ElementAccessExpression = 188, - CallExpression = 189, - NewExpression = 190, - TaggedTemplateExpression = 191, - TypeAssertionExpression = 192, - ParenthesizedExpression = 193, - FunctionExpression = 194, - ArrowFunction = 195, - DeleteExpression = 196, - TypeOfExpression = 197, - VoidExpression = 198, - AwaitExpression = 199, - PrefixUnaryExpression = 200, - PostfixUnaryExpression = 201, - BinaryExpression = 202, - ConditionalExpression = 203, - TemplateExpression = 204, - YieldExpression = 205, - SpreadElement = 206, - ClassExpression = 207, - OmittedExpression = 208, - ExpressionWithTypeArguments = 209, - AsExpression = 210, - NonNullExpression = 211, - MetaProperty = 212, - SyntheticExpression = 213, - TemplateSpan = 214, - SemicolonClassElement = 215, - Block = 216, - VariableStatement = 217, - EmptyStatement = 218, - ExpressionStatement = 219, - IfStatement = 220, - DoStatement = 221, - WhileStatement = 222, - ForStatement = 223, - ForInStatement = 224, - ForOfStatement = 225, - ContinueStatement = 226, - BreakStatement = 227, - ReturnStatement = 228, - WithStatement = 229, - SwitchStatement = 230, - LabeledStatement = 231, - ThrowStatement = 232, - TryStatement = 233, - DebuggerStatement = 234, - VariableDeclaration = 235, - VariableDeclarationList = 236, - FunctionDeclaration = 237, - ClassDeclaration = 238, - InterfaceDeclaration = 239, - TypeAliasDeclaration = 240, - EnumDeclaration = 241, - ModuleDeclaration = 242, - ModuleBlock = 243, - CaseBlock = 244, - NamespaceExportDeclaration = 245, - ImportEqualsDeclaration = 246, - ImportDeclaration = 247, - ImportClause = 248, - NamespaceImport = 249, - NamedImports = 250, - ImportSpecifier = 251, - ExportAssignment = 252, - ExportDeclaration = 253, - NamedExports = 254, - ExportSpecifier = 255, - MissingDeclaration = 256, - ExternalModuleReference = 257, - JsxElement = 258, - JsxSelfClosingElement = 259, - JsxOpeningElement = 260, - JsxClosingElement = 261, - JsxFragment = 262, - JsxOpeningFragment = 263, - JsxClosingFragment = 264, - JsxAttribute = 265, - JsxAttributes = 266, - JsxSpreadAttribute = 267, - JsxExpression = 268, - CaseClause = 269, - DefaultClause = 270, - HeritageClause = 271, - CatchClause = 272, - PropertyAssignment = 273, - ShorthandPropertyAssignment = 274, - SpreadAssignment = 275, - EnumMember = 276, - SourceFile = 277, - Bundle = 278, - UnparsedSource = 279, - InputFiles = 280, - JSDocTypeExpression = 281, - JSDocAllType = 282, - JSDocUnknownType = 283, - JSDocNullableType = 284, - JSDocNonNullableType = 285, - JSDocOptionalType = 286, - JSDocFunctionType = 287, - JSDocVariadicType = 288, - JSDocComment = 289, - JSDocTypeLiteral = 290, - JSDocSignature = 291, - JSDocTag = 292, - JSDocAugmentsTag = 293, - JSDocClassTag = 294, - JSDocCallbackTag = 295, - JSDocEnumTag = 296, - JSDocParameterTag = 297, - JSDocReturnTag = 298, - JSDocThisTag = 299, - JSDocTypeTag = 300, - JSDocTemplateTag = 301, - JSDocTypedefTag = 302, - JSDocPropertyTag = 303, - SyntaxList = 304, - NotEmittedStatement = 305, - PartiallyEmittedExpression = 306, - CommaListExpression = 307, - MergeDeclarationMarker = 308, - EndOfDeclarationMarker = 309, - Count = 310, - FirstAssignment = 58, - LastAssignment = 70, - FirstCompoundAssignment = 59, - LastCompoundAssignment = 70, - FirstReservedWord = 72, - LastReservedWord = 107, - FirstKeyword = 72, - LastKeyword = 145, - FirstFutureReservedWord = 108, - LastFutureReservedWord = 116, - FirstTypeNode = 161, - LastTypeNode = 181, - FirstPunctuation = 17, - LastPunctuation = 70, + BigIntLiteral = 9, + StringLiteral = 10, + JsxText = 11, + JsxTextAllWhiteSpaces = 12, + RegularExpressionLiteral = 13, + NoSubstitutionTemplateLiteral = 14, + TemplateHead = 15, + TemplateMiddle = 16, + TemplateTail = 17, + OpenBraceToken = 18, + CloseBraceToken = 19, + OpenParenToken = 20, + CloseParenToken = 21, + OpenBracketToken = 22, + CloseBracketToken = 23, + DotToken = 24, + DotDotDotToken = 25, + SemicolonToken = 26, + CommaToken = 27, + LessThanToken = 28, + LessThanSlashToken = 29, + GreaterThanToken = 30, + LessThanEqualsToken = 31, + GreaterThanEqualsToken = 32, + EqualsEqualsToken = 33, + ExclamationEqualsToken = 34, + EqualsEqualsEqualsToken = 35, + ExclamationEqualsEqualsToken = 36, + EqualsGreaterThanToken = 37, + PlusToken = 38, + MinusToken = 39, + AsteriskToken = 40, + AsteriskAsteriskToken = 41, + SlashToken = 42, + PercentToken = 43, + PlusPlusToken = 44, + MinusMinusToken = 45, + LessThanLessThanToken = 46, + GreaterThanGreaterThanToken = 47, + GreaterThanGreaterThanGreaterThanToken = 48, + AmpersandToken = 49, + BarToken = 50, + CaretToken = 51, + ExclamationToken = 52, + TildeToken = 53, + AmpersandAmpersandToken = 54, + BarBarToken = 55, + QuestionToken = 56, + ColonToken = 57, + AtToken = 58, + EqualsToken = 59, + PlusEqualsToken = 60, + MinusEqualsToken = 61, + AsteriskEqualsToken = 62, + AsteriskAsteriskEqualsToken = 63, + SlashEqualsToken = 64, + PercentEqualsToken = 65, + LessThanLessThanEqualsToken = 66, + GreaterThanGreaterThanEqualsToken = 67, + GreaterThanGreaterThanGreaterThanEqualsToken = 68, + AmpersandEqualsToken = 69, + BarEqualsToken = 70, + CaretEqualsToken = 71, + Identifier = 72, + BreakKeyword = 73, + CaseKeyword = 74, + CatchKeyword = 75, + ClassKeyword = 76, + ConstKeyword = 77, + ContinueKeyword = 78, + DebuggerKeyword = 79, + DefaultKeyword = 80, + DeleteKeyword = 81, + DoKeyword = 82, + ElseKeyword = 83, + EnumKeyword = 84, + ExportKeyword = 85, + ExtendsKeyword = 86, + FalseKeyword = 87, + FinallyKeyword = 88, + ForKeyword = 89, + FunctionKeyword = 90, + IfKeyword = 91, + ImportKeyword = 92, + InKeyword = 93, + InstanceOfKeyword = 94, + NewKeyword = 95, + NullKeyword = 96, + ReturnKeyword = 97, + SuperKeyword = 98, + SwitchKeyword = 99, + ThisKeyword = 100, + ThrowKeyword = 101, + TrueKeyword = 102, + TryKeyword = 103, + TypeOfKeyword = 104, + VarKeyword = 105, + VoidKeyword = 106, + WhileKeyword = 107, + WithKeyword = 108, + ImplementsKeyword = 109, + InterfaceKeyword = 110, + LetKeyword = 111, + PackageKeyword = 112, + PrivateKeyword = 113, + ProtectedKeyword = 114, + PublicKeyword = 115, + StaticKeyword = 116, + YieldKeyword = 117, + AbstractKeyword = 118, + AsKeyword = 119, + AnyKeyword = 120, + AsyncKeyword = 121, + AwaitKeyword = 122, + BooleanKeyword = 123, + ConstructorKeyword = 124, + DeclareKeyword = 125, + GetKeyword = 126, + InferKeyword = 127, + IsKeyword = 128, + KeyOfKeyword = 129, + ModuleKeyword = 130, + NamespaceKeyword = 131, + NeverKeyword = 132, + ReadonlyKeyword = 133, + RequireKeyword = 134, + NumberKeyword = 135, + ObjectKeyword = 136, + SetKeyword = 137, + StringKeyword = 138, + SymbolKeyword = 139, + TypeKeyword = 140, + UndefinedKeyword = 141, + UniqueKeyword = 142, + UnknownKeyword = 143, + FromKeyword = 144, + GlobalKeyword = 145, + BigIntKeyword = 146, + OfKeyword = 147, + QualifiedName = 148, + ComputedPropertyName = 149, + TypeParameter = 150, + Parameter = 151, + Decorator = 152, + PropertySignature = 153, + PropertyDeclaration = 154, + MethodSignature = 155, + MethodDeclaration = 156, + Constructor = 157, + GetAccessor = 158, + SetAccessor = 159, + CallSignature = 160, + ConstructSignature = 161, + IndexSignature = 162, + TypePredicate = 163, + TypeReference = 164, + FunctionType = 165, + ConstructorType = 166, + TypeQuery = 167, + TypeLiteral = 168, + ArrayType = 169, + TupleType = 170, + OptionalType = 171, + RestType = 172, + UnionType = 173, + IntersectionType = 174, + ConditionalType = 175, + InferType = 176, + ParenthesizedType = 177, + ThisType = 178, + TypeOperator = 179, + IndexedAccessType = 180, + MappedType = 181, + LiteralType = 182, + ImportType = 183, + ObjectBindingPattern = 184, + ArrayBindingPattern = 185, + BindingElement = 186, + ArrayLiteralExpression = 187, + ObjectLiteralExpression = 188, + PropertyAccessExpression = 189, + ElementAccessExpression = 190, + CallExpression = 191, + NewExpression = 192, + TaggedTemplateExpression = 193, + TypeAssertionExpression = 194, + ParenthesizedExpression = 195, + FunctionExpression = 196, + ArrowFunction = 197, + DeleteExpression = 198, + TypeOfExpression = 199, + VoidExpression = 200, + AwaitExpression = 201, + PrefixUnaryExpression = 202, + PostfixUnaryExpression = 203, + BinaryExpression = 204, + ConditionalExpression = 205, + TemplateExpression = 206, + YieldExpression = 207, + SpreadElement = 208, + ClassExpression = 209, + OmittedExpression = 210, + ExpressionWithTypeArguments = 211, + AsExpression = 212, + NonNullExpression = 213, + MetaProperty = 214, + SyntheticExpression = 215, + TemplateSpan = 216, + SemicolonClassElement = 217, + Block = 218, + VariableStatement = 219, + EmptyStatement = 220, + ExpressionStatement = 221, + IfStatement = 222, + DoStatement = 223, + WhileStatement = 224, + ForStatement = 225, + ForInStatement = 226, + ForOfStatement = 227, + ContinueStatement = 228, + BreakStatement = 229, + ReturnStatement = 230, + WithStatement = 231, + SwitchStatement = 232, + LabeledStatement = 233, + ThrowStatement = 234, + TryStatement = 235, + DebuggerStatement = 236, + VariableDeclaration = 237, + VariableDeclarationList = 238, + FunctionDeclaration = 239, + ClassDeclaration = 240, + InterfaceDeclaration = 241, + TypeAliasDeclaration = 242, + EnumDeclaration = 243, + ModuleDeclaration = 244, + ModuleBlock = 245, + CaseBlock = 246, + NamespaceExportDeclaration = 247, + ImportEqualsDeclaration = 248, + ImportDeclaration = 249, + ImportClause = 250, + NamespaceImport = 251, + NamedImports = 252, + ImportSpecifier = 253, + ExportAssignment = 254, + ExportDeclaration = 255, + NamedExports = 256, + ExportSpecifier = 257, + MissingDeclaration = 258, + ExternalModuleReference = 259, + JsxElement = 260, + JsxSelfClosingElement = 261, + JsxOpeningElement = 262, + JsxClosingElement = 263, + JsxFragment = 264, + JsxOpeningFragment = 265, + JsxClosingFragment = 266, + JsxAttribute = 267, + JsxAttributes = 268, + JsxSpreadAttribute = 269, + JsxExpression = 270, + CaseClause = 271, + DefaultClause = 272, + HeritageClause = 273, + CatchClause = 274, + PropertyAssignment = 275, + ShorthandPropertyAssignment = 276, + SpreadAssignment = 277, + EnumMember = 278, + SourceFile = 279, + Bundle = 280, + UnparsedSource = 281, + InputFiles = 282, + JSDocTypeExpression = 283, + JSDocAllType = 284, + JSDocUnknownType = 285, + JSDocNullableType = 286, + JSDocNonNullableType = 287, + JSDocOptionalType = 288, + JSDocFunctionType = 289, + JSDocVariadicType = 290, + JSDocComment = 291, + JSDocTypeLiteral = 292, + JSDocSignature = 293, + JSDocTag = 294, + JSDocAugmentsTag = 295, + JSDocClassTag = 296, + JSDocCallbackTag = 297, + JSDocEnumTag = 298, + JSDocParameterTag = 299, + JSDocReturnTag = 300, + JSDocThisTag = 301, + JSDocTypeTag = 302, + JSDocTemplateTag = 303, + JSDocTypedefTag = 304, + JSDocPropertyTag = 305, + SyntaxList = 306, + NotEmittedStatement = 307, + PartiallyEmittedExpression = 308, + CommaListExpression = 309, + MergeDeclarationMarker = 310, + EndOfDeclarationMarker = 311, + Count = 312, + FirstAssignment = 59, + LastAssignment = 71, + FirstCompoundAssignment = 60, + LastCompoundAssignment = 71, + FirstReservedWord = 73, + LastReservedWord = 108, + FirstKeyword = 73, + LastKeyword = 147, + FirstFutureReservedWord = 109, + LastFutureReservedWord = 117, + FirstTypeNode = 163, + LastTypeNode = 183, + FirstPunctuation = 18, + LastPunctuation = 71, FirstToken = 0, - LastToken = 145, + LastToken = 147, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, - LastLiteralToken = 13, - FirstTemplateToken = 13, - LastTemplateToken = 16, - FirstBinaryOperator = 27, - LastBinaryOperator = 70, - FirstNode = 146, - FirstJSDocNode = 281, - LastJSDocNode = 303, - FirstJSDocTagNode = 292, - LastJSDocTagNode = 303 + LastLiteralToken = 14, + FirstTemplateToken = 14, + LastTemplateToken = 17, + FirstBinaryOperator = 28, + LastBinaryOperator = 71, + FirstNode = 148, + FirstJSDocNode = 283, + LastJSDocNode = 305, + FirstJSDocTagNode = 294, + LastJSDocTagNode = 305 } enum NodeFlags { None = 0, @@ -498,7 +504,6 @@ declare namespace ts { type AsteriskToken = Token; type EqualsGreaterThanToken = Token; type EndOfFileToken = Token & JSDocContainer; - type AtToken = Token; type ReadonlyToken = Token; type AwaitKeywordToken = Token; type PlusToken = Token; @@ -525,7 +530,7 @@ declare namespace ts { } type EntityName = Identifier | QualifiedName; type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; - type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; + type DeclarationName = Identifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; } @@ -536,6 +541,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +638,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +675,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -720,7 +728,7 @@ declare namespace ts { _typeNodeBrand: any; } interface KeywordTypeNode extends TypeNode { - kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; + kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; } interface ImportTypeNode extends NodeWithTypeArguments { kind: SyntaxKind.ImportType; @@ -992,6 +1000,9 @@ declare namespace ts { interface NumericLiteral extends LiteralExpression { kind: SyntaxKind.NumericLiteral; } + interface BigIntLiteral extends LiteralExpression { + kind: SyntaxKind.BigIntLiteral; + } interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; parent: TemplateExpression; @@ -1079,7 +1090,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1539,7 +1550,6 @@ declare namespace ts { } interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; - atToken: AtToken; tagName: Identifier; comment?: string; } @@ -1569,7 +1579,7 @@ declare namespace ts { } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; - constraint: TypeNode | undefined; + constraint: JSDocTypeExpression | undefined; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { @@ -1751,13 +1761,14 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. */ fileExists(path: string): boolean; readFile(path: string): string | undefined; + trace?(s: string): void; } /** * Branded string for keeping track of when we've turned an ambiguous path @@ -1808,11 +1819,13 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): ReadonlyArray | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; sourceFile: SourceFile; + references?: ReadonlyArray; } interface CustomTransformers { /** Custom transformers to evaluate before built-in .js transformations. */ @@ -1836,17 +1849,6 @@ declare namespace ts { /** .ts file (index into sources array) associated with this span */ sourceIndex: number; } - interface SourceMapData { - sourceMapFilePath: string; - jsSourceMappingURL: string; - sourceMapFile: string; - sourceMapSourceRoot: string; - sourceMapSources: string[]; - sourceMapSourcesContent?: (string | null)[]; - inputSourceFileNames: string[]; - sourceMapNames?: string[]; - sourceMapMappings: string; - } /** Return code used by getEmitOutput function to indicate status of the function */ enum ExitStatus { Success = 0, @@ -1918,7 +1920,7 @@ declare namespace ts { typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; + getRootSymbols(symbol: Symbol): ReadonlyArray; getContextualType(node: Expression): Type | undefined; /** * returns unknownSignature in the case of an error. @@ -1936,7 +1938,6 @@ declare namespace ts { /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; @@ -1975,7 +1976,8 @@ declare namespace ts { AllowEmptyTuple = 524288, AllowUniqueESSymbolType = 1048576, AllowEmptyIndexInfoType = 2097152, - IgnoreErrors = 3112960, + AllowNodeModulesRelativePaths = 67108864, + IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, @@ -2056,32 +2058,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2155,44 +2157,47 @@ declare namespace ts { Number = 8, Boolean = 16, Enum = 32, - StringLiteral = 64, - NumberLiteral = 128, - BooleanLiteral = 256, - EnumLiteral = 512, - ESSymbol = 1024, - UniqueESSymbol = 2048, - Void = 4096, - Undefined = 8192, - Null = 16384, - Never = 32768, - TypeParameter = 65536, - Object = 131072, - Union = 262144, - Intersection = 524288, - Index = 1048576, - IndexedAccess = 2097152, - Conditional = 4194304, - Substitution = 8388608, - NonPrimitive = 16777216, - Literal = 448, - Unit = 27072, - StringOrNumberLiteral = 192, - PossiblyFalsy = 29148, - StringLike = 68, - NumberLike = 168, - BooleanLike = 272, - EnumLike = 544, - ESSymbolLike = 3072, - VoidLike = 12288, - UnionOrIntersection = 786432, - StructuredType = 917504, - TypeVariable = 2162688, - InstantiableNonPrimitive = 14745600, - InstantiablePrimitive = 1048576, - Instantiable = 15794176, - StructuredOrInstantiable = 16711680, - Narrowable = 33492479, - NotUnionOrUnit = 16909315 + BigInt = 64, + StringLiteral = 128, + NumberLiteral = 256, + BooleanLiteral = 512, + EnumLiteral = 1024, + BigIntLiteral = 2048, + ESSymbol = 4096, + UniqueESSymbol = 8192, + Void = 16384, + Undefined = 32768, + Null = 65536, + Never = 131072, + TypeParameter = 262144, + Object = 524288, + Union = 1048576, + Intersection = 2097152, + Index = 4194304, + IndexedAccess = 8388608, + Conditional = 16777216, + Substitution = 33554432, + NonPrimitive = 67108864, + Literal = 2944, + Unit = 109440, + StringOrNumberLiteral = 384, + PossiblyFalsy = 117724, + StringLike = 132, + NumberLike = 296, + BigIntLike = 2112, + BooleanLike = 528, + EnumLike = 1056, + ESSymbolLike = 12288, + VoidLike = 49152, + UnionOrIntersection = 3145728, + StructuredType = 3670016, + TypeVariable = 8650752, + InstantiableNonPrimitive = 58982400, + InstantiablePrimitive = 4194304, + Instantiable = 63176704, + StructuredOrInstantiable = 66846720, + Narrowable = 133970943, + NotUnionOrUnit = 67637251 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2203,7 +2208,7 @@ declare namespace ts { aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { - value: string | number; + value: string | number | PseudoBigInt; freshType: LiteralType; regularType: LiteralType; } @@ -2216,6 +2221,9 @@ declare namespace ts { interface NumberLiteralType extends LiteralType { value: number; } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } interface EnumType extends Type { } enum ObjectFlags { @@ -2234,6 +2242,7 @@ declare namespace ts { JsxAttributes = 4096, MarkerType = 8192, JSLiteral = 16384, + FreshLiteral = 32768, ClassOrInterface = 3 } interface ObjectType extends Type { @@ -2490,6 +2499,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2591,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2601,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2673,6 +2674,8 @@ declare namespace ts { primary: boolean; resolvedFileName: string | undefined; packageId?: PackageId; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; @@ -2691,16 +2694,13 @@ declare namespace ts { useCaseSensitiveFileNames(): boolean; getNewLine(): string; readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -2753,7 +2753,8 @@ declare namespace ts { Expression = 1, IdentifierName = 2, MappedTypeParameter = 3, - Unspecified = 4 + Unspecified = 4, + EmbeddedStatement = 5 } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2946,60 +2947,77 @@ declare namespace ts { BarDelimited = 4, AmpersandDelimited = 8, CommaDelimited = 16, - DelimitersMask = 28, - AllowTrailingComma = 32, - Indented = 64, - SpaceBetweenBraces = 128, - SpaceBetweenSiblings = 256, - Braces = 512, - Parenthesis = 1024, - AngleBrackets = 2048, - SquareBrackets = 4096, - BracketsMask = 7680, - OptionalIfUndefined = 8192, - OptionalIfEmpty = 16384, - Optional = 24576, - PreferNewLine = 32768, - NoTrailingNewLine = 65536, - NoInterveningComments = 131072, - NoSpaceIfEmpty = 262144, - SingleElement = 524288, - Modifiers = 131328, - HeritageClauses = 256, - SingleLineTypeLiteralMembers = 384, - MultiLineTypeLiteralMembers = 16449, - TupleTypeElements = 272, - UnionTypeConstituents = 260, - IntersectionTypeConstituents = 264, - ObjectBindingPatternElements = 262576, - ArrayBindingPatternElements = 262448, - ObjectLiteralExpressionProperties = 263122, - ArrayLiteralExpressionElements = 4466, - CommaListElements = 272, - CallExpressionArguments = 1296, - NewExpressionArguments = 9488, - TemplateExpressionSpans = 131072, - SingleLineBlockStatements = 384, - MultiLineBlockStatements = 65, - VariableDeclarationList = 272, - SingleLineFunctionBodyStatements = 384, + AsteriskDelimited = 32, + DelimitersMask = 60, + AllowTrailingComma = 64, + Indented = 128, + SpaceBetweenBraces = 256, + SpaceBetweenSiblings = 512, + Braces = 1024, + Parenthesis = 2048, + AngleBrackets = 4096, + SquareBrackets = 8192, + BracketsMask = 15360, + OptionalIfUndefined = 16384, + OptionalIfEmpty = 32768, + Optional = 49152, + PreferNewLine = 65536, + NoTrailingNewLine = 131072, + NoInterveningComments = 262144, + NoSpaceIfEmpty = 524288, + SingleElement = 1048576, + Modifiers = 262656, + HeritageClauses = 512, + SingleLineTypeLiteralMembers = 768, + MultiLineTypeLiteralMembers = 32897, + TupleTypeElements = 528, + UnionTypeConstituents = 516, + IntersectionTypeConstituents = 520, + ObjectBindingPatternElements = 525136, + ArrayBindingPatternElements = 524880, + ObjectLiteralExpressionProperties = 526226, + ArrayLiteralExpressionElements = 8914, + CommaListElements = 528, + CallExpressionArguments = 2576, + NewExpressionArguments = 18960, + TemplateExpressionSpans = 262144, + SingleLineBlockStatements = 768, + MultiLineBlockStatements = 129, + VariableDeclarationList = 528, + SingleLineFunctionBodyStatements = 768, MultiLineFunctionBodyStatements = 1, ClassHeritageClauses = 0, - ClassMembers = 65, - InterfaceMembers = 65, - EnumMembers = 81, - CaseBlockClauses = 65, - NamedImportsOrExportsElements = 262576, - JsxElementOrFragmentChildren = 131072, - JsxElementAttributes = 131328, - CaseOrDefaultClauseStatements = 81985, - HeritageClauseTypes = 272, - SourceFileStatements = 65537, - Decorators = 24577, - TypeArguments = 26896, - TypeParameters = 26896, - Parameters = 1296, - IndexSignatureParameters = 4432 + ClassMembers = 129, + InterfaceMembers = 129, + EnumMembers = 145, + CaseBlockClauses = 129, + NamedImportsOrExportsElements = 525136, + JsxElementOrFragmentChildren = 262144, + JsxElementAttributes = 262656, + CaseOrDefaultClauseStatements = 163969, + HeritageClauseTypes = 528, + SourceFileStatements = 131073, + Decorators = 49153, + TypeArguments = 53776, + TypeParameters = 53776, + Parameters = 2576, + IndexSignatureParameters = 8848, + JSDocComment = 33 + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } + /** Represents a bigint literal value without requiring bigint support */ + interface PseudoBigInt { + negative: boolean; + base10Value: string; } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; @@ -3114,10 +3132,9 @@ declare namespace ts { function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } -/** Non-internal stuff goes here */ declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray; } declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; @@ -3209,17 +3226,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -3273,6 +3300,7 @@ declare namespace ts { } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; + function isBigIntLiteral(node: Node): node is BigIntLiteral; function isStringLiteral(node: Node): node is StringLiteral; function isJsxText(node: Node): node is JsxText; function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; @@ -3450,6 +3478,7 @@ declare namespace ts { type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail; function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; + function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier; function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; function isModifier(node: Node): node is Modifier; function isEntityName(node: Node): node is EntityName; @@ -3592,7 +3621,7 @@ declare namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -3607,14 +3636,14 @@ declare namespace ts { * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string): Map; + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ interface NonRelativeModuleNameResolutionCache { - getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; + getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; @@ -3622,18 +3651,19 @@ declare namespace ts { } function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; } declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; - function createLiteral(value: number): NumericLiteral; + function createLiteral(value: number | PseudoBigInt): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; - function createLiteral(value: string | number | boolean): PrimaryExpression; + function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; + function createBigIntLiteral(value: string): BigIntLiteral; function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; function createIdentifier(text: string): Identifier; @@ -4134,7 +4164,7 @@ declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; interface FormatDiagnosticsHost { getCurrentDirectory(): string; getCanonicalFileName(fileName: string): string; @@ -4171,14 +4201,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4334,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4358,17 +4400,9 @@ declare namespace ts { /** If provided is used to get the environment variable */ getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } /** * Host to create watch with root files and options @@ -4378,6 +4412,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4448,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,193 +4459,17 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; type EventInitializationFailed = "event::initializationFailed"; - interface SortedReadonlyArray extends ReadonlyArray { - " __sortedArrayBrand": any; - } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4807,9 +4667,9 @@ declare namespace ts { realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. @@ -4817,15 +4677,11 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; + writeFile?(fileName: string, content: string): void; } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; - } + type WithMetadata = T & { + metadata?: unknown; + }; interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; @@ -4843,7 +4699,7 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; @@ -4851,16 +4707,16 @@ declare namespace ts { getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getNavigationTree(fileName: string): NavigationTree; @@ -4882,9 +4738,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5012,7 +4868,7 @@ declare namespace ts { message: string; position: number; } - class TextChange { + interface TextChange { span: TextSpan; newText: string; } @@ -5046,9 +4902,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5114,6 +4977,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5191,24 +5056,25 @@ declare namespace ts { insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter?: boolean; - insertSpaceAfterSemicolonInForStatements?: boolean; - insertSpaceBeforeAndAfterBinaryOperators?: boolean; - insertSpaceAfterConstructor?: boolean; - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - insertSpaceAfterTypeAssertion?: boolean; - insertSpaceBeforeFunctionParenthesis?: boolean; - placeOpenBraceOnNewLineForFunctions?: boolean; - placeOpenBraceOnNewLineForControlBlocks?: boolean; - insertSpaceBeforeTypeAnnotation?: boolean; - indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + readonly insertSpaceAfterCommaDelimiter?: boolean; + readonly insertSpaceAfterSemicolonInForStatements?: boolean; + readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; + readonly insertSpaceAfterConstructor?: boolean; + readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + readonly insertSpaceAfterTypeAssertion?: boolean; + readonly insertSpaceBeforeFunctionParenthesis?: boolean; + readonly placeOpenBraceOnNewLineForFunctions?: boolean; + readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; + readonly insertSpaceBeforeTypeAnnotation?: boolean; + readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } + function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; @@ -5266,15 +5132,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; @@ -5392,8 +5267,9 @@ declare namespace ts { Whitespace = 4, Identifier = 5, NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8 + BigIntLiteral = 7, + StringLiteral = 8, + RegExpLiteral = 9 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -5505,13 +5381,20 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional" + optionalModifier = "optional", + dtsModifier = ".d.ts", + tsModifier = ".ts", + tsxModifier = ".tsx", + jsModifier = ".js", + jsxModifier = ".jsx", + jsonModifier = ".json" } enum ClassificationTypeNames { comment = "comment", identifier = "identifier", keyword = "keyword", numericLiteral = "number", + bigintLiteral = "bigint", operator = "operator", stringLiteral = "string", whiteSpace = "whitespace", @@ -5556,7 +5439,8 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24 + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 } } declare namespace ts { @@ -5648,6 +5532,10 @@ declare namespace ts { function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; } +declare namespace ts { + function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string; + function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string; +} declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; @@ -5737,7 +5625,6 @@ declare namespace ts.server { function ThrowProjectLanguageServiceDisabled(): never; function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; } - function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings; type NormalizedPath = string & { __normalizedPathTag: any; }; @@ -5751,24 +5638,6 @@ declare namespace ts.server { remove(path: NormalizedPath): void; } function createNormalizedPathMap(): NormalizedPathMap; - interface ProjectOptions { - configHasExtendsProperty: boolean; - /** - * true if config file explicitly listed files - */ - configHasFilesProperty: boolean; - configHasIncludeProperty: boolean; - configHasExcludeProperty: boolean; - projectReferences: ReadonlyArray | undefined; - /** - * these fields can be present in the project file - */ - files?: string[]; - wildcardDirectories?: Map; - compilerOptions?: CompilerOptions; - typeAcquisition?: TypeAcquisition; - compileOnSave?: boolean; - } function isInferredProjectName(name: string): boolean; function makeInferredProjectName(counter: number): string; function createSortedArray(): SortedArray; @@ -5836,7 +5705,8 @@ declare namespace ts.server.protocol { GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", OrganizeImports = "organizeImports", - GetEditsForFileRename = "getEditsForFileRename" + GetEditsForFileRename = "getEditsForFileRename", + ConfigurePlugin = "configurePlugin" } /** * A TypeScript Server message @@ -5911,6 +5781,10 @@ declare namespace ts.server.protocol { * Contains message body if success === true. */ body?: any; + /** + * Contains extra information that plugin can include to be passed on + */ + metadata?: unknown; } /** * Arguments for FileRequest messages. @@ -6556,7 +6430,7 @@ declare namespace ts.server.protocol { /** * The file locations referencing the symbol. */ - refs: ReferencesResponseItem[]; + refs: ReadonlyArray; /** * The name of the symbol. */ @@ -6602,15 +6476,17 @@ declare namespace ts.server.protocol { /** * Information about the item to be renamed. */ - interface RenameInfo { + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { /** * True if item can be renamed. */ - canRename: boolean; + canRename: true; /** - * Error message if item can not be renamed. + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ - localizedErrorMessage?: string; + fileToRename?: string; /** * Display name of the item to be renamed. */ @@ -6627,6 +6503,15 @@ declare namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; } /** * A group of text spans, all in 'file'. @@ -6635,7 +6520,11 @@ declare namespace ts.server.protocol { /** The file to which the spans apply */ file: string; /** The text spans in this group */ - locs: TextSpan[]; + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface RenameResponseBody { /** @@ -6770,6 +6659,14 @@ declare namespace ts.server.protocol { */ interface ConfigureResponse extends Response { } + interface ConfigurePluginRequestArguments { + pluginName: string; + configuration: any; + } + interface ConfigurePluginRequest extends Request { + command: CommandTypes.ConfigurePlugin; + arguments: ConfigurePluginRequestArguments; + } /** * Information found in an "open" request. */ @@ -7148,7 +7045,7 @@ declare namespace ts.server.protocol { * begin with prefix. */ interface CompletionsRequest extends FileLocationRequest { - command: CommandTypes.Completions; + command: CommandTypes.Completions | CommandTypes.CompletionInfo; arguments: CompletionsRequestArgs; } /** @@ -7607,6 +7504,7 @@ declare namespace ts.server.protocol { */ interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; + event: DiagnosticEventKind; } interface ConfigFileDiagnosticEventBody { /** @@ -7660,6 +7558,35 @@ declare namespace ts.server.protocol { */ openFiles: string[]; } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } type LargeFileReferencedEventName = "largeFileReferenced"; interface LargeFileReferencedEvent extends Event { event: LargeFileReferencedEventName; @@ -7995,6 +7922,7 @@ declare namespace ts.server.protocol { readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -8126,14 +8054,14 @@ declare namespace ts.server { getSnapshot(): IScriptSnapshot; private ensureRealPath; getFormatCodeSettings(): FormatCodeSettings | undefined; - getPreferences(): UserPreferences | undefined; + getPreferences(): protocol.UserPreferences | undefined; attachToProject(project: Project): boolean; isAttached(project: Project): boolean; detachFromProject(project: Project): void; detachAllProjects(): void; getDefaultProject(): Project; registerFileUpdate(): void; - setOptions(formatSettings: FormatCodeSettings, preferences: UserPreferences | undefined): void; + setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void; getLatestVersion(): string; saveTo(fileName: string): void; reloadFromFile(tempFileName?: NormalizedPath): boolean; @@ -8186,6 +8114,11 @@ declare namespace ts.server { interface PluginModule { create(createInfo: PluginCreateInfo): LanguageService; getExternalFiles?(proj: Project): string[]; + onConfigurationChanged?(config: any): void; + } + interface PluginModuleWithName { + name: string; + module: PluginModule; } type PluginModuleFactory = (mod: { typescript: typeof ts; @@ -8238,6 +8171,7 @@ declare namespace ts.server { * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project */ private projectStateVersion; + protected isInitialLoadPending: () => boolean; private readonly cancellationToken; isNonTsProject(): boolean; isJsOnlyProject(): boolean; @@ -8249,7 +8183,7 @@ declare namespace ts.server { getCompilerOptions(): CompilerOptions; getNewLine(): string; getProjectVersion(): string; - getProjectReferences(): ReadonlyArray; + getProjectReferences(): ReadonlyArray | undefined; getScriptFileNames(): string[]; private getOrCreateScriptInfoAndAttachToProject; getScriptKind(fileName: string): ScriptKind; @@ -8261,10 +8195,11 @@ declare namespace ts.server { useCaseSensitiveFileNames(): boolean; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile(fileName: string): string | undefined; + writeFile(fileName: string, content: string): void; fileExists(file: string): boolean; - resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[]; + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; directoryExists(path: string): boolean; getDirectories(path: string): string[]; log(s: string): void; @@ -8322,11 +8257,11 @@ declare namespace ts.server { filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; protected removeRoot(info: ScriptInfo): void; - protected enableGlobalPlugins(): void; - protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; + protected enableGlobalPlugins(options: CompilerOptions, pluginConfigOverrides: Map | undefined): void; + protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map | undefined): void; + private enableProxy; /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ refreshDiagnostics(): void; - private enableProxy; } /** * If a file is opened and no tsconfig (or jsconfig) is found, @@ -8351,23 +8286,22 @@ declare namespace ts.server { * Otherwise it will create an InferredProject. */ class ConfiguredProject extends Project { - compileOnSaveEnabled: boolean; - private projectReferences; private typeAcquisition; private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; /** Ref count to the project when opened from external project */ private externalProjectRefCount; private projectErrors; + private projectReferences; + protected isInitialLoadPending: () => boolean; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph * @returns: true if set of files in the project stays the same and false - otherwise. */ updateGraph(): boolean; getConfigFilePath(): NormalizedPath; - getProjectReferences(): ReadonlyArray; + getProjectReferences(): ReadonlyArray | undefined; updateReferences(refs: ReadonlyArray | undefined): void; - enablePlugins(): void; /** * Get the errors that dont have any file name associated */ @@ -8391,6 +8325,7 @@ declare namespace ts.server { compileOnSaveEnabled: boolean; excludedFiles: ReadonlyArray; private typeAcquisition; + updateGraph(): boolean; getExcludedFiles(): ReadonlyArray; getTypeAcquisition(): TypeAcquisition; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; @@ -8399,6 +8334,9 @@ declare namespace ts.server { declare namespace ts.server { const maxProgramSizeForNonTsFiles: number; const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + const ProjectLoadingStartEvent = "projectLoadingStart"; + const ProjectLoadingFinishEvent = "projectLoadingFinish"; + const SurveyReady = "surveyReady"; const LargeFileReferencedEvent = "largeFileReferenced"; const ConfigFileDiagEvent = "configFileDiag"; const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -8410,6 +8348,25 @@ declare namespace ts.server { openFiles: string[]; }; } + interface ProjectLoadingStartEvent { + eventName: typeof ProjectLoadingStartEvent; + data: { + project: Project; + reason: string; + }; + } + interface ProjectLoadingFinishEvent { + eventName: typeof ProjectLoadingFinishEvent; + data: { + project: Project; + }; + } + interface SurveyReady { + eventName: typeof SurveyReady; + data: { + surveyId: string; + }; + } interface LargeFileReferencedEvent { eventName: typeof LargeFileReferencedEvent; data: { @@ -8479,16 +8436,22 @@ declare namespace ts.server { } interface FileStats { readonly js: number; + readonly jsSize?: number; readonly jsx: number; + readonly jsxSize?: number; readonly ts: number; + readonly tsSize?: number; readonly tsx: number; + readonly tsxSize?: number; readonly dts: number; + readonly dtsSize?: number; readonly deferred: number; + readonly deferredSize?: number; } interface OpenFileInfo { readonly checkJs: boolean; } - type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; interface SafeList { [name: string]: { @@ -8509,7 +8472,7 @@ declare namespace ts.server { function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; interface HostConfiguration { formatCodeOptions: FormatCodeSettings; - preferences: UserPreferences; + preferences: protocol.UserPreferences; hostInfo: string; extraFileExtensions?: FileExtensionInfo[]; } @@ -8538,6 +8501,7 @@ declare namespace ts.server { * Container of all known scripts */ private readonly filenameToScriptInfo; + private readonly scriptInfoInNodeModulesWatchers; /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -8586,7 +8550,7 @@ declare namespace ts.server { private readonly throttledOperations; private readonly hostConfiguration; private safelist; - private legacySafelist; + private readonly legacySafelist; private pendingProjectUpdates; readonly currentDirectory: NormalizedPath; readonly toCanonicalFileName: (f: string) => string; @@ -8603,10 +8567,13 @@ declare namespace ts.server { readonly globalPlugins: ReadonlyArray; readonly pluginProbeLocations: ReadonlyArray; readonly allowLocalPluginLoads: boolean; + private currentPluginConfigOverrides; readonly typesMapLocation: string | undefined; readonly syntaxOnly?: boolean; /** Tracks projects that we have already sent telemetry for. */ private readonly seenProjects; + /** Tracks projects that we have already sent survey events for. */ + private readonly seenSurveyProjects; constructor(opts: ProjectServiceOptions); toPath(fileName: string): Path; private loadTypesMap; @@ -8628,9 +8595,9 @@ declare namespace ts.server { */ private ensureProjectStructuresUptoDate; getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; - getPreferences(file: NormalizedPath): UserPreferences; + getPreferences(file: NormalizedPath): protocol.UserPreferences; getHostFormatCodeOptions(): FormatCodeSettings; - getHostPreferences(): UserPreferences; + getHostPreferences(): protocol.UserPreferences; private onSourceFileChanged; private handleDeletedFile; private onConfigChangedForConfiguredProject; @@ -8692,15 +8659,13 @@ declare namespace ts.server { private findConfiguredProjectByProjectName; private getConfiguredProjectByCanonicalConfigFilePath; private findExternalProjectByProjectName; - private convertConfigFileContentToProjectOptions; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ private getFilenameForExceededTotalSizeLimitForNonTsFiles; private createExternalProject; - private sendProjectTelemetry; - private addFilesToNonInferredProjectAndUpdateGraph; + private addFilesToNonInferredProject; private createConfiguredProject; private updateNonInferredProjectFiles; - private updateNonInferredProject; + private updateRootAndOptionsOfNonInferredProject; private sendConfigFileDiagEvent; private getOrCreateInferredProjectForProjectRootPathIfEnabled; private getOrCreateSingleInferredProjectIfEnabled; @@ -8708,6 +8673,10 @@ declare namespace ts.server { private createInferredProject; getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; private watchClosedScriptInfo; + private watchClosedScriptInfoInNodeModules; + private getModifiedTime; + private refreshScriptInfo; + private refreshScriptInfosInDirectory; private stopWatchingScriptInfo; private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; private getOrCreateScriptInfoOpenedByClientForNormalizedPath; @@ -8774,6 +8743,7 @@ declare namespace ts.server { applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; openExternalProject(proj: protocol.ExternalProject): void; hasDeferredExtension(): boolean; + configurePlugin(args: protocol.ConfigurePluginRequestArguments): void; } } declare namespace ts.server { @@ -8815,6 +8785,7 @@ declare namespace ts.server { globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; + typesMapLocation?: string; } class Session implements EventSender { private readonly gcTimer; @@ -8837,6 +8808,7 @@ declare namespace ts.server { private defaultEventHandler; private projectsUpdatedInBackgroundEvent; logError(err: Error, cmd: string): void; + private logErrorWorker; send(msg: protocol.Message): void; event(body: T, eventName: string): void; /** @deprecated */ @@ -8881,7 +8853,7 @@ declare namespace ts.server { private getProjects; private getDefaultProject; private getRenameLocations; - private static mapRenameInfo; + private mapRenameInfo; private toSpanGroups; private getReferences; /** @@ -8928,7 +8900,7 @@ declare namespace ts.server { private getFullNavigateToItems; private getSupportedCodeFixes; private isLocation; - private extractPositionAndRange; + private extractPositionOrRange; private getApplicableRefactors; private getEditsForRefactor; private organizeImports; @@ -8944,6 +8916,7 @@ declare namespace ts.server { private convertTextChangeToCodeEdit; private getBraceMatching; private getDiagnosticsForProject; + private configurePlugin; getCanonicalFileName(fileName: string): string; exit(): void; private notRequired; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 19046c62c9a..d89c5621ef6 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -62,18 +62,27 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -88,6 +97,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -477,10 +487,33 @@ var ts; return result; } ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ function flatMap(array, mapfn) { var result; if (array) { - result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { for (var i = 0; i < array.length; i++) { var v = mapfn(array[i], i); if (v) { @@ -495,7 +528,7 @@ var ts; } return result; } - ts.flatMap = flatMap; + ts.flatMapToMutable = flatMapToMutable; function flatMapIterator(iter, mapfn) { var first = iter.next(); if (first.done) { @@ -716,19 +749,25 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) - return []; + return ts.emptyArray; var last = array[0]; var deduplicated = [last]; for (var i = 1; i < array.length; i++) { @@ -759,7 +798,7 @@ var ts; } ts.insertSorted = insertSorted; function sortAndDeduplicate(array, comparer, equalityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); } ts.sortAndDeduplicate = sortAndDeduplicate; function arrayIsEqualTo(array1, array2, equalityComparer) { @@ -771,7 +810,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -912,7 +951,7 @@ var ts; * Returns a new sorted array. */ function sort(array, comparer) { - return array.slice().sort(comparer); + return (array.length === 0 ? array : array.slice().sort(comparer)); } ts.sort = sort; function arrayIterator(array) { @@ -1018,12 +1057,25 @@ var ts; * @param offset An offset into `array` at which to start the search. */ function binarySearch(array, value, keySelector, keyComparer, offset) { - if (!array || array.length === 0) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { return -1; } var low = offset || 0; var high = array.length - 1; - var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); var midKey = keySelector(array[middle]); @@ -1040,7 +1092,7 @@ var ts; } return ~low; } - ts.binarySearch = binarySearch; + ts.binarySearchKey = binarySearchKey; function reduceLeft(array, f, initial, start, count) { if (array && array.length > 0) { var size = array.length; @@ -1148,7 +1200,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1320,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1432,7 +1488,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1935,6 +1993,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -1954,6 +2016,33 @@ var ts; var counts; var marks; var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; /** * Marks a performance event. * @@ -2029,6 +2118,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2048,368 +2497,370 @@ var ts; SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; // Literals SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; - SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; - SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; // Pseudo-literals - SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; + SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail"; // Punctuation - SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken"; // Assignments - SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken"; // Identifiers - SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; + SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier"; // Reserved words - SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword"; // Strict mode reserved words - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword"; // Contextual keywords - SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; - SyntaxKind[SyntaxKind["InferKeyword"] = 126] = "InferKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 127] = "IsKeyword"; - SyntaxKind[SyntaxKind["KeyOfKeyword"] = 128] = "KeyOfKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 129] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 130] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 131] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 132] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 133] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 134] = "NumberKeyword"; - SyntaxKind[SyntaxKind["ObjectKeyword"] = 135] = "ObjectKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 136] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 137] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 138] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword"; - SyntaxKind[SyntaxKind["UnknownKeyword"] = 142] = "UnknownKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 143] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 144] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 145] = "OfKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 146] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 147] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 148] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 149] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 150] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 151] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 152] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 153] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 154] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 155] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 156] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 157] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 158] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 159] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 160] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 161] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 162] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 163] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 164] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 165] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 166] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 167] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 168] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 169] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 170] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 171] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 172] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 173] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 174] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 175] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 176] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 177] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 178] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 179] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 180] = "LiteralType"; - SyntaxKind[SyntaxKind["ImportType"] = 181] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 182] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 183] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 184] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 185] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 186] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 187] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 188] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 189] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 190] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 191] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 192] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 193] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 194] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 195] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 196] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 197] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 198] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 199] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 200] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 201] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 202] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 203] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 204] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 205] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 206] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 207] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 208] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 209] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 210] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 211] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 212] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 213] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 214] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 215] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 216] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 217] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 218] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 219] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 220] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 221] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 222] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 223] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 224] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 225] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 226] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 227] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 228] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 229] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 230] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 231] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 232] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 233] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 234] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 235] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 236] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 237] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 238] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 239] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 240] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 241] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 242] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 243] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 244] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 245] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 246] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 247] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 248] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 249] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 250] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 251] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 252] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 253] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 254] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 255] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 256] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 218] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 257] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 258] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 259] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 260] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 261] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 262] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 263] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 264] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 265] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 266] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 267] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 268] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 269] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 270] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 271] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 272] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 273] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 274] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 275] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 276] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 277] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 278] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 279] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 280] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 281] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 282] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 283] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 284] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 285] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 286] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 287] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 288] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 289] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 290] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 291] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 292] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 310] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; // Markers - SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 145] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 161] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 181] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 145] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode"; - /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -2609,7 +3060,10 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; + // Errors (cont.) + NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors"; // State NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; @@ -2665,6 +3119,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2696,14 +3152,15 @@ var ts; // of a type, such as the global `Promise` type in lib.d.ts). TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; // with call signatures. - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var SymbolFlags; (function (SymbolFlags) { @@ -2734,38 +3191,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2840,14 +3297,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2857,29 +3315,27 @@ var ts; TypeFlags[TypeFlags["Number"] = 8] = "Number"; TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 64] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 128] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 256] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 512] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 1024] = "ESSymbol"; - TypeFlags[TypeFlags["UniqueESSymbol"] = 2048] = "UniqueESSymbol"; - TypeFlags[TypeFlags["Void"] = 4096] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 8192] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 16384] = "Null"; - TypeFlags[TypeFlags["Never"] = 32768] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 65536] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 131072] = "Object"; - TypeFlags[TypeFlags["Union"] = 262144] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 524288] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 1048576] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 2097152] = "IndexedAccess"; - TypeFlags[TypeFlags["Conditional"] = 4194304] = "Conditional"; - TypeFlags[TypeFlags["Substitution"] = 8388608] = "Substitution"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; - /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; - /* @internal */ - TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes"; + TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt"; + TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 16384] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 65536] = "Null"; + TypeFlags[TypeFlags["Never"] = 131072] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 524288] = "Object"; + TypeFlags[TypeFlags["Union"] = 1048576] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 4194304] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; /* @internal */ TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ @@ -2889,40 +3345,41 @@ var ts; /* @internal */ TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 24576] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 448] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 27072] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 192] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 2944] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 2240] = "StringOrNumberLiteralOrUnique"; + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 29120] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 29148] = "PossiblyFalsy"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 16839967] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 32764] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 68] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 168] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 272] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 544] = "EnumLike"; - TypeFlags[TypeFlags["ESSymbolLike"] = 3072] = "ESSymbolLike"; - TypeFlags[TypeFlags["VoidLike"] = 12288] = "VoidLike"; + TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike"; + TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; /* @internal */ - TypeFlags[TypeFlags["DisjointDomains"] = 16809468] = "DisjointDomains"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 786432] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 917504] = "StructuredType"; - TypeFlags[TypeFlags["TypeVariable"] = 2162688] = "TypeVariable"; - TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 14745600] = "InstantiableNonPrimitive"; - TypeFlags[TypeFlags["InstantiablePrimitive"] = 1048576] = "InstantiablePrimitive"; - TypeFlags[TypeFlags["Instantiable"] = 15794176] = "Instantiable"; - TypeFlags[TypeFlags["StructuredOrInstantiable"] = 16711680] = "StructuredOrInstantiable"; + TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion"; + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ @@ -2957,6 +3414,7 @@ var ts; ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -2968,6 +3426,13 @@ var ts; Variance[Variance["Bivariant"] = 3] = "Bivariant"; Variance[Variance["Independent"] = 4] = "Independent"; })(Variance = ts.Variance || (ts.Variance = {})); + /* @internal */ + var JsxReferenceKind; + (function (JsxReferenceKind) { + JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component"; + JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function"; + JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed"; + })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {})); var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; @@ -2993,9 +3458,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3478,31 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue"; + // Object.defineProperty(exports || module.exports, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports"; + // Object.defineProperty(Foo.prototype, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3266,25 +3739,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3303,25 +3772,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3401,6 +3869,7 @@ var ts; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; + EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); var ListFormat; (function (ListFormat) { @@ -3415,64 +3884,66 @@ var ts; ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma"; // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + ListFormat[ListFormat["Indented"] = 128] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings"; // Brackets/Braces - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + ListFormat[ListFormat["Braces"] = 1024] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 49152] = "Optional"; // Other - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; + ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters"; + ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment"; })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); /* @internal */ var PragmaKindFlags; @@ -3565,20 +4036,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3796,17 +4253,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4127,11 +4588,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4742,7 +5204,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5243,11 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4793,7 +5260,7 @@ var ts; An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), - An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), @@ -4837,14 +5304,14 @@ var ts; Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), @@ -4900,7 +5367,7 @@ var ts; Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), - A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), @@ -4983,7 +5450,7 @@ var ts; _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), - Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), @@ -5014,7 +5481,7 @@ var ts; Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), @@ -5024,7 +5491,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5518,15 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5618,15 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5740,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5836,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5934,18 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5976,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5488,6 +5986,7 @@ var ts; _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), @@ -5515,6 +6014,15 @@ var ts; If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5545,6 +6053,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5609,6 +6118,7 @@ var ts; Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -5673,150 +6183,108 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { - return token >= 71 /* Identifier */; + return token >= 72 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; /* @internal */ function tokenIsIdentifierOrKeywordOrGreaterThan(token) { - return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 118 /* AbstractKeyword */, + any: 120 /* AnyKeyword */, + as: 119 /* AsKeyword */, + bigint: 146 /* BigIntKeyword */, + boolean: 123 /* BooleanKeyword */, + break: 73 /* BreakKeyword */, + case: 74 /* CaseKeyword */, + catch: 75 /* CatchKeyword */, + class: 76 /* ClassKeyword */, + continue: 78 /* ContinueKeyword */, + const: 77 /* ConstKeyword */ + }, + _a["" + "constructor"] = 124 /* ConstructorKeyword */, + _a.debugger = 79 /* DebuggerKeyword */, + _a.declare = 125 /* DeclareKeyword */, + _a.default = 80 /* DefaultKeyword */, + _a.delete = 81 /* DeleteKeyword */, + _a.do = 82 /* DoKeyword */, + _a.else = 83 /* ElseKeyword */, + _a.enum = 84 /* EnumKeyword */, + _a.export = 85 /* ExportKeyword */, + _a.extends = 86 /* ExtendsKeyword */, + _a.false = 87 /* FalseKeyword */, + _a.finally = 88 /* FinallyKeyword */, + _a.for = 89 /* ForKeyword */, + _a.from = 144 /* FromKeyword */, + _a.function = 90 /* FunctionKeyword */, + _a.get = 126 /* GetKeyword */, + _a.if = 91 /* IfKeyword */, + _a.implements = 109 /* ImplementsKeyword */, + _a.import = 92 /* ImportKeyword */, + _a.in = 93 /* InKeyword */, + _a.infer = 127 /* InferKeyword */, + _a.instanceof = 94 /* InstanceOfKeyword */, + _a.interface = 110 /* InterfaceKeyword */, + _a.is = 128 /* IsKeyword */, + _a.keyof = 129 /* KeyOfKeyword */, + _a.let = 111 /* LetKeyword */, + _a.module = 130 /* ModuleKeyword */, + _a.namespace = 131 /* NamespaceKeyword */, + _a.never = 132 /* NeverKeyword */, + _a.new = 95 /* NewKeyword */, + _a.null = 96 /* NullKeyword */, + _a.number = 135 /* NumberKeyword */, + _a.object = 136 /* ObjectKeyword */, + _a.package = 112 /* PackageKeyword */, + _a.private = 113 /* PrivateKeyword */, + _a.protected = 114 /* ProtectedKeyword */, + _a.public = 115 /* PublicKeyword */, + _a.readonly = 133 /* ReadonlyKeyword */, + _a.require = 134 /* RequireKeyword */, + _a.global = 145 /* GlobalKeyword */, + _a.return = 97 /* ReturnKeyword */, + _a.set = 137 /* SetKeyword */, + _a.static = 116 /* StaticKeyword */, + _a.string = 138 /* StringKeyword */, + _a.super = 98 /* SuperKeyword */, + _a.switch = 99 /* SwitchKeyword */, + _a.symbol = 139 /* SymbolKeyword */, + _a.this = 100 /* ThisKeyword */, + _a.throw = 101 /* ThrowKeyword */, + _a.true = 102 /* TrueKeyword */, + _a.try = 103 /* TryKeyword */, + _a.type = 140 /* TypeKeyword */, + _a.typeof = 104 /* TypeOfKeyword */, + _a.undefined = 141 /* UndefinedKeyword */, + _a.unique = 142 /* UniqueKeyword */, + _a.unknown = 143 /* UnknownKeyword */, + _a.var = 105 /* VarKeyword */, + _a.void = 106 /* VoidKeyword */, + _a.while = 107 /* WhileKeyword */, + _a.with = 108 /* WithKeyword */, + _a.yield = 117 /* YieldKeyword */, + _a.async = 121 /* AsyncKeyword */, + _a.await = 122 /* AwaitKeyword */, + _a.of = 147 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, ">": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -5951,11 +6419,28 @@ var ts; } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { - ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } } var res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } if (line < lineStarts.length - 1) { ts.Debug.assert(res < lineStarts[line + 1]); } @@ -6394,6 +6879,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6404,8 +6890,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, - isIdentifier: function () { return token === 71 /* Identifier */ || token > 107 /* LastReservedWord */; }, - isReservedWord: function () { return token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */; }, + isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; }, isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, @@ -6423,6 +6909,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6498,18 +6985,29 @@ var ts; end = pos; } } + var result; if (tokenFlags & 512 /* ContainsSeparator */) { - var result = mainFragment; + result = mainFragment; if (decimalFragment) { result += "." + decimalFragment; } if (scientificFragment) { result += scientificFragment; } - return "" + +result; } else { - return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + return { + type: 8 /* NumericLiteral */, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type: type, value: tokenValue }; } } function scanOctalDigits() { @@ -6524,21 +7022,21 @@ var ts; * returning -1 if the given number is unavailable. */ function scanExactNumberOfHexDigits(count, canHaveSeparators) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; } /** * Scans as many hexadecimal digits as are available in the text, - * returning -1 if the given number of digits was unavailable. + * returning "" if the given number of digits was unavailable. */ function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { - var digits = 0; - var value = 0; + var valueChars = []; var allowSeparator = false; var isPreviousTokenSeparator = false; - while (digits < minCount || scanAsManyAsPossible) { + while (valueChars.length < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); if (canHaveSeparators && ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; @@ -6556,29 +7054,24 @@ var ts; continue; } allowSeparator = canHaveSeparators; - if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { - value = value * 16 + ch - 48 /* _0 */; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase } - else if (ch >= 65 /* A */ && ch <= 70 /* F */) { - value = value * 16 + ch - 65 /* A */ + 10; - } - else if (ch >= 97 /* a */ && ch <= 102 /* f */) { - value = value * 16 + ch - 97 /* a */ + 10; - } - else { + else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) || + (ch >= 97 /* a */ && ch <= 102 /* f */))) { break; } + valueChars.push(ch); pos++; - digits++; isPreviousTokenSeparator = false; } - if (digits < minCount) { - value = -1; + if (valueChars.length < minCount) { + valueChars = []; } if (text.charCodeAt(pos - 1) === 95 /* _ */) { error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } - return value; + return String.fromCharCode.apply(String, valueChars); } function scanString(jsxAttributeString) { if (jsxAttributeString === void 0) { jsxAttributeString = false; } @@ -6630,7 +7123,7 @@ var ts; contents += text.substring(start, pos); tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; break; } var currChar = text.charCodeAt(pos); @@ -6638,14 +7131,14 @@ var ts; if (currChar === 96 /* backtick */) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; break; } // '${' if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 14 /* TemplateHead */ : 15 /* TemplateMiddle */; + resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */; break; } // Escape character @@ -6738,7 +7231,8 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; var isInvalidExtendedEscape = false; // Validate the value of the digit if (escapedValue < 0) { @@ -6820,20 +7314,18 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } - return token = 71 /* Identifier */; + return token = 72 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); - var value = 0; + var value = ""; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. - var numberOfDigits = 0; var separatorAllowed = false; var isPreviousTokenSeparator = false; while (true) { @@ -6855,29 +7347,45 @@ var ts; continue; } separatorAllowed = true; - var valueOfCh = ch - 48 /* _0 */; - if (!isDigit(ch) || valueOfCh >= base) { + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { break; } - value = value * base + valueOfCh; + value += text[pos]; pos++; - numberOfDigits++; isPreviousTokenSeparator = false; } - // Invalid binaryIntegerLiteral or octalIntegerLiteral - if (numberOfDigits === 0) { - return -1; - } if (text.charCodeAt(pos - 1) === 95 /* _ */) { // Literal ends with underscore - not allowed error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); - return value; } return value; } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110 /* n */) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9 /* BigIntLiteral */; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + var numericValue = tokenFlags & 128 /* BinarySpecifier */ + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & 256 /* OctalSpecifier */ + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return 8 /* NumericLiteral */; + } + } function scan() { + var _a; startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7424,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6929,82 +7455,87 @@ var ts; case 33 /* exclamation */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 35 /* ExclamationEqualsEqualsToken */; + return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */; } - return pos += 2, token = 33 /* ExclamationEqualsToken */; + return pos += 2, token = 34 /* ExclamationEqualsToken */; } pos++; - return token = 51 /* ExclamationToken */; + return token = 52 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); - return token = 9 /* StringLiteral */; + return token = 10 /* StringLiteral */; case 96 /* backtick */: return token = scanTemplateAndSetTokenValue(); case 37 /* percent */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 64 /* PercentEqualsToken */; + return pos += 2, token = 65 /* PercentEqualsToken */; } pos++; - return token = 42 /* PercentToken */; + return token = 43 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { - return pos += 2, token = 53 /* AmpersandAmpersandToken */; + return pos += 2, token = 54 /* AmpersandAmpersandToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 68 /* AmpersandEqualsToken */; + return pos += 2, token = 69 /* AmpersandEqualsToken */; } pos++; - return token = 48 /* AmpersandToken */; + return token = 49 /* AmpersandToken */; case 40 /* openParen */: pos++; - return token = 19 /* OpenParenToken */; + return token = 20 /* OpenParenToken */; case 41 /* closeParen */: pos++; - return token = 20 /* CloseParenToken */; + return token = 21 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 61 /* AsteriskEqualsToken */; + return pos += 2, token = 62 /* AsteriskEqualsToken */; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 62 /* AsteriskAsteriskEqualsToken */; + return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */; } - return pos += 2, token = 40 /* AsteriskAsteriskToken */; + return pos += 2, token = 41 /* AsteriskAsteriskToken */; } pos++; - return token = 39 /* AsteriskToken */; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } + return token = 40 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { - return pos += 2, token = 43 /* PlusPlusToken */; + return pos += 2, token = 44 /* PlusPlusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 59 /* PlusEqualsToken */; + return pos += 2, token = 60 /* PlusEqualsToken */; } pos++; - return token = 37 /* PlusToken */; + return token = 38 /* PlusToken */; case 44 /* comma */: pos++; - return token = 26 /* CommaToken */; + return token = 27 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { - return pos += 2, token = 44 /* MinusMinusToken */; + return pos += 2, token = 45 /* MinusMinusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 60 /* MinusEqualsToken */; + return pos += 2, token = 61 /* MinusEqualsToken */; } pos++; - return token = 38 /* MinusToken */; + return token = 39 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber(); + tokenValue = scanNumber().value; return token = 8 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { - return pos += 3, token = 24 /* DotDotDotToken */; + return pos += 3, token = 25 /* DotDotDotToken */; } pos++; - return token = 23 /* DotToken */; + return token = 24 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -7055,43 +7586,43 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 63 /* SlashEqualsToken */; + return pos += 2, token = 64 /* SlashEqualsToken */; } pos++; - return token = 41 /* SlashToken */; + return token = 42 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); - if (value < 0) { + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { error(ts.Diagnostics.Hexadecimal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0x" + tokenValue; tokenFlags |= 64 /* HexSpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 2); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { error(ts.Diagnostics.Binary_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0b" + tokenValue; tokenFlags |= 128 /* BinarySpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 8); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { error(ts.Diagnostics.Octal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0o" + tokenValue; tokenFlags |= 256 /* OctalSpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } // Try to parse as an octal if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { @@ -7112,14 +7643,14 @@ var ts; case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - tokenValue = scanNumber(); - return token = 8 /* NumericLiteral */; + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; case 58 /* colon */: pos++; - return token = 56 /* ColonToken */; + return token = 57 /* ColonToken */; case 59 /* semicolon */: pos++; - return token = 25 /* SemicolonToken */; + return token = 26 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7132,20 +7663,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 65 /* LessThanLessThanEqualsToken */; + return pos += 3, token = 66 /* LessThanLessThanEqualsToken */; } - return pos += 2, token = 45 /* LessThanLessThanToken */; + return pos += 2, token = 46 /* LessThanLessThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 30 /* LessThanEqualsToken */; + return pos += 2, token = 31 /* LessThanEqualsToken */; } if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */) { - return pos += 2, token = 28 /* LessThanSlashToken */; + return pos += 2, token = 29 /* LessThanSlashToken */; } pos++; - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7158,15 +7689,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 34 /* EqualsEqualsEqualsToken */; + return pos += 3, token = 35 /* EqualsEqualsEqualsToken */; } - return pos += 2, token = 32 /* EqualsEqualsToken */; + return pos += 2, token = 33 /* EqualsEqualsToken */; } if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { - return pos += 2, token = 36 /* EqualsGreaterThanToken */; + return pos += 2, token = 37 /* EqualsGreaterThanToken */; } pos++; - return token = 58 /* EqualsToken */; + return token = 59 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7178,25 +7709,25 @@ var ts; } } pos++; - return token = 29 /* GreaterThanToken */; + return token = 30 /* GreaterThanToken */; case 63 /* question */: pos++; - return token = 55 /* QuestionToken */; + return token = 56 /* QuestionToken */; case 91 /* openBracket */: pos++; - return token = 21 /* OpenBracketToken */; + return token = 22 /* OpenBracketToken */; case 93 /* closeBracket */: pos++; - return token = 22 /* CloseBracketToken */; + return token = 23 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 70 /* CaretEqualsToken */; + return pos += 2, token = 71 /* CaretEqualsToken */; } pos++; - return token = 50 /* CaretToken */; + return token = 51 /* CaretToken */; case 123 /* openBrace */: pos++; - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; case 124 /* bar */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7208,22 +7739,22 @@ var ts; } } if (text.charCodeAt(pos + 1) === 124 /* bar */) { - return pos += 2, token = 54 /* BarBarToken */; + return pos += 2, token = 55 /* BarBarToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 69 /* BarEqualsToken */; + return pos += 2, token = 70 /* BarEqualsToken */; } pos++; - return token = 49 /* BarToken */; + return token = 50 /* BarToken */; case 125 /* closeBrace */: pos++; - return token = 18 /* CloseBraceToken */; + return token = 19 /* CloseBraceToken */; case 126 /* tilde */: pos++; - return token = 52 /* TildeToken */; + return token = 53 /* TildeToken */; case 64 /* at */: pos++; - return token = 57 /* AtToken */; + return token = 58 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -7261,29 +7792,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 29 /* GreaterThanToken */) { + if (token === 30 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } - return pos += 2, token = 47 /* GreaterThanGreaterThanGreaterThanToken */; + return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 66 /* GreaterThanGreaterThanEqualsToken */; + return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */; } pos++; - return token = 46 /* GreaterThanGreaterThanToken */; + return token = 47 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { pos++; - return token = 31 /* GreaterThanEqualsToken */; + return token = 32 /* GreaterThanEqualsToken */; } } return token; } function reScanSlashToken() { - if (token === 41 /* SlashToken */ || token === 63 /* SlashEqualsToken */) { + if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -7328,7 +7859,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12 /* RegularExpressionLiteral */; + token = 13 /* RegularExpressionLiteral */; } return token; } @@ -7336,7 +7867,7 @@ var ts; * Unconditionally back up and scan a template expression portion. */ function reScanTemplateToken() { - ts.Debug.assert(token === 18 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -7353,14 +7884,14 @@ var ts; if (char === 60 /* lessThan */) { if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; - return token = 28 /* LessThanSlashToken */; + return token = 29 /* LessThanSlashToken */; } pos++; - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; } if (char === 123 /* openBrace */) { pos++; - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; } // First non-whitespace character on this line. var firstNonWhitespace = 0; @@ -7392,7 +7923,7 @@ var ts; } pos++; } - return firstNonWhitespace === -1 ? 11 /* JsxTextAllWhiteSpaces */ : 10 /* JsxText */; + return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -7418,7 +7949,7 @@ var ts; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(/*jsxAttributeString*/ true); - return token = 9 /* StringLiteral */; + return token = 10 /* StringLiteral */; default: // If this scans anything other than `{`, it's a parse error. return scan(); @@ -7442,43 +7973,43 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - return token = 57 /* AtToken */; + return token = 58 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - return token = 39 /* AsteriskToken */; + return token = 40 /* AsteriskToken */; case 123 /* openBrace */: - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; case 125 /* closeBrace */: - return token = 18 /* CloseBraceToken */; + return token = 19 /* CloseBraceToken */; case 91 /* openBracket */: - return token = 21 /* OpenBracketToken */; + return token = 22 /* OpenBracketToken */; case 93 /* closeBracket */: - return token = 22 /* CloseBracketToken */; + return token = 23 /* CloseBracketToken */; case 60 /* lessThan */: - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; case 61 /* equals */: - return token = 58 /* EqualsToken */; + return token = 59 /* EqualsToken */; case 44 /* comma */: - return token = 26 /* CommaToken */; + return token = 27 /* CommaToken */; case 46 /* dot */: - return token = 23 /* DotToken */; + return token = 24 /* DotToken */; case 96 /* backtick */: while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { pos++; } tokenValue = text.substring(tokenPos + 1, pos); pos++; - return token = 13 /* NoSubstitutionTemplateLiteral */; + return token = 14 /* NoSubstitutionTemplateLiteral */; } if (isIdentifierStart(ch, 6 /* Latest */)) { while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7555,10 +8086,12 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); -/** Non-internal stuff goes here */ var ts; (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -7575,7 +8108,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7622,7 +8154,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -7631,7 +8162,9 @@ var ts; writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, - writeSymbol: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, getTextPos: function () { return str.length; }, getLine: function () { return 0; }, getColumn: function () { return 0; }, @@ -7657,22 +8190,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8297,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -7837,7 +8363,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 277 /* SourceFile */) { + while (node && node.kind !== 279 /* SourceFile */) { node = node.parent; } return node; @@ -7845,11 +8371,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 216 /* Block */: - case 244 /* CaseBlock */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return true; } return false; @@ -7983,7 +8509,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8001,12 +8527,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,35 +8567,37 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) || + ts.isBigIntLiteral(node))) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (node.singleQuote) { return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; } else { return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; } - case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return "`" + escapeText(node.text, 96 /* backtick */) + "`"; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: // tslint:disable-next-line no-invalid-template-strings return "`" + escapeText(node.text, 96 /* backtick */) + "${"; - case 15 /* TemplateMiddle */: + case 16 /* TemplateMiddle */: // tslint:disable-next-line no-invalid-template-strings return "}" + escapeText(node.text, 96 /* backtick */) + "${"; - case 16 /* TemplateTail */: + case 17 /* TemplateTail */: return "}" + escapeText(node.text, 96 /* backtick */) + "`"; case 8 /* NumericLiteral */: - case 12 /* RegularExpressionLiteral */: + case 9 /* BigIntLiteral */: + case 13 /* RegularExpressionLiteral */: return node.text; } return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -8084,15 +8620,15 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 235 /* VariableDeclaration */ && node.parent.kind === 272 /* CatchClause */; + return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { - return ts.isModuleDeclaration(node) && node.name.kind === 9 /* StringLiteral */; + return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */; } ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { @@ -8116,11 +8652,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 242 /* ModuleDeclaration */ && (!node.body); + return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 277 /* SourceFile */ || - node.kind === 242 /* ModuleDeclaration */ || + return node.kind === 279 /* SourceFile */ || + node.kind === 244 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -8137,9 +8673,9 @@ var ts; // - 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 switch (node.parent.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.isExternalModule(node.parent); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; @@ -8155,22 +8691,22 @@ var ts; ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 277 /* SourceFile */: - case 244 /* CaseBlock */: - case 272 /* CatchClause */: - case 242 /* ModuleDeclaration */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 274 /* CatchClause */: + case 244 /* ModuleDeclaration */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; - case 216 /* Block */: + case 218 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -8180,9 +8716,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: - case 291 /* JSDocSignature */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 293 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -8192,25 +8728,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 287 /* JSDocFunctionType */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; default: ts.assertType(node); @@ -8220,8 +8756,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: return true; default: return false; @@ -8230,15 +8766,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 217 /* VariableStatement */: - case 238 /* ClassDeclaration */: - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 219 /* VariableStatement */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: return true; default: return false; @@ -8268,12 +8804,13 @@ var ts; ts.getNameFromIndexInfo = getNameFromIndexInfo; function getTextOfPropertyName(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return name.escapedText; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: return ts.Debug.assertNever(name); @@ -8282,11 +8819,11 @@ var ts; ts.getTextOfPropertyName = getTextOfPropertyName; function entityNameToString(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); default: throw ts.Debug.assertNever(name); @@ -8331,7 +8868,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 216 /* Block */) { + if (node.body && node.body.kind === 218 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -8345,7 +8882,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* 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 @@ -8354,25 +8891,25 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 240 /* TypeAliasDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: errorNode = node.name; break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -8408,6 +8945,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8417,11 +8958,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 189 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; + return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 189 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { @@ -8429,20 +8970,20 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 219 /* ExpressionStatement */ - && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 221 /* ExpressionStatement */ + && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return node.kind !== 10 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 149 /* Parameter */ || - node.kind === 148 /* TypeParameter */ || - node.kind === 194 /* FunctionExpression */ || - node.kind === 195 /* ArrowFunction */ || - node.kind === 193 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 151 /* Parameter */ || + node.kind === 150 /* TypeParameter */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 197 /* ArrowFunction */ || + node.kind === 195 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -8458,46 +8999,48 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 181 /* LastTypeNode */) { + if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) { return true; } switch (node.kind) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 134 /* NumberKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 140 /* UndefinedKeyword */: - case 131 /* NeverKeyword */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: return true; - case 105 /* VoidKeyword */: - return node.parent.kind !== 198 /* VoidExpression */; - case 209 /* ExpressionWithTypeArguments */: + case 106 /* VoidKeyword */: + return node.parent.kind !== 200 /* VoidExpression */; + case 211 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 148 /* TypeParameter */: - return node.parent.kind === 179 /* MappedType */ || node.parent.kind === 174 /* InferType */; + case 150 /* TypeParameter */: + return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container - case 71 /* Identifier */: + case 72 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 189 /* 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 === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 187 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 146 /* QualifiedName */: - case 187 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: { + case 148 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + case 100 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 165 /* TypeQuery */) { + if (parent.kind === 167 /* TypeQuery */) { return false; } - if (parent.kind === 181 /* ImportType */) { + if (parent.kind === 183 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -8506,40 +9049,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 181 /* LastTypeNode */) { + if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return node === parent.constraint; - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return node === parent.constraint; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 149 /* Parameter */: - case 235 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: return node === parent.type; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return node === parent.type; - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return node === parent.type; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return node === parent.type; - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -8564,23 +9107,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitor(node); - case 244 /* CaseBlock */: - case 216 /* Block */: - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 229 /* WithStatement */: - case 230 /* SwitchStatement */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 231 /* LabeledStatement */: - case 233 /* TryStatement */: - case 272 /* CatchClause */: + case 246 /* CaseBlock */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -8590,26 +9133,26 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 241 /* EnumDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* 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. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 147 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 149 /* 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(node.name.expression); @@ -8632,10 +9175,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 167 /* ArrayType */) { + if (node && node.kind === 169 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 162 /* TypeReference */) { + else if (node && node.kind === 164 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -8645,12 +9188,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 166 /* TypeLiteral */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 168 /* TypeLiteral */: return node.members; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return node.properties; } } @@ -8658,14 +9201,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 184 /* BindingElement */: - case 276 /* EnumMember */: - case 149 /* Parameter */: - case 273 /* PropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 274 /* ShorthandPropertyAssignment */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 278 /* EnumMember */: + case 151 /* Parameter */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 276 /* ShorthandPropertyAssignment */: + case 237 /* VariableDeclaration */: return true; } } @@ -8677,8 +9220,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 236 /* VariableDeclarationList */ - && node.parent.parent.kind === 217 /* VariableStatement */; + return node.parent.kind === 238 /* VariableDeclarationList */ + && node.parent.parent.kind === 219 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -8689,13 +9232,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return true; } return false; @@ -8706,7 +9249,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 231 /* LabeledStatement */) { + if (node.statement.kind !== 233 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -8714,17 +9257,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 216 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 186 /* ObjectLiteralExpression */; + return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 154 /* MethodDeclaration */ && - (node.parent.kind === 186 /* ObjectLiteralExpression */ || - node.parent.kind === 207 /* ClassExpression */); + return node.kind === 156 /* MethodDeclaration */ && + (node.parent.kind === 188 /* ObjectLiteralExpression */ || + node.parent.kind === 209 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -8737,7 +9280,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 273 /* PropertyAssignment */) { + if (property.kind === 275 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -8774,14 +9317,14 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 277 /* SourceFile */); + ts.Debug.assert(node.kind !== 279 /* SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* 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 @@ -8796,9 +9339,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8809,26 +9352,26 @@ var ts; node = node.parent; } break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 242 /* ModuleDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 241 /* EnumDeclaration */: - case 277 /* SourceFile */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 244 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 243 /* EnumDeclaration */: + case 279 /* SourceFile */: return node; } } @@ -8838,9 +9381,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return container; } } @@ -8862,27 +9405,27 @@ var ts; return node; } switch (node.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: node = node.parent; break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return node; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8898,14 +9441,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 194 /* FunctionExpression */ || func.kind === 195 /* ArrowFunction */) { + if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 193 /* ParenthesizedExpression */) { + while (parent.kind === 195 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 189 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -8916,8 +9459,8 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) - && node.expression.kind === 97 /* SuperKeyword */; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 98 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; /** @@ -8925,20 +9468,20 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) - && node.expression.kind === 99 /* ThisKeyword */; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 100 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; - case 71 /* Identifier */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 148 /* QualifiedName */: return node; } return undefined; @@ -8946,10 +9489,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return node.tag; - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -8958,25 +9501,25 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: // classes are valid targets return true; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 238 /* ClassDeclaration */; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: + return parent.kind === 240 /* ClassDeclaration */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 238 /* ClassDeclaration */; - case 149 /* Parameter */: + && parent.kind === 240 /* ClassDeclaration */; + case 151 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 155 /* Constructor */ - || parent.kind === 154 /* MethodDeclaration */ - || parent.kind === 157 /* SetAccessor */) - && grandparent.kind === 238 /* ClassDeclaration */; + && (parent.kind === 157 /* Constructor */ + || parent.kind === 156 /* MethodDeclaration */ + || parent.kind === 159 /* SetAccessor */) + && grandparent.kind === 240 /* ClassDeclaration */; } return false; } @@ -8992,10 +9535,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 154 /* MethodDeclaration */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 159 /* SetAccessor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -9004,9 +9547,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 260 /* JsxOpeningElement */ || - parent.kind === 259 /* JsxSelfClosingElement */ || - parent.kind === 261 /* JsxClosingElement */) { + if (parent.kind === 262 /* JsxOpeningElement */ || + parent.kind === 261 /* JsxSelfClosingElement */ || + parent.kind === 263 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -9014,56 +9557,57 @@ var ts; ts.isJSXTagName = isJSXTagName; function isExpressionNode(node) { switch (node.kind) { - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 12 /* RegularExpressionLiteral */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 191 /* TaggedTemplateExpression */: - case 210 /* AsExpression */: - case 192 /* TypeAssertionExpression */: - case 211 /* NonNullExpression */: - case 193 /* ParenthesizedExpression */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: - case 195 /* ArrowFunction */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: - case 202 /* BinaryExpression */: - case 203 /* ConditionalExpression */: - case 206 /* SpreadElement */: - case 204 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 208 /* OmittedExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 205 /* YieldExpression */: - case 199 /* AwaitExpression */: - case 212 /* MetaProperty */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 13 /* RegularExpressionLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 212 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 208 /* SpreadElement */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 210 /* OmittedExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 207 /* YieldExpression */: + case 201 /* AwaitExpression */: + case 214 /* MetaProperty */: return true; - case 146 /* QualifiedName */: - while (node.parent.kind === 146 /* QualifiedName */) { + case 148 /* QualifiedName */: + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node); - case 71 /* Identifier */: - if (node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node)) { + return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node); + case 72 /* Identifier */: + if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 99 /* ThisKeyword */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: return isInExpressionContext(node); default: return false; @@ -9073,49 +9617,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 276 /* EnumMember */: - case 273 /* PropertyAssignment */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 186 /* BindingElement */: return parent.initializer === node; - case 219 /* ExpressionStatement */: - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 228 /* ReturnStatement */: - case 229 /* WithStatement */: - case 230 /* SwitchStatement */: - case 269 /* CaseClause */: - case 232 /* ThrowStatement */: + case 221 /* ExpressionStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 230 /* ReturnStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 234 /* ThrowStatement */: return parent.expression === node; - case 223 /* ForStatement */: + case 225 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 236 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 236 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) || forInStatement.expression === node; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return node === parent.expression; - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return node === parent.expression; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return node === parent.expression; - case 150 /* Decorator */: - case 268 /* JsxExpression */: - case 267 /* JsxSpreadAttribute */: - case 275 /* SpreadAssignment */: + case 152 /* Decorator */: + case 270 /* JsxExpression */: + case 269 /* JsxSpreadAttribute */: + case 277 /* SpreadAssignment */: return true; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -9123,7 +9667,7 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */; + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -9132,21 +9676,21 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9160,15 +9704,15 @@ var ts; ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && - (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */); + (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { - if (callExpression.kind !== 189 /* CallExpression */) { + if (callExpression.kind !== 191 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 /* Identifier */ || expression.escapedText !== "require") { + if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") { return false; } if (args.length !== 1) { @@ -9186,29 +9730,29 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; decl = node.parent; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.right === node) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) { name = node.parent.left; decl = name; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54 /* BarBarToken */) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) { if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { name = node.parent.parent.name; decl = node.parent.parent; } - else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.parent.right === node.parent) { + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) { name = node.parent.parent.left; decl = name; } @@ -9216,42 +9760,55 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && - ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; } return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { - if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,47 +9817,47 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 194 /* FunctionExpression */ || - initializer.kind === 207 /* ClassExpression */ || - initializer.kind === 195 /* ArrowFunction */) { + if (initializer.kind === 196 /* FunctionExpression */ || + initializer.kind === 209 /* ClassExpression */ || + initializer.kind === 197 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : - ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { - var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; - if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) { return parent.left; } } @@ -9308,7 +9865,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9323,7 +9880,7 @@ var ts; return name.escapedText === initializer.escapedText; } if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { - return (initializer.expression.kind === 99 /* ThisKeyword */ || + return (initializer.expression.kind === 100 /* ThisKeyword */ || ts.isIdentifier(initializer.expression) && (initializer.expression.escapedText === "window" || initializer.expression.escapedText === "self" || @@ -9352,13 +9909,36 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { - if (expr.operatorToken.kind !== 58 /* EqualsToken */ || + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 59 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } @@ -9367,13 +9947,13 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { - if (lhs.expression.kind === 99 /* ThisKeyword */) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + else if (isModuleExportsPropertyAccessExpression(lhs)) { // module.exports = expr return 2 /* ModuleExports */; } @@ -9398,7 +9978,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,12 +9987,12 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && - expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; @@ -9421,7 +10001,7 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { @@ -9430,14 +10010,14 @@ var ts; ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return node.parent; - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return node.parent.parent; - case 189 /* CallExpression */: - return node.parent; - case 180 /* LiteralType */: + case 191 /* CallExpression */: + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; + case 182 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -9447,12 +10027,12 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return node.moduleSpecifier; - case 246 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 257 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 181 /* ImportType */: + case 248 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 183 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; default: return ts.Debug.assertNever(node); @@ -9461,11 +10041,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return undefined; default: return ts.Debug.assertNever(node); @@ -9473,19 +10053,19 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 247 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 149 /* Parameter */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 274 /* ShorthandPropertyAssignment */: - case 273 /* PropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 151 /* Parameter */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 276 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -9493,14 +10073,13 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 287 /* JSDocFunctionType */ && - node.parameters.length > 0 && - node.parameters[0].name && - node.parameters[0].name.escapedText === "new"; + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -9510,27 +10089,27 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 /* EqualsToken */ + node.expression.operatorToken.kind === 59 /* EqualsToken */ ? node.expression.right : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 /* BarBarToken */ + node.expression.right.operatorToken.kind === 55 /* BarBarToken */ ? node.expression.right.right : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return node.initializer; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return node.initializer; } } @@ -9540,7 +10119,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 242 /* ModuleDeclaration */ + node.body.kind === 244 /* ModuleDeclaration */ ? node.body : undefined; } @@ -9555,10 +10134,14 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.addRange(result, node.jsDoc); } - if (node.kind === 149 /* Parameter */) { + if (node.kind === 151 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 150 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9566,11 +10149,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 273 /* PropertyAssignment */ || - parent.kind === 152 /* PropertyDeclaration */ || - parent.kind === 219 /* ExpressionStatement */ && node.kind === 187 /* PropertyAccessExpression */ || + if (parent.kind === 275 /* PropertyAssignment */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ || getNestedModuleDeclaration(parent) || - ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */) { + ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) { return parent; } // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. @@ -9581,7 +10164,7 @@ var ts; // var x = function(name) { return name.length; } else if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node || - ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */)) { + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) { return parent.parent; } else if (parent.parent && parent.parent.parent && @@ -9604,7 +10187,7 @@ var ts; if (!decl) { return undefined; } - var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; @@ -9639,7 +10222,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 288 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9652,31 +10235,31 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? - binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; - return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 193 /* ParenthesizedExpression */: - case 185 /* ArrayLiteralExpression */: - case 206 /* SpreadElement */: - case 211 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 187 /* ArrayLiteralExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: node = parent; break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -9703,22 +10286,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 216 /* Block */: - case 217 /* VariableStatement */: - case 229 /* WithStatement */: - case 220 /* IfStatement */: - case 230 /* SwitchStatement */: - case 244 /* CaseBlock */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 231 /* LabeledStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 233 /* TryStatement */: - case 272 /* CatchClause */: + case 218 /* Block */: + case 219 /* VariableStatement */: + case 231 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: return true; } return false; @@ -9735,27 +10318,33 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 175 /* ParenthesizedType */); + return walkUp(node, 177 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 193 /* ParenthesizedExpression */); + return walkUp(node, 195 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function skipParentheses(node) { - while (node.kind === 193 /* ParenthesizedExpression */) { + while (node.kind === 195 /* ParenthesizedExpression */) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { + if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 196 /* DeleteExpression */; + return node && node.kind === 198 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -9773,35 +10362,39 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 72 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { - return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 147 /* ComputedPropertyName */ && + return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 149 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -9809,32 +10402,32 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 276 /* EnumMember */: - case 273 /* PropertyAssignment */: - case 187 /* PropertyAccessExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 189 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: // Name on right hand side of dot in a type query or type reference if (parent.right === node) { - while (parent.kind === 146 /* QualifiedName */) { + while (parent.kind === 148 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 165 /* TypeQuery */ || parent.kind === 162 /* TypeReference */; + return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */; } return false; - case 184 /* BindingElement */: - case 251 /* ImportSpecifier */: + case 186 /* BindingElement */: + case 253 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 255 /* ExportSpecifier */: - case 265 /* JsxAttribute */: + case 257 /* ExportSpecifier */: + case 267 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -9849,15 +10442,16 @@ var ts; // export { x as } from ... // export = // export default + // module.exports = function isAliasSymbolDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ || - node.kind === 245 /* NamespaceExportDeclaration */ || - node.kind === 248 /* ImportClause */ && !!node.name || - node.kind === 249 /* NamespaceImport */ || - node.kind === 251 /* ImportSpecifier */ || - node.kind === 255 /* ExportSpecifier */ || - node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + return node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + node.kind === 250 /* ImportClause */ && !!node.name || + node.kind === 251 /* NamespaceImport */ || + node.kind === 253 /* ImportSpecifier */ || + node.kind === 257 /* ExportSpecifier */ || + node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10460,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -9877,12 +10471,12 @@ var ts; } ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; function getClassExtendsHeritageElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; @@ -9894,7 +10488,7 @@ var ts; } ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -9928,11 +10522,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 72 /* FirstKeyword */ <= token && token <= 145 /* LastKeyword */; + return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 117 /* FirstContextualKeyword */ <= token && token <= 145 /* LastContextualKeyword */; + return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -9944,6 +10538,11 @@ var ts; return token !== undefined && isNonContextualKeyword(token); } ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; function isTrivia(token) { return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; } @@ -9962,14 +10561,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (hasModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -9983,10 +10582,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256 /* Async */); @@ -10011,7 +10610,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 147 /* ComputedPropertyName */ && + return name.kind === 149 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -10027,12 +10626,12 @@ var ts; ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return name.escapedText; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); @@ -10048,9 +10647,9 @@ var ts; ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: return true; default: @@ -10059,11 +10658,11 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? ts.idText(node) : node.text; + return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -10078,7 +10677,7 @@ var ts; * Includes the word "Symbol" with unicode escapes */ function isESSymbolIdentifier(node) { - return node.kind === 71 /* Identifier */ && node.escapedText === "Symbol"; + return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { @@ -10087,11 +10686,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 149 /* Parameter */; + return root.kind === 151 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 184 /* BindingElement */) { + while (node.kind === 186 /* BindingElement */) { node = node.parent.parent; } return node; @@ -10099,15 +10698,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 155 /* Constructor */ - || kind === 194 /* FunctionExpression */ - || kind === 237 /* FunctionDeclaration */ - || kind === 195 /* ArrowFunction */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 242 /* ModuleDeclaration */ - || kind === 277 /* SourceFile */; + return kind === 157 /* Constructor */ + || kind === 196 /* FunctionExpression */ + || kind === 239 /* FunctionDeclaration */ + || kind === 197 /* ArrowFunction */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 244 /* ModuleDeclaration */ + || kind === 279 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -10126,38 +10725,38 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 190 /* NewExpression */: + case 192 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 200 /* PrefixUnaryExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 199 /* AwaitExpression */: - case 203 /* ConditionalExpression */: - case 205 /* YieldExpression */: + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: return 1 /* Right */; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (operator) { - case 40 /* AsteriskAsteriskToken */: - case 58 /* EqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 69 /* BarEqualsToken */: + case 41 /* AsteriskAsteriskToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: return 1 /* Right */; } } @@ -10166,15 +10765,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 202 /* BinaryExpression */) { + if (expression.kind === 204 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 200 /* PrefixUnaryExpression */ || expression.kind === 201 /* PostfixUnaryExpression */) { + else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -10184,116 +10783,116 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return 0; - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return 1; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return 2; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return 4; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (operatorKind) { - case 26 /* CommaToken */: + case 27 /* CommaToken */: return 0; - case 58 /* EqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 69 /* BarEqualsToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: return 3; default: return getBinaryOperatorPrecedence(operatorKind); } - case 200 /* PrefixUnaryExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 199 /* AwaitExpression */: + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: return 16; - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return 17; - case 189 /* CallExpression */: + case 191 /* CallExpression */: return 18; - case 190 /* NewExpression */: + case 192 /* NewExpression */: return hasArguments ? 19 : 18; - case 191 /* TaggedTemplateExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 193 /* TaggedTemplateExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return 19; - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 71 /* Identifier */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 72 /* Identifier */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 207 /* ClassExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 193 /* ParenthesizedExpression */: - case 208 /* OmittedExpression */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 195 /* ParenthesizedExpression */: + case 210 /* OmittedExpression */: return 20; default: return -1; } } ts.getOperatorPrecedence = getOperatorPrecedence; - /* @internal */ function getBinaryOperatorPrecedence(kind) { switch (kind) { - case 54 /* BarBarToken */: + case 55 /* BarBarToken */: return 5; - case 53 /* AmpersandAmpersandToken */: + case 54 /* AmpersandAmpersandToken */: return 6; - case 49 /* BarToken */: + case 50 /* BarToken */: return 7; - case 50 /* CaretToken */: + case 51 /* CaretToken */: return 8; - case 48 /* AmpersandToken */: + case 49 /* AmpersandToken */: return 9; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: return 10; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: return 11; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return 12; - case 37 /* PlusToken */: - case 38 /* MinusToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: return 13; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: return 14; - case 40 /* AsteriskAsteriskToken */: + case 41 /* AsteriskAsteriskToken */: return 15; } // -1 is lower than all other precedences. Returning it will cause binary expression @@ -10361,7 +10960,7 @@ var ts; if (fileName) { return fileDiagnostics.get(fileName) || []; } - var fileDiags = ts.flatMap(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); if (!nonFileDiagnostics.length) { return fileDiags; } @@ -10419,7 +11018,7 @@ var ts; } function isIntrinsicJsxName(name) { var ch = name.charCodeAt(0); - return (ch >= 97 /* a */ && ch <= 122 /* z */) || name.indexOf("-") > -1; + return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-"); } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -10502,16 +11101,10 @@ var ts; lineStart = true; } } - function writeTextOfNode(text, node) { - var s = getTextOfNodeFromSourceText(text, node); - write(s); - updateLineCountAndPosFor(s); - } reset(); return { write: write, rawWrite: rawWrite, - writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, increaseIndent: function () { indent++; }, @@ -10534,10 +11127,77 @@ var ts; writePunctuation: write, writeSpace: write, writeStringLiteral: write, - writeSymbol: write + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write }; } ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; function getResolvedExternalModuleName(host, file, referenceFile) { return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } @@ -10600,7 +11260,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10614,7 +11274,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10673,11 +11333,11 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { - return id.originalKeywordKind === 99 /* ThisKeyword */; + return id.originalKeywordKind === 100 /* ThisKeyword */; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { @@ -10688,10 +11348,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 156 /* GetAccessor */) { + if (accessor.kind === 158 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 157 /* SetAccessor */) { + else if (accessor.kind === 159 /* SetAccessor */) { setAccessor = accessor; } else { @@ -10711,10 +11371,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 156 /* GetAccessor */ && !getAccessor) { + if (member.kind === 158 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 157 /* SetAccessor */ && !setAccessor) { + if (member.kind === 159 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -10735,7 +11395,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11411,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -10760,7 +11420,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 289 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -10794,13 +11454,13 @@ var ts; function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { if (comments && comments.length > 0) { if (leadingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } var emitInterveningSeparator = false; for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { var comment = comments_1[_i]; if (emitInterveningSeparator) { - writer.write(" "); + writer.writeSpace(" "); emitInterveningSeparator = false; } writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); @@ -10812,7 +11472,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -10930,7 +11590,7 @@ var ts; } else { // Single line comment of style //.... - writer.write(text.substring(commentPos, commentEnd)); + writer.writeComment(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; @@ -10939,14 +11599,14 @@ var ts; var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { // trimmed forward and ending spaces text - writer.write(currentLineText); + writer.writeComment(currentLineText); if (end !== commentEnd) { writer.writeLine(); } } else { // Empty string - make sure we write empty line - writer.writeLiteral(newLine); + writer.rawWrite(newLine); } } function calculateIndent(text, pos, end) { @@ -11000,7 +11660,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4 /* NestedNamespace */ || (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace)) { + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* Export */; } return flags; @@ -11008,44 +11668,49 @@ var ts; ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { - case 115 /* StaticKeyword */: return 32 /* Static */; - case 114 /* PublicKeyword */: return 4 /* Public */; - case 113 /* ProtectedKeyword */: return 16 /* Protected */; - case 112 /* PrivateKeyword */: return 8 /* Private */; - case 117 /* AbstractKeyword */: return 128 /* Abstract */; - case 84 /* ExportKeyword */: return 1 /* Export */; - case 124 /* DeclareKeyword */: return 2 /* Ambient */; - case 76 /* ConstKeyword */: return 2048 /* Const */; - case 79 /* DefaultKeyword */: return 512 /* Default */; - case 120 /* AsyncKeyword */: return 256 /* Async */; - case 132 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 116 /* StaticKeyword */: return 32 /* Static */; + case 115 /* PublicKeyword */: return 4 /* Public */; + case 114 /* ProtectedKeyword */: return 16 /* Protected */; + case 113 /* PrivateKeyword */: return 8 /* Private */; + case 118 /* AbstractKeyword */: return 128 /* Abstract */; + case 85 /* ExportKeyword */: return 1 /* Export */; + case 125 /* DeclareKeyword */: return 2 /* Ambient */; + case 77 /* ConstKeyword */: return 2048 /* Const */; + case 80 /* DefaultKeyword */: return 512 /* Default */; + case 121 /* AsyncKeyword */: return 256 /* Async */; + case 133 /* ReadonlyKeyword */: return 64 /* Readonly */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 54 /* BarBarToken */ - || token === 53 /* AmpersandAmpersandToken */ - || token === 51 /* ExclamationToken */; + return token === 55 /* BarBarToken */ + || token === 54 /* AmpersandAmpersandToken */ + || token === 52 /* ExclamationToken */; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 58 /* FirstAssignment */ && token <= 70 /* LastAssignment */; + return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment - ? node.operatorToken.kind === 58 /* EqualsToken */ + ? node.operatorToken.kind === 59 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) && ts.isLeftHandSideExpression(node.left); } @@ -11053,8 +11718,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 186 /* ObjectLiteralExpression */ - || kind === 185 /* ArrayLiteralExpression */; + return kind === 188 /* ObjectLiteralExpression */ + || kind === 187 /* ArrayLiteralExpression */; } return false; } @@ -11063,17 +11728,8 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; function isPropertyAccessEntityNameExpression(node) { @@ -11085,17 +11741,17 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 186 /* ObjectLiteralExpression */ && + return expression.kind === 188 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 185 /* ArrayLiteralExpression */ && + return expression.kind === 187 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -11107,10 +11763,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * 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. @@ -11249,6 +11905,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +12017,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11436,8 +12116,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -11514,23 +12194,47 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 201 /* PostfixUnaryExpression */: - case 200 /* PrefixUnaryExpression */: + case 195 /* ParenthesizedExpression */: + return accessKind(parent); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: var operator = parent.operator; - return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 202 /* BinaryExpression */: + return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 204 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? - operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 275 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 187 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11621,7 +12325,7 @@ var ts; } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { - return type.flags & 131072 /* Object */ ? type.objectFlags : 0; + return type.flags & 524288 /* Object */ ? type.objectFlags : 0; } ts.getObjectFlags = getObjectFlags; function typeHasCallOrConstructSignatures(type, checker) { @@ -11672,6 +12376,31 @@ var ts; return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) + || kind === 120 /* AnyKeyword */ + || kind === 143 /* UnknownKeyword */ + || kind === 135 /* NumberKeyword */ + || kind === 146 /* BigIntKeyword */ + || kind === 136 /* ObjectKeyword */ + || kind === 123 /* BooleanKeyword */ + || kind === 138 /* StringKeyword */ + || kind === 139 /* SymbolKeyword */ + || kind === 100 /* ThisKeyword */ + || kind === 106 /* VoidKeyword */ + || kind === 141 /* UndefinedKeyword */ + || kind === 96 /* NullKeyword */ + || kind === 132 /* NeverKeyword */ + || kind === 211 /* ExpressionWithTypeArguments */ + || kind === 284 /* JSDocAllType */ + || kind === 285 /* JSDocUnknownType */ + || kind === 286 /* JSDocNullableType */ + || kind === 287 /* JSDocNonNullableType */ + || kind === 288 /* JSDocOptionalType */ + || kind === 289 /* JSDocFunctionType */ + || kind === 290 /* JSDocVariadicType */; + } + ts.isTypeNodeKind = isTypeNodeKind; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11756,13 +12485,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -11899,9 +12621,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 148 /* TypeParameter */) { + if (d && d.kind === 150 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 239 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) { return current; } } @@ -11909,7 +12631,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 155 /* Constructor */; + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11939,14 +12661,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 235 /* VariableDeclaration */) { + if (node.kind === 237 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 236 /* VariableDeclarationList */) { + if (node && node.kind === 238 /* VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 217 /* VariableStatement */) { + if (node && node.kind === 219 /* VariableStatement */) { flags |= getFlags(node); } return flags; @@ -12090,38 +12812,34 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; - case 219 /* ExpressionStatement */: + break; + case 221 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return expr.name; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; - case 193 /* ParenthesizedExpression */: { + break; + case 195 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 231 /* LabeledStatement */: { + case 233 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12140,31 +12858,36 @@ var ts; /** @internal */ function getNonAssignedNameOfDeclaration(declaration) { switch (declaration.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return declaration; - case 303 /* JSDocPropertyTag */: - case 297 /* JSDocParameterTag */: { + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 146 /* QualifiedName */) { + if (name.kind === 148 /* QualifiedName */) { return name.right; } break; } - case 202 /* BinaryExpression */: { + case 191 /* CallExpression */: + case 204 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: case 3 /* PrototypeProperty */: return expr.left.name; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr.arguments[1]; default: return undefined; } } - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 252 /* ExportAssignment */: { + case 254 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } @@ -12198,15 +12921,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12949,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12350,10 +13089,23 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -12371,684 +13123,688 @@ var ts; return node.kind === 8 /* NumericLiteral */; } ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9 /* BigIntLiteral */; + } + ts.isBigIntLiteral = isBigIntLiteral; function isStringLiteral(node) { - return node.kind === 9 /* StringLiteral */; + return node.kind === 10 /* StringLiteral */; } ts.isStringLiteral = isStringLiteral; function isJsxText(node) { - return node.kind === 10 /* JsxText */; + return node.kind === 11 /* JsxText */; } ts.isJsxText = isJsxText; function isRegularExpressionLiteral(node) { - return node.kind === 12 /* RegularExpressionLiteral */; + return node.kind === 13 /* RegularExpressionLiteral */; } ts.isRegularExpressionLiteral = isRegularExpressionLiteral; function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13 /* NoSubstitutionTemplateLiteral */; + return node.kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; // Pseudo-literals function isTemplateHead(node) { - return node.kind === 14 /* TemplateHead */; + return node.kind === 15 /* TemplateHead */; } ts.isTemplateHead = isTemplateHead; function isTemplateMiddle(node) { - return node.kind === 15 /* TemplateMiddle */; + return node.kind === 16 /* TemplateMiddle */; } ts.isTemplateMiddle = isTemplateMiddle; function isTemplateTail(node) { - return node.kind === 16 /* TemplateTail */; + return node.kind === 17 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; function isIdentifier(node) { - return node.kind === 71 /* Identifier */; + return node.kind === 72 /* Identifier */; } ts.isIdentifier = isIdentifier; // Names function isQualifiedName(node) { - return node.kind === 146 /* QualifiedName */; + return node.kind === 148 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 147 /* ComputedPropertyName */; + return node.kind === 149 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 148 /* TypeParameter */; + return node.kind === 150 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 149 /* Parameter */; + return node.kind === 151 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 150 /* Decorator */; + return node.kind === 152 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 151 /* PropertySignature */; + return node.kind === 153 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 152 /* PropertyDeclaration */; + return node.kind === 154 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 153 /* MethodSignature */; + return node.kind === 155 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 154 /* MethodDeclaration */; + return node.kind === 156 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 155 /* Constructor */; + return node.kind === 157 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 156 /* GetAccessor */; + return node.kind === 158 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 157 /* SetAccessor */; + return node.kind === 159 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 158 /* CallSignature */; + return node.kind === 160 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 159 /* ConstructSignature */; + return node.kind === 161 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 160 /* IndexSignature */; + return node.kind === 162 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 157 /* SetAccessor */ || node.kind === 156 /* GetAccessor */; + return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 161 /* TypePredicate */; + return node.kind === 163 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 162 /* TypeReference */; + return node.kind === 164 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 163 /* FunctionType */; + return node.kind === 165 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 164 /* ConstructorType */; + return node.kind === 166 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 165 /* TypeQuery */; + return node.kind === 167 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 166 /* TypeLiteral */; + return node.kind === 168 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 167 /* ArrayType */; + return node.kind === 169 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 168 /* TupleType */; + return node.kind === 170 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 171 /* UnionType */; + return node.kind === 173 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 172 /* IntersectionType */; + return node.kind === 174 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 173 /* ConditionalType */; + return node.kind === 175 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 174 /* InferType */; + return node.kind === 176 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 175 /* ParenthesizedType */; + return node.kind === 177 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 176 /* ThisType */; + return node.kind === 178 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 177 /* TypeOperator */; + return node.kind === 179 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 178 /* IndexedAccessType */; + return node.kind === 180 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 179 /* MappedType */; + return node.kind === 181 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 180 /* LiteralType */; + return node.kind === 182 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 181 /* ImportType */; + return node.kind === 183 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 182 /* ObjectBindingPattern */; + return node.kind === 184 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 183 /* ArrayBindingPattern */; + return node.kind === 185 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 184 /* BindingElement */; + return node.kind === 186 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 185 /* ArrayLiteralExpression */; + return node.kind === 187 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 186 /* ObjectLiteralExpression */; + return node.kind === 188 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 187 /* PropertyAccessExpression */; + return node.kind === 189 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 188 /* ElementAccessExpression */; + return node.kind === 190 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 189 /* CallExpression */; + return node.kind === 191 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 190 /* NewExpression */; + return node.kind === 192 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 191 /* TaggedTemplateExpression */; + return node.kind === 193 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 192 /* TypeAssertionExpression */; + return node.kind === 194 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 193 /* ParenthesizedExpression */; + return node.kind === 195 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 306 /* PartiallyEmittedExpression */) { + while (node.kind === 308 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 194 /* FunctionExpression */; + return node.kind === 196 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 195 /* ArrowFunction */; + return node.kind === 197 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 196 /* DeleteExpression */; + return node.kind === 198 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 197 /* TypeOfExpression */; + return node.kind === 199 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 198 /* VoidExpression */; + return node.kind === 200 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 199 /* AwaitExpression */; + return node.kind === 201 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 200 /* PrefixUnaryExpression */; + return node.kind === 202 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 201 /* PostfixUnaryExpression */; + return node.kind === 203 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 202 /* BinaryExpression */; + return node.kind === 204 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 203 /* ConditionalExpression */; + return node.kind === 205 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 204 /* TemplateExpression */; + return node.kind === 206 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 205 /* YieldExpression */; + return node.kind === 207 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 206 /* SpreadElement */; + return node.kind === 208 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 207 /* ClassExpression */; + return node.kind === 209 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 208 /* OmittedExpression */; + return node.kind === 210 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */; + return node.kind === 211 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 210 /* AsExpression */; + return node.kind === 212 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 211 /* NonNullExpression */; + return node.kind === 213 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 212 /* MetaProperty */; + return node.kind === 214 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; // Misc function isTemplateSpan(node) { - return node.kind === 214 /* TemplateSpan */; + return node.kind === 216 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 215 /* SemicolonClassElement */; + return node.kind === 217 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Block function isBlock(node) { - return node.kind === 216 /* Block */; + return node.kind === 218 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 217 /* VariableStatement */; + return node.kind === 219 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 218 /* EmptyStatement */; + return node.kind === 220 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 219 /* ExpressionStatement */; + return node.kind === 221 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 220 /* IfStatement */; + return node.kind === 222 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 221 /* DoStatement */; + return node.kind === 223 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 222 /* WhileStatement */; + return node.kind === 224 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 223 /* ForStatement */; + return node.kind === 225 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 224 /* ForInStatement */; + return node.kind === 226 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 225 /* ForOfStatement */; + return node.kind === 227 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 226 /* ContinueStatement */; + return node.kind === 228 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 227 /* BreakStatement */; + return node.kind === 229 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isBreakOrContinueStatement(node) { - return node.kind === 227 /* BreakStatement */ || node.kind === 226 /* ContinueStatement */; + return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 228 /* ReturnStatement */; + return node.kind === 230 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 229 /* WithStatement */; + return node.kind === 231 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 230 /* SwitchStatement */; + return node.kind === 232 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 231 /* LabeledStatement */; + return node.kind === 233 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 232 /* ThrowStatement */; + return node.kind === 234 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 233 /* TryStatement */; + return node.kind === 235 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 234 /* DebuggerStatement */; + return node.kind === 236 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 235 /* VariableDeclaration */; + return node.kind === 237 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 236 /* VariableDeclarationList */; + return node.kind === 238 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 237 /* FunctionDeclaration */; + return node.kind === 239 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 238 /* ClassDeclaration */; + return node.kind === 240 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 239 /* InterfaceDeclaration */; + return node.kind === 241 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 240 /* TypeAliasDeclaration */; + return node.kind === 242 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 241 /* EnumDeclaration */; + return node.kind === 243 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */; + return node.kind === 244 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 243 /* ModuleBlock */; + return node.kind === 245 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 244 /* CaseBlock */; + return node.kind === 246 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 245 /* NamespaceExportDeclaration */; + return node.kind === 247 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */; + return node.kind === 248 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 247 /* ImportDeclaration */; + return node.kind === 249 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 248 /* ImportClause */; + return node.kind === 250 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 249 /* NamespaceImport */; + return node.kind === 251 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 250 /* NamedImports */; + return node.kind === 252 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 251 /* ImportSpecifier */; + return node.kind === 253 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 252 /* ExportAssignment */; + return node.kind === 254 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 253 /* ExportDeclaration */; + return node.kind === 255 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 254 /* NamedExports */; + return node.kind === 256 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 255 /* ExportSpecifier */; + return node.kind === 257 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 256 /* MissingDeclaration */; + return node.kind === 258 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; // Module References function isExternalModuleReference(node) { - return node.kind === 257 /* ExternalModuleReference */; + return node.kind === 259 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 258 /* JsxElement */; + return node.kind === 260 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 259 /* JsxSelfClosingElement */; + return node.kind === 261 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 260 /* JsxOpeningElement */; + return node.kind === 262 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 261 /* JsxClosingElement */; + return node.kind === 263 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 262 /* JsxFragment */; + return node.kind === 264 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 263 /* JsxOpeningFragment */; + return node.kind === 265 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 264 /* JsxClosingFragment */; + return node.kind === 266 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 265 /* JsxAttribute */; + return node.kind === 267 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 266 /* JsxAttributes */; + return node.kind === 268 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 267 /* JsxSpreadAttribute */; + return node.kind === 269 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 268 /* JsxExpression */; + return node.kind === 270 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 269 /* CaseClause */; + return node.kind === 271 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 270 /* DefaultClause */; + return node.kind === 272 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 271 /* HeritageClause */; + return node.kind === 273 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 272 /* CatchClause */; + return node.kind === 274 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 273 /* PropertyAssignment */; + return node.kind === 275 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 274 /* ShorthandPropertyAssignment */; + return node.kind === 276 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 275 /* SpreadAssignment */; + return node.kind === 277 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 276 /* EnumMember */; + return node.kind === 278 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 277 /* SourceFile */; + return node.kind === 279 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 278 /* Bundle */; + return node.kind === 280 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 279 /* UnparsedSource */; + return node.kind === 281 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 281 /* JSDocTypeExpression */; + return node.kind === 283 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 282 /* JSDocAllType */; + return node.kind === 284 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 283 /* JSDocUnknownType */; + return node.kind === 285 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 284 /* JSDocNullableType */; + return node.kind === 286 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 285 /* JSDocNonNullableType */; + return node.kind === 287 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 286 /* JSDocOptionalType */; + return node.kind === 288 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 287 /* JSDocFunctionType */; + return node.kind === 289 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 288 /* JSDocVariadicType */; + return node.kind === 290 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 289 /* JSDocComment */; + return node.kind === 291 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 293 /* JSDocAugmentsTag */; + return node.kind === 295 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 294 /* JSDocClassTag */; + return node.kind === 296 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocEnumTag(node) { - return node.kind === 296 /* JSDocEnumTag */; + return node.kind === 298 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 299 /* JSDocThisTag */; + return node.kind === 301 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 297 /* JSDocParameterTag */; + return node.kind === 299 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 298 /* JSDocReturnTag */; + return node.kind === 300 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 300 /* JSDocTypeTag */; + return node.kind === 302 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 301 /* JSDocTemplateTag */; + return node.kind === 303 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 302 /* JSDocTypedefTag */; + return node.kind === 304 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 303 /* JSDocPropertyTag */; + return node.kind === 305 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */; + return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 290 /* JSDocTypeLiteral */; + return node.kind === 292 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocCallbackTag(node) { - return node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 297 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocSignature(node) { - return node.kind === 291 /* JSDocSignature */; + return node.kind === 293 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); @@ -13059,7 +13815,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 304 /* SyntaxList */; + return n.kind === 306 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13069,7 +13825,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 146 /* FirstNode */; + return kind >= 148 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13078,7 +13834,7 @@ var ts; * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 145 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */; } ts.isToken = isToken; // Node Arrays @@ -13090,7 +13846,7 @@ var ts; // Literals /* @internal */ function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */; + return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */; } ts.isLiteralKind = isLiteralKind; function isLiteralExpression(node) { @@ -13100,7 +13856,7 @@ var ts; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { - return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; + return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isTemplateLiteralToken(node) { @@ -13109,12 +13865,16 @@ var ts; ts.isTemplateLiteralToken = isTemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node) { var kind = node.kind; - return kind === 15 /* TemplateMiddle */ - || kind === 16 /* TemplateTail */; + return kind === 16 /* TemplateMiddle */ + || kind === 17 /* TemplateTail */; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isStringTextContainingNode(node) { - return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -13127,17 +13887,17 @@ var ts; /* @internal */ function isModifierKind(token) { switch (token) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 79 /* DefaultKeyword */: - case 84 /* ExportKeyword */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 115 /* StaticKeyword */: + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 80 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 116 /* StaticKeyword */: return true; } return false; @@ -13150,7 +13910,7 @@ var ts; ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */; + return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -13159,23 +13919,23 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 146 /* QualifiedName */ - || kind === 71 /* Identifier */; + return kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 9 /* StringLiteral */ + return kind === 72 /* Identifier */ + || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 147 /* ComputedPropertyName */; + || kind === 149 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 182 /* ObjectBindingPattern */ - || kind === 183 /* ArrayBindingPattern */; + return kind === 72 /* Identifier */ + || kind === 184 /* ObjectBindingPattern */ + || kind === 185 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -13190,13 +13950,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; default: return false; @@ -13205,14 +13965,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 163 /* FunctionType */: - case 287 /* JSDocFunctionType */: - case 164 /* ConstructorType */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 166 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -13227,29 +13987,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 155 /* Constructor */ - || kind === 152 /* PropertyDeclaration */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 160 /* IndexSignature */ - || kind === 215 /* SemicolonClassElement */; + return kind === 157 /* Constructor */ + || kind === 154 /* PropertyDeclaration */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 162 /* IndexSignature */ + || kind === 217 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */); + return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */); + return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return true; default: return false; @@ -13259,11 +14019,11 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 159 /* ConstructSignature */ - || kind === 158 /* CallSignature */ - || kind === 151 /* PropertySignature */ - || kind === 153 /* MethodSignature */ - || kind === 160 /* IndexSignature */; + return kind === 161 /* ConstructSignature */ + || kind === 160 /* CallSignature */ + || kind === 153 /* PropertySignature */ + || kind === 155 /* MethodSignature */ + || kind === 162 /* IndexSignature */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -13272,51 +14032,28 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 273 /* PropertyAssignment */ - || kind === 274 /* ShorthandPropertyAssignment */ - || kind === 275 /* SpreadAssignment */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 275 /* PropertyAssignment */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 277 /* SpreadAssignment */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type - function isTypeNodeKind(kind) { - return (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) - || kind === 119 /* AnyKeyword */ - || kind === 142 /* UnknownKeyword */ - || kind === 134 /* NumberKeyword */ - || kind === 135 /* ObjectKeyword */ - || kind === 122 /* BooleanKeyword */ - || kind === 137 /* StringKeyword */ - || kind === 138 /* SymbolKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 105 /* VoidKeyword */ - || kind === 140 /* UndefinedKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 131 /* NeverKeyword */ - || kind === 209 /* ExpressionWithTypeArguments */ - || kind === 282 /* JSDocAllType */ - || kind === 283 /* JSDocUnknownType */ - || kind === 284 /* JSDocNullableType */ - || kind === 285 /* JSDocNonNullableType */ - || kind === 286 /* JSDocOptionalType */ - || kind === 287 /* JSDocFunctionType */ - || kind === 288 /* JSDocVariadicType */; - } /** * Node test that determines whether a node is a valid type node. * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* * of a TypeNode. */ function isTypeNode(node) { - return isTypeNodeKind(node.kind); + return ts.isTypeNodeKind(node.kind); } ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return true; } return false; @@ -13327,8 +14064,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 183 /* ArrayBindingPattern */ - || kind === 182 /* ObjectBindingPattern */; + return kind === 185 /* ArrayBindingPattern */ + || kind === 184 /* ObjectBindingPattern */; } return false; } @@ -13336,15 +14073,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 185 /* ArrayLiteralExpression */ - || kind === 186 /* ObjectLiteralExpression */; + return kind === 187 /* ArrayLiteralExpression */ + || kind === 188 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 184 /* BindingElement */ - || kind === 208 /* OmittedExpression */; + return kind === 186 /* BindingElement */ + || kind === 210 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -13353,9 +14090,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: return true; } return false; @@ -13376,8 +14113,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 182 /* ObjectBindingPattern */: - case 186 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: return true; } return false; @@ -13389,8 +14126,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: return true; } return false; @@ -13399,26 +14136,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 187 /* PropertyAccessExpression */ - || kind === 146 /* QualifiedName */ - || kind === 181 /* ImportType */; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */ + || kind === 183 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 187 /* PropertyAccessExpression */ - || kind === 146 /* QualifiedName */; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 191 /* TaggedTemplateExpression */: - case 150 /* Decorator */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 152 /* Decorator */: return true; default: return false; @@ -13426,13 +14163,13 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 189 /* CallExpression */ || node.kind === 190 /* NewExpression */; + return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 204 /* TemplateExpression */ - || kind === 13 /* NoSubstitutionTemplateLiteral */; + return kind === 206 /* TemplateExpression */ + || kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; /* @internal */ @@ -13442,33 +14179,34 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - case 190 /* NewExpression */: - case 189 /* CallExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 191 /* TaggedTemplateExpression */: - case 185 /* ArrayLiteralExpression */: - case 193 /* ParenthesizedExpression */: - case 186 /* ObjectLiteralExpression */: - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: - case 71 /* Identifier */: - case 12 /* RegularExpressionLiteral */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 192 /* NewExpression */: + case 191 /* CallExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 193 /* TaggedTemplateExpression */: + case 187 /* ArrayLiteralExpression */: + case 195 /* ParenthesizedExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 72 /* Identifier */: + case 13 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 101 /* TrueKeyword */: - case 97 /* SuperKeyword */: - case 211 /* NonNullExpression */: - case 212 /* MetaProperty */: - case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 102 /* TrueKeyword */: + case 98 /* SuperKeyword */: + case 213 /* NonNullExpression */: + case 214 /* MetaProperty */: + case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: return false; @@ -13481,13 +14219,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 199 /* AwaitExpression */: - case 192 /* TypeAssertionExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 194 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13496,11 +14234,11 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return true; - case 200 /* PrefixUnaryExpression */: - return expr.operator === 43 /* PlusPlusToken */ || - expr.operator === 44 /* MinusMinusToken */; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 44 /* PlusPlusToken */ || + expr.operator === 45 /* MinusMinusToken */; default: return false; } @@ -13517,15 +14255,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 203 /* ConditionalExpression */: - case 205 /* YieldExpression */: - case 195 /* ArrowFunction */: - case 202 /* BinaryExpression */: - case 206 /* SpreadElement */: - case 210 /* AsExpression */: - case 208 /* OmittedExpression */: - case 307 /* CommaListExpression */: - case 306 /* PartiallyEmittedExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + case 197 /* ArrowFunction */: + case 204 /* BinaryExpression */: + case 208 /* SpreadElement */: + case 212 /* AsExpression */: + case 210 /* OmittedExpression */: + case 309 /* CommaListExpression */: + case 308 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13533,18 +14271,18 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 192 /* TypeAssertionExpression */ - || kind === 210 /* AsExpression */; + return kind === 194 /* TypeAssertionExpression */ + || kind === 212 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 306 /* PartiallyEmittedExpression */; + return node.kind === 308 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 305 /* NotEmittedStatement */; + return node.kind === 307 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13555,13 +14293,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return true; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13569,7 +14307,7 @@ var ts; ts.isIterationStatement = isIterationStatement; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 224 /* ForInStatement */ || node.kind === 225 /* ForOfStatement */; + return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13593,113 +14331,113 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 243 /* ModuleBlock */ - || kind === 242 /* ModuleDeclaration */ - || kind === 71 /* Identifier */; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */ + || kind === 72 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 243 /* ModuleBlock */ - || kind === 242 /* ModuleDeclaration */; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 242 /* ModuleDeclaration */; + return kind === 72 /* Identifier */ + || kind === 244 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 250 /* NamedImports */ - || kind === 249 /* NamespaceImport */; + return kind === 252 /* NamedImports */ + || kind === 251 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */ || node.kind === 241 /* EnumDeclaration */; + return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 195 /* ArrowFunction */ - || kind === 184 /* BindingElement */ - || kind === 238 /* ClassDeclaration */ - || kind === 207 /* ClassExpression */ - || kind === 155 /* Constructor */ - || kind === 241 /* EnumDeclaration */ - || kind === 276 /* EnumMember */ - || kind === 255 /* ExportSpecifier */ - || kind === 237 /* FunctionDeclaration */ - || kind === 194 /* FunctionExpression */ - || kind === 156 /* GetAccessor */ - || kind === 248 /* ImportClause */ - || kind === 246 /* ImportEqualsDeclaration */ - || kind === 251 /* ImportSpecifier */ - || kind === 239 /* InterfaceDeclaration */ - || kind === 265 /* JsxAttribute */ - || kind === 154 /* MethodDeclaration */ - || kind === 153 /* MethodSignature */ - || kind === 242 /* ModuleDeclaration */ - || kind === 245 /* NamespaceExportDeclaration */ - || kind === 249 /* NamespaceImport */ - || kind === 149 /* Parameter */ - || kind === 273 /* PropertyAssignment */ - || kind === 152 /* PropertyDeclaration */ - || kind === 151 /* PropertySignature */ - || kind === 157 /* SetAccessor */ - || kind === 274 /* ShorthandPropertyAssignment */ - || kind === 240 /* TypeAliasDeclaration */ - || kind === 148 /* TypeParameter */ - || kind === 235 /* VariableDeclaration */ - || kind === 302 /* JSDocTypedefTag */ - || kind === 295 /* JSDocCallbackTag */ - || kind === 303 /* JSDocPropertyTag */; + return kind === 197 /* ArrowFunction */ + || kind === 186 /* BindingElement */ + || kind === 240 /* ClassDeclaration */ + || kind === 209 /* ClassExpression */ + || kind === 157 /* Constructor */ + || kind === 243 /* EnumDeclaration */ + || kind === 278 /* EnumMember */ + || kind === 257 /* ExportSpecifier */ + || kind === 239 /* FunctionDeclaration */ + || kind === 196 /* FunctionExpression */ + || kind === 158 /* GetAccessor */ + || kind === 250 /* ImportClause */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 253 /* ImportSpecifier */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 267 /* JsxAttribute */ + || kind === 156 /* MethodDeclaration */ + || kind === 155 /* MethodSignature */ + || kind === 244 /* ModuleDeclaration */ + || kind === 247 /* NamespaceExportDeclaration */ + || kind === 251 /* NamespaceImport */ + || kind === 151 /* Parameter */ + || kind === 275 /* PropertyAssignment */ + || kind === 154 /* PropertyDeclaration */ + || kind === 153 /* PropertySignature */ + || kind === 159 /* SetAccessor */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 150 /* TypeParameter */ + || kind === 237 /* VariableDeclaration */ + || kind === 304 /* JSDocTypedefTag */ + || kind === 297 /* JSDocCallbackTag */ + || kind === 305 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 237 /* FunctionDeclaration */ - || kind === 256 /* MissingDeclaration */ - || kind === 238 /* ClassDeclaration */ - || kind === 239 /* InterfaceDeclaration */ - || kind === 240 /* TypeAliasDeclaration */ - || kind === 241 /* EnumDeclaration */ - || kind === 242 /* ModuleDeclaration */ - || kind === 247 /* ImportDeclaration */ - || kind === 246 /* ImportEqualsDeclaration */ - || kind === 253 /* ExportDeclaration */ - || kind === 252 /* ExportAssignment */ - || kind === 245 /* NamespaceExportDeclaration */; + return kind === 239 /* FunctionDeclaration */ + || kind === 258 /* MissingDeclaration */ + || kind === 240 /* ClassDeclaration */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 243 /* EnumDeclaration */ + || kind === 244 /* ModuleDeclaration */ + || kind === 249 /* ImportDeclaration */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 255 /* ExportDeclaration */ + || kind === 254 /* ExportAssignment */ + || kind === 247 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 227 /* BreakStatement */ - || kind === 226 /* ContinueStatement */ - || kind === 234 /* DebuggerStatement */ - || kind === 221 /* DoStatement */ - || kind === 219 /* ExpressionStatement */ - || kind === 218 /* EmptyStatement */ - || kind === 224 /* ForInStatement */ - || kind === 225 /* ForOfStatement */ - || kind === 223 /* ForStatement */ - || kind === 220 /* IfStatement */ - || kind === 231 /* LabeledStatement */ - || kind === 228 /* ReturnStatement */ - || kind === 230 /* SwitchStatement */ - || kind === 232 /* ThrowStatement */ - || kind === 233 /* TryStatement */ - || kind === 217 /* VariableStatement */ - || kind === 222 /* WhileStatement */ - || kind === 229 /* WithStatement */ - || kind === 305 /* NotEmittedStatement */ - || kind === 309 /* EndOfDeclarationMarker */ - || kind === 308 /* MergeDeclarationMarker */; + return kind === 229 /* BreakStatement */ + || kind === 228 /* ContinueStatement */ + || kind === 236 /* DebuggerStatement */ + || kind === 223 /* DoStatement */ + || kind === 221 /* ExpressionStatement */ + || kind === 220 /* EmptyStatement */ + || kind === 226 /* ForInStatement */ + || kind === 227 /* ForOfStatement */ + || kind === 225 /* ForStatement */ + || kind === 222 /* IfStatement */ + || kind === 233 /* LabeledStatement */ + || kind === 230 /* ReturnStatement */ + || kind === 232 /* SwitchStatement */ + || kind === 234 /* ThrowStatement */ + || kind === 235 /* TryStatement */ + || kind === 219 /* VariableStatement */ + || kind === 224 /* WhileStatement */ + || kind === 231 /* WithStatement */ + || kind === 307 /* NotEmittedStatement */ + || kind === 311 /* EndOfDeclarationMarker */ + || kind === 310 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + if (node.kind === 150 /* TypeParameter */) { + return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -13726,10 +14464,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 216 /* Block */) + if (node.kind !== 218 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 233 /* TryStatement */ || node.parent.kind === 272 /* CatchClause */) { + if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) { return false; } } @@ -13739,81 +14477,81 @@ var ts; /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 257 /* ExternalModuleReference */ - || kind === 146 /* QualifiedName */ - || kind === 71 /* Identifier */; + return kind === 259 /* ExternalModuleReference */ + || kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; } ts.isModuleReference = isModuleReference; // JSX /* @internal */ function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 99 /* ThisKeyword */ - || kind === 71 /* Identifier */ - || kind === 187 /* PropertyAccessExpression */; + return kind === 100 /* ThisKeyword */ + || kind === 72 /* Identifier */ + || kind === 189 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 258 /* JsxElement */ - || kind === 268 /* JsxExpression */ - || kind === 259 /* JsxSelfClosingElement */ - || kind === 10 /* JsxText */ - || kind === 262 /* JsxFragment */; + return kind === 260 /* JsxElement */ + || kind === 270 /* JsxExpression */ + || kind === 261 /* JsxSelfClosingElement */ + || kind === 11 /* JsxText */ + || kind === 264 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 265 /* JsxAttribute */ - || kind === 267 /* JsxSpreadAttribute */; + return kind === 267 /* JsxAttribute */ + || kind === 269 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 268 /* JsxExpression */; + return kind === 10 /* StringLiteral */ + || kind === 270 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 260 /* JsxOpeningElement */ - || kind === 259 /* JsxSelfClosingElement */; + return kind === 262 /* JsxOpeningElement */ + || kind === 261 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 269 /* CaseClause */ - || kind === 270 /* DefaultClause */; + return kind === 271 /* CaseClause */ + || kind === 272 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */; + return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 289 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */; + return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 157 /* SetAccessor */; + return node.kind === 159 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 156 /* GetAccessor */; + return node.kind === 158 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -13843,12 +14581,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 162 /* TypeReference */ || node.kind === 209 /* ExpressionWithTypeArguments */; + return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13877,15 +14615,14 @@ var ts; } ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { - return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; + return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isStringLiteralLike = isStringLiteralLike; })(ts || (ts = {})); /* @internal */ (function (ts) { - /** @internal */ function isNamedImportsOrExports(node) { - return node.kind === 250 /* NamedImports */ || node.kind === 254 /* NamedExports */; + return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function Symbol(flags, name) { @@ -13930,10 +14667,9 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - /* @internal */ function formatStringFromArgs(text, args, baseIndex) { if (baseIndex === void 0) { baseIndex = 0; } - return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); }); + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; function getLocaleSpecificMessage(message) { @@ -13962,7 +14698,6 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; - /* @internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -13987,7 +14722,6 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; - /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -14024,14 +14758,12 @@ var ts; function getDiagnosticFilePath(diagnostic) { return diagnostic.file ? diagnostic.file.path : undefined; } - /* @internal */ function compareDiagnostics(d1, d2) { return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || 0 /* EqualTo */; } ts.compareDiagnostics = compareDiagnostics; - /* @internal */ function compareDiagnosticsSkipRelatedInformation(d1, d2) { return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || ts.compareValues(d1.start, d2.start) || @@ -14092,6 +14824,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14852,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14865,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14323,7 +15067,6 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; - /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -14401,8 +15144,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15365,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14684,6 +15432,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14910,36 +15659,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15067,14 +15837,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +16015,98 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: // 0b or 0B + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: // 0o or 0O + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + var nIndex = stringValue.length - 1; + // Skip leading 0s + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + // Omit leading "0b", "0o", or "0x", and trailing "n" + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + var digit = digitChar <= 57 /* _9 */ + ? digitChar - 48 /* _0 */ + : 10 + digitChar - + (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; })(ts || (ts = {})); var ts; (function (ts) { @@ -15264,10 +16126,10 @@ var ts; var SourceFileConstructor; // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 277 /* SourceFile */) { + if (kind === 279 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 71 /* Identifier */) { + else if (kind === 72 /* Identifier */) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } else if (!ts.isNodeKind(kind)) { @@ -15316,28 +16178,29 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 145 /* LastToken */) { + if (!node || node.kind <= 147 /* LastToken */) { return; } switch (node.kind) { - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -15345,7 +16208,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -15353,405 +16216,399 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 168 /* TupleType */: + case 170 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 174 /* InferType */: + case 176 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 181 /* ImportType */: + case 183 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 175 /* ParenthesizedType */: - case 177 /* TypeOperator */: + case 177 /* ParenthesizedType */: + case 179 /* TypeOperator */: return visitNode(cbNode, node.type); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 179 /* MappedType */: + case 181 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return visitNode(cbNode, node.literal); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 210 /* AsExpression */: + case 212 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return visitNode(cbNode, node.name); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 277 /* SourceFile */: + case 279 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: return visitNode(cbNode, node.label); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 269 /* CaseClause */: + case 271 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 150 /* Decorator */: + case 152 /* Decorator */: return visitNode(cbNode, node.expression); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 276 /* EnumMember */: + case 278 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 250 /* NamedImports */: - case 254 /* NamedExports */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 169 /* OptionalType */: - case 170 /* RestType */: - case 281 /* JSDocTypeExpression */: - case 285 /* JSDocNonNullableType */: - case 284 /* JSDocNullableType */: - case 286 /* JSDocOptionalType */: - case 288 /* JSDocVariadicType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 283 /* JSDocTypeExpression */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 288 /* JSDocOptionalType */: + case 290 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 289 /* JSDocComment */: + case 291 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: - if (node.isNameFirst) { - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression); - } - else { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - } - case 298 /* JSDocReturnTag */: - return visitNode(cbNode, node.typeExpression); - case 300 /* JSDocTypeTag */: - return visitNode(cbNode, node.typeExpression); - case 293 /* JSDocAugmentsTag */: - return visitNode(cbNode, node.class); - case 301 /* JSDocTemplateTag */: - return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302 /* JSDocTypedefTag */: - if (node.typeExpression && - node.typeExpression.kind === 281 /* JSDocTypeExpression */) { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName); - } - else { - return visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - } - case 295 /* JSDocCallbackTag */: - return visitNode(cbNode, node.fullName) || + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303 /* JSDocTemplateTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304 /* JSDocTypedefTag */: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 /* JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297 /* JSDocCallbackTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299 /* JSDocThisTag */: - return visitNode(cbNode, node.typeExpression); - case 296 /* JSDocEnumTag */: - return visitNode(cbNode, node.typeExpression); - case 291 /* JSDocSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - ts.forEach(node.typeParameters, cbNode) || + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293 /* JSDocSignature */: + return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290 /* JSDocTypeLiteral */: - if (node.jsDocPropertyTags) { - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); - } - } - return; - case 306 /* PartiallyEmittedExpression */: + case 292 /* JSDocTypeLiteral */: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294 /* JSDocTag */: + case 296 /* JSDocClassTag */: + return visitNode(cbNode, node.tagName); + case 308 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15761,7 +16618,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16787,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -15965,18 +16826,18 @@ var ts; sourceFile.endOfFileToken = parseTokenNode(); } else { - var statement = createNode(219 /* ExpressionStatement */); + var statement = createNode(221 /* ExpressionStatement */); switch (token()) { - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: statement.expression = parseArrayLiteralExpression(); break; - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: statement.expression = parseTokenNode(); break; - case 38 /* MinusToken */: - if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) { + case 39 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) { statement.expression = parsePrefixUnaryExpression(); } else { @@ -15984,8 +16845,8 @@ var ts; } break; case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) { + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) { statement.expression = parseLiteralNode(); break; } @@ -16121,7 +16982,7 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // 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(277 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -16326,20 +17187,20 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token() === 71 /* Identifier */) { + if (token() === 72 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token() === 116 /* YieldKeyword */ && inYieldContext()) { + if (token() === 117 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) { + if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token() > 107 /* LastReservedWord */; + return token() > 108 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -16382,29 +17243,29 @@ var ts; } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token() === 25 /* SemicolonToken */) { + if (token() === 26 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 25 /* SemicolonToken */) { + if (token() === 26 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } return true; } else { - return parseExpected(25 /* SemicolonToken */); + return parseExpected(26 /* SemicolonToken */); } } function createNode(kind, pos) { nodeCount++; var p = pos >= 0 ? pos : scanner.getStartPos(); return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : - kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } function createNodeWithJSDoc(kind, pos) { @@ -16446,7 +17307,7 @@ var ts; parseErrorAtCurrentToken(diagnosticMessage, arg0); } var result = createNode(kind); - if (kind === 71 /* Identifier */) { + if (kind === 72 /* Identifier */) { result.escapedText = ""; } else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { @@ -16467,9 +17328,9 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(71 /* Identifier */); + var node = createNode(72 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 71 /* Identifier */) { + if (token() !== 72 /* Identifier */) { node.originalKeywordKind = token(); } node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); @@ -16478,7 +17339,7 @@ var ts; } // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; - return createMissingNode(71 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -16488,16 +17349,16 @@ var ts; } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || + token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { var node = parseLiteralNode(); node.text = internIdentifier(node.text); return node; } - if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -16509,13 +17370,13 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(147 /* ComputedPropertyName */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(149 /* ComputedPropertyName */); + parseExpected(22 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker // will error if it sees a comma expression. node.expression = allowInAnd(parseExpression); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function parseContextualModifier(t) { @@ -16530,20 +17391,20 @@ var ts; } function nextTokenCanFollowModifier() { switch (token()) { - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; - case 84 /* ExportKeyword */: + return nextToken() === 84 /* EnumKeyword */; + case 85 /* ExportKeyword */: nextToken(); - if (token() === 79 /* DefaultKeyword */) { + if (token() === 80 /* DefaultKeyword */) { return lookAhead(nextTokenCanFollowDefaultKeyword); } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - case 79 /* DefaultKeyword */: + return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + case 80 /* DefaultKeyword */: return nextTokenCanFollowDefaultKeyword(); - case 115 /* StaticKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: + case 116 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: nextToken(); return canFollowModifier(); default: @@ -16554,18 +17415,18 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 21 /* OpenBracketToken */ - || token() === 17 /* OpenBraceToken */ - || token() === 39 /* AsteriskToken */ - || token() === 24 /* DotDotDotToken */ + return token() === 22 /* OpenBracketToken */ + || token() === 18 /* OpenBraceToken */ + || token() === 40 /* AsteriskToken */ + || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenCanFollowDefaultKeyword() { nextToken(); - return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ || - token() === 109 /* InterfaceKeyword */ || - (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ || + token() === 110 /* InterfaceKeyword */ || + (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -16583,9 +17444,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -16593,21 +17454,29 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 22 /* OpenBracketToken */: + case 40 /* AsteriskToken */: + case 25 /* DotDotDotToken */: + case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` // That way we won't consume the body of a class in its heritage clause. - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -16622,37 +17491,39 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); + return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern(); case 19 /* TypeParameters */: return isIdentifier(); case 15 /* ArrayLiteralMembers */: - if (token() === 26 /* CommaToken */) { - return true; + switch (token()) { + case 27 /* CommaToken */: + case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; } // falls through case 11 /* ArgumentExpressions */: - return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(/*isJSDocParameter*/ false); case 17 /* JSDocParameters */: return isStartOfParameter(/*isJSDocParameter*/ true); case 20 /* TypeArguments */: case 21 /* TupleElementTypes */: - return token() === 26 /* CommaToken */ || isStartOfType(); + return token() === 27 /* CommaToken */ || isStartOfType(); case 22 /* HeritageClauses */: return isHeritageClause(); case 23 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; } return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17 /* OpenBraceToken */); - if (nextToken() === 18 /* CloseBraceToken */) { + ts.Debug.assert(token() === 18 /* OpenBraceToken */); + if (nextToken() === 19 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // @@ -16661,7 +17532,7 @@ var ts; // extends {} extends // extends {} implements var next = nextToken(); - return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */; + return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */; } return true; } @@ -16678,8 +17549,8 @@ var ts; return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 /* ImplementsKeyword */ || - token() === 85 /* ExtendsKeyword */) { + if (token() === 109 /* ImplementsKeyword */ || + token() === 86 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -16707,37 +17578,37 @@ var ts; case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: case 23 /* ImportOrExportSpecifiers */: - return token() === 18 /* CloseBraceToken */; + return token() === 19 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); case 19 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; + return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: case 21 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token() === 22 /* CloseBracketToken */; + return token() === 23 /* CloseBracketToken */; case 17 /* JSDocParameters */: case 16 /* Parameters */: case 18 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 20 /* TypeArguments */: // All other tokens should cause the type-argument to terminate except comma token - return token() !== 26 /* CommaToken */; + return token() !== 27 /* CommaToken */; case 22 /* HeritageClauses */: - return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; + return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; + return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */; case 14 /* JsxChildren */: - return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash); default: return false; } @@ -16757,7 +17628,7 @@ var ts; // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -16927,20 +17798,20 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 155 /* Constructor */: - case 160 /* IndexSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 152 /* PropertyDeclaration */: - case 215 /* SemicolonClassElement */: + case 157 /* Constructor */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 217 /* SemicolonClassElement */: return true; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ && - methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */; + var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */; return !nameIsConstructor; } } @@ -16949,8 +17820,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: return true; } } @@ -16959,58 +17830,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 217 /* VariableStatement */: - case 216 /* Block */: - case 220 /* IfStatement */: - case 219 /* ExpressionStatement */: - case 232 /* ThrowStatement */: - case 228 /* ReturnStatement */: - case 230 /* SwitchStatement */: - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 218 /* EmptyStatement */: - case 233 /* TryStatement */: - case 231 /* LabeledStatement */: - case 221 /* DoStatement */: - case 234 /* DebuggerStatement */: - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: - case 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 219 /* VariableStatement */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 221 /* ExpressionStatement */: + case 234 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 232 /* SwitchStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 220 /* EmptyStatement */: + case 235 /* TryStatement */: + case 233 /* LabeledStatement */: + case 223 /* DoStatement */: + case 236 /* DebuggerStatement */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 276 /* EnumMember */; + return node.kind === 278 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 151 /* PropertySignature */: - case 158 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 153 /* PropertySignature */: + case 160 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 235 /* VariableDeclaration */) { + if (node.kind !== 237 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -17031,7 +17902,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 149 /* Parameter */) { + if (node.kind !== 151 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -17088,7 +17959,7 @@ var ts; var startPos = scanner.getStartPos(); list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(26 /* CommaToken */)) { + if (parseOptional(27 /* CommaToken */)) { // No need to check for a zero length node since we know we parsed a comma continue; } @@ -17098,13 +17969,13 @@ var ts; } // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. - parseExpected(26 /* CommaToken */); + parseExpected(27 /* CommaToken */); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // 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 (considerSemicolonAsDelimiter && token() === 25 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } if (startPos === scanner.getStartPos()) { @@ -17155,8 +18026,8 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); - while (parseOptional(23 /* DotToken */)) { - if (token() === 27 /* LessThanToken */) { + while (parseOptional(24 /* DotToken */)) { + if (token() === 28 /* LessThanToken */) { // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting entity.jsdocDotPos = dotPos; break; @@ -17167,7 +18038,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(146 /* QualifiedName */, entity.pos); + var node = createNode(148 /* QualifiedName */, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -17198,33 +18069,33 @@ 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(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(204 /* TemplateExpression */); + var template = createNode(206 /* TemplateExpression */); template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); var list = []; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */); + } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { - var span = createNode(214 /* TemplateSpan */); + var span = createNode(216 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 18 /* CloseBraceToken */) { + if (token() === 19 /* CloseBraceToken */) { reScanTemplateToken(); literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(16 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */)); + literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */)); } span.literal = literal; return finishNode(span); @@ -17234,18 +18105,17 @@ var ts; } function parseTemplateHead() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); return fragment; } function parseTemplateMiddleOrTemplateTail() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind"); + ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind"); return fragment; } function parseLiteralLikeNode(kind) { var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = text; + node.text = scanner.getTokenValue(); if (scanner.hasExtendedUnicodeEscape()) { node.hasExtendedUnicodeEscape = true; } @@ -17267,24 +18137,24 @@ var ts; } // TYPES function parseTypeReference() { - var node = createNode(162 /* TypeReference */); + var node = createNode(164 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + if (!scanner.hasPrecedingLineBreak() && token() === 28 /* LessThanToken */) { + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */); } return finishNode(node); } // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return ts.nodeIsMissing(node.typeName); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: { + case 165 /* FunctionType */: + case 166 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -17292,20 +18162,20 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(161 /* TypePredicate */, lhs.pos); + var node = createNode(163 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(176 /* ThisType */); + var node = createNode(178 /* ThisType */); nextToken(); return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(282 /* JSDocAllType */); + var result = createNode(284 /* JSDocAllType */); if (postFixEquals) { - return createPostfixType(286 /* JSDocOptionalType */, result); + return createPostfixType(288 /* JSDocOptionalType */, result); } else { nextToken(); @@ -17313,7 +18183,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(285 /* JSDocNonNullableType */); + var result = createNode(287 /* JSDocNonNullableType */); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -17331,64 +18201,66 @@ var ts; // Foo // Foo(?= // (?| - if (token() === 26 /* CommaToken */ || - token() === 18 /* CloseBraceToken */ || - token() === 20 /* CloseParenToken */ || - token() === 29 /* GreaterThanToken */ || - token() === 58 /* EqualsToken */ || - token() === 49 /* BarToken */) { - var result = createNode(283 /* JSDocUnknownType */, pos); + if (token() === 27 /* CommaToken */ || + token() === 19 /* CloseBraceToken */ || + token() === 21 /* CloseParenToken */ || + token() === 30 /* GreaterThanToken */ || + token() === 59 /* EqualsToken */ || + token() === 50 /* BarToken */) { + var result = createNode(285 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(284 /* JSDocNullableType */, pos); + var result = createNode(286 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(287 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); nextToken(); - fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); } - var node = createNode(162 /* TypeReference */); + var node = createNode(164 /* TypeReference */); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(149 /* Parameter */); - if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { + var parameter = createNode(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) { parameter.name = parseIdentifierName(); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); } parameter.type = parseJSDocType(); return finishNode(parameter); } function parseJSDocType() { - var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { - var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); + var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } - if (token() === 58 /* EqualsToken */) { - return createPostfixType(286 /* JSDocOptionalType */, type); + if (token() === 59 /* EqualsToken */) { + return createPostfixType(288 /* JSDocOptionalType */, type); } return type; } function parseTypeQuery() { - var node = createNode(165 /* TypeQuery */); - parseExpected(103 /* TypeOfKeyword */); + var node = createNode(167 /* TypeQuery */); + parseExpected(104 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(148 /* TypeParameter */); + var node = createNode(150 /* TypeParameter */); node.name = parseIdentifier(); - if (parseOptional(85 /* ExtendsKeyword */)) { + if (parseOptional(86 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the // user writes a constraint that is an expression and not an actual type, then parse // it out as an expression (so we can recover well), but report that a type is needed @@ -17407,39 +18279,39 @@ var ts; node.expression = parseUnaryExpressionOrHigher(); } } - if (parseOptional(58 /* EqualsToken */)) { + if (parseOptional(59 /* EqualsToken */)) { node.default = parseType(); } return finishNode(node); } function parseTypeParameters() { - if (token() === 27 /* LessThanToken */) { - return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + if (token() === 28 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */); } } function parseParameterType() { - if (parseOptional(56 /* ColonToken */)) { + if (parseOptional(57 /* ColonToken */)) { return parseType(); } return undefined; } function isStartOfParameter(isJSDocParameter) { - return token() === 24 /* DotDotDotToken */ || + return token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 /* AtToken */ || + token() === 58 /* AtToken */ || isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseParameter() { - var node = createNodeWithJSDoc(149 /* Parameter */); - if (token() === 99 /* ThisKeyword */) { + var node = createNodeWithJSDoc(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); @@ -17454,7 +18326,7 @@ var ts; // to avoid this we'll advance cursor to the next token. nextToken(); } - node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.questionToken = parseOptionalToken(56 /* QuestionToken */); node.type = parseParameterType(); node.initializer = parseInitializer(); return finishNode(node); @@ -17476,16 +18348,16 @@ var ts; return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { - if (returnToken === 36 /* EqualsGreaterThanToken */) { + if (returnToken === 37 /* EqualsGreaterThanToken */) { parseExpected(returnToken); return true; } - else if (parseOptional(56 /* ColonToken */)) { + else if (parseOptional(57 /* ColonToken */)) { return true; } - else if (isType && token() === 36 /* EqualsGreaterThanToken */) { + else if (isType && token() === 37 /* EqualsGreaterThanToken */) { // This is easy to get backward, especially in type contexts, so parse the type anyway - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); nextToken(); return true; } @@ -17506,7 +18378,7 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (!parseExpected(19 /* OpenParenToken */)) { + if (!parseExpected(20 /* OpenParenToken */)) { signature.parameters = createMissingList(); return false; } @@ -17519,12 +18391,12 @@ var ts; parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - return parseExpected(20 /* CloseParenToken */); + return parseExpected(21 /* CloseParenToken */); } function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. // First check if it was a comma. If so, we're done with the member. - if (parseOptional(26 /* CommaToken */)) { + if (parseOptional(27 /* CommaToken */)) { return; } // Didn't have a comma. We must have a (possible ASI) semicolon. @@ -17532,15 +18404,15 @@ var ts; } function parseSignatureMember(kind) { var node = createNodeWithJSDoc(kind); - if (kind === 159 /* ConstructSignature */) { - parseExpected(94 /* NewKeyword */); + if (kind === 161 /* ConstructSignature */) { + parseExpected(95 /* NewKeyword */); } - fillSignature(56 /* ColonToken */, 4 /* Type */, node); + fillSignature(57 /* ColonToken */, 4 /* Type */, node); parseTypeMemberSemicolon(); return finishNode(node); } function isIndexSignature() { - return token() === 21 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { // The only allowed sequence is: @@ -17560,7 +18432,7 @@ var ts; // [] // nextToken(); - if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) { + if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) { return true; } if (ts.isModifierKind(token())) { @@ -17579,39 +18451,39 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token() !== 55 /* QuestionToken */) { + if (token() !== 56 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; + return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(node) { - node.kind = 160 /* IndexSignature */; - node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.kind = 162 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(node) { node.name = parsePropertyName(); - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - node.kind = 153 /* MethodSignature */; + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + node.kind = 155 /* MethodSignature */; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] - fillSignature(56 /* ColonToken */, 4 /* Type */, node); + fillSignature(57 /* ColonToken */, 4 /* Type */, node); } else { - node.kind = 151 /* PropertySignature */; + node.kind = 153 /* PropertySignature */; node.type = parseTypeAnnotation(); - if (token() === 58 /* EqualsToken */) { + if (token() === 59 /* 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. @@ -17623,7 +18495,7 @@ var ts; } function isTypeMemberStart() { // Return true if we have the start of a signature member - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return true; } var idToken = false; @@ -17633,7 +18505,7 @@ var ts; nextToken(); } // Index signatures and computed property names are type members - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers @@ -17644,21 +18516,21 @@ var ts; // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token() === 19 /* OpenParenToken */ || - token() === 27 /* LessThanToken */ || - token() === 55 /* QuestionToken */ || - token() === 56 /* ColonToken */ || - token() === 26 /* CommaToken */ || + return token() === 20 /* OpenParenToken */ || + token() === 28 /* LessThanToken */ || + token() === 56 /* QuestionToken */ || + token() === 57 /* ColonToken */ || + token() === 27 /* CommaToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(158 /* CallSignature */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseSignatureMember(160 /* CallSignature */); } - if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(159 /* ConstructSignature */); + if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161 /* ConstructSignature */); } var node = createNodeWithJSDoc(0 /* Unknown */); node.modifiers = parseModifiers(); @@ -17669,30 +18541,30 @@ var ts; } function nextTokenIsOpenParenOrLessThan() { nextToken(); - return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; + return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */; } function nextTokenIsDot() { - return nextToken() === 23 /* DotToken */; + return nextToken() === 24 /* DotToken */; } function nextTokenIsOpenParenOrLessThanOrDot() { switch (nextToken()) { - case 19 /* OpenParenToken */: - case 27 /* LessThanToken */: - case 23 /* DotToken */: + case 20 /* OpenParenToken */: + case 28 /* LessThanToken */: + case 24 /* DotToken */: return true; } return false; } function parseTypeLiteral() { - var node = createNode(166 /* TypeLiteral */); + var node = createNode(168 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { members = parseList(4 /* TypeMembers */, parseTypeMember); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { members = createMissingList(); @@ -17701,89 +18573,89 @@ var ts; } function isStartOfMappedType() { nextToken(); - if (token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { - return nextToken() === 132 /* ReadonlyKeyword */; + if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + return nextToken() === 133 /* ReadonlyKeyword */; } - if (token() === 132 /* ReadonlyKeyword */) { + if (token() === 133 /* ReadonlyKeyword */) { nextToken(); } - return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; + return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */; } function parseMappedTypeParameter() { - var node = createNode(148 /* TypeParameter */); + var node = createNode(150 /* TypeParameter */); node.name = parseIdentifier(); - parseExpected(92 /* InKeyword */); + parseExpected(93 /* InKeyword */); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(179 /* MappedType */); - parseExpected(17 /* OpenBraceToken */); - if (token() === 132 /* ReadonlyKeyword */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { + var node = createNode(181 /* MappedType */); + parseExpected(18 /* OpenBraceToken */); + if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { node.readonlyToken = parseTokenNode(); - if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) { - parseExpectedToken(132 /* ReadonlyKeyword */); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + parseExpectedToken(133 /* ReadonlyKeyword */); } } - parseExpected(21 /* OpenBracketToken */); + parseExpected(22 /* OpenBracketToken */); node.typeParameter = parseMappedTypeParameter(); - parseExpected(22 /* CloseBracketToken */); - if (token() === 55 /* QuestionToken */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { + parseExpected(23 /* CloseBracketToken */); + if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { node.questionToken = parseTokenNode(); - if (node.questionToken.kind !== 55 /* QuestionToken */) { - parseExpectedToken(55 /* QuestionToken */); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + parseExpectedToken(56 /* QuestionToken */); } } node.type = parseTypeAnnotation(); parseSemicolon(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseTupleElementType() { var pos = getNodePos(); - if (parseOptional(24 /* DotDotDotToken */)) { - var node = createNode(170 /* RestType */, pos); + if (parseOptional(25 /* DotDotDotToken */)) { + var node = createNode(172 /* RestType */, pos); node.type = parseType(); return finishNode(node); } var type = parseType(); - if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 284 /* JSDocNullableType */ && type.pos === type.type.pos) { - type.kind = 169 /* OptionalType */; + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 171 /* OptionalType */; } return type; } function parseTupleType() { - var node = createNode(168 /* TupleType */); - node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + var node = createNode(170 /* TupleType */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(175 /* ParenthesizedType */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(177 /* ParenthesizedType */); + parseExpected(20 /* OpenParenToken */); node.type = parseType(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseFunctionOrConstructorType() { var pos = getNodePos(); - var kind = parseOptional(94 /* NewKeyword */) ? 164 /* ConstructorType */ : 163 /* FunctionType */; + var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */; var node = createNodeWithJSDoc(kind, pos); - fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 23 /* DotToken */ ? undefined : node; + return token() === 24 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(180 /* LiteralType */); + var node = createNode(182 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(200 /* PrefixUnaryExpression */); - unaryMinusExpression.operator = 38 /* MinusToken */; + unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 39 /* MinusToken */; nextToken(); } - var expression = token() === 101 /* TrueKeyword */ || token() === 86 /* FalseKeyword */ + var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */ ? parseTokenNode() : parseLiteralLikeNode(token()); if (negative) { @@ -17796,79 +18668,82 @@ var ts; } function isStartOfTypeOfImportType() { nextToken(); - return token() === 91 /* ImportKeyword */; + return token() === 92 /* ImportKeyword */; } function parseImportType() { sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; - var node = createNode(181 /* ImportType */); - if (parseOptional(103 /* TypeOfKeyword */)) { + var node = createNode(183 /* ImportType */); + if (parseOptional(104 /* TypeOfKeyword */)) { node.isTypeOf = true; } - parseExpected(91 /* ImportKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(92 /* ImportKeyword */); + parseExpected(20 /* OpenParenToken */); node.argument = parseType(); - parseExpected(20 /* CloseParenToken */); - if (parseOptional(23 /* DotToken */)) { + parseExpected(21 /* CloseParenToken */); + if (parseOptional(24 /* DotToken */)) { node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); } node.typeArguments = tryParseTypeArguments(); return finishNode(node); } - function nextTokenIsNumericLiteral() { - return nextToken() === 8 /* NumericLiteral */; + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */; } function parseNonArrayType() { switch (token()) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 138 /* SymbolKeyword */: - case 122 /* BooleanKeyword */: - case 140 /* UndefinedKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 139 /* SymbolKeyword */: + case 123 /* BooleanKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: return parseJSDocAllType(/*postfixEquals*/ false); - case 61 /* AsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: return parseJSDocAllType(/*postfixEquals*/ true); - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseJSDocFunctionType(); - case 51 /* ExclamationToken */: + case 52 /* ExclamationToken */: return parseJSDocNonNullableType(); - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return parseLiteralTypeNode(); - case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); - case 105 /* VoidKeyword */: - case 95 /* NullKeyword */: + case 39 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 106 /* VoidKeyword */: + case 96 /* NullKeyword */: return parseTokenNode(); - case 99 /* ThisKeyword */: { + case 100 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 103 /* TypeOfKeyword */: + case 104 /* TypeOfKeyword */: return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: return parseTupleType(); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return parseParenthesizedType(); - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return parseImportType(); default: return parseTypeReference(); @@ -17876,42 +18751,44 @@ var ts; } function isStartOfType(inStartOfParameter) { switch (token()) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 141 /* UniqueKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 103 /* TypeOfKeyword */: - case 131 /* NeverKeyword */: - case 17 /* OpenBraceToken */: - case 21 /* OpenBracketToken */: - case 27 /* LessThanToken */: - case 49 /* BarToken */: - case 48 /* AmpersandToken */: - case 94 /* NewKeyword */: - case 9 /* StringLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 142 /* UniqueKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 104 /* TypeOfKeyword */: + case 132 /* NeverKeyword */: + case 18 /* OpenBraceToken */: + case 22 /* OpenBracketToken */: + case 28 /* LessThanToken */: + case 50 /* BarToken */: + case 49 /* AmpersandToken */: + case 95 /* NewKeyword */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 135 /* ObjectKeyword */: - case 39 /* AsteriskToken */: - case 55 /* QuestionToken */: - case 51 /* ExclamationToken */: - case 24 /* DotDotDotToken */: - case 126 /* InferKeyword */: - case 91 /* ImportKeyword */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 136 /* ObjectKeyword */: + case 40 /* AsteriskToken */: + case 56 /* QuestionToken */: + case 52 /* ExclamationToken */: + case 25 /* DotDotDotToken */: + case 127 /* InferKeyword */: + case 92 /* ImportKeyword */: return true; - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return !inStartOfParameter; - case 38 /* MinusToken */: - return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); - case 19 /* OpenParenToken */: + case 39 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); @@ -17921,35 +18798,35 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 51 /* ExclamationToken */: - type = createPostfixType(285 /* JSDocNonNullableType */, type); + case 52 /* ExclamationToken */: + type = createPostfixType(287 /* JSDocNonNullableType */, type); break; - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createPostfixType(284 /* JSDocNullableType */, type); + type = createPostfixType(286 /* JSDocNullableType */, type); break; - case 21 /* OpenBracketToken */: - parseExpected(21 /* OpenBracketToken */); + case 22 /* OpenBracketToken */: + parseExpected(22 /* OpenBracketToken */); if (isStartOfType()) { - var node = createNode(178 /* IndexedAccessType */, type.pos); + var node = createNode(180 /* IndexedAccessType */, type.pos); node.objectType = type; node.indexType = parseType(); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); type = finishNode(node); } else { - var node = createNode(167 /* ArrayType */, type.pos); + var node = createNode(169 /* ArrayType */, type.pos); node.elementType = type; - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); type = finishNode(node); } break; @@ -17966,16 +18843,16 @@ var ts; return finishNode(postfix); } function parseTypeOperator(operator) { - var node = createNode(177 /* TypeOperator */); + var node = createNode(179 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseInferType() { - var node = createNode(174 /* InferType */); - parseExpected(126 /* InferKeyword */); - var typeParameter = createNode(148 /* TypeParameter */); + var node = createNode(176 /* InferType */); + parseExpected(127 /* InferKeyword */); + var typeParameter = createNode(150 /* TypeParameter */); typeParameter.name = parseIdentifier(); node.typeParameter = finishNode(typeParameter); return finishNode(node); @@ -17983,10 +18860,10 @@ var ts; function parseTypeOperatorOrHigher() { var operator = token(); switch (operator) { - case 128 /* KeyOfKeyword */: - case 141 /* UniqueKeyword */: + case 129 /* KeyOfKeyword */: + case 142 /* UniqueKeyword */: return parseTypeOperator(operator); - case 126 /* InferKeyword */: + case 127 /* InferKeyword */: return parseInferType(); } return parsePostfixTypeOrHigher(); @@ -18006,27 +18883,27 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(172 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(171 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */); } function isStartOfFunctionType() { - if (token() === 27 /* LessThanToken */) { + if (token() === 28 /* LessThanToken */) { return true; } - return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token() === 99 /* ThisKeyword */) { + if (isIdentifier() || token() === 100 /* ThisKeyword */) { nextToken(); return true; } - if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) { + if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -18036,7 +18913,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -18044,17 +18921,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || - token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || + token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token() === 20 /* CloseParenToken */) { + if (token() === 21 /* CloseParenToken */) { nextToken(); - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -18066,7 +18943,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(161 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -18077,7 +18954,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -18088,49 +18965,50 @@ var ts; return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) { + if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) { return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); - if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { - var node = createNode(173 /* ConditionalType */, type.pos); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) { + var node = createNode(175 /* ConditionalType */, type.pos); node.checkType = type; // The type following 'extends' is not permitted to be another conditional type node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); - parseExpected(55 /* QuestionToken */); + parseExpected(56 /* QuestionToken */); node.trueType = parseTypeWorker(); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.falseType = parseTypeWorker(); return finishNode(node); } return type; } function parseTypeAnnotation() { - return parseOptional(56 /* ColonToken */) ? parseType() : undefined; + return parseOptional(57 /* ColonToken */) ? parseType() : undefined; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { switch (token()) { - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 19 /* OpenParenToken */: - case 21 /* OpenBracketToken */: - case 17 /* OpenBraceToken */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 94 /* NewKeyword */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 71 /* Identifier */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 20 /* OpenParenToken */: + case 22 /* OpenBracketToken */: + case 18 /* OpenBraceToken */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 95 /* NewKeyword */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 72 /* Identifier */: return true; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); default: return isIdentifier(); @@ -18141,18 +19019,18 @@ var ts; return true; } switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 27 /* LessThanToken */: - case 121 /* AwaitKeyword */: - case 116 /* YieldKeyword */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 28 /* LessThanToken */: + case 122 /* AwaitKeyword */: + case 117 /* YieldKeyword */: // Yield/await always starts an expression. Either it is an identifier (in which case // it is definitely an expression). Or it's a keyword (either because we're in // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. @@ -18170,10 +19048,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 17 /* OpenBraceToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && - token() !== 57 /* AtToken */ && + return token() !== 18 /* OpenBraceToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + token() !== 58 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -18187,7 +19065,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) { + while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -18196,7 +19074,7 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(58 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { // AssignmentExpression[in,yield]: @@ -18241,7 +19119,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -18257,7 +19135,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 116 /* YieldKeyword */) { + if (token() === 117 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -18286,15 +19164,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(205 /* YieldExpression */); + var node = createNode(207 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 39 /* AsteriskToken */ || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + (token() === 40 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -18305,20 +19183,20 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(195 /* ArrowFunction */, asyncModifier.pos); + node = createNode(197 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(195 /* ArrowFunction */, identifier.pos); + node = createNode(197 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(149 /* Parameter */, identifier.pos); + var parameter = createNode(151 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); - node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -18343,8 +19221,8 @@ var ts; // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */); - arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return finishNode(arrowFunction); @@ -18354,10 +19232,10 @@ var ts; // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -18367,28 +19245,28 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) { + if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) { return 0 /* False */; } } var first = token(); var second = nextToken(); - if (first === 19 /* OpenParenToken */) { - if (second === 20 /* CloseParenToken */) { + if (first === 20 /* OpenParenToken */) { + if (second === 21 /* CloseParenToken */) { // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. var third = nextToken(); switch (third) { - case 36 /* EqualsGreaterThanToken */: - case 56 /* ColonToken */: - case 17 /* OpenBraceToken */: + case 37 /* EqualsGreaterThanToken */: + case 57 /* ColonToken */: + case 18 /* OpenBraceToken */: return 1 /* True */; default: return 0 /* False */; @@ -18400,42 +19278,42 @@ var ts; // ({ x }) => { } // ([ x ]) // ({ x }) - if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) { + if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) { return 2 /* Unknown */; } // Simple case: "(..." // This is an arrow function with a rest parameter. - if (second === 24 /* DotDotDotToken */) { + if (second === 25 /* DotDotDotToken */) { return 1 /* True */; } // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. - if (ts.isModifierKind(second) && second !== 120 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { return 1 /* True */; } // If we had "(" followed by something that's not an identifier, // then this definitely doesn't look like a lambda. "this" is not // valid, but we want to parse it and then give a semantic error. - if (!isIdentifier() && second !== 99 /* ThisKeyword */) { + if (!isIdentifier() && second !== 100 /* ThisKeyword */) { return 0 /* False */; } switch (nextToken()) { - case 56 /* ColonToken */: + case 57 /* ColonToken */: // If we have something like "(a:", then we must have a // type-annotated parameter in an arrow function expression. return 1 /* True */; - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: nextToken(); // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 58 /* EqualsToken */ || token() === 20 /* CloseParenToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) { return 1 /* True */; } // Otherwise it is definitely not a lambda. return 0 /* False */; - case 26 /* CommaToken */: - case 58 /* EqualsToken */: - case 20 /* CloseParenToken */: + case 27 /* CommaToken */: + case 59 /* EqualsToken */: + case 21 /* CloseParenToken */: // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function return 2 /* Unknown */; } @@ -18443,7 +19321,7 @@ var ts; return 0 /* False */; } else { - ts.Debug.assert(first === 27 /* LessThanToken */); + ts.Debug.assert(first === 28 /* LessThanToken */); // If we have "<" not followed by an identifier, // then this definitely is not an arrow function. if (!isIdentifier()) { @@ -18453,17 +19331,17 @@ var ts; if (sourceFile.languageVariant === 1 /* JSX */) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 85 /* ExtendsKeyword */) { + if (third === 86 /* ExtendsKeyword */) { var fourth = nextToken(); switch (fourth) { - case 58 /* EqualsToken */: - case 29 /* GreaterThanToken */: + case 59 /* EqualsToken */: + case 30 /* GreaterThanToken */: return false; default: return true; } } - else if (third === 26 /* CommaToken */) { + else if (third === 27 /* CommaToken */) { return true; } return false; @@ -18482,7 +19360,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); @@ -18495,23 +19373,23 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { return 1 /* True */; } } return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNodeWithJSDoc(195 /* ArrowFunction */); + var node = createNodeWithJSDoc(197 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. @@ -18521,7 +19399,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) { + if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) { return undefined; } // Parsing a signature isn't enough. @@ -18532,19 +19410,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { + if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); } - if (token() !== 25 /* SemicolonToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && + if (token() !== 26 /* SemicolonToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -18569,20 +19447,20 @@ var ts; } function parseConditionalExpressionRest(leftOperand) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - var questionToken = parseOptionalToken(55 /* QuestionToken */); + var questionToken = parseOptionalToken(56 /* QuestionToken */); if (!questionToken) { return leftOperand; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(203 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(205 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56 /* ColonToken */); + node.colonToken = parseExpectedToken(57 /* ColonToken */); node.whenFalse = ts.nodeIsPresent(node.colonToken) ? parseAssignmentExpressionOrHigher() - : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -18590,7 +19468,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 145 /* OfKeyword */; + return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -18619,16 +19497,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 92 /* InKeyword */ && inDisallowInContext()) { + if (token() === 93 /* InKeyword */ && inDisallowInContext()) { break; } - if (token() === 118 /* AsKeyword */) { + if (token() === 119 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -18649,51 +19527,51 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 92 /* InKeyword */) { + if (inDisallowInContext() && token() === 93 /* InKeyword */) { return false; } return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(202 /* BinaryExpression */, left.pos); + var node = createNode(204 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(210 /* AsExpression */, left.pos); + var node = createNode(212 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(200 /* PrefixUnaryExpression */); + var node = createNode(202 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(196 /* DeleteExpression */); + var node = createNode(198 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(197 /* TypeOfExpression */); + var node = createNode(199 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(198 /* VoidExpression */); + var node = createNode(200 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 121 /* AwaitKeyword */) { + if (token() === 122 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -18703,7 +19581,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(199 /* AwaitExpression */); + var node = createNode(201 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -18727,7 +19605,7 @@ var ts; */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? + return token() === 41 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } @@ -18744,10 +19622,10 @@ var ts; */ var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40 /* AsteriskAsteriskToken */) { + if (token() === 41 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 192 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) { parseErrorAt(pos, end, 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 { @@ -18772,23 +19650,23 @@ var ts; */ function parseSimpleUnaryExpression() { switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: return parsePrefixUnaryExpression(); - case 80 /* DeleteKeyword */: + case 81 /* DeleteKeyword */: return parseDeleteExpression(); - case 103 /* TypeOfKeyword */: + case 104 /* TypeOfKeyword */: return parseTypeOfExpression(); - case 105 /* VoidKeyword */: + case 106 /* VoidKeyword */: return parseVoidExpression(); - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // This is modified UnaryExpression grammar in TypeScript // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); - case 121 /* AwaitKeyword */: + case 122 /* AwaitKeyword */: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -18811,16 +19689,16 @@ var ts; // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 121 /* AwaitKeyword */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 122 /* AwaitKeyword */: return false; - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression if (sourceFile.languageVariant !== 1 /* JSX */) { return false; @@ -18843,21 +19721,21 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseUpdateExpression() { - if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(200 /* PrefixUnaryExpression */); + if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) { + var node = createNode(202 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(201 /* PostfixUnaryExpression */, expression.pos); + if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -18898,7 +19776,7 @@ var ts; // 3)we have a MemberExpression which either completes the LeftHandSideExpression, // or starts the beginning of the first four CallExpression productions. var expression; - if (token() === 91 /* ImportKeyword */) { + if (token() === 92 /* ImportKeyword */) { if (lookAhead(nextTokenIsOpenParenOrLessThan)) { // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" // For example: @@ -18913,8 +19791,8 @@ var ts; var fullStart = scanner.getStartPos(); nextToken(); // advance past the 'import' nextToken(); // advance past the dot - var node = createNode(212 /* MetaProperty */, fullStart); - node.keywordToken = 91 /* ImportKeyword */; + var node = createNode(214 /* MetaProperty */, fullStart); + node.keywordToken = 92 /* ImportKeyword */; node.name = parseIdentifierName(); expression = finishNode(node); sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; @@ -18924,7 +19802,7 @@ var ts; } } else { - expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); } // Now, we *may* be complete. However, we might have consumed the start of a // CallExpression. As such, we need to consume the rest of it here to be complete. @@ -18983,22 +19861,22 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) { + if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(187 /* PropertyAccessExpression */, expression.pos); + var node = createNode(189 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - parseExpectedToken(23 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 260 /* JsxOpeningElement */) { - var node = createNode(258 /* JsxElement */, opening.pos); + if (opening.kind === 262 /* JsxOpeningElement */) { + var node = createNode(260 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -19007,15 +19885,15 @@ var ts; } result = finishNode(node); } - else if (opening.kind === 263 /* JsxOpeningFragment */) { - var node = createNode(262 /* JsxFragment */, opening.pos); + else if (opening.kind === 265 /* JsxOpeningFragment */) { + var node = createNode(264 /* JsxFragment */, opening.pos); node.openingFragment = opening; node.children = parseJsxChildren(node.openingFragment); node.closingFragment = parseJsxClosingFragment(inExpressionContext); result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 259 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -19026,15 +19904,15 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token() === 27 /* LessThanToken */) { + if (inExpressionContext && token() === 28 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(202 /* BinaryExpression */, result.pos); + var badNode = createNode(204 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -19042,8 +19920,8 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10 /* JsxText */); - node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; + var node = createNode(11 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; currentToken = scanner.scanJsxToken(); return finishNode(node); } @@ -19059,15 +19937,15 @@ var ts; parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); } return undefined; - case 28 /* LessThanSlashToken */: + case 29 /* LessThanSlashToken */: case 7 /* ConflictMarkerTrivia */: return undefined; - case 10 /* JsxText */: - case 11 /* JsxTextAllWhiteSpaces */: + case 11 /* JsxText */: + case 12 /* JsxTextAllWhiteSpaces */: return parseJsxText(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); default: return ts.Debug.assertNever(token); @@ -19088,16 +19966,16 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(266 /* JsxAttributes */); + var jsxAttributes = createNode(268 /* JsxAttributes */); jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(27 /* LessThanToken */); - if (token() === 29 /* GreaterThanToken */) { + parseExpected(28 /* LessThanToken */); + if (token() === 30 /* GreaterThanToken */) { // See below for explanation of scanJsxText - var node_1 = createNode(263 /* JsxOpeningFragment */, fullStart); + var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart); scanJsxText(); return finishNode(node_1); } @@ -19105,23 +19983,23 @@ var ts; var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; - if (token() === 29 /* GreaterThanToken */) { + if (token() === 30 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(260 /* JsxOpeningElement */, fullStart); + node = createNode(262 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { - parseExpected(41 /* SlashToken */); + parseExpected(42 /* SlashToken */); if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(259 /* JsxSelfClosingElement */, fullStart); + node = createNode(261 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.typeArguments = typeArguments; @@ -19135,10 +20013,10 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token() === 99 /* ThisKeyword */ ? + var expression = token() === 100 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); + while (parseOptional(24 /* DotToken */)) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -19146,33 +20024,33 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(268 /* JsxExpression */); - if (!parseExpected(17 /* OpenBraceToken */)) { + var node = createNode(270 /* JsxExpression */); + if (!parseExpected(18 /* OpenBraceToken */)) { return undefined; } - if (token() !== 18 /* CloseBraceToken */) { - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + if (token() !== 19 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { - parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(265 /* JsxAttribute */); + var node = createNode(267 /* JsxAttribute */); node.name = parseIdentifierName(); - if (token() === 58 /* EqualsToken */) { + if (token() === 59 /* EqualsToken */) { switch (scanJsxAttributeValue()) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: node.initializer = parseLiteralNode(); break; default: @@ -19183,72 +20061,72 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(267 /* JsxSpreadAttribute */); - parseExpected(17 /* OpenBraceToken */); - parseExpected(24 /* DotDotDotToken */); + var node = createNode(269 /* JsxSpreadAttribute */); + parseExpected(18 /* OpenBraceToken */); + parseExpected(25 /* DotDotDotToken */); node.expression = parseExpression(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(261 /* JsxClosingElement */); - parseExpected(28 /* LessThanSlashToken */); + var node = createNode(263 /* JsxClosingElement */); + parseExpected(29 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxClosingFragment(inExpressionContext) { - var node = createNode(264 /* JsxClosingFragment */); - parseExpected(28 /* LessThanSlashToken */); + var node = createNode(266 /* JsxClosingFragment */); + parseExpected(29 /* LessThanSlashToken */); if (ts.tokenIsIdentifierOrKeyword(token())) { parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(192 /* TypeAssertionExpression */); - parseExpected(27 /* LessThanToken */); + var node = createNode(194 /* TypeAssertionExpression */); + parseExpected(28 /* LessThanToken */); node.type = parseType(); - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(23 /* DotToken */); + var dotToken = parseOptionalToken(24 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; } - if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(211 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName - if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(188 /* ElementAccessExpression */, expression.pos); + if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) { + var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; - if (token() === 22 /* CloseBracketToken */) { - indexedAccess.argumentExpression = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + if (token() === 23 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); } else { var argument = allowInAnd(parseExpression); @@ -19257,7 +20135,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } @@ -19269,13 +20147,13 @@ var ts; } } function isTemplateStartOfTaggedTemplate() { - return token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */; + return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */; } function parseTaggedTemplateRest(tag, typeArguments) { - var tagExpression = createNode(191 /* TaggedTemplateExpression */, tag.pos); + var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos); tagExpression.tag = tag; tagExpression.typeArguments = typeArguments; - tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); return finishNode(tagExpression); @@ -19283,7 +20161,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 27 /* LessThanToken */) { + if (token() === 28 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -19296,15 +20174,15 @@ var ts; expression = parseTaggedTemplateRest(expression, typeArguments); continue; } - var callExpr = createNode(189 /* CallExpression */, expression.pos); + var callExpr = createNode(191 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(189 /* CallExpression */, expression.pos); + else if (token() === 20 /* OpenParenToken */) { + var callExpr = createNode(191 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -19314,17 +20192,17 @@ var ts; } } function parseArgumentList() { - parseExpected(19 /* OpenParenToken */); + parseExpected(20 /* OpenParenToken */); var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(27 /* LessThanToken */)) { + if (!parseOptional(28 /* LessThanToken */)) { return undefined; } var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); - if (!parseExpected(29 /* GreaterThanToken */)) { + if (!parseExpected(30 /* GreaterThanToken */)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } @@ -19336,34 +20214,34 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 19 /* OpenParenToken */: // foo( - case 13 /* NoSubstitutionTemplateLiteral */: // foo `...` - case 14 /* TemplateHead */: // foo `...${100}...` + case 20 /* OpenParenToken */: // foo( + case 14 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 15 /* TemplateHead */: // foo `...${100}...` // these are the only tokens can legally follow a type argument // list. So we definitely want to treat them as type arg lists. - case 23 /* DotToken */: // foo. - case 20 /* CloseParenToken */: // foo) - case 22 /* CloseBracketToken */: // foo] - case 56 /* ColonToken */: // foo: - case 25 /* SemicolonToken */: // foo; - case 55 /* QuestionToken */: // foo? - case 32 /* EqualsEqualsToken */: // foo == - case 34 /* EqualsEqualsEqualsToken */: // foo === - case 33 /* ExclamationEqualsToken */: // foo != - case 35 /* ExclamationEqualsEqualsToken */: // foo !== - case 53 /* AmpersandAmpersandToken */: // foo && - case 54 /* BarBarToken */: // foo || - case 50 /* CaretToken */: // foo ^ - case 48 /* AmpersandToken */: // foo & - case 49 /* BarToken */: // foo | - case 18 /* CloseBraceToken */: // foo } + case 24 /* DotToken */: // foo. + case 21 /* CloseParenToken */: // foo) + case 23 /* CloseBracketToken */: // foo] + case 57 /* ColonToken */: // foo: + case 26 /* SemicolonToken */: // foo; + case 56 /* QuestionToken */: // foo? + case 33 /* EqualsEqualsToken */: // foo == + case 35 /* EqualsEqualsEqualsToken */: // foo === + case 34 /* ExclamationEqualsToken */: // foo != + case 36 /* ExclamationEqualsEqualsToken */: // foo !== + case 54 /* AmpersandAmpersandToken */: // foo && + case 55 /* BarBarToken */: // foo || + case 51 /* CaretToken */: // foo ^ + case 49 /* AmpersandToken */: // foo & + case 50 /* BarToken */: // foo | + case 19 /* CloseBraceToken */: // foo } case 1 /* EndOfFileToken */: // foo // these cases can't legally follow a type arg list. However, they're not legal // expressions either. The user is probably in the middle of a generic type. So // treat it as such. return true; - case 26 /* CommaToken */: // foo, - case 17 /* OpenBraceToken */: // foo { + case 27 /* CommaToken */: // foo, + case 18 /* OpenBraceToken */: // foo { // We don't want to treat these as type arguments. Otherwise we'll parse this // as an invocation expression. Instead, we want to parse out the expression // in isolation from the type arguments. @@ -19375,22 +20253,23 @@ var ts; function parsePrimaryExpression() { switch (token()) { case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return parseLiteralNode(); - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return parseTokenNode(); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return parseParenthesizedExpression(); - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: return parseArrayLiteralExpression(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseObjectLiteralExpression(); - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. // If we encounter `async [no LineTerminator here] function` then this is an async // function; otherwise, its an identifier. @@ -19398,75 +20277,76 @@ var ts; break; } return parseFunctionExpression(); - case 75 /* ClassKeyword */: + case 76 /* ClassKeyword */: return parseClassExpression(); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseFunctionExpression(); - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: return parseNewExpressionOrNewDotTarget(); - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) { return parseLiteralNode(); } break; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNodeWithJSDoc(193 /* ParenthesizedExpression */); - parseExpected(19 /* OpenParenToken */); + var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(206 /* SpreadElement */); - parseExpected(24 /* DotDotDotToken */); + var node = createNode(208 /* SpreadElement */); + parseExpected(25 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(208 /* OmittedExpression */) : + return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(185 /* ArrayLiteralExpression */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(187 /* ArrayLiteralExpression */); + parseExpected(22 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function parseObjectLiteralElement() { var node = createNodeWithJSDoc(0 /* Unknown */); - if (parseOptionalToken(24 /* DotDotDotToken */)) { - node.kind = 275 /* SpreadAssignment */; + if (parseOptionalToken(25 /* DotDotDotToken */)) { + node.kind = 277 /* SpreadAssignment */; node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* GetAccessor */); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); } - if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 157 /* SetAccessor */); + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); } - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } // check if it is short-hand property assignment or normal property assignment @@ -19474,30 +20354,30 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */); if (isShorthandPropertyAssignment) { - node.kind = 274 /* ShorthandPropertyAssignment */; - var equalsToken = parseOptionalToken(58 /* EqualsToken */); + node.kind = 276 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(59 /* EqualsToken */); if (equalsToken) { node.equalsToken = equalsToken; node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } } else { - node.kind = 273 /* PropertyAssignment */; - parseExpected(56 /* ColonToken */); + node.kind = 275 /* PropertyAssignment */; + parseExpected(57 /* ColonToken */); node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(186 /* ObjectLiteralExpression */); - parseExpected(17 /* OpenBraceToken */); + var node = createNode(188 /* ObjectLiteralExpression */); + parseExpected(18 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseFunctionExpression() { @@ -19510,10 +20390,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNodeWithJSDoc(194 /* FunctionExpression */); + var node = createNodeWithJSDoc(196 /* FunctionExpression */); node.modifiers = parseModifiers(); - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; node.name = @@ -19521,7 +20401,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlock(isGenerator | isAsync); if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -19533,10 +20413,10 @@ var ts; } function parseNewExpressionOrNewDotTarget() { var fullStart = scanner.getStartPos(); - parseExpected(94 /* NewKeyword */); - if (parseOptional(23 /* DotToken */)) { - var node_2 = createNode(212 /* MetaProperty */, fullStart); - node_2.keywordToken = 94 /* NewKeyword */; + parseExpected(95 /* NewKeyword */); + if (parseOptional(24 /* DotToken */)) { + var node_2 = createNode(214 /* MetaProperty */, fullStart); + node_2.keywordToken = 95 /* NewKeyword */; node_2.name = parseIdentifierName(); return finishNode(node_2); } @@ -19552,23 +20432,23 @@ var ts; } break; } - var node = createNode(190 /* NewExpression */, fullStart); + var node = createNode(192 /* NewExpression */, fullStart); node.expression = expression; node.typeArguments = typeArguments; - if (node.typeArguments || token() === 19 /* OpenParenToken */) { + if (node.typeArguments || token() === 20 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(216 /* Block */); - if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(218 /* Block */); + if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -19595,52 +20475,52 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(218 /* EmptyStatement */); - parseExpected(25 /* SemicolonToken */); + var node = createNode(220 /* EmptyStatement */); + parseExpected(26 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(220 /* IfStatement */); - parseExpected(90 /* IfKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(222 /* IfStatement */); + parseExpected(91 /* IfKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined; + node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(221 /* DoStatement */); - parseExpected(81 /* DoKeyword */); + var node = createNode(223 /* DoStatement */); + parseExpected(82 /* DoKeyword */); node.statement = parseStatement(); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. - parseOptional(25 /* SemicolonToken */); + parseOptional(26 /* SemicolonToken */); return finishNode(node); } function parseWhileStatement() { - var node = createNode(222 /* WhileStatement */); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(224 /* WhileStatement */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(88 /* ForKeyword */); - var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(89 /* ForKeyword */); + var awaitToken = parseOptionalToken(122 /* AwaitKeyword */); + parseExpected(20 /* OpenParenToken */); var initializer; - if (token() !== 25 /* SemicolonToken */) { - if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { + if (token() !== 26 /* SemicolonToken */) { + if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -19648,33 +20528,33 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(145 /* OfKeyword */) : parseOptional(145 /* OfKeyword */)) { - var forOfStatement = createNode(225 /* ForOfStatement */, pos); + if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) { + var forOfStatement = createNode(227 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } - else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(224 /* ForInStatement */, pos); + else if (parseOptional(93 /* InKeyword */)) { + var forInStatement = createNode(226 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(223 /* ForStatement */, pos); + var forStatement = createNode(225 /* ForStatement */, pos); forStatement.initializer = initializer; - parseExpected(25 /* SemicolonToken */); - if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { + parseExpected(26 /* SemicolonToken */); + if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(25 /* SemicolonToken */); - if (token() !== 20 /* CloseParenToken */) { + parseExpected(26 /* SemicolonToken */); + if (token() !== 21 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -19682,7 +20562,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 227 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -19690,8 +20570,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(228 /* ReturnStatement */); - parseExpected(96 /* ReturnKeyword */); + var node = createNode(230 /* ReturnStatement */); + parseExpected(97 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -19699,42 +20579,42 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(229 /* WithStatement */); - parseExpected(107 /* WithKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(231 /* WithStatement */); + parseExpected(108 /* WithKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(269 /* CaseClause */); - parseExpected(73 /* CaseKeyword */); + var node = createNode(271 /* CaseClause */); + parseExpected(74 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(270 /* DefaultClause */); - parseExpected(79 /* DefaultKeyword */); - parseExpected(56 /* ColonToken */); + var node = createNode(272 /* DefaultClause */); + parseExpected(80 /* DefaultKeyword */); + parseExpected(57 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(230 /* SwitchStatement */); - parseExpected(98 /* SwitchKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(232 /* SwitchStatement */); + parseExpected(99 /* SwitchKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(244 /* CaseBlock */); - parseExpected(17 /* OpenBraceToken */); + parseExpected(21 /* CloseParenToken */); + var caseBlock = createNode(246 /* CaseBlock */); + parseExpected(18 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); node.caseBlock = finishNode(caseBlock); return finishNode(node); } @@ -19746,32 +20626,32 @@ 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(232 /* ThrowStatement */); - parseExpected(100 /* ThrowKeyword */); + var node = createNode(234 /* ThrowStatement */); + parseExpected(101 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(233 /* TryStatement */); - parseExpected(102 /* TryKeyword */); + var node = createNode(235 /* TryStatement */); + parseExpected(103 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token() === 87 /* FinallyKeyword */) { - parseExpected(87 /* FinallyKeyword */); + if (!node.catchClause || token() === 88 /* FinallyKeyword */) { + parseExpected(88 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(272 /* CatchClause */); - parseExpected(74 /* CatchKeyword */); - if (parseOptional(19 /* OpenParenToken */)) { + var result = createNode(274 /* CatchClause */); + parseExpected(75 /* CatchKeyword */); + if (parseOptional(20 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); } else { // Keep shape of node to avoid degrading performance. @@ -19781,8 +20661,8 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(234 /* DebuggerStatement */); - parseExpected(78 /* DebuggerKeyword */); + var node = createNode(236 /* DebuggerStatement */); + parseExpected(79 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); } @@ -19792,13 +20672,13 @@ var ts; // a colon. var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); - if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - node.kind = 231 /* LabeledStatement */; + if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) { + node.kind = 233 /* LabeledStatement */; node.label = expression; node.statement = parseStatement(); } else { - node.kind = 219 /* ExpressionStatement */; + node.kind = 221 /* ExpressionStatement */; node.expression = expression; parseSemicolon(); } @@ -19810,25 +20690,25 @@ var ts; } function nextTokenIsClassKeywordOnSameLine() { nextToken(); - return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: return true; // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; // however, an identifier cannot be followed by another identifier on the same line. This is what we @@ -19851,41 +20731,41 @@ var ts; // I {} // // could be legal, it would add complexity for very little gain. - case 109 /* InterfaceKeyword */: - case 139 /* TypeKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 132 /* ReadonlyKeyword */: + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: nextToken(); // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 144 /* GlobalKeyword */: + case 145 /* GlobalKeyword */: nextToken(); - return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; - case 91 /* ImportKeyword */: + return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */; + case 92 /* ImportKeyword */: nextToken(); - return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); - case 84 /* ExportKeyword */: + return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 85 /* ExportKeyword */: nextToken(); - if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ || - token() === 118 /* AsKeyword */) { + if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ || + token() === 119 /* AsKeyword */) { return true; } continue; - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: nextToken(); continue; default: @@ -19898,50 +20778,50 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 57 /* AtToken */: - case 25 /* SemicolonToken */: - case 17 /* OpenBraceToken */: - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 90 /* IfKeyword */: - case 81 /* DoKeyword */: - case 106 /* WhileKeyword */: - case 88 /* ForKeyword */: - case 77 /* ContinueKeyword */: - case 72 /* BreakKeyword */: - case 96 /* ReturnKeyword */: - case 107 /* WithKeyword */: - case 98 /* SwitchKeyword */: - case 100 /* ThrowKeyword */: - case 102 /* TryKeyword */: - case 78 /* DebuggerKeyword */: + case 58 /* AtToken */: + case 26 /* SemicolonToken */: + case 18 /* OpenBraceToken */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 91 /* IfKeyword */: + case 82 /* DoKeyword */: + case 107 /* WhileKeyword */: + case 89 /* ForKeyword */: + case 78 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 97 /* ReturnKeyword */: + case 108 /* WithKeyword */: + case 99 /* SwitchKeyword */: + case 101 /* ThrowKeyword */: + case 103 /* TryKeyword */: + case 79 /* DebuggerKeyword */: // 'catch' and 'finally' do not actually indicate that the code is part of a statement, // however, we say they are here so that we may gracefully parse them and error later. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return true; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); - case 76 /* ConstKeyword */: - case 84 /* ExportKeyword */: + case 77 /* ConstKeyword */: + case 85 /* ExportKeyword */: return isStartOfDeclaration(); - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 109 /* InterfaceKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: - case 139 /* TypeKeyword */: - case 144 /* GlobalKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 110 /* InterfaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 140 /* TypeKeyword */: + case 145 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 116 /* StaticKeyword */: + case 133 /* 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); @@ -19951,7 +20831,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */; + return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -19960,67 +20840,67 @@ var ts; } function parseStatement() { switch (token()) { - case 25 /* SemicolonToken */: + case 26 /* SemicolonToken */: return parseEmptyStatement(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); - case 104 /* VarKeyword */: - return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); - case 110 /* LetKeyword */: + case 105 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + case 111 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); } break; - case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(createNodeWithJSDoc(237 /* FunctionDeclaration */)); - case 75 /* ClassKeyword */: - return parseClassDeclaration(createNodeWithJSDoc(238 /* ClassDeclaration */)); - case 90 /* IfKeyword */: + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */)); + case 76 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */)); + case 91 /* IfKeyword */: return parseIfStatement(); - case 81 /* DoKeyword */: + case 82 /* DoKeyword */: return parseDoStatement(); - case 106 /* WhileKeyword */: + case 107 /* WhileKeyword */: return parseWhileStatement(); - case 88 /* ForKeyword */: + case 89 /* ForKeyword */: return parseForOrForInOrForOfStatement(); - case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(226 /* ContinueStatement */); - case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(227 /* BreakStatement */); - case 96 /* ReturnKeyword */: + case 78 /* ContinueKeyword */: + return parseBreakOrContinueStatement(228 /* ContinueStatement */); + case 73 /* BreakKeyword */: + return parseBreakOrContinueStatement(229 /* BreakStatement */); + case 97 /* ReturnKeyword */: return parseReturnStatement(); - case 107 /* WithKeyword */: + case 108 /* WithKeyword */: return parseWithStatement(); - case 98 /* SwitchKeyword */: + case 99 /* SwitchKeyword */: return parseSwitchStatement(); - case 100 /* ThrowKeyword */: + case 101 /* ThrowKeyword */: return parseThrowStatement(); - case 102 /* TryKeyword */: + case 103 /* TryKeyword */: // Include 'catch' and 'finally' for error recovery. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return parseTryStatement(); - case 78 /* DebuggerKeyword */: + case 79 /* DebuggerKeyword */: return parseDebuggerStatement(); - case 57 /* AtToken */: + case 58 /* AtToken */: return parseDeclaration(); - case 120 /* AsyncKeyword */: - case 109 /* InterfaceKeyword */: - case 139 /* TypeKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 83 /* EnumKeyword */: - case 84 /* ExportKeyword */: - case 91 /* ImportKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: - case 144 /* GlobalKeyword */: + case 121 /* AsyncKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 84 /* EnumKeyword */: + case 85 /* ExportKeyword */: + case 92 /* ImportKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 118 /* AbstractKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + case 145 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -20029,7 +20909,7 @@ var ts; return parseExpressionOrLabeledStatement(); } function isDeclareModifier(modifier) { - return modifier.kind === 124 /* DeclareKeyword */; + return modifier.kind === 125 /* DeclareKeyword */; } function parseDeclaration() { var node = createNodeWithJSDoc(0 /* Unknown */); @@ -20048,33 +20928,33 @@ var ts; } function parseDeclarationWorker(node) { switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: return parseVariableStatement(node); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseFunctionDeclaration(node); - case 75 /* ClassKeyword */: + case 76 /* ClassKeyword */: return parseClassDeclaration(node); - case 109 /* InterfaceKeyword */: + case 110 /* InterfaceKeyword */: return parseInterfaceDeclaration(node); - case 139 /* TypeKeyword */: + case 140 /* TypeKeyword */: return parseTypeAliasDeclaration(node); - case 83 /* EnumKeyword */: + case 84 /* EnumKeyword */: return parseEnumDeclaration(node); - case 144 /* GlobalKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: + case 145 /* GlobalKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: return parseModuleDeclaration(node); - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return parseImportDeclarationOrImportEqualsDeclaration(node); - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: nextToken(); switch (token()) { - case 79 /* DefaultKeyword */: - case 58 /* EqualsToken */: + case 80 /* DefaultKeyword */: + case 59 /* EqualsToken */: return parseExportAssignment(node); - case 118 /* AsKeyword */: + case 119 /* AsKeyword */: return parseNamespaceExportDeclaration(node); default: return parseExportDeclaration(node); @@ -20083,7 +20963,7 @@ var ts; if (node.decorators || node.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 missing = createMissingNode(256 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; @@ -20094,10 +20974,10 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) { + if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -20105,25 +20985,25 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token() === 26 /* CommaToken */) { - return createNode(208 /* OmittedExpression */); + if (token() === 27 /* CommaToken */) { + return createNode(210 /* OmittedExpression */); } - var node = createNode(184 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(184 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56 /* ColonToken */) { + if (tokenIsIdentifier && token() !== 57 /* ColonToken */) { node.name = propertyName; } else { - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -20131,27 +21011,27 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(182 /* ObjectBindingPattern */); - parseExpected(17 /* OpenBraceToken */); + var node = createNode(184 /* ObjectBindingPattern */); + parseExpected(18 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(183 /* ArrayBindingPattern */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(185 /* ArrayBindingPattern */); + parseExpected(22 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier(); + return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -20160,10 +21040,10 @@ var ts; return parseVariableDeclaration(/*allowExclamation*/ true); } function parseVariableDeclaration(allowExclamation) { - var node = createNode(235 /* VariableDeclaration */); + var node = createNode(237 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); - if (allowExclamation && node.name.kind === 71 /* Identifier */ && - token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (allowExclamation && node.name.kind === 72 /* Identifier */ && + token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -20173,14 +21053,14 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(236 /* VariableDeclarationList */); + var node = createNode(238 /* VariableDeclarationList */); switch (token()) { - case 104 /* VarKeyword */: + case 105 /* VarKeyword */: break; - case 110 /* LetKeyword */: + case 111 /* LetKeyword */: node.flags |= 1 /* Let */; break; - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: node.flags |= 2 /* Const */; break; default: @@ -20196,7 +21076,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() === 145 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -20208,44 +21088,44 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; + return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */; } function parseVariableStatement(node) { - node.kind = 217 /* VariableStatement */; + node.kind = 219 /* VariableStatement */; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return finishNode(node); } function parseFunctionDeclaration(node) { - node.kind = 237 /* FunctionDeclaration */; - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.kind = 239 /* FunctionDeclaration */; + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); return finishNode(node); } function parseConstructorDeclaration(node) { - node.kind = 155 /* Constructor */; - parseExpected(123 /* ConstructorKeyword */); - fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.kind = 157 /* Constructor */; + parseExpected(124 /* ConstructorKeyword */); + fillSignature(57 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); return finishNode(node); } function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { - node.kind = 154 /* MethodDeclaration */; + node.kind = 156 /* MethodDeclaration */; node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); return finishNode(node); } function parsePropertyDeclaration(node) { - node.kind = 152 /* PropertyDeclaration */; - if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.kind = 154 /* PropertyDeclaration */; + if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -20265,12 +21145,12 @@ var ts; return finishNode(node); } function parsePropertyOrMethodDeclaration(node) { - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } return parsePropertyDeclaration(node); @@ -20278,13 +21158,13 @@ var ts; function parseAccessorDeclaration(node, kind) { node.kind = kind; node.name = parsePropertyName(); - fillSignature(56 /* ColonToken */, 0 /* None */, node); + fillSignature(57 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */); return finishNode(node); } function isClassMemberStart() { var idToken; - if (token() === 57 /* AtToken */) { + if (token() === 58 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. @@ -20301,7 +21181,7 @@ var ts; } nextToken(); } - if (token() === 39 /* AsteriskToken */) { + if (token() === 40 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. @@ -20311,24 +21191,24 @@ var ts; nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... if (idToken !== undefined) { // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!ts.isKeyword(idToken) || idToken === 136 /* SetKeyword */ || idToken === 125 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. switch (token()) { - case 19 /* OpenParenToken */: // Method declaration - case 27 /* LessThanToken */: // Generic Method declaration - case 51 /* ExclamationToken */: // Non-null assertion on property name - case 56 /* ColonToken */: // Type Annotation for declaration - case 58 /* EqualsToken */: // Initializer for declaration - case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. + case 20 /* OpenParenToken */: // Method declaration + case 28 /* LessThanToken */: // Generic Method declaration + case 52 /* ExclamationToken */: // Non-null assertion on property name + case 57 /* ColonToken */: // Type Annotation for declaration + case 59 /* EqualsToken */: // Initializer for declaration + case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. return true; default: // Covers @@ -20346,10 +21226,10 @@ var ts; var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(57 /* AtToken */)) { + if (!parseOptional(58 /* AtToken */)) { break; } - var decorator = createNode(150 /* Decorator */, decoratorStart); + var decorator = createNode(152 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -20369,7 +21249,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) { + if (token() === 77 /* 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)) { @@ -20388,7 +21268,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -20398,21 +21278,21 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 25 /* SemicolonToken */) { - var result = createNode(215 /* SemicolonClassElement */); + if (token() === 26 /* SemicolonToken */) { + var result = createNode(217 /* SemicolonClassElement */); nextToken(); return finishNode(result); } var node = createNodeWithJSDoc(0 /* Unknown */); node.decorators = parseDecorators(); node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* GetAccessor */); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); } - if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 157 /* SetAccessor */); + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); } - if (token() === 123 /* ConstructorKeyword */) { + if (token() === 124 /* ConstructorKeyword */) { return parseConstructorDeclaration(node); } if (isIndexSignature()) { @@ -20421,37 +21301,37 @@ var ts; // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || + token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || - token() === 39 /* AsteriskToken */ || - token() === 21 /* OpenBracketToken */) { + token() === 40 /* AsteriskToken */ || + token() === 22 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(node); } if (node.decorators || node.modifiers) { // treat this as a property declaration with a missing name. - node.name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 207 /* ClassExpression */); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */); } function parseClassDeclaration(node) { - return parseClassDeclarationOrExpression(node, 238 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(node, kind) { node.kind = kind; - parseExpected(75 /* ClassKeyword */); + parseExpected(76 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } node.members = parseClassMembers(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -20469,7 +21349,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses() { // ClassTail[Yield,Await] : (Modified) See 14.5 @@ -20481,33 +21361,33 @@ var ts; } function parseHeritageClause() { var tok = token(); - ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. - var node = createNode(271 /* HeritageClause */); + ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(273 /* HeritageClause */); node.token = tok; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); } function parseExpressionWithTypeArguments() { - var node = createNode(209 /* ExpressionWithTypeArguments */); + var node = createNode(211 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); node.typeArguments = tryParseTypeArguments(); return finishNode(node); } function tryParseTypeArguments() { - return token() === 27 /* LessThanToken */ - ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + return token() === 28 /* LessThanToken */ + ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */) : undefined; } function isHeritageClause() { - return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(node) { - node.kind = 239 /* InterfaceDeclaration */; - parseExpected(109 /* InterfaceKeyword */); + node.kind = 241 /* InterfaceDeclaration */; + parseExpected(110 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); @@ -20515,11 +21395,11 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(node) { - node.kind = 240 /* TypeAliasDeclaration */; - parseExpected(139 /* TypeKeyword */); + node.kind = 242 /* TypeAliasDeclaration */; + parseExpected(140 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(58 /* EqualsToken */); + parseExpected(59 /* EqualsToken */); node.type = parseType(); parseSemicolon(); return finishNode(node); @@ -20529,18 +21409,18 @@ 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 = createNodeWithJSDoc(276 /* EnumMember */); + var node = createNodeWithJSDoc(278 /* EnumMember */); node.name = parsePropertyName(); node.initializer = allowInAnd(parseInitializer); return finishNode(node); } function parseEnumDeclaration(node) { - node.kind = 241 /* EnumDeclaration */; - parseExpected(83 /* EnumKeyword */); + node.kind = 243 /* EnumDeclaration */; + parseExpected(84 /* EnumKeyword */); node.name = parseIdentifier(); - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -20548,10 +21428,10 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(243 /* ModuleBlock */); - if (parseExpected(17 /* OpenBraceToken */)) { + var node = createNode(245 /* ModuleBlock */); + if (parseExpected(18 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -20559,20 +21439,20 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(node, flags) { - node.kind = 242 /* ModuleDeclaration */; + node.kind = 244 /* ModuleDeclaration */; // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(23 /* DotToken */) + node.body = parseOptional(24 /* DotToken */) ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(node) { - node.kind = 242 /* ModuleDeclaration */; - if (token() === 144 /* GlobalKeyword */) { + node.kind = 244 /* ModuleDeclaration */; + if (token() === 145 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -20581,7 +21461,7 @@ var ts; node.name = parseLiteralNode(); node.name.text = internIdentifier(node.name.text); } - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -20591,68 +21471,68 @@ var ts; } function parseModuleDeclaration(node) { var flags = 0; - if (token() === 144 /* GlobalKeyword */) { + if (token() === 145 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(node); } - else if (parseOptional(130 /* NamespaceKeyword */)) { + else if (parseOptional(131 /* NamespaceKeyword */)) { flags |= 16 /* Namespace */; } else { - parseExpected(129 /* ModuleKeyword */); - if (token() === 9 /* StringLiteral */) { + parseExpected(130 /* ModuleKeyword */); + if (token() === 10 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(node); } } return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { - return token() === 133 /* RequireKeyword */ && + return token() === 134 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 19 /* OpenParenToken */; + return nextToken() === 20 /* OpenParenToken */; } function nextTokenIsSlash() { - return nextToken() === 41 /* SlashToken */; + return nextToken() === 42 /* SlashToken */; } function parseNamespaceExportDeclaration(node) { - node.kind = 245 /* NamespaceExportDeclaration */; - parseExpected(118 /* AsKeyword */); - parseExpected(130 /* NamespaceKeyword */); + node.kind = 247 /* NamespaceExportDeclaration */; + parseExpected(119 /* AsKeyword */); + parseExpected(131 /* NamespaceKeyword */); node.name = parseIdentifier(); parseSemicolon(); return finishNode(node); } function parseImportDeclarationOrImportEqualsDeclaration(node) { - parseExpected(91 /* ImportKeyword */); + parseExpected(92 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 143 /* FromKeyword */) { + if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) { return parseImportEqualsDeclaration(node, identifier); } } // Import statement - node.kind = 247 /* ImportDeclaration */; + node.kind = 249 /* ImportDeclaration */; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || // import id - token() === 39 /* AsteriskToken */ || // import * - token() === 17 /* OpenBraceToken */) { // import { + token() === 40 /* AsteriskToken */ || // import * + token() === 18 /* OpenBraceToken */) { // import { node.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(143 /* FromKeyword */); + parseExpected(144 /* FromKeyword */); } node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(node); } function parseImportEqualsDeclaration(node, identifier) { - node.kind = 246 /* ImportEqualsDeclaration */; + node.kind = 248 /* ImportEqualsDeclaration */; node.name = identifier; - parseExpected(58 /* EqualsToken */); + parseExpected(59 /* EqualsToken */); node.moduleReference = parseModuleReference(); parseSemicolon(); return finishNode(node); @@ -20664,7 +21544,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(248 /* ImportClause */, fullStart); + var importClause = createNode(250 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -20673,8 +21553,8 @@ var ts; // If there was no default import or if there is comma token after default import // parse namespace or named imports if (!importClause.name || - parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(250 /* NamedImports */); + parseOptional(27 /* CommaToken */)) { + importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */); } return finishNode(importClause); } @@ -20684,15 +21564,15 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(257 /* ExternalModuleReference */); - parseExpected(133 /* RequireKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(259 /* ExternalModuleReference */); + parseExpected(134 /* RequireKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = parseModuleSpecifier(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9 /* StringLiteral */) { + if (token() === 10 /* StringLiteral */) { var result = parseLiteralNode(); result.text = internIdentifier(result.text); return result; @@ -20707,9 +21587,9 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(249 /* NamespaceImport */); - parseExpected(39 /* AsteriskToken */); - parseExpected(118 /* AsKeyword */); + var namespaceImport = createNode(251 /* NamespaceImport */); + parseExpected(40 /* AsteriskToken */); + parseExpected(119 /* AsKeyword */); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } @@ -20722,14 +21602,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(255 /* ExportSpecifier */); + return parseImportOrExportSpecifier(257 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(251 /* ImportSpecifier */); + return parseImportOrExportSpecifier(253 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -20743,9 +21623,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 118 /* AsKeyword */) { + if (token() === 119 /* AsKeyword */) { node.propertyName = identifierName; - parseExpected(118 /* AsKeyword */); + parseExpected(119 /* AsKeyword */); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -20754,24 +21634,24 @@ var ts; else { node.name = identifierName; } - if (kind === 251 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(node) { - node.kind = 253 /* ExportDeclaration */; - if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(143 /* FromKeyword */); + node.kind = 255 /* ExportDeclaration */; + if (parseOptional(40 /* AsteriskToken */)) { + parseExpected(144 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(254 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(256 /* 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() === 143 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(143 /* FromKeyword */); + if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(144 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -20779,12 +21659,12 @@ var ts; return finishNode(node); } function parseExportAssignment(node) { - node.kind = 252 /* ExportAssignment */; - if (parseOptional(58 /* EqualsToken */)) { + node.kind = 254 /* ExportAssignment */; + if (parseOptional(59 /* EqualsToken */)) { node.isExportEquals = true; } else { - parseExpected(79 /* DefaultKeyword */); + parseExpected(80 /* DefaultKeyword */); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -20799,10 +21679,10 @@ var ts; } function isAnExternalModuleIndicatorNode(node) { return ts.hasModifier(node, 1 /* Export */) - || node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */ - || node.kind === 247 /* ImportDeclaration */ - || node.kind === 252 /* ExportAssignment */ - || node.kind === 253 /* ExportDeclaration */ + || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */ + || node.kind === 249 /* ImportDeclaration */ + || node.kind === 254 /* ExportAssignment */ + || node.kind === 255 /* ExportDeclaration */ ? node : undefined; } @@ -20815,7 +21695,7 @@ var ts; return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); } function isImportMeta(node) { - return ts.isMetaProperty(node) && node.keywordToken === 91 /* ImportKeyword */ && node.name.escapedText === "meta"; + return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta"; } var ParsingContext; (function (ParsingContext) { @@ -20866,11 +21746,11 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); - var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); + var result = createNode(283 /* JSDocTypeExpression */); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } fixupParentReferences(result); return finishNode(result); @@ -20958,7 +21838,7 @@ var ts; } loop: while (true) { switch (token()) { - case 57 /* AtToken */: + case 58 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingWhitespace(comments); addTag(parseTag(indent)); @@ -20978,7 +21858,7 @@ var ts; state = 0 /* BeginningOfLine */; indent = 0; break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: var asterisk = scanner.getTokenText(); if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { // If we've already seen an asterisk, then we can no longer parse a tag on this line @@ -20991,13 +21871,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21012,7 +21885,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21034,7 +21909,7 @@ var ts; } } function createJSDocComment() { - var result = createNode(289 /* JSDocComment */, start); + var result = createNode(291 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -21068,61 +21943,60 @@ var ts; } } var precedingLineBreak = scanner.hasPrecedingLineBreak(); - while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { if (token() === 4 /* NewLineTrivia */) { precedingLineBreak = true; } - else if (token() === 39 /* AsteriskToken */) { + else if (token() === 40 /* AsteriskToken */) { precedingLineBreak = false; } nextJSDocToken(); } } function parseTag(indent) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getTokenPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": case "extends": - tag = parseAugmentsTag(atToken, tagName); + tag = parseAugmentsTag(start, tagName); break; case "class": case "constructor": - tag = parseClassTag(atToken, tagName); + tag = parseClassTag(start, tagName); break; case "this": - tag = parseThisTag(atToken, tagName); + tag = parseThisTag(start, tagName); break; case "enum": - tag = parseEnumTag(atToken, tagName); + tag = parseEnumTag(start, tagName); break; case "arg": case "argument": case "param": - return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent); + return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent); case "return": case "returns": - tag = parseReturnTag(atToken, tagName); + tag = parseReturnTag(start, tagName); break; case "template": - tag = parseTemplateTag(atToken, tagName); + tag = parseTemplateTag(start, tagName); break; case "type": - tag = parseTypeTag(atToken, tagName); + tag = parseTypeTag(start, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName, indent); + tag = parseTypedefTag(start, tagName, indent); break; case "callback": - tag = parseCallbackTag(atToken, tagName, indent); + tag = parseCallbackTag(start, tagName, indent); break; default: - tag = parseUnknownTag(atToken, tagName); + tag = parseUnknownTag(start, tagName); break; } if (!tag.comment) { @@ -21152,7 +22026,7 @@ var ts; } indent = 0; break; - case 57 /* AtToken */: + case 58 /* AtToken */: scanner.setTextPos(scanner.getTextPos() - 1); // falls through case 1 /* EndOfFileToken */: @@ -21171,9 +22045,9 @@ var ts; indent += whitespace.length; } break; - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: state = 2 /* SavingComments */; - if (lookAhead(function () { return nextJSDocToken() === 57 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { pushComment(scanner.getTokenText()); nextJSDocToken(); pushComment(scanner.getTokenText()); @@ -21181,7 +22055,7 @@ var ts; } pushComment(scanner.getTokenText()); break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; @@ -21201,9 +22075,8 @@ var ts; removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } - function parseUnknownTag(atToken, tagName) { - var result = createNode(292 /* JSDocTag */, atToken.pos); - result.atToken = atToken; + function parseUnknownTag(start, tagName) { + var result = createNode(294 /* JSDocTag */, start); result.tagName = tagName; return finishNode(result); } @@ -21222,37 +22095,37 @@ var ts; } function tryParseTypeExpression() { skipWhitespaceOrAsterisk(); - return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; + return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { - if (token() === 13 /* NoSubstitutionTemplateLiteral */) { + if (token() === 14 /* NoSubstitutionTemplateLiteral */) { // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; } // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' - var isBracketed = parseOptional(21 /* OpenBracketToken */); + var isBracketed = parseOptional(22 /* OpenBracketToken */); var name = parseJSDocEntityName(); if (isBracketed) { skipWhitespace(); // May have an optional default, e.g. '[foo = 42]' - if (parseOptionalToken(58 /* EqualsToken */)) { + if (parseOptionalToken(59 /* EqualsToken */)) { parseExpression(); } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); } return { name: name, isBracketed: isBracketed }; } function isObjectOrObjectArrayTypeReference(node) { switch (node.kind) { - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return true; - case 167 /* ArrayType */: + case 169 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; } } - function parseParameterOrPropertyTag(atToken, tagName, target, indent) { + function parseParameterOrPropertyTag(start, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -21262,17 +22135,14 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(303 /* JSDocPropertyTag */, atToken.pos) : - createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + createNode(305 /* JSDocPropertyTag */, start) : + createNode(299 /* JSDocParameterTag */, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; } - result.atToken = atToken; result.tagName = tagName; result.typeExpression = typeExpression; result.name = name; @@ -21281,22 +22151,22 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 167 /* ArrayType */) { + if (typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -21304,81 +22174,74 @@ var ts; } } } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) { + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(298 /* JSDocReturnTag */, atToken.pos); - result.atToken = atToken; + var result = createNode(300 /* JSDocReturnTag */, start); result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) { + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(300 /* JSDocTypeTag */, atToken.pos); - result.atToken = atToken; + var result = createNode(302 /* JSDocTypeTag */, start); result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } - function parseAugmentsTag(atToken, tagName) { - var result = createNode(293 /* JSDocAugmentsTag */, atToken.pos); - result.atToken = atToken; + function parseAugmentsTag(start, tagName) { + var result = createNode(295 /* JSDocAugmentsTag */, start); result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } function parseExpressionWithTypeArgumentsForAugments() { - var usedBrace = parseOptional(17 /* OpenBraceToken */); - var node = createNode(209 /* ExpressionWithTypeArguments */); + var usedBrace = parseOptional(18 /* OpenBraceToken */); + var node = createNode(211 /* ExpressionWithTypeArguments */); node.expression = parsePropertyAccessEntityNameExpression(); node.typeArguments = tryParseTypeArguments(); var res = finishNode(node); if (usedBrace) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } return res; } function parsePropertyAccessEntityNameExpression() { var node = parseJSDocIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var prop = createNode(187 /* PropertyAccessExpression */, node.pos); + while (parseOptional(24 /* DotToken */)) { + var prop = createNode(189 /* PropertyAccessExpression */, node.pos); prop.expression = node; prop.name = parseJSDocIdentifierName(); node = finishNode(prop); } return node; } - function parseClassTag(atToken, tagName) { - var tag = createNode(294 /* JSDocClassTag */, atToken.pos); - tag.atToken = atToken; + function parseClassTag(start, tagName) { + var tag = createNode(296 /* JSDocClassTag */, start); tag.tagName = tagName; return finishNode(tag); } - function parseThisTag(atToken, tagName) { - var tag = createNode(299 /* JSDocThisTag */, atToken.pos); - tag.atToken = atToken; + function parseThisTag(start, tagName) { + var tag = createNode(301 /* JSDocThisTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseEnumTag(atToken, tagName) { - var tag = createNode(296 /* JSDocEnumTag */, atToken.pos); - tag.atToken = atToken; + function parseEnumTag(start, tagName) { + var tag = createNode(298 /* JSDocEnumTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseTypedefTag(atToken, tagName, indent) { + function parseTypedefTag(start, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); - typedefTag.atToken = atToken; + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304 /* JSDocTypedefTag */, start); typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); @@ -21390,12 +22253,11 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); } - if (child.kind === 300 /* JSDocTypeTag */) { + if (child.kind === 302 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -21408,7 +22270,7 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 167 /* ArrayType */) { + if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? @@ -21426,8 +22288,8 @@ var ts; return undefined; } var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(242 /* ModuleDeclaration */, pos); + if (parseOptional(24 /* DotToken */)) { + var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos); if (nested) { jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } @@ -21440,25 +22302,23 @@ var ts; } return typeNameOrNamespaceName; } - function parseCallbackTag(atToken, tagName, indent) { - var callbackTag = createNode(295 /* JSDocCallbackTag */, atToken.pos); - callbackTag.atToken = atToken; + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297 /* JSDocCallbackTag */, start); callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); skipWhitespace(); callbackTag.comment = parseTagComments(indent); var child; - var start = scanner.getStartPos(); - var jsdocSignature = createNode(291 /* JSDocSignature */, start); + var jsdocSignature = createNode(293 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { - if (parseOptionalJsdoc(57 /* AtToken */)) { + if (parseOptionalJsdoc(58 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 298 /* JSDocReturnTag */) { + if (tag && tag.kind === 300 /* JSDocReturnTag */) { return tag; } } @@ -21492,18 +22352,18 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { - case 57 /* AtToken */: + case 58 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); - if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -21516,13 +22376,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 71 /* Identifier */: + case 72 /* Identifier */: canParseTag = false; break; case 1 /* EndOfFileToken */: @@ -21530,17 +22390,16 @@ var ts; } } } - function tryParseChildTag(target) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */); - atToken.end = scanner.getTextPos(); + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getStartPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); skipWhitespace(); var t; switch (tagName.escapedText) { case "type": - return target === 1 /* Property */ && parseTypeTag(atToken, tagName); + return target === 1 /* Property */ && parseTypeTag(start, tagName); case "prop": case "property": t = 1 /* Property */; @@ -21556,28 +22415,25 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(start, tagName, target, indent); } - function parseTemplateTag(atToken, tagName) { + function parseTemplateTag(start, tagName) { // the template tag looks like '@template {Constraint} T,U,V' var constraint; - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { constraint = parseJSDocTypeExpression(); } var typeParameters = []; var typeParametersPos = getNodePos(); do { skipWhitespace(); - var typeParameter = createNode(148 /* TypeParameter */); + var typeParameter = createNode(150 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); finishNode(typeParameter); skipWhitespace(); typeParameters.push(typeParameter); - } while (parseOptionalJsdoc(26 /* CommaToken */)); - var result = createNode(301 /* JSDocTemplateTag */, atToken.pos); - result.atToken = atToken; + } while (parseOptionalJsdoc(27 /* CommaToken */)); + var result = createNode(303 /* JSDocTemplateTag */, start); result.tagName = tagName; result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -21596,16 +22452,16 @@ var ts; } function parseJSDocEntityName() { var entity = parseJSDocIdentifierName(); - if (parseOptional(21 /* OpenBracketToken */)) { - parseExpected(22 /* CloseBracketToken */); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> // but it's not worth it to enforce that restriction. } - while (parseOptional(23 /* DotToken */)) { + while (parseOptional(24 /* DotToken */)) { var name = parseJSDocIdentifierName(); - if (parseOptional(21 /* OpenBracketToken */)) { - parseExpected(22 /* CloseBracketToken */); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); } entity = createQualifiedName(entity, name); } @@ -21613,11 +22469,11 @@ var ts; } function parseJSDocIdentifierName(message) { if (!ts.tokenIsIdentifierOrKeyword(token())) { - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(71 /* Identifier */, pos); + var result = createNode(72 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); @@ -21743,9 +22599,9 @@ var ts; } function shouldCheckNode(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 71 /* Identifier */: + case 72 /* Identifier */: return true; } return false; @@ -22323,10 +23179,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 71 /* Identifier */) { + if (lhs.kind === 72 /* Identifier */) { return lhs.escapedText === rhs.escapedText; } - if (lhs.kind === 99 /* ThisKeyword */) { + if (lhs.kind === 100 /* ThisKeyword */) { return true; } // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only @@ -22383,7 +23239,8 @@ var ts; ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.symbol", "lib.esnext.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], - ["esnext.intl", "lib.esnext.intl.d.ts"] + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -22399,8 +23256,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +23270,61 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22455,26 +23366,11 @@ var ts; description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date }, { - name: "pretty", + name: "showConfig", type: "boolean", - showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental - }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, // Basic { @@ -22490,6 +23386,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23406,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23419,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23427,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23445,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23555,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23564,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23573,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23599,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23608,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23642,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23655,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23663,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23673,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23689,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23701,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23712,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22862,42 +23785,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h }, - { - name: "diagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_diagnostic_information - }, - { - name: "extendedDiagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_verbose_diagnostic_information - }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23849,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23869,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23915,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23923,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23951,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23979,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +24070,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +24120,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +24140,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +24148,7 @@ var ts; 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)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +24184,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +24227,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +24252,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23432,6 +24407,9 @@ var ts; } var result = ts.parseJsonText(configFileName, configFileText); var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; @@ -23571,7 +24549,7 @@ var ts; var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 273 /* PropertyAssignment */) { + if (element.kind !== 275 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -23619,20 +24597,24 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { - case 101 /* TrueKeyword */: + case 102 /* TrueKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return true; - case 86 /* FalseKeyword */: + case 87 /* FalseKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return false; - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for return null; // tslint:disable-line:no-null-keyword - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } @@ -23649,13 +24631,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 200 /* PrefixUnaryExpression */: - if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + case 202 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return -Number(valueExpression.operand.text); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -23672,7 +24654,7 @@ var ts; return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); } - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -23712,6 +24694,115 @@ var ts; } return false; } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return false; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + } + return function (path) { return includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return !excludeRe.test(path); }; + } + return function (_) { return false; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } /** * Generate tsconfig configuration when running command line "--init" * @param options commandlineOptions to be generated into tsconfig.json @@ -23722,62 +24813,6 @@ var ts; var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - // There is a typeMap associated with this command-line option so use it to map value back to its name - return ts.forEachEntry(customTypeMap, function (mapValue, key) { - if (mapValue === value) { - return key; - } - }); - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_3 = function (name) { - if (ts.hasProperty(options, name)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - return "continue"; - } - var value = options[name]; - var optionDefinition = optionsNameMap.get(name.toLowerCase()); - if (optionDefinition) { - var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap_1) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result.set(name, value); - } - else { - if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); - } - } - } - } - }; - for (var name in options) { - _loop_3(name); - } - return result; - } function getDefaultValueForOption(option) { switch (option.type) { case "number": @@ -23926,7 +24961,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24979,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23980,19 +25030,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +25049,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +25062,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24110,11 +25174,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24142,26 +25201,30 @@ var ts; } function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { - errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return undefined; - } - var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return undefined; + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } } + return extendedConfigPath; } - return extendedConfigPath; + // If the path isn't a rooted or relative path, resolve like a module + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +25232,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25446,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24408,10 +25471,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24421,9 +25489,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24431,7 +25515,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24442,16 +25526,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24584,7 +25668,7 @@ var ts; } } /** - * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. * Also converts enum values back to strings. */ /* @internal */ @@ -24640,6 +25724,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24649,14 +25739,15 @@ var ts; Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; Extensions[Extensions["Json"] = 2] = "Json"; - Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */ + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25756,97 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24748,9 +25888,13 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24769,8 +25913,10 @@ var ts; trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24779,13 +25925,12 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - if (!options.preserveSymlinks) { - resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); - } + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -24794,14 +25939,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } - return ts.forEach(typeRoots, function (typeRoot) { + return ts.firstDefined(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,8 +25962,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - var resolvedFile = resolvedTypeScriptOnly(result && result.value); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + var resolvedFile = resolvedTypeScriptOnly(result); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -24856,14 +26009,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -24874,29 +26031,56 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); } ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + /*@internal*/ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName) { + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); - var perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = ts.createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); } - function getOrCreateCacheForModuleName(nonRelativeModuleName) { + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); - var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); } - return perModuleNameCache; + return result; } function createPerModuleNameCache() { var directoryPathMap = ts.createMap(); @@ -24971,13 +26155,19 @@ var ts; return perFolderCache && perFolderCache.get(moduleName); } ts.resolveModuleNameFromCache = resolveModuleNameFromCache; - function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } var containingDirectory = ts.getDirectoryPath(containingFile); - var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { @@ -24999,10 +26189,10 @@ var ts; } switch (moduleResolution) { case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; default: return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); @@ -25011,7 +26201,7 @@ var ts; perFolderCache.set(moduleName, result); if (!ts.isExternalModuleNameRelative(moduleName)) { // put result in per-module name cache - cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); } } } @@ -25086,15 +26276,28 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +26335,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +26354,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,95 +26365,72 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!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); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; - function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? - tryResolve(Extensions.JavaScript) : - (tryResolve(Extensions.TypeScript) || - tryResolve(Extensions.JavaScript) || - (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); if (result && result.value) { var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +26444,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +26461,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,10 +26492,15 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; /** * This will be called on the successfully resolved path from `loadModuleFromFile`. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) @@ -25352,52 +26538,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @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; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - if (extensions === Extensions.Json) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25407,16 +26587,17 @@ var ts; return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.TSConfig: case Extensions.Json: return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26611,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26649,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,51 +26661,72 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { - // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25542,6 +26738,7 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TSConfig: case Extensions.Json: return extension === ".json" /* Json */; case Extensions.TypeScript: @@ -25550,87 +26747,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26877,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,68 +26890,69 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } - function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } if (!ts.isExternalModuleNameRelative(moduleName)) { - var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26967,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25758,24 +26998,24 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: if (!(ts.hasModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. other uninstantiated module declarations. - case 243 /* ModuleBlock */: { + case 245 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateWorker(n); @@ -25797,9 +27037,9 @@ var ts; }); return state_1; } - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return getModuleInstanceState(node); - case 71 /* Identifier */: + case 72 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should // be considered the same as type alias if (node.isInJSDocNamespace) { @@ -25944,19 +27184,23 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + 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.kind === 252 /* ExportAssignment */) { + if (node.kind === 254 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -25965,7 +27209,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -25977,36 +27221,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: return "__constructor" /* Constructor */; - case 163 /* FunctionType */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: + case 165 /* FunctionType */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: return "__call" /* Call */; - case 164 /* ConstructorType */: - case 159 /* ConstructSignature */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: return "__new" /* New */; - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return "__index" /* Index */; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 149 /* Parameter */: + case 151 /* 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 === 287 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -26075,7 +27319,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26103,7 +27348,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; } @@ -26130,7 +27375,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 255 /* ExportSpecifier */ || (node.kind === 246 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -26153,12 +27398,12 @@ var ts; // 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.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26197,7 +27442,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 195 /* ArrowFunction */) { + if (node.kind !== 197 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -26229,7 +27474,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property intialization checks. - currentReturnTarget = isIIFE || node.kind === 155 /* Constructor */ ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; @@ -26242,13 +27487,13 @@ var ts; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { node.flags |= emitFlags; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 155 /* Constructor */) { + if (node.kind === 157 /* Constructor */) { node.returnFlowNode = currentFlow; } } @@ -26291,8 +27536,8 @@ var ts; } } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -26321,81 +27566,82 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: bindWhileStatement(node); break; - case 221 /* DoStatement */: + case 223 /* DoStatement */: bindDoStatement(node); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: bindForStatement(node); break; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: bindIfStatement(node); break; - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: bindTryStatement(node); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: bindSwitchStatement(node); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: bindCaseBlock(node); break; - case 269 /* CaseClause */: + case 271 /* CaseClause */: bindCaseClause(node); break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: bindLabeledStatement(node); break; - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: bindCallExpressionFlow(node); break; - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 277 /* SourceFile */: { + case 279 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; default: @@ -26406,24 +27652,26 @@ var ts; } function isNarrowingExpression(expr) { switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return isNarrowableReference(expr); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return hasNarrowableArgument(expr); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 200 /* PrefixUnaryExpression */: - return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 202 /* PrefixUnaryExpression */: + return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 199 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || + return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && @@ -26438,7 +27686,7 @@ var ts; } } } - if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26452,32 +27700,32 @@ var ts; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return isNarrowableReference(expr.left); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); - case 92 /* InKeyword */: + case 93 /* InKeyword */: return isNarrowableInOperands(expr.left, expr.right); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return isNarrowableOperand(expr.right); } } @@ -26512,8 +27760,8 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -26551,34 +27799,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 220 /* IfStatement */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: return parent.expression === node; - case 223 /* ForStatement */: - case 203 /* ConditionalExpression */: + case 225 /* ForStatement */: + case 205 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 193 /* ParenthesizedExpression */) { + if (node.kind === 195 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 200 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 202 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 54 /* BarBarToken */); + return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 55 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 193 /* ParenthesizedExpression */ || - node.parent.kind === 200 /* PrefixUnaryExpression */ && - node.parent.operator === 51 /* ExclamationToken */) { + while (node.parent.kind === 195 /* ParenthesizedExpression */ || + node.parent.kind === 202 /* PrefixUnaryExpression */ && + node.parent.operator === 52 /* ExclamationToken */) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -26619,7 +27867,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 231 /* LabeledStatement */ + var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */ ? ts.lastOrUndefined(activeLabels) : undefined; // if do statement is wrapped in labeled statement then target labels for break/continue with or without @@ -26653,13 +27901,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 225 /* ForOfStatement */) { + if (node.kind === 227 /* ForOfStatement */) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 236 /* VariableDeclarationList */) { + if (node.initializer.kind !== 238 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -26681,7 +27929,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 228 /* ReturnStatement */) { + if (node.kind === 230 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -26701,7 +27949,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 227 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -26797,7 +28045,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 270 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; @@ -26821,7 +28069,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -26865,14 +28112,14 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } - if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { + if (!node.statement || node.statement.kind !== 223 /* DoStatement */) { // do statement sets current flow inside bindDoStatement addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -26883,10 +28130,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 185 /* ArrayLiteralExpression */) { + else if (node.kind === 187 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 206 /* SpreadElement */) { + if (e.kind === 208 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -26894,16 +28141,16 @@ var ts; } } } - else if (node.kind === 186 /* ObjectLiteralExpression */) { + else if (node.kind === 188 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 273 /* PropertyAssignment */) { + if (p.kind === 275 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 274 /* ShorthandPropertyAssignment */) { + else if (p.kind === 276 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 275 /* SpreadAssignment */) { + else if (p.kind === 277 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -26911,7 +28158,7 @@ var ts; } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -26922,7 +28169,7 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51 /* ExclamationToken */) { + if (node.operator === 52 /* ExclamationToken */) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; @@ -26932,20 +28179,20 @@ var ts; } else { bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -26959,7 +28206,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 188 /* ElementAccessExpression */) { + if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -26970,7 +28217,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -27008,6 +28255,7 @@ var ts; } } function bindJSDocTypeAlias(node) { + node.tagName.parent = node; if (node.fullName) { setParentPointers(node, node.fullName); } @@ -27017,10 +28265,10 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 193 /* ParenthesizedExpression */) { + while (expr.kind === 195 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 194 /* FunctionExpression */ || expr.kind === 195 /* ArrowFunction */) { + if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -27028,7 +28276,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -27037,54 +28285,54 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 186 /* ObjectLiteralExpression */: - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 266 /* JsxAttributes */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 268 /* JsxAttributes */: return 1 /* IsContainer */; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 179 /* MappedType */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: - case 287 /* JSDocFunctionType */: - case 163 /* FunctionType */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 164 /* ConstructorType */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 289 /* JSDocFunctionType */: + case 165 /* FunctionType */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 166 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 272 /* CatchClause */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 244 /* CaseBlock */: + case 274 /* CatchClause */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 246 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 216 /* Block */: + case 218 /* 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 @@ -27117,45 +28365,45 @@ var ts; // 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 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 277 /* SourceFile */: + case 279 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 186 /* ObjectLiteralExpression */: - case 239 /* InterfaceDeclaration */: - case 266 /* JsxAttributes */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 188 /* ObjectLiteralExpression */: + case 241 /* InterfaceDeclaration */: + case 268 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 291 /* JSDocSignature */: - case 160 /* IndexSignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 287 /* JSDocFunctionType */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 240 /* TypeAliasDeclaration */: - case 179 /* MappedType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 293 /* JSDocSignature */: + case 162 /* IndexSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 289 /* JSDocFunctionType */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -27176,11 +28424,11 @@ var ts; : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 277 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 277 /* SourceFile */ || body.kind === 243 /* ModuleBlock */)) { + var body = node.kind === 279 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 253 /* ExportDeclaration */ || stat.kind === 252 /* ExportAssignment */) { + if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { return true; } } @@ -27208,7 +28456,7 @@ var ts; } else { var pattern = void 0; - if (node.name.kind === 9 /* StringLiteral */) { + if (node.name.kind === 10 /* StringLiteral */) { var text = node.name.text; if (ts.hasZeroOrOneAsteriskCharacter(text)) { pattern = ts.tryParsePattern(text); @@ -27217,7 +28465,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +28485,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27264,7 +28512,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) { continue; } var identifier = prop.name; @@ -27276,7 +28524,7 @@ var ts; // 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 === 273 /* PropertyAssignment */ || prop.kind === 274 /* ShorthandPropertyAssignment */ || prop.kind === 154 /* MethodDeclaration */ + var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -27308,10 +28556,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -27325,9 +28573,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27345,9 +28590,9 @@ var ts; currentFlow = { flags: 2 /* Start */ }; parent = typeAlias; bind(typeAlias.typeExpression); - if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { + if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27363,8 +28608,8 @@ var ts; // check for reserved words used as identifiers in strict mode code. function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && + node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 117 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && !(node.flags & 4194304 /* Ambient */)) { // Report error only if there are no parse errors in file @@ -27400,7 +28645,7 @@ var ts; } function checkStrictModeDeleteExpression(node) { // Grammar checking - if (inStrictMode && node.expression.kind === 71 /* Identifier */) { + if (inStrictMode && node.expression.kind === 72 /* 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); @@ -27411,7 +28656,7 @@ var ts; return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71 /* Identifier */) { + if (name && name.kind === 72 /* 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 @@ -27452,8 +28697,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 277 /* SourceFile */ && - blockScopeContainer.kind !== 242 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 279 /* SourceFile */ && + blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -27479,7 +28724,7 @@ var ts; function checkStrictModePrefixUnaryExpression(node) { // Grammar checking if (inStrictMode) { - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -27548,7 +28793,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 145 /* LastToken */) { + if (node.kind > 147 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -27572,7 +28817,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27610,7 +28855,7 @@ var ts; function bindWorker(node) { switch (node.kind) { /* Strict mode checks */ - case 71 /* Identifier */: + case 72 /* Identifier */: // for typedef type names with namespaces, bind the new jsdoc type symbol here // because it requires all containing namespaces to be in effect, namely the // current "blockScopeContainer" needs to be set to its immediate namespace parent. @@ -27619,32 +28864,32 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through - case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 274 /* ShorthandPropertyAssignment */)) { + case 100 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; - case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27668,142 +28913,155 @@ var ts; // Nothing to do break; default: - ts.Debug.fail("Unknown special property assignment kind"); + ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return checkStrictModeCatchClause(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return checkStrictModeWithStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 176 /* ThisType */: + case 178 /* ThisType */: seenThisKeyword = true; return; - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: break; // Binding the children will handle everything - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return bindTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return bindParameter(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return bindPropertyWorker(node); - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 276 /* EnumMember */: + case 278 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); - case 237 /* FunctionDeclaration */: + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); + case 239 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); - case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); - case 163 /* FunctionType */: - case 287 /* JSDocFunctionType */: - case 291 /* JSDocSignature */: - case 164 /* ConstructorType */: + case 158 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); + case 159 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + case 166 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 179 /* MappedType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 181 /* MappedType */: return bindAnonymousTypeWorker(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return bindFunctionExpression(node); - case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + case 191 /* CallExpression */: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; // Nothing to do + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); - case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - case 241 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); + case 242 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + case 243 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return bindJsxAttributes(node); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return bindImportClause(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return bindExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return bindExportAssignment(node); - case 277 /* SourceFile */: + case 279 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 216 /* Block */: + case 218 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 297 /* JSDocParameterTag */: - if (node.parent.kind === 291 /* JSDocSignature */) { + case 299 /* JSDocParameterTag */: + if (node.parent.kind === 293 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 290 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { break; } // falls through - case 303 /* JSDocPropertyTag */: + case 305 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -27835,37 +29093,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27892,6 +29148,21 @@ var ts; } return true; } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } function bindExportsPropertyAssignment(node) { // When we create a property via 'exports.foo = bar', the 'exports.foo' property access // expression is the declaration @@ -27901,7 +29172,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27928,17 +29199,17 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. - if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) { var l = thisContainer.parent.left; if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); @@ -27951,18 +29222,18 @@ var ts; declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } break; - case 155 /* Constructor */: - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: // this.foo assignment in a source file // Do not bind. It would be nice to support this someday though. break; @@ -27971,10 +29242,10 @@ var ts; } } function bindSpecialPropertyDeclaration(node) { - if (node.expression.kind === 99 /* ThisKeyword */) { + if (node.expression.kind === 100 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 277 /* SourceFile */) { + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -27988,7 +29259,11 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28005,11 +29280,17 @@ var ts; classPrototype.parent = lhs; bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } function bindSpecialPropertyAssignment(node) { var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28033,42 +29314,48 @@ var ts; node.expression.parent = node; bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); } - function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) - : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; - namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ + : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,11 +29364,14 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -28090,7 +29380,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28132,7 +29422,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 238 /* ClassDeclaration */) { + if (node.kind === 240 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); } else { @@ -28174,8 +29464,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,15 +29480,15 @@ var ts; // 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 */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } function bindParameter(node) { - if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -28207,7 +29500,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +29518,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,26 +29559,26 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 174 /* InferType */) { + else if (node.parent.kind === 176 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28300,13 +29593,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 218 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) || // report error on class declarations - node.kind === 238 /* ClassDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,24 +29635,23 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return true; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.hasModifier(s, 2048 /* Const */); default: return false; } } - /* @internal */ function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || @@ -28382,6 +29672,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28393,58 +29686,58 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return computeNewExpression(node, subtreeFlags); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); - case 149 /* Parameter */: + case 151 /* Parameter */: return computeParameter(node, subtreeFlags); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return computeCatchClause(node, subtreeFlags); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 155 /* Constructor */: + case 157 /* Constructor */: return computeConstructor(node, subtreeFlags); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return computePropertyDeclaration(node, subtreeFlags); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return computeMethod(node, subtreeFlags); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -28457,61 +29750,61 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } - if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + if (expression.kind === 92 /* ImportKeyword */) { + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 186 /* ObjectLiteralExpression */) { + if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ESNext if they contain rest transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 185 /* ArrayLiteralExpression */) { + else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ - || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { + else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ + || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28522,25 +29815,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28550,8 +29843,8 @@ 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 (expressionKind === 210 /* AsExpression */ - || expressionKind === 192 /* TypeAssertionExpression */) { + if (expressionKind === 212 /* AsExpression */ + || expressionKind === 194 /* TypeAssertionExpression */) { transformFlags |= 3 /* AssertTypeScript */; } // If the expression of a ParenthesizedExpression is a destructuring assignment, @@ -28575,44 +29868,44 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 85 /* ExtendsKeyword */: + case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; - case 108 /* ImplementsKeyword */: + case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; @@ -28621,7 +29914,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28632,7 +29925,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28644,7 +29937,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28654,11 +29947,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28674,7 +29967,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28685,7 +29978,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28699,11 +29992,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28711,10 +30004,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28726,7 +30019,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28739,13 +30032,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28758,7 +30051,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28774,13 +30067,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28790,7 +30083,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28807,26 +30100,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28834,18 +30129,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28853,7 +30150,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28864,22 +30161,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28888,7 +30185,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28899,7 +30196,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28908,78 +30205,78 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { - case 120 /* AsyncKeyword */: - case 199 /* AwaitExpression */: + case 121 /* AsyncKeyword */: + case 201 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 306 /* PartiallyEmittedExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; break; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 211 /* NonNullExpression */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 213 /* NonNullExpression */: + case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: - case 10 /* JsxText */: - case 261 /* JsxClosingElement */: - case 262 /* JsxFragment */: - case 263 /* JsxOpeningFragment */: - case 264 /* JsxClosingFragment */: - case 265 /* JsxAttribute */: - case 266 /* JsxAttributes */: - case 267 /* JsxSpreadAttribute */: - case 268 /* JsxExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 11 /* JsxText */: + case 263 /* JsxClosingElement */: + case 264 /* JsxFragment */: + case 265 /* JsxOpeningFragment */: + case 266 /* JsxClosingFragment */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 270 /* JsxExpression */: // These nodes are Jsx syntax. transformFlags |= 4 /* AssertJsx */; break; - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 204 /* TemplateExpression */: - case 191 /* TaggedTemplateExpression */: - case 274 /* ShorthandPropertyAssignment */: - case 115 /* StaticKeyword */: - case 212 /* MetaProperty */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + case 276 /* ShorthandPropertyAssignment */: + case 116 /* StaticKeyword */: + case 214 /* MetaProperty */: // These nodes are ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { transformFlags |= 192 /* AssertES2015 */; } @@ -28989,65 +30286,69 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } break; - case 225 /* ForOfStatement */: + case 9 /* BigIntLiteral */: + transformFlags |= 8 /* AssertESNext */; + break; + case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { transformFlags |= 8 /* AssertESNext */; } transformFlags |= 192 /* AssertES2015 */; break; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 148 /* TypeParameter */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 161 /* TypePredicate */: - case 162 /* TypeReference */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 165 /* TypeQuery */: - case 166 /* TypeLiteral */: - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 169 /* OptionalType */: - case 170 /* RestType */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 173 /* ConditionalType */: - case 174 /* InferType */: - case 175 /* ParenthesizedType */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 176 /* ThisType */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 180 /* LiteralType */: - case 245 /* NamespaceExportDeclaration */: + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 163 /* TypePredicate */: + case 164 /* TypeReference */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 167 /* TypeQuery */: + case 168 /* TypeLiteral */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 176 /* InferType */: + case 177 /* ParenthesizedType */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = 3 /* AssertTypeScript */; excludeFlags = -3 /* TypeExcludes */; break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29056,93 +30357,93 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + case 208 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; - case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + case 277 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; - case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + case 184 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; - case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + case 185 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; - case 150 /* Decorator */: + case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; - case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + case 188 /* ObjectLiteralExpression */: + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; } break; - case 185 /* ArrayLiteralExpression */: - case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + case 187 /* ArrayLiteralExpression */: + case 192 /* NewExpression */: + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } break; - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + case 279 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29155,71 +30456,71 @@ var ts; * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather * than calling this function. */ - /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) { + if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { return -3 /* TypeExcludes */; } switch (kind) { - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; - case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; - case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; - case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; - case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 137 /* StringKeyword */: - case 135 /* ObjectKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 148 /* TypeParameter */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 187 /* ArrayLiteralExpression */: + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + case 244 /* ModuleDeclaration */: + return 647001409 /* ModuleExcludes */; + case 151 /* Parameter */: + return 637535553 /* ParameterExcludes */; + case 197 /* ArrowFunction */: + return 653604161 /* ArrowFunctionExcludes */; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return 653620545 /* FunctionExcludes */; + case 238 /* VariableDeclarationList */: + return 639894849 /* VariableDeclarationListExcludes */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 638121281 /* ClassExcludes */; + case 157 /* Constructor */: + return 653616449 /* ConstructorExcludes */; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return 653616449 /* MethodOrAccessorExcludes */; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 138 /* StringKeyword */: + case 136 /* ObjectKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; - case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; - case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 306 /* PartiallyEmittedExpression */: - case 193 /* ParenthesizedExpression */: - case 97 /* SuperKeyword */: + case 188 /* ObjectLiteralExpression */: + return 638358849 /* ObjectLiteralExcludes */; + case 274 /* CatchClause */: + return 637797697 /* CatchClauseExcludes */; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return 637666625 /* BindingPatternExcludes */; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + case 195 /* ParenthesizedExpression */: + case 98 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29277,7 +30578,7 @@ var ts; if (shouldBail) return; // Visit the type's related types, if any - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var objectType = type; var objectFlags = objectType.objectFlags; if (objectFlags & 4 /* Reference */) { @@ -29293,16 +30594,16 @@ var ts; visitObjectType(objectType); } } - if (type.flags & 65536 /* TypeParameter */) { + if (type.flags & 262144 /* TypeParameter */) { visitTypeParameter(type); } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { visitUnionOrIntersectionType(type); } - if (type.flags & 1048576 /* Index */) { + if (type.flags & 4194304 /* Index */) { visitIndexType(type); } - if (type.flags & 2097152 /* IndexedAccess */) { + if (type.flags & 8388608 /* IndexedAccess */) { visitIndexedAccessType(type); } } @@ -29391,7 +30692,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 165 /* TypeQuery */) { + if (d.type && d.type.kind === 167 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -29434,6 +30735,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30767,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29463,10 +30777,12 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); @@ -29625,27 +30941,13 @@ var ts; var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); return parsed ? isImplementationOfOverload(parsed) : undefined; }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return ts.Debug.fail(); - links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); - } - return links.immediateTarget; - }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { - var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isParameter); @@ -29669,15 +30971,17 @@ var ts; getNumberType: function () { return numberType; }, createPromiseType: createPromiseType, createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, getESSymbolType: function () { return esSymbolType; }, getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -29685,7 +30989,7 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, - getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, @@ -29739,7 +31043,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29762,24 +31067,43 @@ var ts; var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); - var undefinedType = createIntrinsicType(8192 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(8192 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(16384 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(16384 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); - var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); - var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); - var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(4096 /* Void */, "void"); - var neverType = createIntrinsicType(32768 /* Never */, "never"); - var silentNeverType = createIntrinsicType(32768 /* Never */, "never"); - var implicitNeverType = createIntrinsicType(32768 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -29792,18 +31116,18 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(65536 /* TypeParameter */); - var markerSubType = createType(65536 /* TypeParameter */); + var markerSuperType = createType(262144 /* TypeParameter */); + var markerSubType = createType(262144 /* TypeParameter */); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(65536 /* TypeParameter */); + var markerOtherType = createType(262144 /* TypeParameter */); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29815,6 +31139,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +31159,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +31171,9 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29852,6 +31181,7 @@ var ts; var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -29877,84 +31207,99 @@ var ts; TypeFacts[TypeFacts["None"] = 0] = "None"; TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; - TypeFacts[TypeFacts["TypeofEQBoolean"] = 4] = "TypeofEQBoolean"; - TypeFacts[TypeFacts["TypeofEQSymbol"] = 8] = "TypeofEQSymbol"; - TypeFacts[TypeFacts["TypeofEQObject"] = 16] = "TypeofEQObject"; - TypeFacts[TypeFacts["TypeofEQFunction"] = 32] = "TypeofEQFunction"; - TypeFacts[TypeFacts["TypeofEQHostObject"] = 64] = "TypeofEQHostObject"; - TypeFacts[TypeFacts["TypeofNEString"] = 128] = "TypeofNEString"; - TypeFacts[TypeFacts["TypeofNENumber"] = 256] = "TypeofNENumber"; - TypeFacts[TypeFacts["TypeofNEBoolean"] = 512] = "TypeofNEBoolean"; - TypeFacts[TypeFacts["TypeofNESymbol"] = 1024] = "TypeofNESymbol"; - TypeFacts[TypeFacts["TypeofNEObject"] = 2048] = "TypeofNEObject"; - TypeFacts[TypeFacts["TypeofNEFunction"] = 4096] = "TypeofNEFunction"; - TypeFacts[TypeFacts["TypeofNEHostObject"] = 8192] = "TypeofNEHostObject"; - TypeFacts[TypeFacts["EQUndefined"] = 16384] = "EQUndefined"; - TypeFacts[TypeFacts["EQNull"] = 32768] = "EQNull"; - TypeFacts[TypeFacts["EQUndefinedOrNull"] = 65536] = "EQUndefinedOrNull"; - TypeFacts[TypeFacts["NEUndefined"] = 131072] = "NEUndefined"; - TypeFacts[TypeFacts["NENull"] = 262144] = "NENull"; - TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; - TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; - TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["All"] = 4194303] = "All"; + TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; + TypeFacts[TypeFacts["All"] = 16777215] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. - TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; - TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; - TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; - TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; - TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; - TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; - TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; - TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; - TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; - TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; - TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; - TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; - TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; - TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; - TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; - TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; - TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; - TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; - TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; - TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; - TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; - TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; - TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; - TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; - TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; - TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts"; + TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts"; + TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, number: 2 /* TypeofEQNumber */, - boolean: 4 /* TypeofEQBoolean */, - symbol: 8 /* TypeofEQSymbol */, - undefined: 16384 /* EQUndefined */, - object: 16 /* TypeofEQObject */, - function: 32 /* TypeofEQFunction */ + bigint: 4 /* TypeofEQBigInt */, + boolean: 8 /* TypeofEQBoolean */, + symbol: 16 /* TypeofEQSymbol */, + undefined: 65536 /* EQUndefined */, + object: 32 /* TypeofEQObject */, + function: 64 /* TypeofEQFunction */ }); var typeofNEFacts = ts.createMapFromTemplate({ - string: 128 /* TypeofNEString */, - number: 256 /* TypeofNENumber */, - boolean: 512 /* TypeofNEBoolean */, - symbol: 1024 /* TypeofNESymbol */, - undefined: 131072 /* NEUndefined */, - object: 2048 /* TypeofNEObject */, - function: 4096 /* TypeofNEFunction */ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ }); var typeofTypesByName = ts.createMapFromTemplate({ string: stringType, number: numberType, + bigint: bigintType, boolean: booleanType, symbol: esSymbolType, undefined: undefinedType @@ -29975,6 +31320,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +31457,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,10 +31518,14 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { - target = cloneSymbol(target); + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); } // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { @@ -30184,8 +31535,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30204,55 +31556,56 @@ var ts; else if (target.flags & 1024 /* NamespaceModule */) { error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } - else { + else { // error var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30268,7 +31621,8 @@ var ts; } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { - target.set(id, target.has(id) ? mergeSymbol(target.get(id), sourceSymbol) : sourceSymbol); + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); }); } function mergeModuleAugmentation(moduleName) { @@ -30330,7 +31684,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { - return node.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -30360,8 +31714,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30388,17 +31742,17 @@ var ts; } if (declaration.pos <= usage.pos) { // declaration is before usage - if (declaration.kind === 184 /* BindingElement */) { + if (declaration.kind === 186 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 184 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 235 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage); } - else if (declaration.kind === 235 /* VariableDeclaration */) { + else if (declaration.kind === 237 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -30417,12 +31771,12 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 252 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -30430,9 +31784,9 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 217 /* VariableStatement */: - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 219 /* VariableStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -30453,16 +31807,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 152 /* PropertyDeclaration */ && + current.parent.kind === 154 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 154 /* MethodDeclaration */) { + if (declaration.kind === 156 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -30504,27 +31858,35 @@ var ts; // - 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 & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 149 /* Parameter */ || - lastLocation.kind === 148 /* TypeParameter */ + lastLocation.kind === 151 /* Parameter */ || + lastLocation.kind === 150 /* TypeParameter */ // local types not visible outside the function body : false; } - if (meaning & 67216319 /* 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 === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (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 === 151 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } - else if (location.kind === 173 /* ConditionalType */) { + else if (location.kind === 175 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -30538,14 +31900,14 @@ var ts; } } switch (location.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -30569,7 +31931,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 255 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) { break; } } @@ -30583,13 +31945,13 @@ var ts; } } break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* 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 @@ -30599,17 +31961,20 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } } } break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30624,7 +31989,7 @@ var ts; } break loop; } - if (location.kind === 207 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -30632,11 +31997,11 @@ var ts; } } break; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. - if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { + if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30652,29 +32017,29 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -30687,7 +32052,7 @@ var ts; } } break; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -30696,7 +32061,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 === 149 /* Parameter */) { + if (location.parent && location.parent.kind === 151 /* Parameter */) { location = location.parent; } // @@ -30709,8 +32074,8 @@ var ts; location = location.parent; } break; - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); break; @@ -30724,13 +32089,13 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { result.isReferenced |= meaning; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30739,7 +32104,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,16 +32159,15 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -30812,12 +32176,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: // For `namespace N { N; }` + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -30829,7 +32193,7 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 148 /* TypeParameter */) { + if (decl.kind === 150 /* TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 @@ -30884,10 +32248,10 @@ var ts; */ function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -30897,9 +32261,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +32282,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30951,7 +32318,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30968,6 +32335,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -30983,13 +32353,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node; - case 248 /* ImportClause */: + case 250 /* ImportClause */: return node.parent; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return node.parent.parent; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -30999,7 +32369,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -31037,7 +32407,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +32461,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31147,7 +32517,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31181,7 +32551,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31191,20 +32561,20 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 252 /* ExportAssignment */: - case 202 /* BinaryExpression */: + case 257 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 254 /* ExportAssignment */: + case 204 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -31215,10 +32585,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32619,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31265,11 +32635,11 @@ var ts; var node = getDeclarationOfAliasSymbol(symbol); if (!node) return ts.Debug.fail(); - if (node.kind === 252 /* ExportAssignment */) { + if (node.kind === 254 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 255 /* ExportSpecifier */) { + else if (node.kind === 257 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -31287,22 +32657,22 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 146 /* QualifiedName */) { + if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31311,19 +32681,19 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; - if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + if (name.kind === 72 /* Identifier */) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; } } - else if (name.kind === 146 /* QualifiedName */ || name.kind === 187 /* PropertyAccessExpression */) { - var left = name.kind === 146 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 146 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) { + var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -31331,7 +32701,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32736,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32752,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,8 +32774,18 @@ var ts; return symbol && symbol.valueDeclaration; } } - function resolveExternalModuleName(location, moduleReferenceExpression) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); } function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { if (isForAugmentation === void 0) { isForAugmentation = false; } @@ -31421,7 +32813,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32832,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32864,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32872,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,24 +32884,28 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { return exported; } var merged = cloneSymbol(exported); @@ -31530,7 +32926,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 277 /* SourceFile */)) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); return symbol; } @@ -31598,7 +32994,7 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 32764 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -31688,6 +33084,50 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } /** * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` @@ -31696,10 +33136,12 @@ var ts; var container = getParentOfSymbol(symbol); if (container) { var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { - return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope } - return ts.append(additionalContainers, container); + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); } var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); if (!ts.length(candidates)) { @@ -31737,13 +33179,13 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 155 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -31766,7 +33208,7 @@ var ts; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(131072 /* Object */); + var type = createType(524288 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; type.members = undefined; @@ -31821,12 +33263,12 @@ var ts; } } switch (location.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -31837,7 +33279,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +33329,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31923,7 +33368,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -31938,10 +33383,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: continue; default: return false; @@ -31952,11 +33397,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +33439,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32048,10 +33503,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -32098,21 +33553,21 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 165 /* TypeQuery */ || + if (entityName.parent.kind === 167 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 147 /* ComputedPropertyName */) { + entityName.parent.kind === 149 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || - entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ || + entityName.parent.kind === 248 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32125,7 +33580,7 @@ var ts; } function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } - var nodeFlags = 3112960 /* IgnoreErrors */; + var nodeFlags = 70221824 /* IgnoreErrors */; if (flags & 2 /* UseOnlyExternalAliasing */) { nodeFlags |= 128 /* UseOnlyExternalAliasing */; } @@ -32135,6 +33590,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32151,15 +33609,15 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 164 /* ConstructorType */ : 163 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 159 /* ConstructSignature */ : 158 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */; } - var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 return writer; } } @@ -32167,7 +33625,7 @@ var ts; if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -32217,9 +33675,15 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, - visitedSymbols: undefined, + visitedTypes: undefined, + symbolDepth: undefined, inferTypeParameters: undefined, approximateLength: 0 }; @@ -32243,85 +33707,92 @@ var ts; } if (type.flags & 1 /* Any */) { context.approximateLength += 3; - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } if (type.flags & 2 /* Unknown */) { - return ts.createKeywordTypeNode(142 /* UnknownKeyword */); + return ts.createKeywordTypeNode(143 /* UnknownKeyword */); } if (type.flags & 4 /* String */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(137 /* StringKeyword */); + return ts.createKeywordTypeNode(138 /* StringKeyword */); } if (type.flags & 8 /* Number */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(134 /* NumberKeyword */); + return ts.createKeywordTypeNode(135 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146 /* BigIntKeyword */); } if (type.flags & 16 /* Boolean */) { context.approximateLength += 7; - return ts.createKeywordTypeNode(122 /* BooleanKeyword */); + return ts.createKeywordTypeNode(123 /* BooleanKeyword */); } - if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { + if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined)); + return enumLiteralName; } - if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + if (type.flags & 1056 /* EnumLike */) { + return symbolToTypeNode(type.symbol, context, 67897832 /* Type */); } - if (type.flags & 64 /* StringLiteral */) { + if (type.flags & 128 /* StringLiteral */) { context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & 128 /* NumberLiteral */) { + if (type.flags & 256 /* NumberLiteral */) { context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } - if (type.flags & 256 /* BooleanLiteral */) { + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512 /* BooleanLiteral */) { context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 2048 /* UniqueESSymbol */) { + if (type.flags & 8192 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } context.approximateLength += 13; - return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); + return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */)); } - if (type.flags & 4096 /* Void */) { + if (type.flags & 16384 /* Void */) { context.approximateLength += 4; - return ts.createKeywordTypeNode(105 /* VoidKeyword */); + return ts.createKeywordTypeNode(106 /* VoidKeyword */); } - if (type.flags & 8192 /* Undefined */) { + if (type.flags & 32768 /* Undefined */) { context.approximateLength += 9; - return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + return ts.createKeywordTypeNode(141 /* UndefinedKeyword */); } - if (type.flags & 16384 /* Null */) { + if (type.flags & 65536 /* Null */) { context.approximateLength += 4; - return ts.createKeywordTypeNode(95 /* NullKeyword */); + return ts.createKeywordTypeNode(96 /* NullKeyword */); } - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { context.approximateLength += 5; - return ts.createKeywordTypeNode(131 /* NeverKeyword */); + return ts.createKeywordTypeNode(132 /* NeverKeyword */); } - if (type.flags & 1024 /* ESSymbol */) { + if (type.flags & 4096 /* ESSymbol */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(138 /* SymbolKeyword */); + return ts.createKeywordTypeNode(139 /* SymbolKeyword */); } - if (type.flags & 16777216 /* NonPrimitive */) { + if (type.flags & 67108864 /* NonPrimitive */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(135 /* ObjectKeyword */); + return ts.createKeywordTypeNode(136 /* ObjectKeyword */); } - if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { + if (type.flags & 262144 /* TypeParameter */ && type.isThisType) { if (context.flags & 4194304 /* InObjectTypeLiteral */) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; @@ -32335,16 +33806,16 @@ var ts; } var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); return typeReferenceToTypeNode(type); } - if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && - type.flags & 65536 /* TypeParameter */ && + type.flags & 262144 /* TypeParameter */ && ts.length(type.symbol.declarations) && ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && @@ -32355,20 +33826,23 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } - if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { - var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -32379,23 +33853,23 @@ var ts; } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & 1048576 /* Index */) { + if (type.flags & 4194304 /* Index */) { var indexedType = type.type; context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 2097152 /* IndexedAccess */) { + if (type.flags & 8388608 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } - if (type.flags & 4194304 /* Conditional */) { + if (type.flags & 16777216 /* Conditional */) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); var saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; @@ -32406,12 +33880,12 @@ var ts; context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } - if (type.flags & 8388608 /* Substitution */) { + if (type.flags & 33554432 /* Substitution */) { return typeToTypeNodeHelper(type.typeVariable, context); } return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; var appropriateConstraintTypeNode; @@ -32430,43 +33904,52 @@ var ts; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { + var typeId = "" + type.id; var symbol = type.symbol; var id; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects - else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } - else if (context.visitedSymbols && context.visitedSymbols.has(id)) { + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { - context.approximateLength += 3; - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return createElidedInformationPlaceholder(context); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.visitedSymbols) { - context.visitedSymbols = ts.createMap(); + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); } - context.visitedSymbols.set(id, true); + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); var result = createTypeNodeFromObjectType(type); - context.visitedSymbols.delete(id); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); return result; } } @@ -32480,11 +33963,11 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 277 /* SourceFile */ || declaration.parent.kind === 243 /* ModuleBlock */; + return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } @@ -32501,12 +33984,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 163 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 164 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context); return signatureNode; } } @@ -32533,8 +34016,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +34056,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +34069,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32638,17 +34121,22 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 158 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 159 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ? - createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : - resolvedType.stringIndexInfo; - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context)); + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context); + } + typeElements.push(indexSignature); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); @@ -32679,31 +34167,34 @@ var ts; return typeElements.length ? typeElements : undefined; } } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; if (propertySymbol.valueDeclaration) { @@ -32715,10 +34206,16 @@ var ts; } else { var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; } @@ -32769,7 +34266,7 @@ var ts; } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 137 /* StringKeyword */ : 134 /* NumberKeyword */); + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -32782,7 +34279,7 @@ var ts; } context.approximateLength += (name.length + 4); return ts.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { var typeParameters; @@ -32793,7 +34290,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -32812,18 +34309,18 @@ var ts; returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } if (context.flags & 256 /* SuppressAnyReturnType */) { - if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) { returnTypeNode = undefined; } } else if (!returnTypeNode) { - returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */); } context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +34331,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32846,9 +34343,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -32857,16 +34354,16 @@ var ts; var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; - var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - parameterDeclaration.name.kind === 146 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; - var questionToken = isOptional ? ts.createToken(55 /* QuestionToken */) : undefined; + var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); @@ -32875,21 +34372,34 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 184 /* BindingElement */) { + if (clone.kind === 186 /* BindingElement */) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32900,13 +34410,22 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + var parentSpecifiers; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); - if (ts.length(parents)) { - for (var _i = 0, _a = parents; _i < _a.length; _i++) { - var parent = _a[_i]; + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); @@ -32929,6 +34448,24 @@ var ts; } return [symbol]; } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } } } function typeParametersToTypeParameterDeclarations(symbol, context) { @@ -32966,7 +34503,7 @@ var ts; return top; } function getSpecifierForModuleSymbol(symbol, context) { - var file = ts.getDeclarationOfKind(symbol, 277 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -32996,7 +34533,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,12 +34548,20 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); @@ -33103,6 +34655,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33143,7 +34698,7 @@ var ts; if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { - var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); @@ -33156,12 +34711,12 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 24576 /* Nullable */)) { - if (t.flags & (256 /* BooleanLiteral */ | 512 /* EnumLiteral */)) { - var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 262144 /* Union */) { + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) { + var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33171,9 +34726,9 @@ var ts; result.push(t); } } - if (flags & 16384 /* Null */) + if (flags & 65536 /* Null */) result.push(nullType); - if (flags & 8192 /* Undefined */) + if (flags & 32768 /* Undefined */) result.push(undefinedType); return result || types; } @@ -33188,8 +34743,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 175 /* ParenthesizedType */; }); - if (node.kind === 240 /* TypeAliasDeclaration */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; }); + if (node.kind === 242 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -33197,11 +34752,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 243 /* ModuleBlock */ && + node.parent.kind === 245 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); } /** * Gets a human-readable name for a symbol. @@ -33224,27 +34779,30 @@ var ts; var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 235 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 207 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var nameType = symbol.nameType; if (nameType) { - if (nameType.flags & 64 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; } - if (nameType && nameType.flags & 2048 /* UniqueESSymbol */) { + if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; } } @@ -33261,27 +34819,27 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 237 /* FunctionDeclaration */: - case 241 /* EnumDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 243 /* EnumDeclaration */: + case 248 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -33289,53 +34847,53 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 246 /* ImportEqualsDeclaration */ && parent.kind !== 277 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 155 /* Constructor */: - case 159 /* ConstructSignature */: - case 158 /* CallSignature */: - case 160 /* IndexSignature */: - case 149 /* Parameter */: - case 243 /* ModuleBlock */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 166 /* TypeLiteral */: - case 162 /* TypeReference */: - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 175 /* ParenthesizedType */: + case 157 /* Constructor */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 151 /* Parameter */: + case 245 /* ModuleBlock */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 164 /* TypeReference */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 177 /* 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 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: return false; // Type parameters are always visible - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: // Source file and namespace export are always visible - case 277 /* SourceFile */: - case 245 /* NamespaceExportDeclaration */: + case 279 /* SourceFile */: + case 247 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return false; default: return false; @@ -33344,11 +34902,11 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + if (node.parent && node.parent.kind === 254 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + else if (node.parent.kind === 257 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34927,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34976,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33426,6 +34986,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33439,12 +35001,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 235 /* VariableDeclaration */: - case 236 /* VariableDeclarationList */: - case 251 /* ImportSpecifier */: - case 250 /* NamedImports */: - case 249 /* NamespaceImport */: - case 248 /* ImportClause */: + case 237 /* VariableDeclaration */: + case 238 /* VariableDeclarationList */: + case 253 /* ImportSpecifier */: + case 252 /* NamedImports */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: return false; default: return true; @@ -33474,28 +35036,36 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); + return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); - if (source.flags & 32768 /* Never */) { + source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); + if (source.flags & 131072 /* Never */) { return emptyObjectType; } - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } - var members = ts.createSymbolTable(); - var names = ts.createUnderscoreEscapedMap(); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var name = properties_2[_i]; - names.set(ts.getTextOfPropertyName(name), true); + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - if (!names.has(prop.escapedName) + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getNonReadonlySymbol(prop)); + members.set(prop.escapedName, getSpreadSymbol(prop)); } } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); @@ -33519,8 +35089,12 @@ var ts; if (isTypeAny(parentType)) { return parentType; } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } var type; - if (pattern.kind === 182 /* ObjectBindingPattern */) { + if (pattern.kind === 184 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -33538,51 +35112,9 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - var isLate = isLateBindableName(name); - var isWellKnown = ts.isComputedPropertyName(name) && ts.isWellKnownSymbolSyntactically(name.expression); - if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { - var exprType = checkExpression(name.expression); - if (isTypeAssignableToKind(exprType, 3072 /* ESSymbolLike */)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); - } - return anyType; - } - var indexerType = isTypeAssignableToKind(exprType, 168 /* NumberLike */) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); - if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(parentType, 1 /* Number */)) { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType)); - } - } - return indexerType || 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. - var nameType = isLate ? checkComputedPropertyName(name) : undefined; - var text = isLate ? getLateBoundNameFromType(nameType) : - isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : - ts.getTextOfPropertyName(name); - // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation - if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { - parentType = getNonNullableType(parentType); - } - if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType)); - } - return anyType; - } - var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); - type = declaredType && getFlowTypeOfReference(declaration, declaredType) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || - getIndexTypeOfType(parentType, 0 /* String */); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return errorType; - } + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); } } else { @@ -33590,27 +35122,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33618,11 +35150,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { - type = getTypeWithFacts(type, 131072 /* NEUndefined */); + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) { + type = getTypeWithFacts(type, 524288 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33634,11 +35166,11 @@ var ts; } function isNullOrUndefined(node) { var expr = ts.skipParentheses(node); - return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 185 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -33648,11 +35180,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 224 /* ForInStatement */) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (65536 /* TypeParameter */ | 1048576 /* Index */) ? getExtractStringType(indexType) : stringType; + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 225 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* 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, @@ -33670,8 +35202,8 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no @@ -33685,11 +35217,11 @@ var ts; return autoArrayType; } } - if (declaration.kind === 149 /* Parameter */) { + if (declaration.kind === 151 /* 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 === 157 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 156 /* GetAccessor */); + if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -33701,16 +35233,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +35268,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33747,14 +35285,14 @@ var ts; var types; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = ts.isBinaryExpression(declaration) ? declaration : + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +35300,11 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,26 +35312,24 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; } } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(24576 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +35348,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +35362,35 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); - if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + if (type.flags & 524288 /* Object */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33851,9 +35414,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33862,9 +35423,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 155 /* Constructor */ || - thisContainer.kind === 237 /* FunctionDeclaration */ || - (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 157 /* Constructor */ || + thisContainer.kind === 239 /* FunctionDeclaration */ || + (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -33876,8 +35437,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +35446,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33899,8 +35460,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33939,7 +35500,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var hasRestElement = !!(lastElement && lastElement.kind === 184 /* BindingElement */ && lastElement.dotDotDotToken); + var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken); if (elements.length === 0 || elements.length === 1 && hasRestElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -33962,7 +35523,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 182 /* ObjectBindingPattern */ + return pattern.kind === 184 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -33984,7 +35545,7 @@ var ts; reportErrorsFromWidening(declaration, type); } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & 2048 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } return getWidenedType(type); @@ -33992,16 +35553,16 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 149 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -34037,19 +35598,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } - if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + if (declaration.kind === 254 /* ExportAssignment */) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && - (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +35631,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34085,6 +35653,14 @@ var ts; || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } @@ -34095,7 +35671,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 156 /* GetAccessor */) { + if (accessor.kind === 158 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -34122,9 +35698,9 @@ var ts; return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); } function getTypeOfAccessorsWorker(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */); + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34152,14 +35728,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34168,7 +35742,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* 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)); } } @@ -34176,13 +35750,13 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 2162688 /* TypeVariable */ ? baseConstructorType : undefined; + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34208,9 +35782,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 202 /* BinaryExpression */ || - declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + else if (declaration.kind === 204 /* BinaryExpression */ || + declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) { + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35793,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35822,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35831,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34329,7 +35895,7 @@ var ts; var target = getTargetType(type); return target === checkBase || ts.some(getBaseTypes(target), check); } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return ts.some(type.types, check); } return false; @@ -34353,35 +35919,35 @@ var ts; return undefined; } switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 287 /* JSDocFunctionType */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 179 /* MappedType */: - case 173 /* ConditionalType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 181 /* MappedType */: + case 175 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 179 /* MappedType */) { + if (node.kind === 181 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 173 /* ConditionalType */) { + else if (node.kind === 175 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */ || node.kind === 239 /* InterfaceDeclaration */) && + (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } @@ -34389,7 +35955,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, 239 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -34398,9 +35964,9 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 239 /* InterfaceDeclaration */ || - node.kind === 238 /* ClassDeclaration */ || - node.kind === 207 /* ClassExpression */ || + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || + node.kind === 209 /* ClassExpression */ || ts.isTypeAlias(node)) { var declaration = node; result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); @@ -34427,27 +35993,24 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { return true; } - if (type.flags & 2162688 /* TypeVariable */) { + if (type.flags & 8650752 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34473,7 +36036,7 @@ var ts; ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag checkExpression(extended.expression); } - if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */)) { + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -34483,7 +36046,18 @@ var ts; return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } return type.resolvedBaseConstructorType = errorType; } type.resolvedBaseConstructorType = baseConstructorType; @@ -34512,13 +36086,15 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 1 /* Any */))) { + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? 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 @@ -34529,8 +36105,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34547,7 +36123,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { @@ -34577,14 +36153,14 @@ var ts; // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return !!(type.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 524288 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -34603,7 +36179,7 @@ var ts; } } else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -34620,7 +36196,7 @@ var ts; function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 /* InterfaceDeclaration */) { + if (declaration.kind === 241 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -34629,7 +36205,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34661,7 +36237,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536 /* TypeParameter */); + type.thisType = createType(262144 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -34678,7 +36254,7 @@ var ts; return errorType; } var declaration = ts.find(symbol.declarations, function (d) { - return ts.isJSDocTypeAlias(d) || d.kind === 240 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */; }); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. @@ -34702,10 +36278,10 @@ var ts; return links.declaredType; } function isStringConcatExpression(expr) { - if (expr.kind === 9 /* StringLiteral */) { + if (expr.kind === 10 /* StringLiteral */) { return true; } - else if (expr.kind === 202 /* BinaryExpression */) { + else if (expr.kind === 204 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -34716,15 +36292,15 @@ var ts; return !(member.flags & 4194304 /* Ambient */); } switch (expr.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return true; - case 200 /* PrefixUnaryExpression */: - return expr.operator === 38 /* MinusToken */ && + case 202 /* PrefixUnaryExpression */: + return expr.operator === 39 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -34738,10 +36314,10 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241 /* EnumDeclaration */) { + if (declaration.kind === 243 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) { return links.enumKind = 1 /* Literal */; } if (!isLiteralEnumMember(member)) { @@ -34753,7 +36329,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -34765,19 +36341,19 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241 /* EnumDeclaration */) { + if (declaration.kind === 243 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); - if (enumType_1.flags & 262144 /* Union */) { - enumType_1.flags |= 512 /* EnumLiteral */; + if (enumType_1.flags & 1048576 /* Union */) { + enumType_1.flags |= 1024 /* EnumLiteral */; enumType_1.symbol = symbol; } return links.declaredType = enumType_1; @@ -34800,7 +36376,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(65536 /* TypeParameter */); + var type = createType(262144 /* TypeParameter */); type.symbol = symbol; links.declaredType = type; } @@ -34844,22 +36420,23 @@ var ts; */ function isThislessType(node) { switch (node.kind) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 135 /* ObjectKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: - case 180 /* LiteralType */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + case 182 /* LiteralType */: return true; - case 167 /* ArrayType */: + case 169 /* ArrayType */: return isThislessType(node.elementType); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -34885,7 +36462,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 155 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -34901,12 +36478,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -34950,7 +36527,7 @@ var ts; * Indicates whether a type can be used as a late-bound name. */ function isTypeUsableAsLateBoundName(type) { - return !!(type.flags & 2240 /* StringOrNumberLiteralOrUnique */); + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); } /** * Indicates whether a declaration name is definitely late-bindable. @@ -34993,10 +36570,10 @@ var ts; * Gets the symbolic name for a late-bound member from its type. */ function getLateBoundNameFromType(type) { - if (type.flags & 2048 /* UniqueESSymbol */) { + if (type.flags & 8192 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +36593,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35161,7 +36738,7 @@ var ts; return needApparentType ? getApparentType(ref) : ref; } } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } return needApparentType ? getApparentType(type) : type; @@ -35270,7 +36847,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35290,7 +36867,7 @@ var ts; function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { return s; } } @@ -35324,8 +36901,7 @@ var ts; // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional // parameters and may differ in return types. When signatures differ in return types, the resulting return // type is the union of the constituent return types. - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + function getUnionSignatures(signatureLists) { var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { @@ -35371,8 +36947,8 @@ var ts; 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 callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -35407,7 +36983,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35430,7 +37006,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35468,7 +37044,7 @@ var ts; if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 2162688 /* TypeVariable */)) { + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -35484,6 +37060,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35501,7 +37078,7 @@ var ts; var modifiers = getMappedTypeModifiers(type.mappedType); var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; - var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; @@ -35511,6 +37088,7 @@ var ts; inferredProp.nameType = prop.nameType; inferredProp.propertyType = getTypeOfSymbol(prop); inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -35529,12 +37107,12 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateModifiers = getMappedTypeModifiers(type); - var include = keyofStringsOnly ? 64 /* StringLiteral */ : 2240 /* StringOrNumberLiteralOrUnique */; + var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); @@ -35544,11 +37122,9 @@ var ts; } } else { - // First, if the constraint type is a type parameter, obtain the base constraint. Then, - // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 14745600 /* InstantiableNonPrimitive */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 1048576 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); @@ -35560,7 +37136,7 @@ var ts; var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. - if (t.flags & 2240 /* StringOrNumberLiteralOrUnique */) { + if (t.flags & 8576 /* StringOrNumberLiteralOrUnique */) { var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || @@ -35572,7 +37148,7 @@ var ts; // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks // mode, if the underlying property is optional we remove 'undefined' from the type. prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; @@ -35595,7 +37171,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35608,8 +37184,8 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 177 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; + return constraintDeclaration.kind === 179 /* TypeOperator */ && + constraintDeclaration.operator === 129 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { @@ -35625,16 +37201,16 @@ var ts; // the modifiers type is T. Otherwise, the modifiers type is {}. var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 1048576 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } function getMappedTypeModifiers(type) { var declaration = type.declaration; - return (declaration.readonlyToken ? declaration.readonlyToken.kind === 38 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | - (declaration.questionToken ? declaration.questionToken.kind === 38 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); } function getMappedTypeOptionality(type) { var modifiers = getMappedTypeModifiers(type); @@ -35653,7 +37229,7 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { if (type.objectFlags & 4 /* Reference */) { resolveTypeReferenceMembers(type); } @@ -35670,10 +37246,10 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 262144 /* Union */) { + else if (type.flags & 1048576 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -35681,7 +37257,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; @@ -35690,7 +37266,7 @@ var ts; * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -35714,7 +37290,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { break; } } @@ -35724,12 +37300,13 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 786432 /* UnionOrIntersection */ ? + return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { - return obj.properties.some(function (property) { + var list = obj.properties; + return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); @@ -35737,7 +37314,7 @@ var ts; } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 262144 /* Union */)) { + if (!(unionType.flags & 1048576 /* Union */)) { return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); @@ -35756,24 +37333,33 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : - type.flags & 2097152 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : - type.flags & 4194304 /* Conditional */ ? getConstraintOfConditionalType(type) : + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { var rootTrueType = type.root.trueType; - var rootTrueConstraint = rootTrueType.flags & 8388608 /* Substitution */ ? rootTrueType.substitute : rootTrueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); } return type.resolvedDefaultConstraint; @@ -35785,11 +37371,12 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); - if (!(instantiated.flags & 32768 /* Never */)) { + if (!(instantiated.flags & 131072 /* Never */)) { return instantiated; } } @@ -35804,23 +37391,23 @@ var ts; var hasDisjointDomainType = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 15794176 /* Instantiable */) { + if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). var constraint = getConstraintOfType(t); - while (constraint && constraint.flags & (65536 /* TypeParameter */ | 1048576 /* Index */ | 4194304 /* Conditional */)) { + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { constraint = getConstraintOfType(constraint); } if (constraint) { // A constraint that isn't a union type implies that the final type would be a non-union // type as well. Since non-union constraints are of no interest, we can exit here. - if (!(constraint.flags & 262144 /* Union */)) { + if (!(constraint.flags & 1048576 /* Union */)) { return undefined; } constraints = ts.append(constraints, constraint); } } - else if (t.flags & 16809468 /* DisjointDomains */) { + else if (t.flags & 67238908 /* DisjointDomains */) { hasDisjointDomainType = true; } } @@ -35832,7 +37419,7 @@ var ts; // intersection operation to reduce the union constraints. for (var _b = 0, _c = type.types; _b < _c.length; _b++) { var t = _c[_b]; - if (t.flags & 16809468 /* DisjointDomains */) { + if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } } @@ -35842,11 +37429,11 @@ var ts; return undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; + return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -35864,6 +37451,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +37459,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35884,45 +37482,42 @@ var ts; return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { - if (t.flags & 65536 /* TypeParameter */) { + if (t.flags & 262144 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint); } - if (t.flags & 786432 /* UnionOrIntersection */) { + if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 262144 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 524288 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 1048576 /* Index */) { + if (t.flags & 4194304 /* Index */) { return keyofConstraintType; } - if (t.flags & 2097152 /* IndexedAccess */) { + if (t.flags & 8388608 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } - if (t.flags & 4194304 /* Conditional */) { + if (t.flags & 16777216 /* Conditional */) { var constraint = getConstraintOfConditionalType(t); return constraint && getBaseConstraint(constraint); } - if (t.flags & 8388608 /* Substitution */) { + if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,26 +37567,42 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 /* StringLike */ ? globalStringType : + t.flags & 296 /* NumberLike */ ? globalNumberType : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 528 /* BooleanLike */ ? globalBooleanType : + t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : + t.flags & 4194304 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var indexTypes; - var isUnion = containingType.flags & 262144 /* Union */; + var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; @@ -36016,10 +37627,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36104,27 +37715,31 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 917504 /* StructuredType */) { + if (type.flags & 3670016 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -36138,7 +37753,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 917504 /* StructuredType */) { + if (type.flags & 3670016 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -36192,12 +37807,12 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 286 /* JSDocOptionalType */ + node.type && node.type.kind === 288 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -36231,7 +37846,7 @@ var ts; return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -36256,30 +37871,32 @@ var ts; } function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { - if (!typeArguments) { - typeArguments = []; - } - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { - defaultType = anyType; - } - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - typeArguments.length = typeParameters.length; - } + if (!numTypeParameters) { + return []; } - return typeArguments; + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); @@ -36292,7 +37909,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37922,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36315,7 +37932,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 180 /* LiteralType */) { + if (type && type.kind === 182 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter @@ -36329,20 +37946,20 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 156 /* GetAccessor */ || declaration.kind === 157 /* SetAccessor */) && + if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) && !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 155 /* Constructor */ ? + var classType = declaration.kind === 157 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37990,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36396,13 +38013,13 @@ var ts; if (!node) return false; switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node.escapedText === "arguments" && ts.isExpressionNode(node); - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return node.name.kind === 147 /* ComputedPropertyName */ + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node.name.kind === 149 /* ComputedPropertyName */ && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -36460,7 +38077,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36477,7 +38094,7 @@ var ts; function createTypePredicateFromTypePredicateNode(node, func) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71 /* Identifier */) { + if (parameterName.kind === 72 /* Identifier */) { return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); } else { @@ -36487,7 +38104,7 @@ var ts; function getTypePredicateParameterIndex(parameterList, parameter) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { return i; } } @@ -36501,6 +38118,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36526,7 +38144,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 155 /* Constructor */) { + if (declaration.kind === 157 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -36536,12 +38154,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -36556,8 +38174,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +38220,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36615,7 +38237,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 === 155 /* Constructor */ || signature.declaration.kind === 159 /* ConstructSignature */; // TODO: GH#18217 + var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217 var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -36629,7 +38251,7 @@ var ts; return symbol.members.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 134 /* NumberKeyword */ : 137 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -36656,7 +38278,7 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */); return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { @@ -36664,13 +38286,13 @@ var ts; if (typeParameter.symbol) { for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.parent.kind === 174 /* InferType */) { + if (declaration.parent.kind === 176 /* InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. var grandParent = declaration.parent.parent; - if (grandParent.kind === 162 /* TypeReference */) { + if (grandParent.kind === 164 /* TypeReference */) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -36695,7 +38317,7 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter // declaration, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 149 /* Parameter */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } } @@ -36719,7 +38341,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -36792,10 +38414,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36825,7 +38447,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36852,9 +38474,9 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -36880,14 +38502,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +38531,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36904,16 +38540,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -36936,13 +38577,13 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { - var result = createType(8388608 /* Substitution */); + var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 168 /* TupleType */ && node.elementTypes.length === 1; + return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1; } function getImpliedConstraint(typeVariable, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : @@ -36951,9 +38592,9 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 289 /* JSDocComment */) { + while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 173 /* ConditionalType */ && node === parent.trueType) { + if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -36964,7 +38605,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */); + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -37022,23 +38663,23 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getNullableType(type, 16384 /* Null */) : type; + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37065,9 +38706,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: return declaration; } } @@ -37076,7 +38717,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 131072 /* Object */)) { + if (!(type.flags & 524288 /* Object */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } @@ -37087,10 +38728,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37118,6 +38759,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37144,12 +38788,21 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType; + } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -37198,7 +38851,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(65536 /* TypeParameter */); + var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); if (i < maxLength) { var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); property.type = typeParameter; @@ -37220,7 +38873,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536 /* TypeParameter */); + type.thisType = createType(262144 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -37255,8 +38908,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var lastElement = ts.lastOrUndefined(node.elementTypes); - var restElement_1 = lastElement && lastElement.kind === 170 /* RestType */ ? lastElement : undefined; - var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 169 /* OptionalType */ && n !== restElement_1; }) + 1; + var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1; var elementTypes = ts.map(node.elementTypes, function (n) { var type = getTypeFromTypeNode(n); return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; @@ -37265,6 +38918,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37295,16 +38956,17 @@ var ts; var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 27072 /* Unit */ && combined & 27072 /* Unit */) { + if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) { return true; } combined |= t.flags; - if (combined & 24576 /* Nullable */ && combined & (131072 /* Object */ | 16777216 /* NonPrimitive */) || - combined & 16777216 /* NonPrimitive */ && combined & (16809468 /* DisjointDomains */ & ~16777216 /* NonPrimitive */) || - combined & 68 /* StringLike */ && combined & (16809468 /* DisjointDomains */ & ~68 /* StringLike */) || - combined & 168 /* NumberLike */ && combined & (16809468 /* DisjointDomains */ & ~168 /* NumberLike */) || - combined & 3072 /* ESSymbolLike */ && combined & (16809468 /* DisjointDomains */ & ~3072 /* ESSymbolLike */) || - combined & 12288 /* VoidLike */ && combined & (16809468 /* DisjointDomains */ & ~12288 /* VoidLike */)) { + if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) || + combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || + combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || + combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || + combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) || + combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || + combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) { return true; } } @@ -37312,20 +38974,18 @@ var ts; } function addTypeToUnion(typeSet, includes, type) { var flags = type.flags; - if (flags & 262144 /* Union */) { + if (flags & 1048576 /* Union */) { return addTypesToUnion(typeSet, includes, type.types); } // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are // another form of 'never' (in that they have an empty value domain). We could in theory turn // intersections of unit types into 'never' upon construction, but deferring the reduction makes it // easier to reason about their origin. - if (!(flags & 32768 /* Never */ || flags & 524288 /* Intersection */ && isEmptyIntersectionType(type))) { + if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { includes |= flags & ~939524096 /* ConstructionFlags */; - if (flags & 3 /* AnyOrUnknown */) { - if (type === wildcardType) - includes |= 268435456 /* Wildcard */; - } - else if (!strictNullChecks && flags & 24576 /* Nullable */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(flags & 134217728 /* ContainsWideningType */)) includes |= 134217728 /* NonWideningType */; } @@ -37333,10 +38993,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +39008,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - 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 isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37373,11 +39021,11 @@ var ts; } function isSetOfLiteralsFromSameEnum(types) { var first = types[0]; - if (first.flags & 512 /* EnumLiteral */) { + if (first.flags & 1024 /* EnumLiteral */) { var firstEnum = getParentOfSymbol(first.symbol); for (var i = 1; i < types.length; i++) { var other = types[i]; - if (!(other.flags & 512 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { return false; } } @@ -37402,10 +39050,11 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || - t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37428,25 +39077,27 @@ var ts; } var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); - if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1 /* Literal */: + if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + neverType; + } } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { - removeRedundantLiteralTypes(typeSet, includes); - } - break; - case 2 /* Subtype */: - removeSubtypes(typeSet); - break; - } - if (typeSet.length === 0) { - return includes & 16384 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : - includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -37483,7 +39134,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -37493,10 +39144,11 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 24576 /* Nullable */); - type = createType(262144 /* Union */ | propagatedFlags | unionOfUnitTypes); + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(1048576 /* Union */ | propagatedFlags); unionTypes.set(id, type); type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; /* Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. @@ -37518,11 +39170,14 @@ var ts; } function addTypeToIntersection(typeSet, includes, type) { var flags = type.flags; - if (flags & 524288 /* Intersection */) { + if (flags & 2097152 /* Intersection */) { return addTypesToIntersection(typeSet, includes, type.types); } - if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { - includes |= 536870912 /* EmptyObject */; + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912 /* EmptyObject */)) { + includes |= 536870912 /* EmptyObject */; + typeSet.push(type); + } } else { includes |= flags & ~939524096 /* ConstructionFlags */; @@ -37530,10 +39185,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +39194,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37553,9 +39205,10 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 4 /* String */ && includes & 64 /* StringLiteral */ || - t.flags & 8 /* Number */ && includes & 128 /* NumberLiteral */ || - t.flags & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */; + var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37568,10 +39221,11 @@ var ts; for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { var u = unionTypes_1[_i]; if (!containsType(u.types, type)) { - var primitive = type.flags & 64 /* StringLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ ? numberType : - type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : - undefined; + var primitive = type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + undefined; if (!primitive || !containsType(u.types, primitive)) { return false; } @@ -37584,13 +39238,16 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; }); + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } var i = index + 1; // Remove all but the first union of primitive types and collect them in // the unionTypes array. while (i < types.length) { var t = types[i]; - if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) { + if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -37619,7 +39276,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */); + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -37635,22 +39292,23 @@ var ts; function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); - if (includes & 32768 /* Never */) { + if (includes & 131072 /* Never */) { return neverType; } if (includes & 1 /* Any */) { return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; } - if (!strictNullChecks && includes & 24576 /* Nullable */) { - return includes & 8192 /* Undefined */ ? undefinedType : nullType; + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 32768 /* Undefined */ ? undefinedType : nullType; } - if (includes & 4 /* String */ && includes & 64 /* StringLiteral */ || - includes & 8 /* Number */ && includes & 128 /* NumberLiteral */ || - includes & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */) { + if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 536870912 /* EmptyObject */ && !(includes & 131072 /* Object */)) { - typeSet.push(emptyObjectType); + if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { return unknownType; @@ -37658,8 +39316,8 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - if (includes & 262144 /* Union */) { - if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) { + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -37667,15 +39325,15 @@ var ts; } // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. - var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 262144 /* Union */) !== 0; }); + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; }); var unionType = typeSet[unionIndex_1]; return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 24576 /* Nullable */); - type = createType(524288 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(2097152 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. @@ -37692,7 +39350,7 @@ var ts; return links.resolvedType; } function createIndexType(type, stringsOnly) { - var result = createType(1048576 /* Index */); + var result = createType(4194304 /* Index */); result.type = type; result.stringsOnly = stringsOnly; return result; @@ -37702,14 +39360,22 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } - function getLiteralTypeFromPropertyName(prop, include) { + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) : - name && name.kind === 147 /* ComputedPropertyName */ && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : - getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); } if (type && type.flags & include) { return type; @@ -37717,8 +39383,8 @@ var ts; } return neverType; } - function getLiteralTypeFromPropertyNames(type, include) { - return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromPropertyName(t, include); })); + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); } function getNonEnumNumberIndexInfo(type) { var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); @@ -37726,16 +39392,16 @@ var ts; } function getIndexType(type, stringsOnly) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } - return type.flags & 262144 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - type.flags & 524288 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : type === wildcardType ? wildcardType : type.flags & 1 /* Any */ ? keyofConstraintType : - stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */) : - getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, 2048 /* UniqueESSymbol */)]) : - getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */ | 2048 /* UniqueESSymbol */)]) : - getLiteralTypeFromPropertyNames(type, 2240 /* StringOrNumberLiteralOrUnique */); + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) : + getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */); } function getExtractStringType(type) { if (keyofStringsOnly) { @@ -37746,17 +39412,17 @@ var ts; } function getIndexTypeOrString(type) { var indexType = getExtractStringType(getIndexType(type)); - return indexType.flags & 32768 /* Never */ ? stringType : indexType; + return indexType.flags & 131072 /* Never */ ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { switch (node.operator) { - case 128 /* KeyOfKeyword */: + case 129 /* KeyOfKeyword */: links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); break; - case 141 /* UniqueKeyword */: - links.resolvedType = node.type.kind === 138 /* SymbolKeyword */ + case 142 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 139 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) : errorType; break; @@ -37765,7 +39431,7 @@ var ts; return links.resolvedType; // TODO: GH#18217 } function createIndexedAccessType(objectType, indexType) { - var type = createType(2097152 /* IndexedAccess */); + var type = createType(8388608 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; return type; @@ -37786,56 +39452,63 @@ var ts; if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { return true; } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { return ts.every(type.types, isJSLiteralType); } - if (type.flags & 524288 /* Intersection */) { + if (type.flags & 2097152 /* Intersection */) { return ts.some(type.types, isJSLiteralType); } - if (type.flags & 15794176 /* Instantiable */) { + if (type.flags & 63176704 /* Instantiable */) { return isJSLiteralType(getResolvedBaseConstraint(type)); } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - undefined; + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } - if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { - if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) { + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { return objectType; } - var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { - var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = getIndexNodeForAccessExpression(accessNode); error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { @@ -37843,7 +39516,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768 /* Never */) { + if (indexType.flags & 131072 /* Never */) { return neverType; } if (isJSLiteralType(objectType)) { @@ -37869,15 +39542,15 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { return anyType; } if (accessNode) { - var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; - if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { @@ -37887,30 +39560,38 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 /* ElementAccessExpression */ + ? accessNode.argumentExpression + : accessNode.kind === 180 /* IndexedAccessType */ + ? accessNode.indexType + : accessNode.kind === 149 /* ComputedPropertyName */ + ? accessNode.expression + : accessNode; } function isGenericObjectType(type) { - return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); } function isGenericIndexType(type) { - return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); - } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); } function getSimplifiedType(type) { - return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 1048576 /* Union */) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // the type itself if no transformation is possible. @@ -37922,37 +39603,20 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); - } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 1048576 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 63176704 /* Instantiable */)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37960,7 +39624,7 @@ var ts; if (isGenericMappedType(objectType)) { return type.simplified = substituteIndexedMappedType(objectType, type); } - if (objectType.flags & 65536 /* TypeParameter */) { + if (objectType.flags & 262144 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); @@ -37973,7 +39637,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -37982,7 +39647,7 @@ var ts; // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 188 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } @@ -37998,19 +39663,30 @@ var ts; // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38018,7 +39694,7 @@ var ts; var objectType = getTypeFromTypeNode(node.objectType); var indexType = getTypeFromTypeNode(node.indexType); var resolved = getIndexedAccessType(objectType, indexType, node); - links.resolvedType = resolved.flags & 2097152 /* IndexedAccess */ && + links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && resolved.objectType === objectType && resolved.indexType === indexType ? getConstrainedTypeVariable(resolved, node) : resolved; @@ -38040,7 +39716,7 @@ var ts; return links.resolvedType; } function getActualTypeVariable(type) { - return type.flags & 8388608 /* Substitution */ ? type.typeVariable : type; + return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); @@ -38051,7 +39727,7 @@ var ts; // If this is a distributive conditional type and the check type is generic we need to defer // resolution of the conditional type such that a later instantiation will properly distribute // over union types. - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 15794176 /* Instantiable */); + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); @@ -38090,7 +39766,7 @@ var ts; } // Return a deferred type for a check that is neither definitely true nor definitely false var erasedCheckType = getActualTypeVariable(checkType); - var result = createType(4194304 /* Conditional */); + var result = createType(16777216 /* Conditional */); result.root = root; result.checkType = erasedCheckType; result.extendsType = extendsType; @@ -38122,7 +39798,7 @@ var ts; return true; } while (node) { - if (node.kind === 173 /* ConditionalType */) { + if (node.kind === 175 /* ConditionalType */) { if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { return true; } @@ -38145,7 +39821,7 @@ var ts; extendsType: getTypeFromTypeNode(node.extendsType), trueType: getTypeFromTypeNode(node.trueType), falseType: getTypeFromTypeNode(node.falseType), - isDistributive: !!(checkType.flags & 65536 /* TypeParameter */), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, @@ -38188,7 +39864,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39894,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39908,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38265,6 +39941,9 @@ var ts; function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } /** * Since the source of spread types are object literals, which are not binary, * this function should be called in a left folding style, with left = previous result of getSpreadType @@ -38277,21 +39956,37 @@ var ts; if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { return unknownType; } - if (left.flags & 32768 /* Never */) { + if (left.flags & 131072 /* Never */) { return right; } - if (right.flags & 32768 /* Never */) { + if (right.flags & 131072 /* Never */) { return left; } - if (left.flags & 262144 /* Union */) { + if (left.flags & 1048576 /* Union */) { return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); } - if (right.flags & 262144 /* Union */) { + if (right.flags & 1048576 /* Union */) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); } - if (right.flags & (272 /* BooleanLike */ | 168 /* NumberLike */ | 68 /* StringLike */ | 544 /* EnumLike */ | 16777216 /* NonPrimitive */ | 1048576 /* Index */)) { + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { return left; } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & 2097152 /* Intersection */) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); var stringIndexInfo; @@ -38311,7 +40006,7 @@ var ts; skippedPrivateMembers.set(rightProp.escapedName, true); } else if (isSpreadableProperty(rightProp)) { - members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { @@ -38326,7 +40021,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); var result = createSymbol(flags, leftProp.escapedName); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -38335,27 +40030,28 @@ var ts; } } else { - members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= typeFlags | 268435456 /* ContainsObjectLiteral */; - spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); + spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */) - ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) - : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable + return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isReadonly && !isSetonlyAccessor) { return prop; } var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); var result = createSymbol(flags, prop.escapedName); - result.type = getTypeOfSymbol(prop); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); result.declarations = prop.declarations; result.nameType = prop.nameType; result.syntheticOrigin = prop; @@ -38374,10 +40070,11 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; + freshType.freshType = freshType; type.freshType = freshType; } return type.freshType; @@ -38385,21 +40082,27 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + return type.flags & 2944 /* Literal */ ? type.regularType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } + function isFreshLiteralType(type) { + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; + } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', // where NNN is the text representation of a numeric literal and SSS are the characters // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where // EEE is a unique id for the containing enum type. - var qualifier = typeof value === "number" ? "#" : "@"; - var key = enumId ? enumId + qualifier + value : qualifier + value; + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); var type = literalTypes.get(key); if (!type) { - var flags = (typeof value === "number" ? 128 /* NumberLiteral */ : 64 /* StringLiteral */) | (enumId ? 512 /* EnumLiteral */ : 0); + var flags = (typeof value === "number" ? 256 /* NumberLiteral */ : + typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) | + (enumId ? 1024 /* EnumLiteral */ : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; } return type; } @@ -38411,7 +40114,7 @@ var ts; return links.resolvedType; } function createUniqueESSymbolType(symbol) { - var type = createType(2048 /* UniqueESSymbol */); + var type = createType(8192 /* UniqueESSymbol */); type.symbol = symbol; return type; } @@ -38426,9 +40129,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 239 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) { if (!ts.hasModifier(container, 32 /* Static */) && - (container.kind !== 155 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -38444,87 +40147,89 @@ var ts; } function getTypeFromTypeNode(node) { switch (node.kind) { - case 119 /* AnyKeyword */: - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: + case 120 /* AnyKeyword */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: return anyType; - case 142 /* UnknownKeyword */: + case 143 /* UnknownKeyword */: return unknownType; - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: return stringType; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: return numberType; - case 122 /* BooleanKeyword */: + case 146 /* BigIntKeyword */: + return bigintType; + case 123 /* BooleanKeyword */: return booleanType; - case 138 /* SymbolKeyword */: + case 139 /* SymbolKeyword */: return esSymbolType; - case 105 /* VoidKeyword */: + case 106 /* VoidKeyword */: return voidType; - case 140 /* UndefinedKeyword */: + case 141 /* UndefinedKeyword */: return undefinedType; - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: return nullType; - case 131 /* NeverKeyword */: + case 132 /* NeverKeyword */: return neverType; - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; - case 176 /* ThisType */: - case 99 /* ThisKeyword */: + case 178 /* ThisType */: + case 100 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return getTypeFromTypeReference(node); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return booleanType; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return getTypeFromOptionalTypeNode(node); - case 171 /* UnionType */: + case 173 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 175 /* ParenthesizedType */: - case 170 /* RestType */: - case 285 /* JSDocNonNullableType */: - case 281 /* JSDocTypeExpression */: + case 177 /* ParenthesizedType */: + case 172 /* RestType */: + case 287 /* JSDocNonNullableType */: + case 283 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 287 /* JSDocFunctionType */: - case 291 /* JSDocSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 174 /* InferType */: + case 176 /* InferType */: return getTypeFromInferTypeNode(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode - case 71 /* Identifier */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 148 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -38591,7 +40296,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38605,10 +40310,10 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function wildcardMapper(type) { - return type.flags & 65536 /* TypeParameter */ ? wildcardType : type; + return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; } function cloneTypeParameter(typeParameter) { - var result = createType(65536 /* TypeParameter */); + var result = createType(262144 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -38654,7 +40359,7 @@ var ts; } function instantiateSymbol(symbol, mapper) { var links = getSymbolLinks(symbol); - if (links.type && !maybeTypeOfKind(links.type, 131072 /* Object */ | 15794176 /* Instantiable */)) { + if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { // If the type of the symbol is already resolved, and if that type could not possibly // be affected by instantiation, simply return the symbol itself. return symbol; @@ -38692,7 +40397,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +40407,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38734,8 +40439,8 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 146 /* QualifiedName */ || - node.parent.kind === 162 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + return !(node.kind === 148 /* QualifiedName */ || + node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks @@ -38743,26 +40448,36 @@ var ts; // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 216 /* Block */ ? "quit" : n === container_3; })) { + if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) { return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { - case 176 /* ThisType */: + case 178 /* ThisType */: return !!tp.isThisType; - case 71 /* Identifier */: + case 72 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return true; } return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +40487,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38812,13 +40531,19 @@ var ts; var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); var modifiers = getMappedTypeModifiers(type); return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38851,61 +40576,77 @@ var ts; if (root.isDistributive) { var checkType_1 = root.checkType; var instantiatedType = mapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & (262144 /* Union */ | 32768 /* Never */)) { + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return mapper(type); + } + if (flags & 524288 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } function getWildcardInstantiation(type) { - return type.flags & (32764 /* Primitive */ | 3 /* AnyOrUnknown */ | 32768 /* Never */) ? type : + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); } function instantiateIndexInfo(info, mapper) { @@ -38914,34 +40655,34 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 202 /* BinaryExpression */: - return node.operatorToken.kind === 54 /* BarBarToken */ && + case 204 /* BinaryExpression */: + return node.operatorToken.kind === 55 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 266 /* JsxAttributes */: - return ts.some(node.properties, isContextSensitive); - case 265 /* JsxAttribute */: { + case 268 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 268 /* JsxExpression */: { + case 270 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -38958,7 +40699,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 195 /* ArrowFunction */) { + if (node.kind !== 197 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -38971,14 +40712,14 @@ var ts; function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. var body = node.body; - return body.kind === 216 /* Block */ ? false : isContextSensitive(body); + return body.kind === 218 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); @@ -38989,7 +40730,7 @@ var ts; return result; } } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -39004,6 +40745,9 @@ var ts; function compareTypesAssignable(source, target) { return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } function isTypeSubtypeOf(source, target) { return isTypeRelatedTo(source, target, subtypeRelation); } @@ -39019,11 +40763,12 @@ var ts; // Note that this check ignores type parameters and only considers the // inheritance hierarchy. function isTypeDerivedFrom(source, target) { - return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : - target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : - source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39049,33 +40794,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { - case 268 /* JsxExpression */: - case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); - case 202 /* BinaryExpression */: + case 270 /* JsxExpression */: + case 195 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: - case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage); } break; - case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); - case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); - case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + case 188 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation); + case 187 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation); + case 268 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target, relation); + case 197 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40894,17 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */) + continue; // Don't elaborate on indexes on generic variables + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40913,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39112,16 +40924,19 @@ var ts; var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; var issuedElaboration = false; if (!targetProp) { - var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40970,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +41003,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39208,17 +41028,17 @@ var ts; prop = _a[_i]; if (ts.isSpreadAssignment(prop)) return [3 /*break*/, 7]; - type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), 2240 /* StringOrNumberLiteralOrUnique */); - if (!type || (type.flags & 32768 /* Never */)) { + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 131072 /* Never */)) { return [3 /*break*/, 7]; } _b = prop.kind; switch (_b) { - case 157 /* SetAccessor */: return [3 /*break*/, 2]; - case 156 /* GetAccessor */: return [3 /*break*/, 2]; - case 154 /* MethodDeclaration */: return [3 /*break*/, 2]; - case 274 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 273 /* PropertyAssignment */: return [3 /*break*/, 4]; + case 159 /* SetAccessor */: return [3 /*break*/, 2]; + case 158 /* GetAccessor */: return [3 /*break*/, 2]; + case 156 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 275 /* PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -39239,8 +41059,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,14 +41090,15 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 154 /* MethodDeclaration */ && - kind !== 153 /* MethodSignature */ && kind !== 155 /* Constructor */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ && + kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -39295,11 +41116,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39311,7 +41132,7 @@ var ts; var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && - (getFalsyFlags(sourceType) & 24576 /* Nullable */) === (getFalsyFlags(targetType) & 24576 /* Nullable */); + (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); var related = callbacks ? // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : @@ -39325,13 +41146,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39403,12 +41224,15 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 131072 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 /* NonPrimitive */ ? true : - type.flags & 262144 /* Union */ ? ts.some(type.types, isEmptyObjectType) : - type.flags & 524288 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : + return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 /* NonPrimitive */ ? true : + type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : false; } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type); + } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { if (sourceSymbol === targetSymbol) { return true; @@ -39445,43 +41269,45 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 3 /* AnyOrUnknown */ || s & 32768 /* Never */ || source === wildcardType) + if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType) return true; - if (t & 32768 /* Never */) + if (t & 131072 /* Never */) return false; - if (s & 68 /* StringLike */ && t & 4 /* String */) + if (s & 132 /* StringLike */ && t & 4 /* String */) return true; - if (s & 64 /* StringLiteral */ && s & 512 /* EnumLiteral */ && - t & 64 /* StringLiteral */ && !(t & 512 /* EnumLiteral */) && + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && + t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 168 /* NumberLike */ && t & 8 /* Number */) + if (s & 296 /* NumberLike */ && t & 8 /* Number */) return true; - if (s & 128 /* NumberLiteral */ && s & 512 /* EnumLiteral */ && - t & 128 /* NumberLiteral */ && !(t & 512 /* EnumLiteral */) && + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && + t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 272 /* BooleanLike */ && t & 16 /* Boolean */) + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) return true; - if (s & 3072 /* ESSymbolLike */ && t & 1024 /* ESSymbol */) + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) + return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) return true; if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 512 /* EnumLiteral */ && t & 512 /* EnumLiteral */) { - if (s & 262144 /* Union */ && t & 262144 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 448 /* Literal */ && t & 448 /* Literal */ && + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 8192 /* Undefined */ && (!strictNullChecks || t & (8192 /* Undefined */ | 4096 /* Void */))) + if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */))) return true; - if (s & 16384 /* Null */ && (!strictNullChecks || t & 16384 /* Null */)) + if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */)) return true; - if (s & 131072 /* Object */ && t & 16777216 /* NonPrimitive */) + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) return true; - if (s & 2048 /* UniqueESSymbol */ || t & 2048 /* UniqueESSymbol */) + if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) @@ -39489,30 +41315,30 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (8 /* Number */ | 128 /* NumberLiteral */) && !(s & 512 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 128 /* NumberLiteral */ && t & 512 /* EnumLiteral */)) + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; } return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(target)) { target = target.regularType; } if (source === target || - relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */) { + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */) { + if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) { return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); } return false; @@ -39532,6 +41358,7 @@ var ts; */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -39539,7 +41366,7 @@ var ts; var depth = 0; var expandingFlags = 0 /* None */; var overflow = false; - var isIntersectionConstituent = false; + var suppressNextError = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (overflow) { @@ -39566,15 +41393,27 @@ var ts; } } var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } if (errorOutputContainer) { errorOutputContainer.error = diag; } diagnostics.add(diag); // TODO: GH#18217 } return result !== 0 /* False */; - function reportError(message, arg0, arg1, arg2) { + function reportError(message, arg0, arg1, arg2, arg3) { ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } } function reportRelationError(message, source, target) { var sourceType = typeToString(source); @@ -39607,7 +41446,7 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 786432 /* UnionOrIntersection */)) { + if (!(type.flags & 3145728 /* UnionOrIntersection */)) { return false; } // at this point we know that this is union or intersection type possibly with nullable constituents. @@ -39615,7 +41454,7 @@ var ts; var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 24576 /* Nullable */) { + if (t.flags & 98304 /* Nullable */) { continue; } if (seenNonNullable) { @@ -39631,24 +41470,24 @@ var ts; * * Ternary.Maybe if they are related with assumptions of other relationships, or * * Ternary.False if they are not related. */ - function isRelatedTo(source, target, reportErrors, headMessage) { + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(target)) { target = target.regularType; } - if (source.flags & 8388608 /* Substitution */) { + if (source.flags & 33554432 /* Substitution */) { source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } - if (target.flags & 8388608 /* Substitution */) { + if (target.flags & 33554432 /* Substitution */) { target = target.typeVariable; } - if (source.flags & 2097152 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { source = getSimplifiedType(source); } - if (target.flags & 2097152 /* IndexedAccess */) { + if (target.flags & 8388608 /* IndexedAccess */) { target = getSimplifiedType(target); } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. @@ -39660,10 +41499,10 @@ var ts; // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" // when dealing with generics. // * We also don't deal with primitive source types, since we already halt elaboration below. - if (target.flags & 262144 /* Union */ && source.flags & 131072 /* Object */ && - target.types.length <= 3 && maybeTypeOfKind(target, 24576 /* Nullable */)) { - var nullStrippedTarget = extractTypesOfKind(target, ~24576 /* Nullable */); - if (!(nullStrippedTarget.flags & (262144 /* Union */ | 32768 /* Never */))) { + if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); + if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { target = nullStrippedTarget; } } @@ -39673,11 +41512,12 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (isObjectLiteralType(source) && source.flags & 33554432 /* FreshLiteral */) { - var discriminantType = target.flags & 262144 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) { + var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -39692,14 +41532,11 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && - !hasCommonProperties(source, target)) { + !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); var constructs = getSignaturesOfType(source, 1 /* Construct */); @@ -39715,25 +41552,24 @@ var ts; } var result = 0 /* False */; var saveErrorInfo = errorInfo; - var saveIsIntersectionConstituent = isIntersectionConstituent; - isIntersectionConstituent = false; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); } else { - if (target.flags & 262144 /* Union */) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */) && !(target.flags & 32764 /* Primitive */)); + if (target.flags & 1048576 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); } - else if (target.flags & 524288 /* Intersection */) { - isIntersectionConstituent = true; + else if (target.flags & 2097152 /* Intersection */) { + isIntersectionConstituent = true; // set here to affect the following trio of checks result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 524288 /* Intersection */) { + else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -39749,13 +41585,13 @@ var ts; // breaking the intersection apart. result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } - if (!result && (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - if (!result && source.flags & 524288 /* Intersection */) { + if (!result && source.flags & 2097152 /* Intersection */) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -39765,22 +41601,23 @@ var ts; // we need to check this constraint against a union on the target side. Also, given a type // variable V constrained to 'string | number', 'V & number' has a combined constraint of // 'string & number | number & number' which reduces to just 'number'. - var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 262144 /* Union */)); + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */)); if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 131072 /* Object */ && target.flags & 32764 /* Primitive */) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 131072 /* Object */ && globalObjectType === source) { + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } - else if (ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && target.flags & 524288 /* Intersection */) { + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { var targetTypes = target.types; var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); @@ -39790,6 +41627,10 @@ var ts; return result; } } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } reportRelationError(headMessage, source, target); } return result; @@ -39797,49 +41638,23 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); + if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); } - if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { + if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { @@ -39849,17 +41664,18 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. if (!errorNode) return { value: ts.Debug.fail() }; - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { @@ -39888,13 +41704,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39910,7 +41729,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 262144 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -39923,16 +41742,17 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; } function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { var sourceObjectFlags = ts.getObjectFlags(source); - if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 262144 /* Union */) { + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { return ts.find(unionTarget.types, function (target) { - if (target.flags & 131072 /* Object */) { + if (target.flags & 524288 /* Object */) { var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); if (overlapObjFlags & 4 /* Reference */) { return source.target === target.target; @@ -39950,39 +41770,33 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); - if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } + if (target.flags & 1048576 /* Union */) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; var targetTypes = target.types; for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); + var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); if (!related) { return 0 /* False */; } @@ -39992,7 +41806,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 262144 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -40017,9 +41831,10 @@ var ts; } return result; } - function typeArgumentsRelatedTo(source, target, variances, reportErrors) { - var sources = source.typeArguments || ts.emptyArray; - var targets = target.typeArguments || ts.emptyArray; + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } @@ -40073,7 +41888,7 @@ var ts; // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function recursiveTypeRelatedTo(source, target, reportErrors) { + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { if (overflow) { return 0 /* False */; } @@ -40116,7 +41931,7 @@ var ts; expandingFlags |= 1 /* Source */; if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) expandingFlags |= 2 /* Target */; - var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -40139,13 +41954,57 @@ var ts; function getConstraintForRelation(type) { return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } - function structuredTypeRelatedTo(source, target, reportErrors) { + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288 /* Object */)) { + if (flags & 4194304 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 8388608 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 16777216 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 65536 /* TypeParameter */) { - // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144 /* TypeParameter */) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -40155,9 +42014,9 @@ var ts; } } } - else if (target.flags & 1048576 /* Index */) { + else if (target.flags & 4194304 /* Index */) { // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 1048576 /* Index */) { + if (source.flags & 4194304 /* Index */) { if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } @@ -40168,20 +42027,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } - else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (target.flags & 8388608 /* IndexedAccess */) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40190,23 +42054,24 @@ var ts; var template = getTemplateTypeFromMappedType(target); var modifiers = getMappedTypeModifiers(target); if (!(modifiers & 8 /* ExcludeOptional */)) { - if (template.flags & 2097152 /* IndexedAccess */ && template.objectType === source && + if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source && template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } } - if (source.flags & 2162688 /* TypeVariable */) { - if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + if (source.flags & 8650752 /* TypeVariable */) { + if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { // A type S[K] is related to a type T[J] if S is related to T and K is related to J. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { result &= isRelatedTo(source.indexType, target.indexType, reportErrors); @@ -40217,29 +42082,32 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 65536 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~16777216 /* NonPrimitive */))) { + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { errorInfo = saveErrorInfo; return result; } } - else { - var instantiated = getTypeWithThisArgument(constraint, source); - if (result = isRelatedTo(instantiated, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; } } - else if (source.flags & 1048576 /* Index */) { + else if (source.flags & 4194304 /* Index */) { if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { errorInfo = saveErrorInfo; return result; } } - else if (source.flags & 4194304 /* Conditional */) { - if (target.flags & 4194304 /* Conditional */) { + else if (source.flags & 16777216 /* Conditional */) { + if (target.flags & 16777216 /* Conditional */) { // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, // and Y1 is related to Y2. @@ -40272,13 +42140,33 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); - if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { return result; } // The type arguments did not relate appropriately, but it may be because we have no variance @@ -40305,36 +42193,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +42235,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40373,7 +42251,24 @@ var ts; var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } } return 0 /* False */; } @@ -40420,8 +42315,8 @@ var ts; } } var properties = getPropertiesOfObjectType(target); - for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { - var targetProp = properties_3[_b]; + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { @@ -40491,35 +42386,8 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { + if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -40549,8 +42417,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40647,7 +42515,7 @@ var ts; continue; } // Skip over symbol-named members - if (prop.nameType && prop.nameType.flags & 2048 /* UniqueESSymbol */) { + if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) { continue; } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { @@ -40742,6 +42610,51 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -40749,62 +42662,71 @@ var ts; result.objectFlags |= 8192 /* MarkerType */; return result; } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } // Return an array containing the variance of each type parameter. The variance is effectively // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } function getVariances(type) { if (!strictFunctionTypes) { return ts.emptyArray; } - var typeParameters = type.typeParameters || ts.emptyArray; - var variances = type.variances; - if (!variances) { - if (type === globalArrayType || type === globalReadonlyArrayType) { - // Arrays are known to be covariant, no need to spend time computing this - variances = [1 /* Covariant */]; - } - else { - // The emptyArray singleton is used to signal a recursive invocation. - type.variances = ts.emptyArray; - variances = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - // We first compare instantiations where the type parameter is replaced with - // marker types that have a known subtype relationship. From this we can infer - // invariance, covariance, contravariance or bivariance. - var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); - var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); - var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | - (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); - // If the instantiations appear to be related bivariantly it may be because the - // type parameter is independent (i.e. it isn't witnessed anywhere in the generic - // type). To determine this we compare instantiations where the type parameter is - // replaced with marker types that are known to be unrelated. - if (variance === 3 /* Bivariant */ && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { - variance = 4 /* Independent */; - } - variances.push(variance); - } - } - type.variances = variances; + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return ts.emptyArray; } - return variances; + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } // Return true if the given type reference has a 'void' type argument for a covariant type parameter. // See comment at call in recursiveTypeRelatedTo for when this case matters. function hasCovariantVoidArgument(type, variances) { for (var i = 0; i < variances.length; i++) { - if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 4096 /* Void */) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { return true; } } return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -40897,13 +42819,13 @@ var ts; // levels, but unequal at some level beyond that. function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 131072 /* Object */) { + if (depth >= 5 && type.flags & 524288 /* Object */) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 131072 /* Object */ && t.symbol === symbol) { + if (t.flags & 524288 /* Object */ && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -40958,12 +42880,8 @@ var ts; return true; } // A source signature partially matches a target signature if the target signature has no fewer required - // parameters and no more overall parameters than the source signature (where a signature with a rest - // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = sourceHasRestParameter ? 1 : 0; - var targetRestCount = targetHasRestParameter ? 1 : 0; - if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) { + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { return true; } return false; @@ -41009,7 +42927,7 @@ var ts; for (var i = 0; i < targetLen; i++) { var s = getTypeAtPosition(source, i); var t = getTypeAtPosition(target, i); - var related = compareTypes(s, t); + var related = compareTypes(t, s); if (!related) { return 0 /* False */; } @@ -41030,8 +42948,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41054,9 +42972,9 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 24576 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 24576 /* Nullable */) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) : getUnionType(types, 2 /* Subtype */); } // Return the leftmost type for which no type to the right is a subtype. @@ -41069,11 +42987,14 @@ var ts; function isReadonlyArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 24576 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isEmptyArrayLiteralType(type) { var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; @@ -41083,40 +43004,47 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { - return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); + return !(type.flags & (109440 /* Unit */ | 131072 /* Never */)); } function isUnitType(type) { - return !!(type.flags & 27072 /* Unit */); + return !!(type.flags & 109440 /* Unit */); } function isLiteralType(type) { return type.flags & 16 /* Boolean */ ? true : - type.flags & 262144 /* Union */ ? type.flags & 512 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : + type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 /* StringLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : - type; + return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 512 /* BooleanLiteral */ ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : - type; + return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : + type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : + type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; } function getWidenedUniqueESSymbolType(type) { - return type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : type; } function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { @@ -41135,13 +43063,21 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41150,15 +43086,16 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : - type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : - type.flags & 29148 /* PossiblyFalsy */; + return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 : + type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 : + type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 : + type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 : + type.flags & 117724 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 29120 /* DefinitelyFalsy */); }) : + return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) : type; } function extractDefinitelyFalsyTypes(type) { @@ -41167,10 +43104,13 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : - type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + type.flags & 64 /* BigInt */ ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) || + type.flags & 128 /* StringLiteral */ && type.value === "" || + type.flags & 256 /* NumberLiteral */ && type.value === 0 || + type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : neverType; } /** @@ -41179,15 +43119,15 @@ var ts; * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both */ function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (8192 /* Undefined */ | 16384 /* Null */); + var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */); return missing === 0 ? type : - missing === 8192 /* Undefined */ ? getUnionType([type, undefinedType]) : - missing === 16384 /* Null */ ? getUnionType([type, nullType]) : + missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 65536 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } function getOptionalType(type) { ts.Debug.assert(strictNullChecks); - return type.flags & 8192 /* Undefined */ ? type : getUnionType([type, undefinedType]); + return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { if (!deferredGlobalNonNullableTypeAlias) { @@ -41197,7 +43137,7 @@ var ts; if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); } - return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -41240,7 +43180,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && type.flags & 33554432 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -41250,7 +43190,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; + regularNew.flags = resolved.flags; regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); type.regularType = regularNew; return regularNew; @@ -41338,15 +43278,15 @@ var ts; } function getWidenedTypeWithContext(type, context) { if (type.flags & 402653184 /* RequiresWidening */) { - if (type.flags & 24576 /* Nullable */) { + if (type.flags & 98304 /* Nullable */) { return anyType; } if (isObjectLiteralType(type)) { return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); - var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 24576 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). @@ -41372,7 +43312,7 @@ var ts; function reportWideningErrorsInType(type) { var errorReported = false; if (type.flags & 134217728 /* ContainsWideningType */) { - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } @@ -41408,68 +43348,90 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { - case 202 /* BinaryExpression */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + case 204 /* BinaryExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 149 /* Parameter */: + case 151 /* Parameter */: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - if (!declaration.name) { + case 289 /* JSDocFunctionType */: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; break; - case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + case 181 /* MappedType */: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41518,11 +43480,11 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - return !!(type.flags & 15794176 /* Instantiable */ || + return !!(type.flags & 63176704 /* Instantiable */ || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || - type.flags & 786432 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -41531,13 +43493,13 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || !!(type.flags & 786432 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { - if (!(t.flags & 64 /* StringLiteral */)) { + if (!(t.flags & 128 /* StringLiteral */)) { return; } var name = ts.escapeLeadingUnderscores(t.value); @@ -41558,25 +43520,25 @@ var ts; * property is computed by inferring from the source property type to X for the type * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ - function inferTypeForHomomorphicMappedType(source, target) { - var key = source.id + "," + target.id; + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } reverseMappedCache.set(key, undefined); - var type = createReverseMappedType(source, target); + var type = createReverseMappedType(source, target, constraint); reverseMappedCache.set(key, type); return type; } - function createReverseMappedType(source, target) { + function createReverseMappedType(source, target, constraint) { var properties = getPropertiesOfType(source); if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { return undefined; } // If any property contains context sensitive functions that have been skipped, the source type // is incomplete and we can't infer a meaningful input type. - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var prop = properties_4[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { return undefined; } @@ -41584,13 +43546,13 @@ var ts; // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been // applied to the element type(s). if (isArrayType(source)) { - return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isReadonlyArrayType(source)) { - return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isTupleType(source)) { - var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); @@ -41600,30 +43562,46 @@ var ts; var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; + reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); } - function inferReverseMappedType(sourceType, target) { - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = target.flags & 524288 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; - if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (!sourceProp) { - return targetProp; - } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3 /*break*/, 3]; + return [4 /*yield*/, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; } - } - return undefined; + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -41645,7 +43623,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41671,8 +43651,8 @@ var ts; } return; } - if (source.flags & 262144 /* Union */ && target.flags & 262144 /* Union */ && !(source.flags & 512 /* EnumLiteral */ && target.flags & 512 /* EnumLiteral */) || - source.flags & 524288 /* Intersection */ && target.flags & 524288 /* Intersection */) { + if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) || + source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -41695,7 +43675,7 @@ var ts; (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } - else if (t.flags & (128 /* NumberLiteral */ | 64 /* StringLiteral */)) { + else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) { var b = getBaseTypeOfLiteralType(t); if (typeIdenticalToSomeType(b, target.types)) { (matchingTypes || (matchingTypes = [])).push(t, b); @@ -41710,7 +43690,7 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 2162688 /* TypeVariable */) { + if (target.flags & 8650752 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding @@ -41718,7 +43698,7 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType) { + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -41731,19 +43711,39 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } - if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 63176704 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments @@ -41760,12 +43760,12 @@ var ts; } } } - else if (source.flags & 1048576 /* Index */ && target.flags & 1048576 /* Index */) { + else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { contravariant = !contravariant; inferFromTypes(source.type, target.type); contravariant = !contravariant; } - else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 1048576 /* Index */) { + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; var savePriority = priority; @@ -41774,17 +43774,20 @@ var ts; priority = savePriority; contravariant = !contravariant; } - else if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (source.flags & 4194304 /* Conditional */ && target.flags & 4194304 /* Conditional */) { + else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } - else if (target.flags & 786432 /* UnionOrIntersection */) { + else if (target.flags & 16777216 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -41809,7 +43812,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 262144 /* Union */) { + else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -41818,10 +43821,25 @@ var ts; } } else { - if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } - if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -41831,7 +43849,7 @@ var ts; // an instantiation of the same generic type), we do not explore this target as it would yield // no further inferences. We exclude the static side of classes from this check since it shares // its symbol with the instance side which would lead to false positives. - var isNonConstructorObject = target.flags & 131072 /* Object */ && + var isNonConstructorObject = target.flags & 524288 /* Object */ && !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { @@ -41847,6 +43865,13 @@ var ts; } } } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { @@ -41859,7 +43884,7 @@ var ts; } } function getInferenceInfoForType(type) { - if (type.flags & 2162688 /* TypeVariable */) { + if (type.flags & 8650752 /* TypeVariable */) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -41869,6 +43894,44 @@ var ts; } return undefined; } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* HomomorphicMappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } function inferFromObjectTypes(source, target) { if (isGenericMappedType(source) && isGenericMappedType(target)) { // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer @@ -41878,31 +43941,7 @@ var ts; } if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 1048576 /* Index */) { - // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, - // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source - // type and then make a secondary inference from that type to T. We make a secondary inference - // such that direct inferences to T get priority over inferences to Partial, for example. - var inference = getInferenceInfoForType(constraintType.type); - if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - var savePriority = priority; - priority |= 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; - } - } - return; - } - if (constraintType.flags & 65536 /* TypeParameter */) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. - var savePriority = priority; - priority |= 4 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { return; } } @@ -41915,33 +43954,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +43995,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +44039,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42007,11 +44059,11 @@ var ts; reducedTypes.push(t); } } - return type.flags & 262144 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +44081,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +44094,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +44107,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +44136,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +44165,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42124,7 +44207,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 165 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 146 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the @@ -42133,20 +44216,20 @@ var ts; // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } - if (node.kind === 99 /* ThisKeyword */) { + if (node.kind === 100 /* ThisKeyword */) { return "0"; } - if (node.kind === 187 /* PropertyAccessExpression */) { + if (node.kind === 189 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); return key && key + "." + ts.idText(node.name); } - if (node.kind === 184 /* BindingElement */) { + if (node.kind === 186 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 184 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -42155,14 +44238,14 @@ var ts; } function getBindingElementNameText(element) { var parent = element.parent; - if (parent.kind === 182 /* ObjectBindingPattern */) { + if (parent.kind === 184 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.idText(name); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return name.text; default: @@ -42176,29 +44259,29 @@ var ts; } function isMatchingReference(source, target) { switch (source.kind) { - case 71 /* Identifier */: - return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 235 /* VariableDeclaration */ || target.kind === 184 /* BindingElement */) && + case 72 /* Identifier */: + return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99 /* ThisKeyword */: - return target.kind === 99 /* ThisKeyword */; - case 97 /* SuperKeyword */: - return target.kind === 97 /* SuperKeyword */; - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 100 /* ThisKeyword */: + return target.kind === 100 /* ThisKeyword */; + case 98 /* SuperKeyword */: + return target.kind === 98 /* SuperKeyword */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 184 /* BindingElement */: - if (target.kind !== 187 /* PropertyAccessExpression */) + case 186 /* BindingElement */: + if (target.kind !== 189 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 184 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 235 /* VariableDeclaration */) { + if (source.parent.parent.kind === 237 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; return !!maybeId && isMatchingReference(maybeId, t.expression); } @@ -42211,7 +44294,7 @@ var ts; undefined; } function containsMatchingReference(source, target) { - while (source.kind === 187 /* PropertyAccessExpression */) { + while (source.kind === 189 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -42224,32 +44307,52 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 187 /* PropertyAccessExpression */ && + return target.kind === 189 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71 /* Identifier */) { + if (expr.kind === 72 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 187 /* PropertyAccessExpression */) { + if (expr.kind === 189 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 262144 /* Union */) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; + function isDiscriminantType(type) { + if (type.flags & 1048576 /* Union */) { + if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { + return true; } } return false; } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576 /* Union */); + } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -42276,7 +44379,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -42289,16 +44392,35 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 32768 /* Never */) { + if (assignedType.flags & 131072 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +44428,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42322,55 +44444,66 @@ var ts; function getTypeFacts(type) { var flags = type.flags; if (flags & 4 /* String */) { - return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; } - if (flags & 64 /* StringLiteral */) { + if (flags & 128 /* StringLiteral */) { var isEmpty = type.value === ""; return strictNullChecks ? - isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : + isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; } if (flags & (8 /* Number */ | 32 /* Enum */)) { - return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; } - if (flags & 128 /* NumberLiteral */) { + if (flags & 256 /* NumberLiteral */) { var isZero = type.value === 0; return strictNullChecks ? - isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : - isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; + isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : + isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : + isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; } if (flags & 16 /* Boolean */) { - return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; } - if (flags & 272 /* BooleanLike */) { + if (flags & 528 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 524288 /* Object */) { + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ : + strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } - if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { - return 2457472 /* UndefinedFacts */; + if (flags & (16384 /* Void */ | 32768 /* Undefined */)) { + return 9830144 /* UndefinedFacts */; } - if (flags & 16384 /* Null */) { - return 2340752 /* NullFacts */; + if (flags & 65536 /* Null */) { + return 9363232 /* NullFacts */; } - if (flags & 3072 /* ESSymbolLike */) { - return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; } - if (flags & 16777216 /* NonPrimitive */) { - return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } - if (flags & 15794176 /* Instantiable */) { + if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 786432 /* UnionOrIntersection */) { + if (flags & 3145728 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } - return 4194303 /* All */; + return 16777215 /* All */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -42378,7 +44511,7 @@ var ts; function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); + return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); } return type; } @@ -42390,7 +44523,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42398,15 +44531,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 185 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 273 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 225 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -42423,21 +44556,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return stringType; - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return undefinedType; - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -42445,7 +44578,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 182 /* ObjectBindingPattern */ ? + var type = pattern.kind === 184 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -42463,39 +44596,39 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 224 /* ForInStatement */) { + if (node.parent.parent.kind === 226 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 225 /* ForOfStatement */) { + if (node.parent.parent.kind === 227 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 235 /* VariableDeclaration */ ? + return node.kind === 237 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { - return node.kind === 235 /* VariableDeclaration */ && node.initializer && + return node.kind === 237 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 184 /* BindingElement */ && node.parent.kind === 202 /* BinaryExpression */ && + node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return getReferenceCandidate(node.left); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return getReferenceCandidate(node.right); } } @@ -42503,13 +44636,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 193 /* ParenthesizedExpression */ || - parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + return parent.kind === 195 /* ParenthesizedExpression */ || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 269 /* CaseClause */) { + if (clause.kind === 271 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -42525,14 +44658,31 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271 /* CaseClause */) { + if (clause.expression.kind === 10 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { - return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 262144 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -42541,34 +44691,37 @@ var ts; } return true; } - if (source.flags & 512 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); + return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); } return f(type) ? type : neverType; } function mapType(type, mapper, noReductions) { - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { return type; } - if (!(type.flags & 262144 /* Union */)) { + if (!(type.flags & 1048576 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42591,12 +44744,14 @@ var ts; // typeWithPrimitives have been replaced with occurrences of string literals and numeric // literals in typeWithLiterals, respectively. function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* StringLiteral */) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* NumberLiteral */)) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) { return mapType(typeWithPrimitives, function (t) { - return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 64 /* StringLiteral */) : - t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 128 /* NumberLiteral */) : - t; + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : + t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : + t; }); } return typeWithPrimitives; @@ -42630,9 +44785,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 32768 /* Never */ ? + return elementType.flags & 131072 /* Never */ ? autoArrayType : - createArrayType(elementType.flags & 262144 /* Union */ ? + createArrayType(elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType); } @@ -42648,9 +44803,9 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - if (!(t.flags & 32768 /* Never */)) { + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; } @@ -42672,15 +44827,15 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 187 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || - parent.parent.kind === 189 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 188 /* ElementAccessExpression */ && + var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 202 /* BinaryExpression */ && - parent.parent.operatorToken.kind === 58 /* EqualsToken */ && + parent.parent.kind === 204 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 59 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 168 /* NumberLike */); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -42691,7 +44846,7 @@ var ts; return links.maybeTypePredicate; } function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97 /* SuperKeyword */) { + if (node.expression.kind !== 98 /* SuperKeyword */) { var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); @@ -42713,7 +44868,7 @@ var ts; if (flowAnalysisDisabled) { return errorType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 33492479 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) { return declaredType; } var sharedFlowStart = sharedFlowCount; @@ -42723,14 +44878,14 @@ var ts; // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. - var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent && reference.parent.kind === 211 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 32768 /* Never */) { + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { return declaredType; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42796,9 +44951,9 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.container; if (container && container !== flowContainer && - reference.kind !== 187 /* PropertyAccessExpression */ && - reference.kind !== 188 /* ElementAccessExpression */ && - reference.kind !== 99 /* ThisKeyword */) { + reference.kind !== 189 /* PropertyAccessExpression */ && + reference.kind !== 190 /* ElementAccessExpression */ && + reference.kind !== 100 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -42833,11 +44988,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + if (declaredType.flags & 1048576 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,15 +45001,27 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } + // for (const _ in ref) acts as a nonnull on ref + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } // Assignment doesn't affect reference return undefined; } function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 189 /* CallExpression */ ? + var expr = node.kind === 191 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -42862,15 +45029,16 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -42884,7 +45052,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { return flowType; } // If we have an antecedent type (meaning we're reachable in some way), we first @@ -42901,19 +45069,25 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 32768 /* Never */ ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43027,8 +45201,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 262144 /* Union */) || - expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + if (!(computedType.flags & 1048576 /* Union */) || + expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { return false; } var access = expr; @@ -43049,10 +45223,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); + return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } if (isMatchingReferenceDiscriminant(expr, declaredType)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } if (containsMatchingReferenceDiscriminant(reference, expr)) { return declaredType; @@ -43070,7 +45244,7 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if ((type.flags & (262144 /* Union */ | 131072 /* Object */)) || (type.flags & 65536 /* TypeParameter */ && type.isThisType)) { + if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); } @@ -43078,19 +45252,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -43109,15 +45283,15 @@ var ts; return declaredType; } break; - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 92 /* InKeyword */: + case 93 /* InKeyword */: var target = getReferenceCandidate(expr.right); if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; - case 26 /* CommaToken */: + case 27 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } return type; @@ -43126,28 +45300,28 @@ var ts; if (type.flags & 1 /* Any */) { return type; } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 24576 /* Nullable */) { + if (valueType.flags & 98304 /* Nullable */) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; + var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */; var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - valueType.flags & 16384 /* Null */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : + valueType.flags & 65536 /* Null */ ? + assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : + assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 16909315 /* NotUnionOrUnit */) { + if (type.flags & 67637251 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 32768 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -43159,40 +45333,47 @@ var ts; // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { return declaredType; } return type; } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 15794176 /* Instantiable */) { + if (type.flags & 63176704 /* Instantiable */) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43203,27 +45384,115 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 32768 /* Never */ ? neverType : + var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 /* Any */ ? type : globalFunctionType; + case "object": + return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjusted clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { return declaredType; } return type; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43240,22 +45509,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43263,9 +45522,9 @@ var ts; } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 32768 /* Never */)) { + if (!(assignableType.flags & 131072 /* Never */)) { return assignableType; } } @@ -43305,7 +45564,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 188 /* ElementAccessExpression */ || invokedExpression.kind === 187 /* PropertyAccessExpression */) { + if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -43322,20 +45581,20 @@ var ts; // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 200 /* PrefixUnaryExpression */: - if (expr.operator === 51 /* ExclamationToken */) { + case 202 /* PrefixUnaryExpression */: + if (expr.operator === 52 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -43349,7 +45608,7 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 71 /* Identifier */) { + if (location.kind === 72 /* Identifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } @@ -43370,17 +45629,17 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 243 /* ModuleBlock */ || - node.kind === 277 /* SourceFile */ || - node.kind === 152 /* PropertyDeclaration */; + node.kind === 245 /* ModuleBlock */ || + node.kind === 279 /* SourceFile */ || + node.kind === 154 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43388,13 +45647,13 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 149 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) { symbol.isAssigned = true; } } @@ -43409,21 +45668,21 @@ var ts; /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 149 /* Parameter */ && + declaration.kind === 151 /* Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 8192 /* Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 8192 /* Undefined */); - return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 187 /* PropertyAccessExpression */ || - parent.kind === 189 /* CallExpression */ && parent.expression === node || - parent.kind === 188 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 184 /* BindingElement */ && parent.name === node && !!parent.initializer; + return parent.kind === 189 /* PropertyAccessExpression */ || + parent.kind === 191 /* CallExpression */ && parent.expression === node || + parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { - return type.flags & 14745600 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 24576 /* Nullable */); + return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */); } function getConstraintForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, @@ -43436,7 +45695,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43454,7 +45713,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 195 /* ArrowFunction */) { + if (container.kind === 197 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { @@ -43475,28 +45734,28 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 238 /* ClassDeclaration */ + if (declaration.kind === 240 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); } } - else if (declaration.kind === 207 /* ClassExpression */) { + else if (declaration.kind === 209 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 277 /* SourceFile */) { + while (container.kind !== 279 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43509,12 +45768,17 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } return errorType; } } @@ -43538,7 +45802,7 @@ var ts; // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 149 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -43547,8 +45811,8 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 194 /* FunctionExpression */ || - flowContainer.kind === 195 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ || + flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -43557,9 +45821,9 @@ var ts; // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || - isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || - node.parent.kind === 211 /* NonNullExpression */ || - declaration.kind === 235 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) || + node.parent.kind === 213 /* NonNullExpression */ || + declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 4194304 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -43568,7 +45832,7 @@ var ts; // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (type === autoType || type === autoArrayType) { + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); @@ -43577,7 +45841,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -43587,10 +45851,13 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 272 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -43611,26 +45878,46 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + 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 === 223 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && + if (container.kind === 225 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 193 /* ParenthesizedExpression */) { + while (current.parent.kind === 195 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -43638,9 +45925,9 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 200 /* PrefixUnaryExpression */ || current.parent.kind === 201 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) { var expr = current.parent; - isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; + isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */; } if (!isAssigned) { return false; @@ -43651,7 +45938,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 152 /* PropertyDeclaration */ || container.kind === 155 /* Constructor */) { + if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -43719,37 +46006,37 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 155 /* Constructor */) { + if (container.kind === 157 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 195 /* ArrowFunction */) { + if (container.kind === 197 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } switch (container.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* 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 241 /* EnumDeclaration */: + case 243 /* 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 155 /* Constructor */: + case 157 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: if (ts.hasModifier(container, 32 /* Static */)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -43760,39 +46047,43 @@ var ts; var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ? + var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } } return type || anyType; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,16 +46098,68 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 196 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 156 /* MethodDeclaration */ && + container.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 196 /* FunctionExpression */ && + container.parent.kind === 275 /* PropertyAssignment */ && + container.parent.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === 196 /* FunctionExpression */ && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -43830,15 +46173,15 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 149 /* Parameter */; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 189 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 195 /* ArrowFunction */) { + while (container && container.kind === 197 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -43851,14 +46194,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 147 /* ComputedPropertyName */; }); - if (current && current.kind === 147 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; }); + if (current && current.kind === 149 /* 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 === 186 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -43866,7 +46209,7 @@ var ts; } return errorType; } - if (!isCallExpression && container.kind === 155 /* Constructor */) { + if (!isCallExpression && container.kind === 157 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { @@ -43898,16 +46241,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // 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: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43919,20 +46264,21 @@ var ts; // // 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); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = 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 === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. + if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -43946,7 +46292,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 186 /* ObjectLiteralExpression */) { + if (container.parent.kind === 188 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -43967,7 +46313,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 155 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 157 /* 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 errorType; @@ -43982,7 +46328,7 @@ 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 === 155 /* Constructor */; + return container.kind === 157 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -43990,21 +46336,21 @@ var 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\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) { if (ts.hasModifier(container, 32 /* Static */)) { - return container.kind === 154 /* MethodDeclaration */ || - container.kind === 153 /* MethodSignature */ || - container.kind === 156 /* GetAccessor */ || - container.kind === 157 /* SetAccessor */; + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */; } else { - return container.kind === 154 /* MethodDeclaration */ || - container.kind === 153 /* MethodSignature */ || - container.kind === 156 /* GetAccessor */ || - container.kind === 157 /* SetAccessor */ || - container.kind === 152 /* PropertyDeclaration */ || - container.kind === 151 /* PropertySignature */ || - container.kind === 155 /* Constructor */; + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */ || + container.kind === 154 /* PropertyDeclaration */ || + container.kind === 153 /* PropertySignature */ || + container.kind === 157 /* Constructor */; } } } @@ -44012,10 +46358,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 154 /* MethodDeclaration */ || - func.kind === 156 /* GetAccessor */ || - func.kind === 157 /* SetAccessor */) && func.parent.kind === 186 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 194 /* FunctionExpression */ && func.parent.kind === 273 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 156 /* MethodDeclaration */ || + func.kind === 158 /* GetAccessor */ || + func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -44023,11 +46369,11 @@ var ts; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 524288 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 195 /* ArrowFunction */) { + if (func.kind === 197 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -44039,7 +46385,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44054,7 +46400,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 273 /* PropertyAssignment */) { + if (literal.parent.kind !== 275 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -44068,9 +46414,9 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = func.parent; - if (parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) { var target = parent.left; - if (target.kind === 187 /* PropertyAccessExpression */ || target.kind === 188 /* ElementAccessExpression */) { + if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) { var expression = target.expression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { @@ -44096,7 +46442,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44130,7 +46476,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 149 /* Parameter */) { + if (declaration.kind === 151 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -44142,7 +46488,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 184 /* BindingElement */) { + if (parentDeclaration.kind !== 186 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -44163,9 +46509,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44212,7 +46570,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44220,10 +46578,13 @@ var ts; // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 191 /* TaggedTemplateExpression */) { + if (template.parent.kind === 193 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -44232,26 +46593,33 @@ var ts; var binaryExpression = node.parent; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { - case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; - case 54 /* BarBarToken */: + case 59 /* EqualsToken */: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; - case 53 /* AmpersandAmpersandToken */: - case 26 /* CommaToken */: + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; default: return undefined; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,26 +46637,57 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return ts.Debug.fail("Does not apply"); default: return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - if (t.flags & 917504 /* StructuredType */) { + if (t.flags & 3670016 /* StructuredType */) { var prop = getPropertyOfType(t, name); if (prop) { return getTypeOfSymbol(prop); @@ -44299,6 +46698,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +46707,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44329,8 +46726,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44346,7 +46743,6 @@ var ts; // type of T. function getContextualTypeForElementExpression(arrayContextualType, index) { return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) - || getIndexTypeOfContextualType(arrayContextualType, 1 /* Number */) || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); } // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. @@ -44388,54 +46784,44 @@ var ts; // recursive (and possibly infinite) invocations of getContextualType. function isPossiblyDiscriminantValue(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 71 /* Identifier */: + case 9 /* BigIntLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 72 /* Identifier */: + case 141 /* UndefinedKeyword */: return true; - case 187 /* PropertyAccessExpression */: - case 193 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 195 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 270 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44464,52 +46850,54 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 186 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 195 /* ArrowFunction */: - case 228 /* ReturnStatement */: + case 197 /* ArrowFunction */: + case 230 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 201 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); + case 191 /* CallExpression */: + case 192 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 185 /* ArrayLiteralExpression */: { + case 187 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 214 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 204 /* TemplateExpression */); + case 216 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 193 /* ParenthesizedExpression */: { + case 195 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent); } return undefined; @@ -44519,67 +46907,16 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; } - var valueType = checkExpression(node.tagName); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); + return getContextualTypeForArgumentAtIndex(node, 0); } - function getJsxSignaturesParameterTypes(valueType, isJs, context) { - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (valueType.flags & 4 /* String */) { - return anyType; - } - else if (valueType.flags & 64 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = valueType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - } - return anyType; - } - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(valueType, 1 /* Construct */); - var ctor = true; - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, 0 /* Call */); - ctor = false; - if (signatures.length === 0) { - // We found no signatures at all, which is an error - return errorType; - } - } - var links = getNodeLinks(context); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(valueType); - var cachedResolved = links.resolvedSignatures.get(cacheKey); - if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { - signatures = cachedResolved; - } - else if (!cachedResolved) { - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); - } - return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); @@ -44594,22 +46931,40 @@ var ts; var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } return attributesType; } - function getJsxPropsTypeFromClassType(sig, isJs, context, reportErrors) { + function getJsxPropsTypeFromClassType(sig, context) { var ns = getJsxNamespaceAt(context); var forcedLookupLocation = getJsxElementPropertiesName(ns); var attributesType = forcedLookupLocation === undefined @@ -44622,7 +46977,7 @@ var ts; : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); if (!attributesType) { // There is no property named 'props' on this instance type - if (reportErrors && !!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); } return emptyObjectType; @@ -44640,7 +46995,7 @@ var ts; var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); var hostClassType = getReturnTypeOfSignature(sig); apparentAttributesType = intersectTypes(typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) : intrinsicClassAttribs, apparentAttributesType); } var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); @@ -44676,7 +47031,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 194 /* FunctionExpression */ || node.kind === 195 /* ArrowFunction */; + return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -44695,7 +47050,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -44704,13 +47059,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 262144 /* Union */)) { + if (!(type.flags & 1048576 /* Union */)) { return getContextualCallSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44743,10 +47098,10 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 184 /* BindingElement */ && !!node.initializer) || - (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + return (node.kind === 186 /* BindingElement */ && !!node.initializer) || + (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44755,7 +47110,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elementCount; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 206 /* SpreadElement */) { + if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -44768,7 +47123,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,47 +47132,59 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } - if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { + if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) { hasNonEndingSpreadElement = true; } } if (!hasNonEndingSpreadElement) { - var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206 /* SpreadElement */; + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - 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 (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + 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 (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) { + if (e.kind !== 210 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44826,12 +47193,12 @@ var ts; } function isNumericName(name) { switch (name.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return isNumericComputedName(name); - case 71 /* Identifier */: + case 72 /* Identifier */: return isNumericLiteralName(name.escapedText); case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return isNumericLiteralName(name.text); default: return false; @@ -44840,7 +47207,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAssignableToKind(checkComputedPropertyName(name), 168 /* NumberLike */); + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -44875,8 +47242,8 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (links.resolvedType.flags & 24576 /* Nullable */ || - !isTypeAssignableToKind(links.resolvedType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */) && + if (links.resolvedType.flags & 98304 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -44896,6 +47263,17 @@ var ts; var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + } function checkObjectLiteral(node, checkMode) { var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking @@ -44903,13 +47281,13 @@ var ts; var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 33554432 /* FreshLiteral */; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44919,15 +47297,15 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 147 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 273 /* PropertyAssignment */ || - memberDecl.kind === 274 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 275 /* PropertyAssignment */ || + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : - memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -44938,7 +47316,7 @@ var ts; } } typeFlags |= type.flags; - var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? + var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : @@ -44949,8 +47327,8 @@ 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 === 273 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 274 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -44975,12 +47353,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 275 /* SpreadAssignment */) { + else if (memberDecl.kind === 277 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -44992,7 +47370,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); offset = i + 1; continue; } @@ -45002,10 +47380,10 @@ 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 === 156 /* GetAccessor */ || memberDecl.kind === 157 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (computedNameType && !(computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */)) { + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { if (isTypeAssignableTo(computedNameType, numberType)) { hasComputedNumberProperty = true; @@ -45039,7 +47417,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); } return spread; } @@ -45048,9 +47426,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; - result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); - result.objectFlags |= 128 /* ObjectLiteral */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; + result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -45060,20 +47437,17 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 24576 /* Nullable */)) { - propagatedFlags |= (result.flags & 939524096 /* PropagatingFlags */); - } + propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; return result; } } function isValidSpreadType(type) { - return !!(type.flags & (3 /* AnyOrUnknown */ | 16777216 /* NonPrimitive */) || - getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 131072 /* Object */ && !isGenericMappedType(type) || - type.flags & 786432 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); } function checkJsxSelfClosingElementDeferred(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node, 0 /* Normal */); + checkJsxOpeningLikeElementOrOpeningFragment(node); } function checkJsxSelfClosingElement(node, _checkMode) { checkNodeDeferred(node); @@ -45081,7 +47455,7 @@ var ts; } function checkJsxElementDeferred(node) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, 0 /* Normal */); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -45089,18 +47463,20 @@ var ts; else { checkExpression(node.closingElement.tagName); } + checkJsxChildren(node); } function checkJsxElement(node, _checkMode) { checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } - function checkJsxFragment(node, checkMode) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { error(node, compilerOptions.jsxFactory ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } + checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } /** @@ -45114,7 +47490,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) { - return tagName.kind === 71 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); + return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); } function checkJsxAttribute(node, checkMode) { return node.initializer @@ -45133,16 +47509,19 @@ var ts; function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); - var spread = emptyObjectType; + var spread = emptyJsxObjectType; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45157,9 +47536,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +47546,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,11 +47555,11 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 258 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -45191,32 +47570,35 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); } } if (hasSpreadAnyType) { return anyType; } - if (typeToIntersect && spread !== emptyObjectType) { + if (typeToIntersect && spread !== emptyJsxObjectType) { return getIntersectionType([typeToIntersect, spread]); } - return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable * @param attributesTable a symbol table of attributes property */ function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; - result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; return result; } } @@ -45226,7 +47608,7 @@ var ts; var child = _a[_i]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. - if (child.kind === 10 /* JsxText */) { + if (child.kind === 11 /* JsxText */) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); } @@ -45248,7 +47630,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45289,57 +47671,6 @@ var ts; } return links.resolvedSymbol; } - function instantiateJsxSignatures(node, signatures) { - var instantiatedSignatures = []; - var candidateForTypeArgumentError; - var hasTypeArgumentError = !!node.typeArguments; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); - if (typeArgumentInstantiated) { - hasTypeArgumentError = false; - instantiatedSignatures.push(typeArgumentInstantiated); - } - else { - if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - candidateForTypeArgumentError = signature; - } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - } - else { - instantiatedSignatures.push(signature); - } - } - if (node.typeArguments && hasTypeArgumentError) { - if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); - } - // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine - else if (node.typeArguments.length !== 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); - } - } - return instantiatedSignatures; - } - function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { - if (reportErrors === void 0) { reportErrors = false; } - if (!node.typeArguments) { - return; - } - if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - return; - } - var args = checkTypeArguments(signature, node.typeArguments, reportErrors); - if (!args) { - return; - } - return getSignatureInstantiation(signature, args, isJavascript); - } function getJsxNamespaceAt(location) { var links = location && getNodeLinks(location); if (links && links.jsxNamespace) { @@ -45373,7 +47704,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +47728,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45410,217 +47741,78 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - return undefined; + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; } - if (propsType.flags & 524288 /* Intersection */) { - var propsApparentType = []; - for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { - var t = _a[_i]; - propsApparentType.push(getApparentType(t)); + else if (elementType.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; } - return getIntersectionType(propsApparentType); - } - return getApparentType(propsType); - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return only attributes type of successfully resolved call signature. - * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) - * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); - if (callSignature !== unknownSignature) { - var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); - var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; } } - return undefined; - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return all attributes type of resolved call signature including candidate signatures. - * This function assumes that the caller handled other possible element type of the JSX element. - * This function is a behavior used by language service when looking up completion in JSX element. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - var candidate = candidatesOutArray_1[_i]; - var callReturnType = getReturnTypeOfSignature(candidate); - // TODO: GH#18217: callReturnType should always be defined... - var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - var shouldBeCandidate = true; - for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217 - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - // If we can't find any matching, just return everything. - if (!result) { - result = allMatchingAttributesType; - } - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { - var links = getNodeLinks(openingLikeElement); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(elementType); - if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { - return; - } - else if (links.resolvedSignatures.get(cacheKey)) { - return links.resolvedSignatures.get(cacheKey); - } - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + var apparentElemType = getApparentType(elementType); // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(elementType, 1 /* Construct */); + var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); if (signatures.length === 0) { // No construct signatures, try call signatures - signatures = getSignaturesOfType(elementType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - if (reportErrors) { - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - } + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0 /* Component */) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { // Mixed + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { return; } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - // Instantiate in context of source type - var results = instantiateJsxSignatures(openingLikeElement, signatures); - links.resolvedSignatures.set(cacheKey, results); - return results; - } - /** - * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. - * For instance: - * declare function Foo(attr: { p1: string}): JSX.Element; - * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" - * - * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. - * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component - * - * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement - * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature - * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present - * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) - * @return attributes type if able to resolve the type of node - * anyType if there is no type ElementAttributesProperty or there is an error - * emptyObjectType if there is no "prop" in the element instance type - */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType.flags & 262144 /* Union */) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), 2 /* Subtype */); - } - // Shortcircuit any - if (isTypeAny(elementType)) { - return elementType; - } - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - else if (elementType.flags & 4 /* String */) { - return anyType; - } - else if (elementType.flags & 64 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - // If we need to report an error, we already done so here. So just return any to prevent any more error downstream - return anyType; - } - // Get the element instance type (the result of newing or invoking this tag) - var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); - if (!ts.length(instantiatedSignatures)) { - return errorType; - } - var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */); - // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. - // Otherwise get only attributes type from the signature picked by choose-overload logic. - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -45644,53 +47836,6 @@ var ts; } return links.resolvedJsxElementAttributesType; } - /** - * Get attributes type of the given custom opening-like JSX element. - * This function is intended to be called from a caller that handles intrinsic JSX element already. - * @param node a custom JSX opening-like element - * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component - */ - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); - } - /** - * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. - * This function is called by language service (see: completions-tryGetGlobalSymbols). - * @param node a JSX opening-like element to get attributes type for - */ - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - // Because in language service, the given JSX opening-like element may be incomplete and therefore, - // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); - } - } - /** - * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. - * @param node a JSXOpeningLikeElement node - * @return an attributes type of the given node - */ - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); - } - } - /** - * Given a JSX attribute, returns the symbol for the corresponds property - * of the element attributes type. Will return unknownSymbol for attributes - * that have no matching element attributes type property. - */ - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.escapedText); - return prop || unknownSymbol; - } function getJsxElementClassTypeAt(location) { var type = getJsxType(JsxNames.ElementClass, location); if (type === errorType) @@ -45724,7 +47869,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -45735,7 +47880,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45746,10 +47891,8 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } /** @@ -45766,7 +47909,7 @@ var ts; * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType */ function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 131072 /* Object */) { + if (targetType.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -45776,7 +47919,7 @@ var ts; return true; } } - else if (targetType.flags & 786432 /* UnionOrIntersection */) { + else if (targetType.flags & 3145728 /* UnionOrIntersection */) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -45784,55 +47927,12 @@ var ts; } } } - else if (targetType.flags & 4194304 /* Conditional */) { + else if (targetType.flags & 16777216 /* Conditional */) { return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); } return false; } - /** - * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. - * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" - * Check assignablity between given attributes property, "source attributes", and the "target attributes" - * @param openingLikeElement an opening-like JSX element to check its JSXAttributes - */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { - // The function involves following steps: - // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. - // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) - // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. - // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); - // sourceAttributesType is a type of an attributes properties. - // i.e
- // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); - // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties - var isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); - // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { - var attribute = _a[_i]; - if (!ts.isJsxAttribute(attribute)) { - continue; - } - var attrName = attribute.name; - var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); - // We break here so that errors won't be cascading - break; - } - } - } - else if (!isSourceAttributeTypeAssignableToTarget) { - checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); - } - } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -45856,10 +47956,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45872,7 +47972,7 @@ var ts; */ function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name; + var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); @@ -45904,7 +48004,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -45944,13 +48044,13 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { return true; } - if (type.flags & 65536 /* TypeParameter */) { + if (type.flags & 262144 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } @@ -45970,19 +48070,26 @@ var ts; function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + return getNonNullableType(type); + } + return type; + } function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { if (type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 24576 /* Nullable */; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 8192 /* Undefined */ ? kind & 16384 /* Null */ ? + error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); - return t.flags & (24576 /* Nullable */ | 32768 /* Never */) ? errorType : t; + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } @@ -46015,7 +48122,7 @@ var ts; return anyType; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } return errorType; } @@ -46026,12 +48133,12 @@ var ts; } else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); + markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } } @@ -46040,9 +48147,9 @@ var ts; // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 187 /* PropertyAccessExpression */ || + if (node.kind !== 189 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 262144 /* Union */)) { + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } // If strict null checks and strict property initialization checks are enabled, if we have @@ -46050,17 +48157,23 @@ var ts; // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && left.kind === 99 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 155 /* Constructor */ && flowContainer.parent === declaration.parent) { + if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) { assumeUninitialized = true; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -46079,8 +48192,8 @@ var ts; && !isPropertyDeclaredInAncestorClass(prop)) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 238 /* ClassDeclaration */ && - node.parent.kind !== 162 /* TypeReference */ && + else if (valueDeclaration.kind === 240 /* ClassDeclaration */ && + node.parent.kind !== 164 /* TypeReference */ && !(valueDeclaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -46092,9 +48205,9 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return true; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: @@ -46132,7 +48245,7 @@ var ts; function reportNonexistentProperty(propNode, containingType) { var errorInfo; var relatedInfo; - if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { + if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -46172,7 +48285,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46224,7 +48337,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -46241,16 +48354,16 @@ var ts; } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: - return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 146 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 148 /* QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 181 /* ImportType */: + case 183 /* ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -46277,20 +48390,20 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * 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 === 236 /* VariableDeclarationList */) { + if (initializer.kind === 238 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 71 /* Identifier */) { + else if (initializer.kind === 72 /* Identifier */) { return getResolvedSymbol(initializer); } return undefined; @@ -46307,13 +48420,13 @@ var ts; */ function isForInVariableForNumericPropertyNames(expr) { var e = ts.skipParentheses(expr); - if (e.kind === 71 /* Identifier */) { + if (e.kind === 72 /* Identifier */) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3 /* Variable */) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 224 /* ForInStatement */ && + if (node.kind === 226 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -46331,7 +48444,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 190 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 192 /* 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); @@ -46343,15 +48456,15 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) { error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46362,7 +48475,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 3072 /* ESSymbolLike */) === 0) { + if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -46389,8 +48502,7 @@ var ts; return true; } function callLikeExpressionMayHaveTypeArguments(node) { - // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) - return ts.isCallOrNewExpression(node); + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); } function resolveUntypedCall(node) { if (callLikeExpressionMayHaveTypeArguments(node)) { @@ -46398,10 +48510,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 191 /* TaggedTemplateExpression */) { + if (node.kind === 193 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 150 /* Decorator */) { + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -46428,8 +48543,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -46465,25 +48580,23 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 206 /* SpreadElement */ || arg.kind === 213 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call + var argCount; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". - return true; - } - if (node.kind === 191 /* TaggedTemplateExpression */) { - // 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 + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193 /* TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 204 /* TemplateExpression */) { + if (node.template.kind === 206 /* 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 lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -46494,35 +48607,53 @@ var ts; // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. var templateLiteral = node.template; - ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */); + ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + else if (node.kind === 152 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 190 /* NewExpression */); + ts.Debug.assert(node.kind === 192 /* NewExpression */); return getMinArgumentCount(signature) === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. - if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { return false; } // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = argCount >= getMinArgumentCount(signature); - return callIsIncomplete || hasEnoughArguments; + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; } function hasCorrectTypeArgumentArity(signature, typeArguments) { // If the user supplied type arguments, but the number of type arguments does not match @@ -46534,7 +48665,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -46545,7 +48676,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,16 +48685,11 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, node, context) { - // Skip context sensitive pass - var skipContextParamType = getTypeAtPosition(signature, 0); - var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); - inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); - // Standard pass - var paramType = getTypeAtPosition(signature, 0); - var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } @@ -46579,11 +48705,14 @@ var ts; inference.inferredType = undefined; } } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (node.kind !== 150 /* Decorator */) { + if (node.kind !== 152 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -46612,71 +48741,50 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; 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 !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. - return arg.kind === 213 /* SyntheticExpression */ ? + return arg.kind === 215 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; - var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 32764 /* Primitive */ | 1048576 /* Index */); + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */); var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,27 +48793,40 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2 /* Mixed */; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. * @param node a JSX opening-like element we are trying to figure its call signature @@ -46713,37 +48834,20 @@ var ts; * @param relation a relationship to check parameter and argument type * @param excludeArgument */ - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: - // 1. callIsIncomplete - // 2. attributes property has same number of properties as the parameter object type. - // We can figure that out by resolving attributes property and check number of properties in the resolved type - // If the call has correct arity, we will then check if the argument type and parameter type is assignable - var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete - if (callIsIncomplete) { - return true; - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, // can be specified by users through attributes property. - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 190 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -46756,346 +48860,142 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; 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 !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); - if (callee.kind === 187 /* PropertyAccessExpression */ || callee.kind === 188 /* ElementAccessExpression */) { + if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) { return callee.expression; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { - if (node.kind === 191 /* TaggedTemplateExpression */) { + if (node.kind === 193 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 - if (template.kind === 204 /* TemplateExpression */) { + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 152 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* 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); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* 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. + var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 1; + case 154 /* PropertyDeclaration */: + return 2; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 151 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,15 +49004,19 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; var minCount = getMinArgumentCount(sig); var maxCount = getParameterCount(sig); if (minCount < argCount && minCount > belowArgCount) belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,22 +49027,31 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -47146,14 +49059,15 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { - var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 150 /* Decorator */; + var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 152 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; var typeArguments; if (!isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -47161,40 +49075,26 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47222,7 +49122,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -47246,32 +49146,33 @@ var ts; // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, // skip the checkApplicableSignature check. - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". - return candidateForArgumentError; + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); - } - else if (candidateForArgumentArityError) { - diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); - } - else if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); - } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +49192,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47364,7 +49285,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47375,7 +49296,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47414,17 +49335,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47443,7 +49374,7 @@ var ts; return maxParamsIndex; } function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { @@ -47477,11 +49408,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47493,16 +49424,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47515,8 +49453,8 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -47575,11 +49513,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47592,7 +49532,7 @@ var ts; return false; } var firstBase = baseTypes[0]; - if (firstBase.flags & 524288 /* Intersection */) { + if (firstBase.flags & 2097152 /* Intersection */) { var types = firstBase.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); var i = 0; @@ -47649,10 +49589,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47676,8 +49617,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47691,16 +49632,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 149 /* Parameter */: + case 151 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -47716,8 +49657,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47736,6 +49677,46 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node); + var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.type = result; + return createSignature(declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } /** * Sometimes, we have a decorator that could accept zero arguments, * but is receiving too many arguments as part of the decorator invocation. @@ -47745,52 +49726,22 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } - /** - * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. - * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName - * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) - * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. - * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function - * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); - if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); - } - return undefined; - } function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); - case 150 /* Decorator */: + case 152 /* Decorator */: return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: - // This code-path is called by language service - var exprTypes = checkExpression(node.tagName); - return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); - if (sfcResult && sfcResult !== unknownSignature) { - return sfcResult; - } - var sigs = getInstantiatedJsxSignatures(node, exprType); - if (candidatesOutArray && ts.length(sigs)) { - candidatesOutArray.push.apply(candidatesOutArray, sigs); - } - return ts.length(sigs) ? sigs[0] : unknownSignature; - }) || unknownSignature; + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -47824,34 +49775,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { - if (type.flags & 131072 /* Object */) { + function isJSConstructorType(type) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,22 +49819,19 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } var parent = node.parent; - while (parent && parent.kind === 187 /* PropertyAccessExpression */) { + while (parent && parent.kind === 189 /* PropertyAccessExpression */) { parent = parent.parent; } - if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) { var right = ts.getInitializerOfBinaryExpression(parent); return ts.isObjectLiteralExpression(right) && right; } @@ -47905,15 +49857,15 @@ var ts; if (!checkGrammarTypeArguments(node, node.typeArguments)) checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { return voidType; } - if (node.kind === 190 /* NewExpression */) { + if (node.kind === 192 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 155 /* Constructor */ && - declaration.kind !== 159 /* ConstructSignature */ && - declaration.kind !== 164 /* ConstructorType */ && + declaration.kind !== 157 /* Constructor */ && + declaration.kind !== 161 /* ConstructSignature */ && + declaration.kind !== 166 /* 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 @@ -47921,10 +49873,10 @@ var ts; // Note:JS inferred classes might come from a variable declaration instead of a function declaration. // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. var funcSymbol = checkExpression(node.expression).symbol; - if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { + if (!funcSymbol && node.expression.kind === 72 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,18 +49887,18 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property // as a fresh unique symbol literal type. - if (returnType.flags & 3072 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49924,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -47987,7 +49939,7 @@ var ts; for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 8192 /* Undefined */ || specifierType.flags & 16384 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal @@ -48031,7 +49983,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48040,9 +49992,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 237 /* FunctionDeclaration */ + ? 239 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 235 /* VariableDeclaration */ + ? 237 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -48078,10 +50030,10 @@ var ts; } function checkMetaProperty(node) { checkGrammarMetaProperty(node); - if (node.keywordToken === 94 /* NewKeyword */) { + if (node.keywordToken === 95 /* NewKeyword */) { return checkNewTargetMetaProperty(node); } - if (node.keywordToken === 91 /* ImportKeyword */) { + if (node.keywordToken === 92 /* ImportKeyword */) { return checkImportMetaProperty(node); } return ts.Debug.assertNever(node.keywordToken); @@ -48092,7 +50044,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 155 /* Constructor */) { + else if (container.kind === 157 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -48156,14 +50108,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +50121,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,15 +50145,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48222,6 +50152,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48274,7 +50215,7 @@ var ts; for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71 /* Identifier */) { + if (element.name.kind === 72 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } else { @@ -48288,7 +50229,7 @@ var ts; if (!links.type) { links.type = contextualType; var decl = parameter.valueDeclaration; - if (decl.name.kind !== 71 /* Identifier */) { + if (decl.name.kind !== 72 /* Identifier */) { // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType) { links.type = getTypeFromBindingPattern(decl.name); @@ -48307,6 +50248,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48328,7 +50279,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 216 /* Block */) { + if (func.body.kind !== 218 /* Block */) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any @@ -48424,10 +50375,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 199 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48442,7 +50444,7 @@ var ts; if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - if (ts.some(func.body.statements, function (statement) { return statement.kind === 230 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -48464,7 +50466,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -48477,7 +50479,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48485,11 +50487,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; - case 154 /* MethodDeclaration */: - return func.parent.kind === 186 /* ObjectLiteralExpression */; + case 156 /* MethodDeclaration */: + return func.parent.kind === 188 /* ObjectLiteralExpression */; default: return false; } @@ -48508,16 +50510,16 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 153 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 216 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 32768 /* Never */) { + if (returnType && returnType.flags & 131072 /* Never */) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -48546,7 +50548,8 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48556,14 +50559,16 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 194 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -48598,7 +50603,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48609,7 +50613,7 @@ var ts; getAwaitedType(type) || errorType : type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function @@ -48625,7 +50629,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 216 /* Block */) { + if (node.body.kind === 218 /* Block */) { checkSourceElement(node.body); } else { @@ -48648,34 +50652,66 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAssignableToKind(type, 168 /* NumberLike */)) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { error(operand, diagnostic); return false; } return true; } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } 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 + // Object.defineProperty assignments with writable false or no setter // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || - symbol.flags & 8 /* EnumMember */); + symbol.flags & 8 /* EnumMember */ || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); } 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 === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) && - expr.expression.kind === 99 /* ThisKeyword */) { + (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) && + expr.expression.kind === 100 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 155 /* Constructor */)) { + if (!(func && func.kind === 157 /* Constructor */)) { return true; } // If func.parent is a class and symbol is a (readonly) property of that class, or @@ -48688,13 +50724,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) { + if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return !!declaration && declaration.kind === 249 /* NamespaceImport */; + return !!declaration && declaration.kind === 251 /* NamespaceImport */; } } } @@ -48703,7 +50739,7 @@ var ts; function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); - if (node.kind !== 71 /* Identifier */ && node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { + if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -48712,7 +50748,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -48749,37 +50785,52 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operand.kind === 8 /* NumericLiteral */) { - if (node.operator === 38 /* MinusToken */) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - else if (node.operator === 37 /* PlusToken */) { - return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); - } + switch (node.operand.kind) { + case 8 /* NumericLiteral */: + switch (node.operator) { + case 39 /* MinusToken */: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38 /* PlusToken */: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9 /* BigIntLiteral */: + if (node.operator === 39 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } } switch (node.operator) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 3072 /* ESSymbolLike */)) { + if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } - return numberType; - case 51 /* ExclamationToken */: + if (node.operator === 38 /* PlusToken */) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52 /* ExclamationToken */: checkTruthinessExpression(node.operand); - var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); - return facts === 1048576 /* Truthy */ ? falseType : - facts === 2097152 /* Falsy */ ? trueType : + var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : + facts === 8388608 /* Falsy */ ? trueType : booleanType; - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } - return numberType; + return getUnaryResultType(operandType); } return errorType; } @@ -48788,11 +50839,20 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number return numberType; } // Return true if type might be of the given kind. A union or intersection type might be of a given @@ -48801,10 +50861,10 @@ var ts; if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { return true; } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48816,21 +50876,22 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (3 /* AnyOrUnknown */ | 4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */)) { + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { return false; } - return !!(kind & 168 /* NumberLike */) && isTypeAssignableTo(source, numberType) || - !!(kind & 68 /* StringLike */) && isTypeAssignableTo(source, stringType) || - !!(kind & 272 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || - !!(kind & 4096 /* Void */) && isTypeAssignableTo(source, voidType) || - !!(kind & 32768 /* Never */) && isTypeAssignableTo(source, neverType) || - !!(kind & 16384 /* Null */) && isTypeAssignableTo(source, nullType) || - !!(kind & 8192 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || - !!(kind & 1024 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || - !!(kind & 16777216 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { - return source.flags & 262144 /* Union */ ? + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : isTypeAssignableToKind(source, kind, strict); } @@ -48850,7 +50911,7 @@ var ts; // 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 (!isTypeAny(leftType) && - allTypesAssignableToKind(leftType, 32764 /* Primitive */)) { + allTypesAssignableToKind(leftType, 131068 /* 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 @@ -48869,10 +50930,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 168 /* NumberLike */ | 3072 /* ESSymbolLike */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + if (!isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -48882,8 +50943,8 @@ var ts; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; @@ -48891,9 +50952,9 @@ var ts; /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { if (rightIsThis === void 0) { rightIsThis = false; } - if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { + if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -48902,13 +50963,13 @@ var ts; var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 275 /* SpreadAssignment */) { + else if (property.kind === 277 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } @@ -48960,11 +51021,11 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 208 /* OmittedExpression */) { - if (element.kind !== 206 /* SpreadElement */) { + if (element.kind !== 210 /* OmittedExpression */) { + if (element.kind !== 208 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48985,13 +51046,13 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 202 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49002,14 +51063,14 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 8192 /* Undefined */)) { - sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); } @@ -49018,21 +51079,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 202 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 186 /* ObjectLiteralExpression */) { + if (target.kind === 188 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 185 /* ArrayLiteralExpression */) { + if (target.kind === 187 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 275 /* SpreadAssignment */ ? + var error = target.parent.kind === 277 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { @@ -49051,72 +51112,73 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 191 /* TaggedTemplateExpression */: - case 204 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 193 /* TaggedTemplateExpression */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 140 /* UndefinedKeyword */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: - case 195 /* ArrowFunction */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 197 /* TypeOfExpression */: - case 211 /* NonNullExpression */: - case 259 /* JsxSelfClosingElement */: - case 258 /* JsxElement */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 141 /* UndefinedKeyword */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 199 /* TypeOfExpression */: + case 213 /* NonNullExpression */: + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: return true; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { - case 51 /* ExclamationToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: + case 52 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: return true; } return false; // Some forms listed here for clarity - case 198 /* VoidExpression */: // Explicit opt-out - case 192 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 210 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 200 /* VoidExpression */: // Explicit opt-out + case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */); + if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */); } var leftType; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { leftType = checkTruthinessExpression(left, checkMode); } else { @@ -49124,28 +51186,28 @@ var ts; } var rightType = checkExpression(right, checkMode); switch (operator) { - case 39 /* AsteriskToken */: - case 40 /* AsteriskAsteriskToken */: - case 61 /* AsteriskEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 42 /* PercentToken */: - case 64 /* PercentEqualsToken */: - case 38 /* MinusToken */: - case 60 /* MinusEqualsToken */: - case 45 /* LessThanLessThanToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: + case 40 /* AsteriskToken */: + case 41 /* AsteriskAsteriskToken */: + case 62 /* AsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 43 /* PercentToken */: + case 65 /* PercentEqualsToken */: + case 39 /* MinusToken */: + case 61 /* MinusEqualsToken */: + case 46 /* LessThanLessThanToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -49154,36 +51216,61 @@ var ts; 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 & 272 /* BooleanLike */) && - (rightType.flags & 272 /* BooleanLike */) && + if ((leftType.flags & 528 /* BooleanLike */) && + (rightType.flags & 528 /* BooleanLike */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; } else { // otherwise just check each operand separately and report errors as normal - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType_1 = numberType; } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) { + switch (operator) { + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; } - return numberType; - case 37 /* PlusToken */: - case 59 /* PlusEqualsToken */: + case 38 /* PlusToken */: + case 60 /* PlusEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 68 /* StringLike */) && !isTypeAssignableToKind(rightType, 68 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeAssignableToKind(leftType, 168 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 168 /* NumberLike */, /*strict*/ true)) { + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) { // 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 (isTypeAssignableToKind(leftType, 68 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 68 /* StringLike */, /*strict*/ true)) { + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -49200,26 +51287,27 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 59 /* PlusEqualsToken */) { + if (operator === 60 /* PlusEqualsToken */) { checkAssignmentOperator(resultType); } return resultType; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: if (checkForDisallowedESSymbolOperand(operator)) { leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { reportOperatorError(); } } return booleanType; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -49230,29 +51318,38 @@ var ts; reportOperatorError(); } return booleanType; - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return checkInstanceOfExpression(left, right, leftType, rightType); - case 92 /* InKeyword */: + case 93 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); - case 53 /* AmpersandAmpersandToken */: - return getTypeFacts(leftType) & 1048576 /* Truthy */ ? + case 54 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 4194304 /* Truthy */ ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; - case 54 /* BarBarToken */: - return getTypeFacts(leftType) & 2097152 /* Falsy */ ? + case 55 /* BarBarToken */: + return getTypeFacts(leftType) & 8388608 /* Falsy */ ? getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; - case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + case 59 /* EqualsToken */: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || + declKind !== 2 /* ModuleExports */ && + declKind !== 6 /* Prototype */ && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1 /* Class */)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } return leftType; } else { checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); } - case 26 /* CommaToken */: + case 27 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -49260,15 +51357,14 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { - var rightType_1 = checkExpression(right, checkMode); - for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2 /* ModuleExports */) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49278,12 +51374,12 @@ var ts; } } function isEvalNode(node) { - return node.kind === 71 /* Identifier */ && node.escapedText === "eval"; + return node.kind === 72 /* Identifier */ && node.escapedText === "eval"; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 3072 /* ESSymbolLike */) ? left : - maybeTypeOfKind(rightType, 3072 /* ESSymbolLike */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -49293,15 +51389,15 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - return 54 /* BarBarToken */; - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - return 35 /* ExclamationEqualsEqualsToken */; - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: - return 53 /* AmpersandAmpersandToken */; + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + return 55 /* BarBarToken */; + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + return 36 /* ExclamationEqualsEqualsToken */; + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + return 54 /* AmpersandAmpersandToken */; default: return undefined; } @@ -49321,8 +51417,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +51427,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49348,11 +51444,11 @@ var ts; } function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { switch (operatorToken.kind) { - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); } return undefined; @@ -49430,14 +51526,14 @@ var ts; // A place where we actually *are* concerned with the expressions' types are // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { - if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) { error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49473,25 +51569,21 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 192 /* TypeAssertionExpression */ || node.kind === 210 /* AsExpression */; + return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */; } function checkDeclarationInitializer(declaration) { var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { - if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304 /* Nullable */) { + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49499,34 +51591,36 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 786432 /* UnionOrIntersection */) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { var types = contextualType.types; return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } - if (contextualType.flags & 14745600 /* InstantiableNonPrimitive */) { + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { // If the contextual type is a type variable constrained to a primitive type, consider // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || - maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || - maybeTypeOfKind(constraint, 1024 /* ESSymbol */) && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (64 /* StringLiteral */ | 1048576 /* Index */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || - contextualType.flags & 128 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || - contextualType.flags & 256 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 256 /* BooleanLiteral */) || - contextualType.flags & 2048 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */)); + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || + contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49534,7 +51628,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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -49545,7 +51639,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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -49573,15 +51667,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +51693,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +51710,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; - if (node.kind === 146 /* QualifiedName */) { + if (node.kind === 148 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49622,10 +51724,10 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 165 /* TypeQuery */ && node.parent.exprName === node)); + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === 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_or_type_query); } @@ -49633,102 +51735,105 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return checkIdentifier(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return checkThisExpression(node); - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return checkSuperExpression(node); - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: return nullWideningType; - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101 /* TrueKeyword */: + case 9 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102 /* TrueKeyword */: return trueType; - case 86 /* FalseKeyword */: + case 87 /* FalseKeyword */: return falseType; - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return checkTemplateExpression(node); - case 12 /* RegularExpressionLiteral */: + case 13 /* RegularExpressionLiteral */: return globalRegExpType; - case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); - case 186 /* ObjectLiteralExpression */: + case 187 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 189 /* CallExpression */: - if (node.expression.kind === 91 /* ImportKeyword */) { + case 191 /* CallExpression */: + if (node.expression.kind === 92 /* ImportKeyword */) { return checkImportCallExpression(node); } /* falls through */ - case 190 /* NewExpression */: + case 192 /* NewExpression */: return checkCallExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return checkClassExpression(node); - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return checkAssertion(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return checkNonNullAssertion(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return checkMetaProperty(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return checkDeleteExpression(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return checkVoidExpression(node); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return checkAwaitExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 208 /* OmittedExpression */: + case 210 /* OmittedExpression */: return undefinedWideningType; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return checkYieldExpression(node); - case 213 /* SyntheticExpression */: + case 215 /* SyntheticExpression */: return node.type; - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return checkJsxElement(node, checkMode); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 262 /* JsxFragment */: - return checkJsxFragment(node, checkMode); - case 266 /* JsxAttributes */: + case 264 /* JsxFragment */: + return checkJsxFragment(node); + case 268 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -49757,9 +51862,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49769,7 +51871,7 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 155 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -49780,16 +51882,16 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { + if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 195 /* ArrowFunction */) { + if (func.kind === 197 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -49838,13 +51940,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 195 /* ArrowFunction */: - case 158 /* CallSignature */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 163 /* FunctionType */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 197 /* ArrowFunction */: + case 160 /* CallSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 165 /* FunctionType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -49858,11 +51960,11 @@ var ts; continue; } var name = element.name; - if (name.kind === 71 /* Identifier */ && name.escapedText === predicateVariableName) { + if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 183 /* ArrayBindingPattern */ || name.kind === 182 /* ObjectBindingPattern */) { + else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -49871,13 +51973,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 160 /* IndexSignature */) { + if (node.kind === 162 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 163 /* FunctionType */ || node.kind === 237 /* FunctionDeclaration */ || node.kind === 164 /* ConstructorType */ || - node.kind === 158 /* CallSignature */ || node.kind === 155 /* Constructor */ || - node.kind === 159 /* ConstructSignature */) { + else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ || + node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ || + node.kind === 161 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -49907,10 +52009,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 158 /* CallSignature */: + case 160 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -49940,7 +52042,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -49957,7 +52059,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 155 /* Constructor */) { + if (member.kind === 157 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -49972,16 +52074,16 @@ var ts; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (name && memberName) { switch (member.kind) { - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: addName(names, name, memberName, 1 /* Getter */); break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: addName(names, name, memberName, 2 /* Setter */); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: addName(names, name, memberName, 3 /* Property */); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: addName(names, name, memberName, 4 /* Method */); break; } @@ -50044,15 +52146,15 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151 /* PropertySignature */) { + if (member.kind === 153 /* PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: memberName = name.text; break; - case 71 /* Identifier */: + case 72 /* Identifier */: memberName = ts.idText(name); break; default: @@ -50069,7 +52171,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 239 /* InterfaceDeclaration */) { + if (node.kind === 241 /* 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 @@ -50089,7 +52191,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -50097,7 +52199,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -50124,7 +52226,7 @@ var ts; checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 154 /* MethodDeclaration */ && node.body) { + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -50149,7 +52251,7 @@ var ts; return; } function isInstancePropertyWithInitializer(n) { - return n.kind === 152 /* PropertyDeclaration */ && + return n.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } @@ -50179,7 +52281,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -50204,7 +52306,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -50214,13 +52316,13 @@ 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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(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 === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); @@ -50238,7 +52340,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -50255,7 +52357,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +52388,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50334,7 +52436,7 @@ var ts; var seenOptionalElement = false; for (var i = 0; i < elementTypes.length; i++) { var e = elementTypes[i]; - if (e.kind === 170 /* RestType */) { + if (e.kind === 172 /* RestType */) { if (i !== elementTypes.length - 1) { grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); break; @@ -50343,7 +52445,7 @@ var ts; error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); } } - else if (e.kind === 169 /* OptionalType */) { + else if (e.kind === 171 /* OptionalType */) { seenOptionalElement = true; } else if (seenOptionalElement) { @@ -50358,14 +52460,14 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 2097152 /* IndexedAccess */)) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { return type; } // Check if the index type is assignable to 'keyof T' for the object type. var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 188 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -50373,7 +52475,7 @@ var ts; } // Check if we're indexing with a numeric type and if either object or index types // is a generic type with a constraint that has a numeric index signature. - if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -50387,8 +52489,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50405,7 +52507,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 173 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -50422,9 +52524,9 @@ var ts; var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 239 /* InterfaceDeclaration */ && - n.parent.kind !== 238 /* ClassDeclaration */ && - n.parent.kind !== 207 /* ClassExpression */ && + if (n.parent.kind !== 241 /* InterfaceDeclaration */ && + n.parent.kind !== 240 /* ClassDeclaration */ && + n.parent.kind !== 209 /* ClassExpression */ && n.flags & 4194304 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -50515,7 +52617,7 @@ var ts; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */) && + var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) && ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -50554,7 +52656,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = node.flags & 4194304 /* Ambient */; - var inAmbientContextOrInterface = node.parent.kind === 239 /* InterfaceDeclaration */ || node.parent.kind === 166 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -50565,7 +52667,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 === 237 /* FunctionDeclaration */ || node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */ || node.kind === 155 /* Constructor */) { + if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -50617,8 +52719,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var signature = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -50627,6 +52729,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,32 +52793,25 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return 2 /* ExportType */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values if (!ts.isEntityNameExpression(d.expression)) { return 1 /* ExportValue */; @@ -50717,17 +52819,17 @@ var ts; d = d.expression; /* falls through */ // The below options all declare an Alias, which is allowed to merge with other values within the importing module - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 248 /* ImportClause */: - var result_3 = 0 /* None */; + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 237 /* FunctionDeclaration */: - case 251 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 239 /* FunctionDeclaration */: + case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); @@ -50774,7 +52876,7 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -50805,7 +52907,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -50953,10 +53055,10 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { - if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { @@ -50976,7 +53078,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -50995,24 +53097,24 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 149 /* Parameter */: + case 151 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -51033,7 +53135,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51058,50 +53160,55 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 172 /* IntersectionType */: - case 171 /* UnionType */: - var commonEntityName = void 0; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175 /* ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 131 /* NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); - if (!individualEntityName) { - // Individual is something like string number - // So it would be serialized to either that type or object - // Safe to return here - return undefined; - } - if (commonEntityName) { - // Note this is in sync with the transformation that happens for type node. - // Keep this in sync with serializeUnionOrIntersectionType - // Verify if they refer to same entity and is identifier - // return undefined if they dont match because we would emit object - if (!ts.isIdentifier(commonEntityName) || - !ts.isIdentifier(individualEntityName) || - commonEntityName.escapedText !== individualEntityName.escapedText) { - return undefined; - } - } - else { - commonEntityName = individualEntityName; - } - } - return commonEntityName; - case 175 /* ParenthesizedType */: + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; } } } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } function getParameterTypeNodeForDecoratorCheck(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; @@ -51121,14 +53228,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 149 /* Parameter */) { + if (node.kind === 151 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -51137,23 +53244,23 @@ var ts; } } break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 149 /* Parameter */: + case 151 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -51206,16 +53313,22 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); } } } } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } function checkJSDocAugmentsTag(node) { var classLike = ts.getJSDocHost(node); if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { @@ -51238,9 +53351,9 @@ var ts; } function getIdentifierFromEntityNameExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return node.name; default: return undefined; @@ -51253,7 +53366,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 && node.name.kind === 147 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -51282,7 +53395,7 @@ var ts; } } } - var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); @@ -51291,8 +53404,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51302,7 +53415,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51311,7 +53424,7 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. - if (produceDiagnostics) { + if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) { var sourceFile = ts.getSourceFileOfNode(node); var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); if (!potentiallyUnusedIdentifiers) { @@ -51327,44 +53440,44 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 239 /* InterfaceDeclaration */: - checkUnusedTypeParameters(node, addDiagnostic); - break; - case 277 /* SourceFile */: - case 242 /* ModuleDeclaration */: - case 216 /* Block */: - case 244 /* CaseBlock */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 279 /* SourceFile */: + case 244 /* ModuleDeclaration */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - if (node.body) { + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 240 /* TypeAliasDeclaration */: - case 174 /* InferType */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; + case 176 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; default: ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); } @@ -51379,77 +53492,73 @@ var ts; return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 154 /* MethodDeclaration */: - case 152 /* PropertyDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - if (member.kind === 157 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { - // Already would have reported an error on the getter. - break; - } - var symbol = getSymbolOfNode(member); - if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. break; - case 155 /* Constructor */: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } - break; - case 160 /* IndexSignature */: - case 215 /* SemicolonClassElement */: - // Can't be private - break; - default: - ts.Debug.fail(); - } + } + break; + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) + if (ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174 /* InferType */) { - var typeParameter = node.typeParameter; - if (isTypeParameterUnused(typeParameter)) { - addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } } - } - else { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - var seenParentsWithEveryUnused = new ts.NodeSet(); - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var typeParameter = typeParameters_2[_i]; - if (!isTypeParameterUnused(typeParameter)) - continue; - var name = ts.idText(typeParameter.name); - var parent = typeParameter.parent; - if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { - if (seenParentsWithEveryUnused.tryAdd(parent)) { - var range = ts.isJSDocTemplateTag(parent) - // Whole @template tag - ? ts.rangeOfNode(parent) - // Include the `<>` in the error message - : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; - var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; - var arg0 = only ? name : undefined; - addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); - } - } - else { - addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); - } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } @@ -51520,7 +53629,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 @@ -51538,7 +53647,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 235 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 236 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -51559,7 +53668,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -51571,24 +53680,24 @@ var ts; } function bindingNameText(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.idText(name); - case 183 /* ArrayBindingPattern */: - case 182 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 248 /* ImportClause */ || node.kind === 251 /* ImportSpecifier */ || node.kind === 249 /* NamespaceImport */; + return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 248 /* ImportClause */ ? decl : decl.kind === 249 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 216 /* Block */) { + if (node.kind === 218 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -51618,12 +53727,12 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 151 /* PropertySignature */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 153 /* MethodSignature */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { + if (node.kind === 154 /* PropertyDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 156 /* MethodDeclaration */ || + node.kind === 155 /* MethodSignature */ || + node.kind === 158 /* GetAccessor */ || + node.kind === 159 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -51632,7 +53741,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 149 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -51642,7 +53751,7 @@ var ts; function checkIfThisIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { - var isDeclaration_1 = node.kind !== 71 /* Identifier */; + var isDeclaration_1 = node.kind !== 72 /* Identifier */; if (isDeclaration_1) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -51657,7 +53766,7 @@ var ts; function checkIfNewTargetIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { - var isDeclaration_2 = node.kind !== 71 /* Identifier */; + var isDeclaration_2 = node.kind !== 72 /* Identifier */; if (isDeclaration_2) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } @@ -51683,7 +53792,7 @@ var ts; } // 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 === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 279 /* 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)); } @@ -51698,7 +53807,7 @@ var ts; } // 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 === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -51733,7 +53842,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 235 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -51745,17 +53854,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 236 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 217 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 219 /* 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 === 216 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 243 /* ModuleBlock */ || - container.kind === 242 /* ModuleDeclaration */ || - container.kind === 277 /* SourceFile */); + (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 245 /* ModuleBlock */ || + container.kind === 244 /* ModuleDeclaration */ || + container.kind === 279 /* 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 @@ -51770,7 +53879,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 !== 149 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -51781,14 +53890,14 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 187 /* PropertyAccessExpression */) { + if (n.kind === 189 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } - else if (n.kind === 71 /* Identifier */) { + else if (n.kind === 72 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51800,8 +53909,8 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 149 /* Parameter */ || - symbol.valueDeclaration.kind === 184 /* BindingElement */) { + if (symbol.valueDeclaration.kind === 151 /* Parameter */ || + symbol.valueDeclaration.kind === 186 /* BindingElement */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -51815,7 +53924,7 @@ var ts; return ts.isFunctionLike(current.parent) || // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - (current.parent.kind === 152 /* PropertyDeclaration */ && + (current.parent.kind === 154 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)); })) { @@ -51848,18 +53957,18 @@ 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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 184 /* BindingElement */) { - if (node.parent.kind === 182 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + if (node.kind === 186 /* BindingElement */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 147 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -51870,29 +53979,29 @@ var ts; var nameText = ts.getTextOfPropertyName(name); if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { - checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property); } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 183 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 149 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) { var initializerType = checkExpressionCached(node.initializer); if (strictNullChecks && node.name.elements.length === 0) { checkNonNullType(initializerType, node); @@ -51911,15 +54020,20 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); checkParameterInitializer(node); } } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } } else { // Node is a secondary declaration, check that type is identical to primary declaration and check that @@ -51927,21 +54041,20 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */) { + if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -51950,14 +54063,14 @@ var ts; } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 152 /* PropertyDeclaration */ || nextDeclaration.kind === 151 /* PropertySignature */ + var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 149 /* Parameter */ && right.kind === 235 /* VariableDeclaration */) || - (left.kind === 235 /* VariableDeclaration */ && right.kind === 149 /* Parameter */)) { + if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) || + (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -51996,7 +54109,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 218 /* EmptyStatement */) { + if (node.thenStatement.kind === 220 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -52015,7 +54128,7 @@ var ts; } function checkTruthinessExpression(node, checkMode) { var type = checkExpression(node, checkMode); - if (type.flags & 4096 /* Void */) { + if (type.flags & 16384 /* Void */) { error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); } return type; @@ -52023,12 +54136,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -52062,14 +54175,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 === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side - if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* 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. @@ -52095,13 +54208,13 @@ var ts; function checkForInStatement(node) { // Grammar checking checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* 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); @@ -52115,7 +54228,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 === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -52128,7 +54241,7 @@ var ts; } // 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 (rightType === neverType || !isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -52183,16 +54296,16 @@ var ts; // This allows us to find other non-string element types from an array unioned with // a string. if (allowStringInput) { - if (arrayType.flags & 262144 /* Union */) { + if (arrayType.flags & 1048576 /* Union */) { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the result of filter is a new array. var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 68 /* StringLike */); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } } - else if (arrayType.flags & 68 /* StringLike */) { + else if (arrayType.flags & 132 /* StringLike */) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -52205,7 +54318,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType.flags & 32768 /* Never */) { + if (arrayType.flags & 131072 /* Never */) { return stringType; } } @@ -52236,7 +54349,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); if (hasStringConstituent && arrayElementType) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 68 /* StringLike */) { + if (arrayElementType.flags & 132 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], 2 /* Subtype */); @@ -52301,13 +54414,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52334,9 +54451,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52444,7 +54563,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 4096 /* Void */ | 3 /* AnyOrUnknown */); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { // Grammar checking @@ -52460,7 +54579,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); var functionFlags = ts.getFunctionFlags(func); var isGenerator = functionFlags & 1 /* Generator */; - if (strictNullChecks || node.expression || returnType.flags & 32768 /* Never */) { + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (isGenerator) { // AsyncGenerator function or Generator function // A generator does not need its return expressions checked against its return type. @@ -52469,12 +54588,12 @@ var ts; // for generators. return; } - else if (func.kind === 157 /* SetAccessor */) { + else if (func.kind === 159 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 155 /* Constructor */) { + else if (func.kind === 157 /* Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -52495,7 +54614,7 @@ var ts; } } } - else if (func.kind !== 155 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -52524,7 +54643,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 270 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -52536,7 +54655,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 269 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 271 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -52565,7 +54684,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 231 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -52672,8 +54791,8 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 202 /* BinaryExpression */ || - name.kind === 147 /* ComputedPropertyName */ || + (propDeclaration.kind === 204 /* BinaryExpression */ || + name.kind === 149 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -52702,6 +54821,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -52877,18 +54997,21 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 2162688 /* TypeVariable */)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52916,7 +55039,7 @@ var ts; } } else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -52931,7 +55054,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52950,7 +55073,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -52976,7 +55099,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 238 /* ClassDeclaration */ || d.kind === 239 /* InterfaceDeclaration */; + return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -53015,7 +55138,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 || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { - if (derivedClassDecl.kind === 207 /* ClassExpression */) { + if (derivedClassDecl.kind === 209 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -53065,8 +55188,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -53097,7 +55220,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 8192 /* Undefined */)) { + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -53107,16 +55230,18 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 152 /* PropertyDeclaration */ && + return node.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 8192 /* Undefined */); + return !(getFalsyFlags(flowType) & 32768 /* Undefined */); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -53129,7 +55254,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -53234,60 +55359,60 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { - case 37 /* PlusToken */: return value_2; - case 38 /* MinusToken */: return -value_2; - case 52 /* TildeToken */: return ~value_2; + case 38 /* PlusToken */: return value_2; + case 39 /* MinusToken */: return -value_2; + case 53 /* TildeToken */: return ~value_2; } } break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { switch (expr.operatorToken.kind) { - case 49 /* BarToken */: return left | right; - case 48 /* AmpersandToken */: return left & right; - case 46 /* GreaterThanGreaterThanToken */: return left >> right; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; - case 45 /* LessThanLessThanToken */: return left << right; - case 50 /* CaretToken */: return left ^ right; - case 39 /* AsteriskToken */: return left * right; - case 41 /* SlashToken */: return left / right; - case 37 /* PlusToken */: return left + right; - case 38 /* MinusToken */: return left - right; - case 42 /* PercentToken */: return left % right; - case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right); + case 50 /* BarToken */: return left | right; + case 49 /* AmpersandToken */: return left & right; + case 47 /* GreaterThanGreaterThanToken */: return left >> right; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 46 /* LessThanLessThanToken */: return left << right; + case 51 /* CaretToken */: return left ^ right; + case 40 /* AsteriskToken */: return left * right; + case 42 /* SlashToken */: return left / right; + case 38 /* PlusToken */: return left + right; + case 39 /* MinusToken */: return left - right; + case 43 /* PercentToken */: return left % right; + case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right); } } - else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 37 /* PlusToken */) { + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) { return left + right; } break; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return expr.text; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return evaluate(expr.expression); - case 71 /* Identifier */: + case 72 /* Identifier */: var identifier = expr; if (isInfinityOrNaNString(identifier.escapedText)) { return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 188 /* ElementAccessExpression */: - case 187 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 187 /* PropertyAccessExpression */) { + if (ex.kind === 189 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -53318,10 +55443,10 @@ var ts; } } function isConstantMemberAccess(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 187 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 188 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && - node.argumentExpression.kind === 9 /* StringLiteral */; + return node.kind === 72 /* Identifier */ || + node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10 /* StringLiteral */; } function checkEnumDeclaration(node) { if (!produceDiagnostics) { @@ -53358,7 +55483,7 @@ var ts; 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 !== 241 /* EnumDeclaration */) { + if (declaration.kind !== 243 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -53381,8 +55506,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { var declaration = declarations_8[_i]; - if ((declaration.kind === 238 /* ClassDeclaration */ || - (declaration.kind === 237 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 240 /* ClassDeclaration */ || + (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304 /* Ambient */)) { return declaration; } @@ -53419,7 +55544,7 @@ var ts; return; } if (!checkGrammarDecoratorsAndModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { + if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } @@ -53445,7 +55570,7 @@ 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, 238 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -53495,23 +55620,23 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* 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 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 184 /* BindingElement */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -53522,12 +55647,12 @@ var ts; break; } // falls through - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 237 /* FunctionDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -53540,7 +55665,7 @@ var ts; var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { // symbol should not originate in augmentation - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -53548,17 +55673,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: do { node = node.left; - } while (node.kind !== 71 /* Identifier */); + } while (node.kind !== 72 /* Identifier */); return node; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: do { node = node.expression; - } while (node.kind !== 71 /* Identifier */); + } while (node.kind !== 72 /* Identifier */); return node; } } @@ -53572,9 +55697,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 253 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -53603,19 +55728,19 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 255 /* ExportSpecifier */ ? + var message = node.kind === 257 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && node.kind === 257 /* ExportSpecifier */ + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53641,7 +55766,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -53665,17 +55790,17 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53701,10 +55826,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 243 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; - if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -53721,7 +55846,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 277 /* SourceFile */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 242 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -53729,13 +55854,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53750,8 +55875,8 @@ 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 === 277 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -53764,9 +55889,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 71 /* Identifier */) { + if (node.expression.kind === 72 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +55923,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53839,14 +55964,14 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 237 /* FunctionDeclaration */ && declaration.kind !== 154 /* MethodDeclaration */) || + return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -53857,163 +55982,163 @@ var ts; // 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 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return checkTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return checkParameter(node); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return checkPropertyDeclaration(node); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return checkSignatureDeclaration(node); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return checkMethodDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return checkConstructorDeclaration(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return checkAccessorDeclaration(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return checkTypeReferenceNode(node); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return checkTypePredicate(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return checkTypeQuery(node); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return checkTypeLiteral(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return checkArrayType(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return checkTupleType(node); - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 175 /* ParenthesizedType */: - case 169 /* OptionalType */: - case 170 /* RestType */: + case 177 /* ParenthesizedType */: + case 171 /* OptionalType */: + case 172 /* RestType */: return checkSourceElement(node.type); - case 176 /* ThisType */: + case 178 /* ThisType */: return checkThisType(node); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return checkTypeOperator(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return checkConditionalType(node); - case 174 /* InferType */: + case 176 /* InferType */: return checkInferType(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return checkImportType(node); - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 297 /* JSDocParameterTag */: + case 299 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 287 /* JSDocFunctionType */: - checkSignatureDeclaration(node); + case 289 /* JSDocFunctionType */: + checkJSDocFunctionType(node); // falls through - case 285 /* JSDocNonNullableType */: - case 284 /* JSDocNullableType */: - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: - case 290 /* JSDocTypeLiteral */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + case 292 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 281 /* JSDocTypeExpression */: + case 283 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return checkMappedType(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return checkBlock(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return checkVariableStatement(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return checkExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return checkIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return checkDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return checkWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return checkForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return checkForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return checkForOfStatement(node); - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return checkReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return checkWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return checkSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return checkLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return checkThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return checkTryStatement(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return checkBindingElement(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return checkClassDeclaration(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return checkImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return checkExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return checkExportAssignment(node); - case 218 /* EmptyStatement */: - case 234 /* DebuggerStatement */: + case 220 /* EmptyStatement */: + case 236 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return checkMissingDeclaration(node); } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54084,31 +56209,38 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: checkClassExpressionDeferred(node); break; - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 258 /* JsxElement */: + case 260 /* JsxElement */: checkJsxElementDeferred(node); break; } @@ -54144,9 +56276,9 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54157,7 +56289,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54239,13 +56370,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 242 /* ModuleDeclaration */: + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + // falls through + case 244 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -54253,17 +56388,17 @@ var ts; // falls through // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* 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 (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -54305,17 +56440,17 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 71 /* Identifier */ && + return name.kind === 72 /* Identifier */ && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 148 /* TypeParameter */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: + case 150 /* TypeParameter */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: return true; default: return false; @@ -54323,16 +56458,16 @@ var ts; } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 146 /* QualifiedName */) { + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 162 /* TypeReference */; + return node.parent.kind === 164 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 187 /* PropertyAccessExpression */) { + while (node.parent.kind === 189 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 209 /* ExpressionWithTypeArguments */; + return node.parent.kind === 211 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -54345,12 +56480,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54360,13 +56495,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 146 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 246 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 252 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -54375,7 +56510,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54392,7 +56527,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 181 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -54401,8 +56536,8 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 187 /* PropertyAccessExpression */ && + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -54410,17 +56545,17 @@ var ts; return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } } else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 246 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } @@ -54438,11 +56573,11 @@ 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 === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) { + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54454,11 +56589,11 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 297 /* JSDocParameterTag */) { + if (entityName.parent.kind === 299 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54467,19 +56602,19 @@ var ts; // Missing entity name. return undefined; } - if (entityName.kind === 71 /* Identifier */) { + if (entityName.kind === 72 /* Identifier */) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { + else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 187 /* PropertyAccessExpression */) { + if (entityName.kind === 189 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -54489,20 +56624,17 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 265 /* JsxAttribute */) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 161 /* TypePredicate */) { + if (entityName.parent.kind === 163 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -54513,17 +56645,20 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(parent); + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(parent.parent); } - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (parent.kind === 184 /* BindingElement */ && - grandParent.kind === 182 /* ObjectBindingPattern */ && + else if (parent.kind === 186 /* BindingElement */ && + grandParent.kind === 184 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -54533,11 +56668,11 @@ var ts; } } switch (node.kind) { - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -54549,29 +56684,32 @@ var ts; return checkExpression(node).symbol; } // falls through - case 176 /* ThisType */: + case 178 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return checkExpression(node).symbol; - case 123 /* ConstructorKeyword */: + case 124 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 155 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } // falls through case 8 /* NumericLiteral */: // index access @@ -54581,19 +56719,22 @@ var ts; ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); - case 79 /* DefaultKeyword */: - case 89 /* FunctionKeyword */: - case 36 /* EqualsGreaterThanToken */: + case 80 /* DefaultKeyword */: + case 90 /* FunctionKeyword */: + case 37 /* EqualsGreaterThanToken */: + case 76 /* ClassKeyword */: return getSymbolOfNode(node.parent); - case 181 /* ImportType */: + case 183 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85 /* ExportKeyword */: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + if (location && location.kind === 276 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,30 +56742,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54665,28 +56801,28 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 186 /* ObjectLiteralExpression */ || expr.kind === 185 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 225 /* ForOfStatement */) { + if (expr.parent.kind === 227 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 202 /* BinaryExpression */) { + if (expr.parent.kind === 204 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 273 /* PropertyAssignment */) { + if (expr.parent.kind === 275 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 185 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; @@ -54719,13 +56855,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return getLiteralType(name.text); + case 149 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54765,7 +56920,7 @@ var ts; if (!ts.isGeneratedIdentifier(nodeIn)) { var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -54786,13 +56941,13 @@ var ts; // 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 & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54821,7 +56976,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 277 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -54841,7 +56996,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,11 +57009,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54874,9 +57029,9 @@ var ts; // * 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 isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -54917,18 +57072,18 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return node.expression - && node.expression.kind === 71 /* Identifier */ + && node.expression.kind === 72 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -54936,7 +57091,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 277 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -54950,7 +57105,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +57118,8 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && + target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +57164,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55017,15 +57192,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 276 /* EnumMember */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 278 /* EnumMember */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 276 /* EnumMember */) { + if (node.kind === 278 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -55039,7 +57214,7 @@ var ts; return undefined; } function isFunctionType(type) { - return !!(type.flags & 131072 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeNameIn, location) { // ensure both `typeName` and `location` are parse tree nodes. @@ -55052,9 +57227,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55076,22 +57251,25 @@ var ts; else if (type.flags & 3 /* AnyOrUnknown */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 4096 /* Void */ | 24576 /* Nullable */ | 32768 /* Never */)) { + else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeAssignableToKind(type, 272 /* BooleanLike */)) { + else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeAssignableToKind(type, 168 /* NumberLike */)) { + else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 68 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 3072 /* ESSymbolLike */)) { + else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -55107,14 +57285,14 @@ var ts; function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; - if (type.flags & 2048 /* UniqueESSymbol */ && + if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } @@ -55126,7 +57304,7 @@ var ts; function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); @@ -55134,7 +57312,7 @@ var ts; function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } var type = getWidenedType(getRegularTypeOfExpression(expr)); return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); @@ -55156,7 +57334,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +57349,19 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } - function createLiteralConstValue(node) { + function createLiteralConstValue(node, tracker) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node, tracker); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +57404,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55253,12 +57434,12 @@ var ts; getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 157 /* SetAccessor */ ? 156 /* GetAccessor */ : 157 /* SetAccessor */; + var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 157 /* SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 156 /* GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -55266,10 +57447,15 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { - return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; + return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -55280,9 +57466,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55332,7 +57518,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 277 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -55347,12 +57533,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 242 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 277 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -55371,6 +57557,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55415,6 +57604,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55442,31 +57633,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55478,7 +57668,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55526,14 +57716,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 154 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 156 /* 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 === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */) { + else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* 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); @@ -55550,23 +57740,23 @@ var ts; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 132 /* ReadonlyKeyword */) { - if (node.kind === 151 /* PropertySignature */ || node.kind === 153 /* MethodSignature */) { + if (modifier.kind !== 133 /* ReadonlyKeyword */) { + if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 160 /* IndexSignature */) { + if (node.kind === 162 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 76 /* ConstKeyword */: - if (node.kind !== 241 /* EnumDeclaration */) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); + case 77 /* ConstKeyword */: + if (node.kind !== 243 /* EnumDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */)); } break; - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: + case 115 /* PublicKeyword */: + case 114 /* ProtectedKeyword */: + case 113 /* PrivateKeyword */: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); @@ -55580,11 +57770,11 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { - if (modifier.kind === 112 /* PrivateKeyword */) { + if (modifier.kind === 113 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -55593,7 +57783,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -55603,10 +57793,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -55615,18 +57805,18 @@ var ts; flags |= 32 /* Static */; lastStatic = modifier; break; - case 132 /* ReadonlyKeyword */: + case 133 /* ReadonlyKeyword */: if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */ && node.kind !== 160 /* IndexSignature */ && node.kind !== 149 /* Parameter */) { + else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; lastReadonly = modifier; break; - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: if (flags & 1 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -55639,52 +57829,52 @@ 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 === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; - case 79 /* DefaultKeyword */: - var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + case 80 /* DefaultKeyword */: + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; break; - case 124 /* DeclareKeyword */: + case 125 /* DeclareKeyword */: if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 243 /* ModuleBlock */) { + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; lastDeclare = modifier; break; - case 117 /* AbstractKeyword */: + case 118 /* AbstractKeyword */: if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 238 /* ClassDeclaration */) { - if (node.kind !== 154 /* MethodDeclaration */ && - node.kind !== 152 /* PropertyDeclaration */ && - node.kind !== 156 /* GetAccessor */ && - node.kind !== 157 /* SetAccessor */) { + if (node.kind !== 240 /* ClassDeclaration */) { + if (node.kind !== 156 /* MethodDeclaration */ && + node.kind !== 154 /* PropertyDeclaration */ && + node.kind !== 158 /* GetAccessor */ && + node.kind !== 159 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 238 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -55696,14 +57886,14 @@ var ts; } flags |= 128 /* Abstract */; break; - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -55711,7 +57901,7 @@ var ts; break; } } - if (node.kind === 155 /* Constructor */) { + if (node.kind === 157 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -55726,13 +57916,13 @@ var ts; } return false; } - else if ((node.kind === 247 /* ImportDeclaration */ || node.kind === 246 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -55753,38 +57943,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 242 /* ModuleDeclaration */: - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 149 /* Parameter */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 244 /* ModuleDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 151 /* Parameter */: return false; default: - if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return false; } switch (node.kind) { - case 237 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 238 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 239 /* InterfaceDeclaration */: - case 217 /* VariableStatement */: - case 240 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */); + case 240 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */); + case 241 /* InterfaceDeclaration */: + case 219 /* VariableStatement */: + case 242 /* TypeAliasDeclaration */: return true; - case 241 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); + case 243 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */); default: ts.Debug.fail(); return false; @@ -55796,10 +57986,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -55852,11 +58042,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -55896,12 +58107,12 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 137 /* StringKeyword */ && parameter.type.kind !== 134 /* NumberKeyword */) { + if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) { var type = getTypeFromTypeNode(parameter.type); if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); } - if (type.flags & 262144 /* Union */ && allTypesAssignableToKind(type, 64 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); @@ -55932,7 +58143,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 208 /* OmittedExpression */) { + if (arg.kind === 210 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -55962,7 +58173,7 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (heritageClause.token === 86 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -55975,7 +58186,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -55991,14 +58202,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (heritageClause.token === 86 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } // Grammar checking heritageClause inside class declaration @@ -56009,20 +58220,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 147 /* ComputedPropertyName */) { + if (node.kind !== 149 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 202 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 237 /* FunctionDeclaration */ || - node.kind === 194 /* FunctionExpression */ || - node.kind === 154 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 156 /* MethodDeclaration */); if (node.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -56034,6 +58245,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56045,15 +58259,15 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 /* SpreadAssignment */) { + if (prop.kind === 277 /* SpreadAssignment */) { continue; } var name = prop.name; - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 274 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 276 /* 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); @@ -56062,7 +58276,7 @@ var ts; if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 154 /* MethodDeclaration */) { + if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -56077,21 +58291,23 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 275 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { checkGrammarNumericLiteral(name); } // falls through - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: currentKind = 1 /* Property */; break; - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: currentKind = 2 /* GetAccessor */; break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: currentKind = 4 /* SetAccessor */; break; default: @@ -56128,7 +58344,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 267 /* JsxSpreadAttribute */) { + if (attr.kind === 269 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -56138,7 +58354,7 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 268 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -56147,12 +58363,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 225 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 236 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -56167,20 +58383,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* 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 === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* 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); @@ -56207,11 +58423,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 156 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 157 /* SetAccessor */) { + else if (kind === 159 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -56235,23 +58451,23 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } function checkGrammarTypeOperatorNode(node) { - if (node.operator === 141 /* UniqueKeyword */) { - if (node.type.kind !== 138 /* SymbolKeyword */) { - return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(138 /* SymbolKeyword */)); + if (node.operator === 142 /* UniqueKeyword */) { + if (node.type.kind !== 139 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */)); } var parent = ts.walkUpParenthesizedTypes(node.parent); switch (parent.kind) { - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: var decl = parent; - if (decl.name.kind !== 71 /* Identifier */) { + if (decl.name.kind !== 72 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); } if (!ts.isVariableDeclarationInVariableStatement(decl)) { @@ -56261,13 +58477,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: if (!ts.hasModifier(parent, 32 /* Static */) || !ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: if (!ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -56286,15 +58502,18 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 154 /* MethodDeclaration */) { - if (node.parent.kind === 186 /* ObjectLiteralExpression */) { + if (node.kind === 156 /* MethodDeclaration */) { + if (node.parent.kind === 188 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 120 /* AsyncKeyword */)) { + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56312,14 +58531,14 @@ var ts; if (node.flags & 4194304 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 154 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 156 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 239 /* InterfaceDeclaration */) { + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 166 /* TypeLiteral */) { + else if (node.parent.kind === 168 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -56330,11 +58549,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 226 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 228 /* 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); @@ -56342,8 +58561,8 @@ var ts; return false; } break; - case 230 /* SwitchStatement */: - if (node.kind === 227 /* BreakStatement */ && !node.label) { + case 232 /* SwitchStatement */: + if (node.kind === 229 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -56358,13 +58577,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 227 /* BreakStatement */ + var message = node.kind === 229 /* 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 === 227 /* BreakStatement */ + var message = node.kind === 229 /* 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); @@ -56387,30 +58606,45 @@ var ts; } } function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 /* BigIntLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 9 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { + if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56421,7 +58655,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 217 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && @@ -56438,7 +58672,7 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkESModuleMarker(name) { - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } @@ -56455,8 +58689,8 @@ var ts; return false; } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71 /* Identifier */) { - if (name.originalKeywordKind === 110 /* LetKeyword */) { + if (name.kind === 72 /* Identifier */) { + if (name.originalKeywordKind === 111 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -56483,15 +58717,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return false; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -56509,12 +58743,12 @@ var ts; function checkGrammarMetaProperty(node) { var escapedText = node.name.escapedText; switch (node.keywordToken) { - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: if (escapedText !== "target") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); } break; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: if (escapedText !== "meta") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); } @@ -56550,10 +58784,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56568,7 +58803,7 @@ var ts; return true; } } - else if (node.parent.kind === 239 /* InterfaceDeclaration */) { + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -56576,7 +58811,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 166 /* TypeLiteral */) { + else if (node.parent.kind === 168 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -56584,8 +58819,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -56605,13 +58840,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 239 /* InterfaceDeclaration */ || - node.kind === 240 /* TypeAliasDeclaration */ || - node.kind === 247 /* ImportDeclaration */ || - node.kind === 246 /* ImportEqualsDeclaration */ || - node.kind === 253 /* ExportDeclaration */ || - node.kind === 252 /* ExportAssignment */ || - node.kind === 245 /* NamespaceExportDeclaration */ || + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 242 /* TypeAliasDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 255 /* ExportDeclaration */ || + node.kind === 254 /* ExportAssignment */ || + node.kind === 247 /* NamespaceExportDeclaration */ || ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -56620,7 +58855,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 === 217 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -56647,7 +58882,7 @@ var ts; // 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 === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -56669,20 +58904,32 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 180 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 276 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */; + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */; var literal = (withMinus ? "-" : "") + "0o" + node.text; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } return false; } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6 /* ESNext */) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { @@ -56727,8 +58974,8 @@ var ts; /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); @@ -56736,14 +58983,14 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 248 /* ImportClause */: // For default import - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: // For rename import `x as y` + case 250 /* ImportClause */: // For default import + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: // For rename import `x as y` return true; - case 71 /* Identifier */: + case 72 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 251 /* ImportSpecifier */; + return decl.parent.kind === 253 /* ImportSpecifier */; default: return false; } @@ -56763,7 +59010,7 @@ var ts; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); function typeIsLiteralType(type) { - return !!(type.flags & 448 /* Literal */); + return !!(type.flags & 2944 /* Literal */); } })(ts || (ts = {})); var ts; @@ -56827,6 +59074,9 @@ var ts; if (typeof value === "number") { return createNumericLiteral(value + ""); } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } @@ -56846,14 +59096,20 @@ var ts; return node; } ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9 /* BigIntLiteral */); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; function createStringLiteral(text) { - var node = createSynthesizedNode(9 /* StringLiteral */); + var node = createSynthesizedNode(10 /* StringLiteral */); node.text = text; return node; } ts.createStringLiteral = createStringLiteral; function createRegularExpressionLiteral(text) { - var node = createSynthesizedNode(12 /* RegularExpressionLiteral */); + var node = createSynthesizedNode(13 /* RegularExpressionLiteral */); node.text = text; return node; } @@ -56864,7 +59120,7 @@ var ts; return node; } function createIdentifier(text, typeArguments) { - var node = createSynthesizedNode(71 /* Identifier */); + var node = createSynthesizedNode(72 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateFlags = 0 /* None */; @@ -56945,23 +59201,23 @@ var ts; ts.createToken = createToken; // Reserved words function createSuper() { - return createSynthesizedNode(97 /* SuperKeyword */); + return createSynthesizedNode(98 /* SuperKeyword */); } ts.createSuper = createSuper; function createThis() { - return createSynthesizedNode(99 /* ThisKeyword */); + return createSynthesizedNode(100 /* ThisKeyword */); } ts.createThis = createThis; function createNull() { - return createSynthesizedNode(95 /* NullKeyword */); + return createSynthesizedNode(96 /* NullKeyword */); } ts.createNull = createNull; function createTrue() { - return createSynthesizedNode(101 /* TrueKeyword */); + return createSynthesizedNode(102 /* TrueKeyword */); } ts.createTrue = createTrue; function createFalse() { - return createSynthesizedNode(86 /* FalseKeyword */); + return createSynthesizedNode(87 /* FalseKeyword */); } ts.createFalse = createFalse; // Modifiers @@ -56972,44 +59228,44 @@ var ts; function createModifiersFromModifierFlags(flags) { var result = []; if (flags & 1 /* Export */) { - result.push(createModifier(84 /* ExportKeyword */)); + result.push(createModifier(85 /* ExportKeyword */)); } if (flags & 2 /* Ambient */) { - result.push(createModifier(124 /* DeclareKeyword */)); + result.push(createModifier(125 /* DeclareKeyword */)); } if (flags & 512 /* Default */) { - result.push(createModifier(79 /* DefaultKeyword */)); + result.push(createModifier(80 /* DefaultKeyword */)); } if (flags & 2048 /* Const */) { - result.push(createModifier(76 /* ConstKeyword */)); + result.push(createModifier(77 /* ConstKeyword */)); } if (flags & 4 /* Public */) { - result.push(createModifier(114 /* PublicKeyword */)); + result.push(createModifier(115 /* PublicKeyword */)); } if (flags & 8 /* Private */) { - result.push(createModifier(112 /* PrivateKeyword */)); + result.push(createModifier(113 /* PrivateKeyword */)); } if (flags & 16 /* Protected */) { - result.push(createModifier(113 /* ProtectedKeyword */)); + result.push(createModifier(114 /* ProtectedKeyword */)); } if (flags & 128 /* Abstract */) { - result.push(createModifier(117 /* AbstractKeyword */)); + result.push(createModifier(118 /* AbstractKeyword */)); } if (flags & 32 /* Static */) { - result.push(createModifier(115 /* StaticKeyword */)); + result.push(createModifier(116 /* StaticKeyword */)); } if (flags & 64 /* Readonly */) { - result.push(createModifier(132 /* ReadonlyKeyword */)); + result.push(createModifier(133 /* ReadonlyKeyword */)); } if (flags & 256 /* Async */) { - result.push(createModifier(120 /* AsyncKeyword */)); + result.push(createModifier(121 /* AsyncKeyword */)); } return result; } ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; // Names function createQualifiedName(left, right) { - var node = createSynthesizedNode(146 /* QualifiedName */); + var node = createSynthesizedNode(148 /* QualifiedName */); node.left = left; node.right = asName(right); return node; @@ -57028,7 +59284,7 @@ var ts; : expression; } function createComputedPropertyName(expression) { - var node = createSynthesizedNode(147 /* ComputedPropertyName */); + var node = createSynthesizedNode(149 /* ComputedPropertyName */); node.expression = parenthesizeForComputedName(expression); return node; } @@ -57041,7 +59297,7 @@ var ts; ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(148 /* TypeParameter */); + var node = createSynthesizedNode(150 /* TypeParameter */); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -57057,7 +59313,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149 /* Parameter */); + var node = createSynthesizedNode(151 /* Parameter */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -57081,7 +59337,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(150 /* Decorator */); + var node = createSynthesizedNode(152 /* Decorator */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -57094,7 +59350,7 @@ var ts; ts.updateDecorator = updateDecorator; // Type Elements function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(151 /* PropertySignature */); + var node = createSynthesizedNode(153 /* PropertySignature */); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -57114,12 +59370,12 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createSynthesizedNode(152 /* PropertyDeclaration */); + var node = createSynthesizedNode(154 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); - node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined; - node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined; + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined; node.type = type; node.initializer = initializer; return node; @@ -57129,8 +59385,8 @@ var ts; return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name - || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined) - || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined) + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) @@ -57138,7 +59394,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(153 /* MethodSignature */, typeParameters, parameters, type); + var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -57155,7 +59411,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(154 /* MethodDeclaration */); + var node = createSynthesizedNode(156 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -57183,7 +59439,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(155 /* Constructor */); + var node = createSynthesizedNode(157 /* Constructor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -57203,7 +59459,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(156 /* GetAccessor */); + var node = createSynthesizedNode(158 /* GetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57226,7 +59482,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(157 /* SetAccessor */); + var node = createSynthesizedNode(159 /* SetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57247,7 +59503,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(158 /* CallSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -57255,7 +59511,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(159 /* ConstructSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -57263,7 +59519,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(160 /* IndexSignature */); + var node = createSynthesizedNode(162 /* IndexSignature */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -57303,7 +59559,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(161 /* TypePredicate */); + var node = createSynthesizedNode(163 /* TypePredicate */); node.parameterName = asName(parameterName); node.type = type; return node; @@ -57317,7 +59573,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(162 /* TypeReference */); + var node = createSynthesizedNode(164 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -57331,7 +59587,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(163 /* FunctionType */, typeParameters, parameters, type); + return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -57339,7 +59595,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(164 /* ConstructorType */, typeParameters, parameters, type); + return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -57347,7 +59603,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(165 /* TypeQuery */); + var node = createSynthesizedNode(167 /* TypeQuery */); node.exprName = exprName; return node; } @@ -57359,7 +59615,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(166 /* TypeLiteral */); + var node = createSynthesizedNode(168 /* TypeLiteral */); node.members = createNodeArray(members); return node; } @@ -57371,7 +59627,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(167 /* ArrayType */); + var node = createSynthesizedNode(169 /* ArrayType */); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -57383,7 +59639,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(168 /* TupleType */); + var node = createSynthesizedNode(170 /* TupleType */); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -57395,7 +59651,7 @@ var ts; } ts.updateTupleTypeNode = updateTupleTypeNode; function createOptionalTypeNode(type) { - var node = createSynthesizedNode(169 /* OptionalType */); + var node = createSynthesizedNode(171 /* OptionalType */); node.type = ts.parenthesizeArrayTypeMember(type); return node; } @@ -57407,7 +59663,7 @@ var ts; } ts.updateOptionalTypeNode = updateOptionalTypeNode; function createRestTypeNode(type) { - var node = createSynthesizedNode(170 /* RestType */); + var node = createSynthesizedNode(172 /* RestType */); node.type = type; return node; } @@ -57419,7 +59675,7 @@ var ts; } ts.updateRestTypeNode = updateRestTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(171 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(173 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -57427,7 +59683,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(172 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -57446,7 +59702,7 @@ var ts; : node; } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createSynthesizedNode(173 /* ConditionalType */); + var node = createSynthesizedNode(175 /* ConditionalType */); node.checkType = ts.parenthesizeConditionalTypeMember(checkType); node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); node.trueType = trueType; @@ -57464,7 +59720,7 @@ var ts; } ts.updateConditionalTypeNode = updateConditionalTypeNode; function createInferTypeNode(typeParameter) { - var node = createSynthesizedNode(174 /* InferType */); + var node = createSynthesizedNode(176 /* InferType */); node.typeParameter = typeParameter; return node; } @@ -57476,7 +59732,7 @@ var ts; } ts.updateInferTypeNode = updateInferTypeNode; function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { - var node = createSynthesizedNode(181 /* ImportType */); + var node = createSynthesizedNode(183 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = asNodeArray(typeArguments); @@ -57494,7 +59750,7 @@ var ts; } ts.updateImportTypeNode = updateImportTypeNode; function createParenthesizedType(type) { - var node = createSynthesizedNode(175 /* ParenthesizedType */); + var node = createSynthesizedNode(177 /* ParenthesizedType */); node.type = type; return node; } @@ -57506,12 +59762,12 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(176 /* ThisType */); + return createSynthesizedNode(178 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; function createTypeOperatorNode(operatorOrType, type) { - var node = createSynthesizedNode(177 /* TypeOperator */); - node.operator = typeof operatorOrType === "number" ? operatorOrType : 128 /* KeyOfKeyword */; + var node = createSynthesizedNode(179 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */; node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } @@ -57521,7 +59777,7 @@ var ts; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(178 /* IndexedAccessType */); + var node = createSynthesizedNode(180 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -57535,7 +59791,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(179 /* MappedType */); + var node = createSynthesizedNode(181 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -57553,7 +59809,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(180 /* LiteralType */); + var node = createSynthesizedNode(182 /* LiteralType */); node.literal = literal; return node; } @@ -57566,7 +59822,7 @@ var ts; ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(182 /* ObjectBindingPattern */); + var node = createSynthesizedNode(184 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -57578,7 +59834,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(183 /* ArrayBindingPattern */); + var node = createSynthesizedNode(185 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -57590,7 +59846,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(184 /* BindingElement */); + var node = createSynthesizedNode(186 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -57609,7 +59865,7 @@ var ts; ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(185 /* ArrayLiteralExpression */); + var node = createSynthesizedNode(187 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -57623,7 +59879,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(186 /* ObjectLiteralExpression */); + var node = createSynthesizedNode(188 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -57637,7 +59893,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(187 /* PropertyAccessExpression */); + var node = createSynthesizedNode(189 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); @@ -57654,7 +59910,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(188 /* ElementAccessExpression */); + var node = createSynthesizedNode(190 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -57668,7 +59924,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(189 /* CallExpression */); + var node = createSynthesizedNode(191 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -57684,7 +59940,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(190 /* NewExpression */); + var node = createSynthesizedNode(192 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -57700,7 +59956,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { - var node = createSynthesizedNode(191 /* TaggedTemplateExpression */); + var node = createSynthesizedNode(193 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); if (template) { node.typeArguments = asNodeArray(typeArgumentsOrTemplate); @@ -57723,7 +59979,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(192 /* TypeAssertionExpression */); + var node = createSynthesizedNode(194 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -57737,7 +59993,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(193 /* ParenthesizedExpression */); + var node = createSynthesizedNode(195 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -57749,7 +60005,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(194 /* FunctionExpression */); + var node = createSynthesizedNode(196 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -57773,12 +60029,12 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(195 /* ArrowFunction */); + var node = createSynthesizedNode(197 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(36 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */); node.body = ts.parenthesizeConciseBody(body); return node; } @@ -57795,7 +60051,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(196 /* DeleteExpression */); + var node = createSynthesizedNode(198 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57807,7 +60063,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(197 /* TypeOfExpression */); + var node = createSynthesizedNode(199 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57819,7 +60075,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(198 /* VoidExpression */); + var node = createSynthesizedNode(200 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57831,7 +60087,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(199 /* AwaitExpression */); + var node = createSynthesizedNode(201 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57843,7 +60099,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(200 /* PrefixUnaryExpression */); + var node = createSynthesizedNode(202 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -57856,7 +60112,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(201 /* PostfixUnaryExpression */); + var node = createSynthesizedNode(203 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -57869,7 +60125,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(202 /* BinaryExpression */); + var node = createSynthesizedNode(204 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -57886,11 +60142,11 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(203 /* ConditionalExpression */); + var node = createSynthesizedNode(205 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); - node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); - node.colonToken = whenFalse ? colonToken : createToken(56 /* ColonToken */); + node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */); node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); return node; } @@ -57906,7 +60162,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(204 /* TemplateExpression */); + var node = createSynthesizedNode(206 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -57920,33 +60176,33 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createTemplateHead(text) { - var node = createSynthesizedNode(14 /* TemplateHead */); + var node = createSynthesizedNode(15 /* TemplateHead */); node.text = text; return node; } ts.createTemplateHead = createTemplateHead; function createTemplateMiddle(text) { - var node = createSynthesizedNode(15 /* TemplateMiddle */); + var node = createSynthesizedNode(16 /* TemplateMiddle */); node.text = text; return node; } ts.createTemplateMiddle = createTemplateMiddle; function createTemplateTail(text) { - var node = createSynthesizedNode(16 /* TemplateTail */); + var node = createSynthesizedNode(17 /* TemplateTail */); node.text = text; return node; } ts.createTemplateTail = createTemplateTail; function createNoSubstitutionTemplateLiteral(text) { - var node = createSynthesizedNode(13 /* NoSubstitutionTemplateLiteral */); + var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */); node.text = text; return node; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(205 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + var node = createSynthesizedNode(207 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; } ts.createYield = createYield; @@ -57958,7 +60214,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(206 /* SpreadElement */); + var node = createSynthesizedNode(208 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -57970,7 +60226,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(207 /* ClassExpression */); + var node = createSynthesizedNode(209 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57991,11 +60247,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(208 /* OmittedExpression */); + return createSynthesizedNode(210 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(209 /* ExpressionWithTypeArguments */); + var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -58009,7 +60265,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(210 /* AsExpression */); + var node = createSynthesizedNode(212 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -58023,7 +60279,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(211 /* NonNullExpression */); + var node = createSynthesizedNode(213 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -58035,7 +60291,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(212 /* MetaProperty */); + var node = createSynthesizedNode(214 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -58049,7 +60305,7 @@ var ts; ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(214 /* TemplateSpan */); + var node = createSynthesizedNode(216 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -58063,12 +60319,12 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(215 /* SemicolonClassElement */); + return createSynthesizedNode(217 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(216 /* Block */); + var block = createSynthesizedNode(218 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -58082,7 +60338,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(217 /* VariableStatement */); + var node = createSynthesizedNode(219 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -58097,11 +60353,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(218 /* EmptyStatement */); + return createSynthesizedNode(220 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; function createExpressionStatement(expression) { - var node = createSynthesizedNode(219 /* ExpressionStatement */); + var node = createSynthesizedNode(221 /* ExpressionStatement */); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -58117,7 +60373,7 @@ var ts; /** @deprecated Use `updateExpressionStatement` instead. */ ts.updateStatement = updateExpressionStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(220 /* IfStatement */); + var node = createSynthesizedNode(222 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -58133,7 +60389,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(221 /* DoStatement */); + var node = createSynthesizedNode(223 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -58147,7 +60403,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(222 /* WhileStatement */); + var node = createSynthesizedNode(224 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -58161,7 +60417,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(223 /* ForStatement */); + var node = createSynthesizedNode(225 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -58179,7 +60435,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(224 /* ForInStatement */); + var node = createSynthesizedNode(226 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -58195,7 +60451,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(225 /* ForOfStatement */); + var node = createSynthesizedNode(227 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -58213,7 +60469,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(226 /* ContinueStatement */); + var node = createSynthesizedNode(228 /* ContinueStatement */); node.label = asName(label); return node; } @@ -58225,7 +60481,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(227 /* BreakStatement */); + var node = createSynthesizedNode(229 /* BreakStatement */); node.label = asName(label); return node; } @@ -58237,7 +60493,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(228 /* ReturnStatement */); + var node = createSynthesizedNode(230 /* ReturnStatement */); node.expression = expression; return node; } @@ -58249,7 +60505,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(229 /* WithStatement */); + var node = createSynthesizedNode(231 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -58263,7 +60519,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(230 /* SwitchStatement */); + var node = createSynthesizedNode(232 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -58277,7 +60533,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(231 /* LabeledStatement */); + var node = createSynthesizedNode(233 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -58291,7 +60547,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(232 /* ThrowStatement */); + var node = createSynthesizedNode(234 /* ThrowStatement */); node.expression = expression; return node; } @@ -58303,7 +60559,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(233 /* TryStatement */); + var node = createSynthesizedNode(235 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -58319,11 +60575,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(234 /* DebuggerStatement */); + return createSynthesizedNode(236 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(235 /* VariableDeclaration */); + var node = createSynthesizedNode(237 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -58340,7 +60596,7 @@ var ts; ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(236 /* VariableDeclarationList */); + var node = createSynthesizedNode(238 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; @@ -58353,7 +60609,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(237 /* FunctionDeclaration */); + var node = createSynthesizedNode(239 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -58379,7 +60635,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(238 /* ClassDeclaration */); + var node = createSynthesizedNode(240 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58401,7 +60657,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(239 /* InterfaceDeclaration */); + var node = createSynthesizedNode(241 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58423,7 +60679,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(240 /* TypeAliasDeclaration */); + var node = createSynthesizedNode(242 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58443,7 +60699,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(241 /* EnumDeclaration */); + var node = createSynthesizedNode(243 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58462,7 +60718,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(242 /* ModuleDeclaration */); + var node = createSynthesizedNode(244 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -58481,7 +60737,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(243 /* ModuleBlock */); + var node = createSynthesizedNode(245 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -58493,7 +60749,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(244 /* CaseBlock */); + var node = createSynthesizedNode(246 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -58505,7 +60761,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(245 /* NamespaceExportDeclaration */); + var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -58517,7 +60773,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(246 /* ImportEqualsDeclaration */); + var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58535,7 +60791,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(247 /* ImportDeclaration */); + var node = createSynthesizedNode(249 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -58553,7 +60809,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(248 /* ImportClause */); + var node = createSynthesizedNode(250 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -58567,7 +60823,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(249 /* NamespaceImport */); + var node = createSynthesizedNode(251 /* NamespaceImport */); node.name = name; return node; } @@ -58579,7 +60835,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(250 /* NamedImports */); + var node = createSynthesizedNode(252 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -58591,7 +60847,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(251 /* ImportSpecifier */); + var node = createSynthesizedNode(253 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -58605,11 +60861,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(252 /* ExportAssignment */); + var node = createSynthesizedNode(254 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -58622,7 +60878,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(253 /* ExportDeclaration */); + var node = createSynthesizedNode(255 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -58640,7 +60896,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(254 /* NamedExports */); + var node = createSynthesizedNode(256 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -58652,7 +60908,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(255 /* ExportSpecifier */); + var node = createSynthesizedNode(257 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -58667,7 +60923,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(257 /* ExternalModuleReference */); + var node = createSynthesizedNode(259 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -58678,9 +60934,57 @@ var ts; : node; } ts.updateExternalModuleReference = updateExternalModuleReference; + // JSDoc + /* @internal */ + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + /* @internal */ + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + /* @internal */ + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + /* @internal */ + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + /* @internal */ + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291 /* JSDocComment */); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + /* @internal */ + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(258 /* JsxElement */); + var node = createSynthesizedNode(260 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -58696,7 +61000,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); + var node = createSynthesizedNode(261 /* JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -58712,7 +61016,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(260 /* JsxOpeningElement */); + var node = createSynthesizedNode(262 /* JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -58728,7 +61032,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(261 /* JsxClosingElement */); + var node = createSynthesizedNode(263 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -58740,7 +61044,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxFragment(openingFragment, children, closingFragment) { - var node = createSynthesizedNode(262 /* JsxFragment */); + var node = createSynthesizedNode(264 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -58756,7 +61060,7 @@ var ts; } ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(265 /* JsxAttribute */); + var node = createSynthesizedNode(267 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -58770,7 +61074,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(266 /* JsxAttributes */); + var node = createSynthesizedNode(268 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -58782,7 +61086,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(267 /* JsxSpreadAttribute */); + var node = createSynthesizedNode(269 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -58794,7 +61098,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(268 /* JsxExpression */); + var node = createSynthesizedNode(270 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -58808,7 +61112,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(269 /* CaseClause */); + var node = createSynthesizedNode(271 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -58822,7 +61126,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(270 /* DefaultClause */); + var node = createSynthesizedNode(272 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -58834,7 +61138,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(271 /* HeritageClause */); + var node = createSynthesizedNode(273 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -58847,7 +61151,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(272 /* CatchClause */); + var node = createSynthesizedNode(274 /* CatchClause */); node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -58862,7 +61166,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(273 /* PropertyAssignment */); + var node = createSynthesizedNode(275 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = ts.parenthesizeExpressionForList(initializer); @@ -58877,7 +61181,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(274 /* ShorthandPropertyAssignment */); + var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -58891,7 +61195,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(275 /* SpreadAssignment */); + var node = createSynthesizedNode(277 /* SpreadAssignment */); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } @@ -58904,7 +61208,7 @@ var ts; ts.updateSpreadAssignment = updateSpreadAssignment; // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(276 /* EnumMember */); + var node = createSynthesizedNode(278 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -58925,7 +61229,7 @@ var ts; (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { - var updated = createSynthesizedNode(277 /* SourceFile */); + var updated = createSynthesizedNode(279 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -59009,7 +61313,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(305 /* NotEmittedStatement */); + var node = createSynthesizedNode(307 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -59021,7 +61325,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -59033,7 +61337,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(308 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -59048,7 +61352,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -59064,17 +61368,17 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 307 /* CommaListExpression */) { + if (node.kind === 309 /* CommaListExpression */) { return node.elements; } - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { return [node.left, node.right]; } } return node; } function createCommaList(elements) { - var node = createSynthesizedNode(307 /* CommaListExpression */); + var node = createSynthesizedNode(309 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -59087,14 +61391,14 @@ var ts; ts.updateCommaList = updateCommaList; function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = ts.createNode(278 /* Bundle */); + var node = ts.createNode(280 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; function createUnparsedSourceFile(text, mapPath, map) { - var node = ts.createNode(279 /* UnparsedSource */); + var node = ts.createNode(281 /* UnparsedSource */); node.text = text; node.sourceMapPath = mapPath; node.sourceMapText = map; @@ -59102,7 +61406,7 @@ var ts; } ts.createUnparsedSourceFile = createUnparsedSourceFile; function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { - var node = ts.createNode(280 /* InputFiles */); + var node = ts.createNode(282 /* InputFiles */); node.javascriptText = javascript; node.javascriptMapPath = javascriptMapPath; node.javascriptMapText = javascriptMapText; @@ -59144,47 +61448,47 @@ var ts; } ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { - return createBinary(left, 26 /* CommaToken */, right); + return createBinary(left, 27 /* CommaToken */, right); } ts.createComma = createComma; function createLessThan(left, right) { - return createBinary(left, 27 /* LessThanToken */, right); + return createBinary(left, 28 /* LessThanToken */, right); } ts.createLessThan = createLessThan; function createAssignment(left, right) { - return createBinary(left, 58 /* EqualsToken */, right); + return createBinary(left, 59 /* EqualsToken */, right); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 34 /* EqualsEqualsEqualsToken */, right); + return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 35 /* ExclamationEqualsEqualsToken */, right); + return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 37 /* PlusToken */, right); + return createBinary(left, 38 /* PlusToken */, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 38 /* MinusToken */, right); + return createBinary(left, 39 /* MinusToken */, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand) { - return createPostfix(operand, 43 /* PlusPlusToken */); + return createPostfix(operand, 44 /* PlusPlusToken */); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 53 /* AmpersandAmpersandToken */, right); + return createBinary(left, 54 /* AmpersandAmpersandToken */, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 54 /* BarBarToken */, right); + return createBinary(left, 55 /* BarBarToken */, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(51 /* ExclamationToken */, operand); + return createPrefix(52 /* ExclamationToken */, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { @@ -59245,7 +61549,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -59756,7 +62060,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 231 /* LabeledStatement */ + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -59768,19 +62072,20 @@ var ts; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = ts.skipParentheses(node); switch (target.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return cacheIdentifiers; - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: return false; - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -59795,7 +62100,7 @@ var ts; thisArg = ts.createThis(); target = callee; } - else if (callee.kind === 97 /* SuperKeyword */) { + else if (callee.kind === 98 /* SuperKeyword */) { thisArg = ts.createThis(); target = languageVersion < 2 /* ES2015 */ ? ts.setTextRange(ts.createIdentifier("_super"), callee) @@ -59807,7 +62112,7 @@ var ts; } else { switch (callee.kind) { - case 187 /* PropertyAccessExpression */: { + case 189 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -59820,7 +62125,7 @@ var ts; } break; } - case 188 /* ElementAccessExpression */: { + case 190 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -59877,14 +62182,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -59892,7 +62197,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_9 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -59903,7 +62208,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_9.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -59915,15 +62220,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_9.push(setter); + properties_8.push(setter); } - properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_9, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -60161,6 +62466,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +62494,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -60207,7 +62515,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 193 /* ParenthesizedExpression */) { + if (skipped.kind === 195 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -60241,10 +62549,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -60256,7 +62564,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 205 /* YieldExpression */) { + && operand.kind === 207 /* YieldExpression */) { return false; } return true; @@ -60293,7 +62601,7 @@ var ts; // the same kind (recursively). // "a"+(1+2) => "a"+(1+2) // "a"+("b"+"c") => "a"+"b"+"c" - if (binaryOperator === 37 /* PlusToken */) { + if (binaryOperator === 38 /* PlusToken */) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -60328,10 +62636,10 @@ var ts; // // While addition is associative in mathematics, JavaScript's `+` is not // guaranteed to be associative as it is overloaded with string concatenation. - return binaryOperator === 39 /* AsteriskToken */ - || binaryOperator === 49 /* BarToken */ - || binaryOperator === 48 /* AmpersandToken */ - || binaryOperator === 50 /* CaretToken */; + return binaryOperator === 40 /* AsteriskToken */ + || binaryOperator === 50 /* BarToken */ + || binaryOperator === 49 /* AmpersandToken */ + || binaryOperator === 51 /* CaretToken */; } /** * This function determines whether an expression consists of a homogeneous set of @@ -60344,7 +62652,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -60359,7 +62667,7 @@ var ts; return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(203 /* ConditionalExpression */, 55 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { @@ -60394,8 +62702,8 @@ var ts; var needsParens = isCommaSequence(check); if (!needsParens) { switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: needsParens = true; } } @@ -60411,9 +62719,9 @@ var ts; function parenthesizeForNew(expression) { var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return ts.createParen(expression); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return !leftmostExpr.arguments ? ts.createParen(expression) : expression; @@ -60436,7 +62744,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 190 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -60474,7 +62782,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, 26 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -60485,29 +62793,29 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 194 /* FunctionExpression */ || kind === 195 /* ArrowFunction */) { + if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 186 /* ObjectLiteralExpression */ || leftmostExpressionKind === 194 /* FunctionExpression */) { + if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeConditionalTypeMember(member) { - return member.kind === 173 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; } ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return ts.createParenthesizedType(member); } return parenthesizeConditionalTypeMember(member); @@ -60515,9 +62823,9 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 165 /* TypeQuery */: - case 177 /* TypeOperator */: - case 174 /* InferType */: + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 176 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -60543,28 +62851,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: node = node.operand; continue; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: node = node.left; continue; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: node = node.condition; continue; - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: node = node.tag; continue; - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 210 /* AsExpression */: - case 188 /* ElementAccessExpression */: - case 187 /* PropertyAccessExpression */: - case 211 /* NonNullExpression */: - case 306 /* PartiallyEmittedExpression */: + case 212 /* AsExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 213 /* NonNullExpression */: + case 308 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -60572,15 +62880,15 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 186 /* ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) { return ts.setTextRange(ts.createParen(body), body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { - return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || - node.kind === 307 /* CommaListExpression */; + return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 309 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; @@ -60593,13 +62901,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 211 /* NonNullExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 213 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -60624,7 +62932,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 211 /* NonNullExpression */) { + while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) { node = node.expression; } return node; @@ -60632,11 +62940,11 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 193 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); - case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -60654,7 +62962,7 @@ var ts; * the containing expression is created/updated. */ function isIgnorableParen(node) { - return node.kind === 193 /* ParenthesizedExpression */ + return node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -60719,10 +63027,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 247 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 249 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 253 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -60738,7 +63046,7 @@ var ts; */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 - if (moduleName.kind === 9 /* StringLiteral */) { + if (moduleName.kind === 10 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) || ts.getSynthesizedClone(moduleName); @@ -60841,7 +63149,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -60853,11 +63161,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -60889,12 +63197,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 149 /* Parameter */: - case 184 /* BindingElement */: + case 151 /* Parameter */: + case 186 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 206 /* SpreadElement */: - case 275 /* SpreadAssignment */: + case 208 /* SpreadElement */: + case 277 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -60906,7 +63214,7 @@ var ts; */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 184 /* BindingElement */: + case 186 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -60918,7 +63226,7 @@ var ts; : propertyName; } break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -60930,7 +63238,7 @@ var ts; : propertyName; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -60945,7 +63253,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; - return kind === 9 /* StringLiteral */ + return kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */; } /** @@ -60953,13 +63261,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -60999,11 +63307,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 182 /* ObjectBindingPattern */: - case 186 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -61164,276 +63472,276 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */) || kind === 176 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) { return node; } switch (kind) { // Names - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 149 /* Parameter */: + case 151 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 150 /* Decorator */: + case 152 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); // Type elements - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 153 /* MethodSignature */: + case 155 /* MethodSignature */: return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 155 /* Constructor */: + case 157 /* Constructor */: return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 158 /* CallSignature */: + case 160 /* CallSignature */: return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 163 /* FunctionType */: + case 165 /* FunctionType */: return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 164 /* ConstructorType */: + case 166 /* ConstructorType */: return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); - case 168 /* TupleType */: + case 170 /* TupleType */: return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 170 /* RestType */: + case 172 /* RestType */: return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 171 /* UnionType */: + case 173 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); - case 174 /* InferType */: + case 176 /* InferType */: return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 181 /* ImportType */: + case 183 /* ImportType */: return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 179 /* MappedType */: + case 181 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); // Binding patterns - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); // Expression - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 210 /* AsExpression */: + case 212 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 216 /* Block */: + case 218 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 250 /* NamedImports */: + case 252 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 254 /* NamedExports */: + case 256 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 255 /* ExportSpecifier */: + case 257 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -61475,58 +63783,58 @@ var ts; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 161 /* TypePredicate */ && kind <= 180 /* LiteralType */)) { + if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 215 /* SemicolonClassElement */: - case 218 /* EmptyStatement */: - case 208 /* OmittedExpression */: - case 234 /* DebuggerStatement */: - case 305 /* NotEmittedStatement */: + case 217 /* SemicolonClassElement */: + case 220 /* EmptyStatement */: + case 210 /* OmittedExpression */: + case 236 /* DebuggerStatement */: + case 307 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 149 /* Parameter */: + case 151 /* Parameter */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 150 /* Decorator */: + case 152 /* Decorator */: result = reduceNode(node.expression, cbNode, result); break; // Type member - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61535,12 +63843,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 155 /* Constructor */: + case 157 /* Constructor */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61548,7 +63856,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61556,49 +63864,50 @@ var ts; result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 190 /* NewExpression */: + case 192 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNode(node.template, cbNode, result); break; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -61606,123 +63915,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 193 /* ParenthesizedExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 199 /* AwaitExpression */: - case 205 /* YieldExpression */: - case 206 /* SpreadElement */: - case 211 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 210 /* AsExpression */: + case 212 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; // Element - case 216 /* Block */: + case 218 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 221 /* DoStatement */: + case 223 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 222 /* WhileStatement */: - case 229 /* WithStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61731,7 +64040,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61739,139 +64048,140 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 250 /* NamedImports */: - case 254 /* NamedExports */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: result = reduceNode(node.openingFragment, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingFragment, cbNode, result); break; - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); // falls through - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 272 /* CatchClause */: + case 274 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 277 /* SourceFile */: + case 279 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -61944,7 +64254,7 @@ var ts; function aggregateTransformFlagsForSubtree(node) { // We do not transform ambient declarations or types, so there is no need to // recursively aggregate transform flags. - if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 209 /* ExpressionWithTypeArguments */)) { + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) { return 0 /* None */; } // Aggregate the transform flags of each child. @@ -61994,7 +64304,7 @@ var ts; }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, - __debugObjectFlags: { get: function () { return this.flags & 131072 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ @@ -62031,288 +64341,623 @@ var ts; /* @internal */ var ts; (function (ts) { - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + // Current source map file and its index in the sources list + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + // Last recorded and encoded mappings + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - // And failing that, check the disk - var text = host.readFile(path); // TODO: GH#18217 - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + // Then reencode all the updated mappings into the overall map + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } } - }; - cached.set(path, file); - return file; + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } + } + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + /** + * Tries to find the sourceMappingURL comment at the end of a file. + * @param text The source text of the file. + * @param lineStarts The line starts of the file. + */ + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + // empty + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + // Next entry is on same line - no action needed + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); } }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 /* comma */ || + mappings.charCodeAt(pos) === 59 /* semicolon */); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + // 6 digit number + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } } - ts.createSourceFileLikeCache = createSourceFileLikeCache; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - var sourcemaps; - (function (sourcemaps) { - sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; - function decode(host, mapPath, map, program, fallbackCache) { - if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } - var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; - var decodedMappings; - var generatedOrderedMappings; - var sourceOrderedMappings; - return { - getOriginalPosition: getOriginalPosition, - getGeneratedPosition: getGeneratedPosition - }; - function getGeneratedPosition(loc) { - var maps = getSourceOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { - return loc; - } - return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos - } - function getOriginalPosition(loc) { - var maps = getGeneratedOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos - } - function getSourceFileLike(fileName, location) { - // Lookup file in program, if provided - var path = ts.toPath(fileName, location, host.getCanonicalFileName); - var file = program && program.getSourceFile(path); - // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file - if (!file || file.resolvedPath !== path) { - // Otherwise check the cache (which may hit disk) - return fallbackCache.get(path); - } - return file; - } - function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { - var file = getSourceFileLike(fileName, directory); - if (!file) { - return -1; - } - return ts.getPositionOfLineAndCharacter(file, line, character); - } - function getDecodedMappings() { - return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host)); - } - function getSourceOrderedMappings() { - return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); - } - function getGeneratedOrderedMappings() { - return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); - } - function compareProcessedPositionSourcePositions(a, b) { - return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || - ts.compareValues(a.sourcePosition, b.sourcePosition); - } - function compareProcessedPositionEmittedPositions(a, b) { - return ts.compareValues(a.emittedPosition, b.emittedPosition); - } - function processPosition(position) { - var sourcePath = map.sources[position.sourceIndex]; - return { - emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), - sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), - sourcePath: sourcePath, - }; - } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : + value >= 26 && value < 52 ? 97 /* a */ + value - 26 : + value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : + value === 62 ? 43 /* plus */ : + value === 63 ? 47 /* slash */ : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : + ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : + ch === 43 /* plus */ ? 62 : + ch === 47 /* slash */ ? 63 : + -1; + } + 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; } - sourcemaps.decode = decode; - /*@internal*/ - function decodeMappings(map) { - var state = { - encodedText: map.mappings, - currentNameIndex: undefined, - sourceMapNamesLength: map.names ? map.names.length : undefined, - currentEmittedColumn: 0, - currentEmittedLine: 0, - currentSourceColumn: 0, - currentSourceLine: 0, - currentSourceIndex: 0, - decodingIndex: 0 - }; - function captureSpan() { - return { - emittedColumn: state.currentEmittedColumn, - emittedLine: state.currentEmittedLine, - sourceColumn: state.currentSourceColumn, - sourceIndex: state.currentSourceIndex, - sourceLine: state.currentSourceLine, - nameIndex: state.currentNameIndex - }; + 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 + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; } return { - get decodingIndex() { return state.decodingIndex; }, - get error() { return state.error; }, - get lastSpan() { return captureSpan(); }, - next: function () { - if (hasCompletedDecoding(state) || state.error) - return { done: true, value: undefined }; - if (!decodeSinglePosition(state)) - return { done: true, value: undefined }; - return { done: false, value: captureSpan() }; - } + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex }; } - sourcemaps.decodeMappings = decodeMappings; - function calculateDecodedMappings(map, processPosition, host) { - var decoder = decodeMappings(map); - var positions = ts.arrayFrom(decoder, processPosition); - if (decoder.error) { - if (host && host.log) { - host.log("Encountered error while decoding sourcemap: " + decoder.error); - } - return []; - } - return positions; - } - function hasCompletedDecoding(state) { - return state.decodingIndex === state.encodedText.length; - } - function decodeSinglePosition(state) { - while (state.decodingIndex < state.encodedText.length) { - var char = state.encodedText.charCodeAt(state.decodingIndex); - if (char === 59 /* semicolon */) { - // New line - state.currentEmittedLine++; - state.currentEmittedColumn = 0; - state.decodingIndex++; - continue; - } - if (char === 44 /* comma */) { - // Next entry is on same line - no action needed - state.decodingIndex++; - continue; - } - // Read the current position - // 1. Column offset from prev read jsColumn - state.currentEmittedColumn += base64VLQFormatDecode(); - // Incorrect emittedColumn dont support this map - if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { - return false; - } - // 2. Relative sourceIndex - state.currentSourceIndex += base64VLQFormatDecode(); - // Incorrect sourceIndex dont support this map - if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { - return false; - } - // Dont support reading mappings that dont have information about original source position - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { - return false; - } - // 3. Relative sourceLine 0 based - state.currentSourceLine += base64VLQFormatDecode(); - // Incorrect sourceLine dont support this map - if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { - return false; - } - // 4. Relative sourceColumn 0 based - state.currentSourceColumn += base64VLQFormatDecode(); - // Incorrect sourceColumn dont support this map - if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { - return false; - } - // 5. Check if there is name: - if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { - if (state.currentNameIndex === undefined) { - state.currentNameIndex = 0; + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); } - state.currentNameIndex += base64VLQFormatDecode(); - // Incorrect nameIndex dont support this map - // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap - // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { - // return; - // } - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { - return false; - } - // Entry should be complete - return true; - } - createErrorIfCondition(/*condition*/ true, "No encoded entry found"); - return false; - function createErrorIfCondition(condition, errormsg) { - if (state.error) { - // An error was already reported - return true; - } - if (condition) { - state.error = errormsg; - } - return condition; - } - function base64VLQFormatDecode() { - var moreDigits = true; - var shiftCount = 0; - var value = 0; - for (; moreDigits; state.decodingIndex++) { - if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return undefined; // TODO: GH#18217 - } - // 6 digit number - var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); - // If msb is set, we still have more bits to continue - moreDigits = (currentByte & 32) !== 0; - // least significant 5 bits are the next msbs in the final value. - value = value | ((currentByte & 31) << shiftCount); - shiftCount += 5; - } - // Least significant bit if 1 represents negative and rest of the msb is actual absolute value - if ((value & 1) === 0) { - // + number - value = value >> 1; + decodedMappings = ts.emptyArray; } else { - // - number - value = value >> 1; - value = -value; + decodedMappings = mappings; } - return value; } + return decodedMappings; } - function base64FormatDecode(char) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; } - function isSourceMappingSegmentEnd(encodedText, pos) { - return (pos === encodedText.length || - encodedText.charCodeAt(pos) === 44 /* comma */ || - encodedText.charCodeAt(pos) === 59 /* semicolon */); + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; } - })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; })(ts || (ts = {})); /* @internal */ var ts; @@ -62335,7 +64980,7 @@ var ts; function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 277 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -62381,7 +65026,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -62389,13 +65034,13 @@ var ts; externalImports.push(node); hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; - case 246 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { + case 248 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -62425,13 +65070,13 @@ var ts; } } break; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -62439,7 +65084,7 @@ var ts; } } break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default function() { } @@ -62459,7 +65104,7 @@ var ts; } } break; - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default class { } @@ -62811,8 +65456,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62878,7 +65523,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63075,8 +65720,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -63106,14 +65751,14 @@ var ts; var pendingExpressions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 278 /* Bundle */) { + if (node.kind === 280 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280 /* InputFiles */) { + if (prepend.kind === 282 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); } return prepend; @@ -63162,16 +65807,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 277 /* SourceFile */: - case 244 /* CaseBlock */: - case 243 /* ModuleBlock */: - case 216 /* Block */: + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 245 /* ModuleBlock */: + case 218 /* Block */: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 238 /* ClassDeclaration */: - case 237 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: if (ts.hasModifier(node, 2 /* Ambient */)) { break; } @@ -63183,7 +65828,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 238 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); } if (ts.isClassDeclaration(node)) { // XXX: should probably also cover interfaces and type aliases that can have type variables? @@ -63231,10 +65876,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -63255,13 +65900,13 @@ var ts; return node; } switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -63281,11 +65926,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 253 /* ExportDeclaration */ || - node.kind === 247 /* ImportDeclaration */ || - node.kind === 248 /* ImportClause */ || - (node.kind === 246 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 257 /* ExternalModuleReference */)) { + if (node.kind === 255 /* ExportDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 250 /* ImportClause */ || + (node.kind === 248 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 259 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -63315,19 +65960,19 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 152 /* PropertyDeclaration */: - case 160 /* IndexSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); @@ -63337,7 +65982,7 @@ var ts; if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { return undefined; } - else if (currentNamespace && node.kind === 84 /* ExportKeyword */) { + else if (currentNamespace && node.kind === 85 /* ExportKeyword */) { return undefined; } return node; @@ -63354,67 +65999,67 @@ var ts; return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 133 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 169 /* OptionalType */: - case 170 /* RestType */: - case 166 /* TypeLiteral */: - case 161 /* TypePredicate */: - case 148 /* TypeParameter */: - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 105 /* VoidKeyword */: - case 138 /* SymbolKeyword */: - case 164 /* ConstructorType */: - case 163 /* FunctionType */: - case 165 /* TypeQuery */: - case 162 /* TypeReference */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 173 /* ConditionalType */: - case 175 /* ParenthesizedType */: - case 176 /* ThisType */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 180 /* LiteralType */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 168 /* TypeLiteral */: + case 163 /* TypePredicate */: + case 150 /* TypeParameter */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 123 /* BooleanKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 132 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 139 /* SymbolKeyword */: + case 166 /* ConstructorType */: + case 165 /* FunctionType */: + case 167 /* TypeQuery */: + case 164 /* TypeReference */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 177 /* ParenthesizedType */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: // TypeScript type nodes are elided. - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: // TypeScript index signatures are elided. - case 150 /* Decorator */: + case 152 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 155 /* Constructor */: + case 157 /* Constructor */: return visitConstructor(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -63425,7 +66070,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -63436,35 +66081,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 149 /* Parameter */: + case 151 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -63474,35 +66119,35 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: @@ -63539,7 +66184,7 @@ var ts; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); - if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) facts |= 2 /* HasConstructorDecorators */; @@ -63608,7 +66253,7 @@ var ts; // return C; // }(); // - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18 /* CloseBraceToken */); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */); var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -63810,7 +66455,7 @@ var ts; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85 /* ExtendsKeyword */; })); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; })); var classExpression = ts.createClassExpression( /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, heritageClauses, members); @@ -63818,7 +66463,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63866,9 +66511,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -63984,7 +66631,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -64055,7 +66702,7 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 152 /* PropertyDeclaration */ + return member.kind === 154 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } @@ -64066,8 +66713,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -64083,8 +66730,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { - var property = properties_11[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var expression = transformInitializedProperty(property, receiver); ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -64195,12 +66842,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -64353,7 +67000,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 152 /* PropertyDeclaration */ + ? member.kind === 154 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? ts.createVoidZero() @@ -64454,13 +67101,13 @@ var ts; if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); } if (properties) { decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); @@ -64476,10 +67123,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 152 /* PropertyDeclaration */; + return kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 154 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -64489,7 +67136,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 154 /* MethodDeclaration */; + return node.kind === 156 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -64500,12 +67147,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return true; } return false; @@ -64522,15 +67169,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 152 /* PropertyDeclaration */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: return serializeTypeNode(node.type); - case 157 /* SetAccessor */: - case 156 /* GetAccessor */: + case 159 /* SetAccessor */: + case 158 /* GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 154 /* MethodDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 156 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -64567,7 +67214,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 156 /* GetAccessor */) { + if (container && node.kind === 158 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -64612,77 +67259,83 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: return ts.createVoidZero(); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return ts.createIdentifier("Function"); - case 167 /* ArrayType */: - case 168 /* TupleType */: + case 169 /* ArrayType */: + case 170 /* TupleType */: return ts.createIdentifier("Array"); - case 161 /* TypePredicate */: - case 122 /* BooleanKeyword */: + case 163 /* TypePredicate */: + case 123 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: return ts.createIdentifier("String"); - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 180 /* LiteralType */: + case 182 /* LiteralType */: switch (node.literal.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return ts.createIdentifier("String"); case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 9 /* BigIntLiteral */: + return getGlobalBigIntNameWithFallback(); + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: return ts.Debug.failBadSyntaxKind(node.literal); } - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: return ts.createIdentifier("Number"); - case 138 /* SymbolKeyword */: + case 146 /* BigIntKeyword */: + return getGlobalBigIntNameWithFallback(); + case 139 /* SymbolKeyword */: return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return serializeTypeReferenceNode(node); - case 172 /* IntersectionType */: - case 171 /* UnionType */: - return serializeUnionOrIntersectionType(node); - case 165 /* TypeQuery */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 166 /* TypeLiteral */: - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 176 /* ThisType */: - case 181 /* ImportType */: + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return serializeTypeList(node.types); + case 175 /* ConditionalType */: + return serializeTypeList([node.trueType, node.falseType]); + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 168 /* TypeLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 178 /* ThisType */: + case 183 /* ImportType */: break; default: return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } - function serializeUnionOrIntersectionType(node) { + function serializeTypeList(types) { // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175 /* ParenthesizedType */) { + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } - if (typeNode.kind === 131 /* NeverKeyword */) { + if (typeNode.kind === 132 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedIndividual = serializeTypeNode(typeNode); @@ -64718,6 +67371,10 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); @@ -64725,6 +67382,8 @@ var ts; return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); case ts.TypeReferenceSerializationKind.BooleanType: return ts.createIdentifier("Boolean"); case ts.TypeReferenceSerializationKind.NumberLikeType: @@ -64756,12 +67415,12 @@ var ts; * @param node The entity name to serialize. */ function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { // A -> typeof A !== undefined && A var copied = serializeEntityNameAsExpression(node); return createCheckedValue(copied, copied); } - if (node.left.kind === 71 /* Identifier */) { + if (node.left.kind === 72 /* Identifier */) { // A.B -> typeof A !== undefined && A.B return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); } @@ -64777,7 +67436,7 @@ var ts; */ function serializeEntityNameAsExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were // a source tree node for the purposes of the checker. var name = ts.getMutableClone(node); @@ -64785,7 +67444,7 @@ var ts; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. return name; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -64806,6 +67465,15 @@ var ts; function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 /* ESNext */ + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } /** * A simple inlinable expression is an expression which can be copied into multiple locations * without risk of repeating any sideeffects and whose value could not possibly change between @@ -64886,9 +67554,9 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 85 /* ExtendsKeyword */) { + if (node.token === 86 /* ExtendsKeyword */) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(85 /* ExtendsKeyword */, types), node); + return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); } return undefined; } @@ -65284,7 +67952,7 @@ var ts; var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); var valueExpression = transformEnumMemberDeclarationValue(member); var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); - var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? innerAssignment : ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); @@ -65365,12 +68033,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 277 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 241 /* EnumDeclaration */) { + if (node.kind === 243 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -65495,7 +68163,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 243 /* ModuleBlock */) { + if (body.kind === 245 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -65541,13 +68209,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 243 /* ModuleBlock */) { + if (body.kind !== 245 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -65588,7 +68256,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 249 /* NamespaceImport */) { + if (node.kind === 251 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -65782,7 +68450,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65801,7 +68469,7 @@ var ts; function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } function enableSubstitutionForClassAliases() { @@ -65809,7 +68477,7 @@ var ts; enabledSubstitutions |= 1 /* ClassAliases */; // We need to enable substitutions for identifiers. This allows us to // substitute class names inside of a class declaration. - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); // Keep track of class aliases. classAliases = []; } @@ -65819,17 +68487,17 @@ var ts; enabledSubstitutions |= 2 /* NamespaceExports */; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. - context.enableSubstitution(71 /* Identifier */); - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); + context.enableSubstitution(72 /* Identifier */); + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(242 /* ModuleDeclaration */); + context.enableEmitNotification(244 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 242 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 241 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */; } /** * Hook for node emit. @@ -65888,11 +68556,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -65904,7 +68572,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // 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. @@ -65930,9 +68598,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 277 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 242 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 241 /* EnumDeclaration */); + if (container && container.kind !== 279 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), /*location*/ node); @@ -66044,6 +68712,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66064,19 +68740,29 @@ var ts; return node; } switch (node.kind) { - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitAwaitExpression(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66084,27 +68770,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 216 /* Block */: - case 230 /* SwitchStatement */: - case 244 /* CaseBlock */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 233 /* TryStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 220 /* IfStatement */: - case 229 /* WithStatement */: - case 231 /* LabeledStatement */: + case 218 /* Block */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 231 /* WithStatement */: + case 233 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -66305,7 +68991,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 195 /* ArrowFunction */; + var isArrowFunction = node.kind === 197 /* 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 @@ -66318,23 +69004,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66352,6 +69048,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66378,15 +69076,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(189 /* CallExpression */); - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(238 /* ClassDeclaration */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); } } /** @@ -66409,6 +69109,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66426,24 +69134,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66462,24 +69170,68 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 /* ClassDeclaration */ - || kind === 155 /* Constructor */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66489,7 +69241,7 @@ var ts; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); var generatorFunc = ts.createFunctionExpression( - /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), /*name*/ undefined, /*typeParameters*/ undefined, /*parameters*/ [], @@ -66507,12 +69259,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66535,6 +69287,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66551,7 +69309,7 @@ var ts; return visitorWorker(node, /*noDestructuringValue*/ true); } function visitorNoAsyncModifier(node) { - if (node.kind === 120 /* AsyncKeyword */) { + if (node.kind === 121 /* AsyncKeyword */) { return undefined; } return node; @@ -66561,48 +69319,58 @@ var ts; return node; } switch (node.kind) { - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitAwaitExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return visitVoidExpression(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return visitConstructorDeclaration(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: return visitGetAccessorDeclaration(node); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitParameter(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitExpressionStatement(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66635,7 +69403,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 225 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); @@ -66647,7 +69415,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 275 /* SpreadAssignment */) { + if (e.kind === 277 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -66656,7 +69424,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 273 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */ ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -66667,14 +69435,14 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); // If the first element is a spread element, then the first argument to __assign is {}: // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 186 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -66699,10 +69467,10 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } - else if (node.operatorToken.kind === 26 /* CommaToken */) { + else if (node.operatorToken.kind === 27 /* CommaToken */) { return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); @@ -66714,7 +69482,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66731,7 +69499,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66828,7 +69596,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66925,25 +69693,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( - /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66967,7 +69747,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -66987,15 +69767,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(189 /* CallExpression */); - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(238 /* ClassDeclaration */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); } } /** @@ -67018,6 +69800,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67035,24 +69825,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67071,19 +69861,19 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 /* ClassDeclaration */ - || kind === 155 /* Constructor */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67184,13 +69974,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67198,15 +69988,15 @@ var ts; } function transformJsxChildToExpression(node) { switch (node.kind) { - case 10 /* JsxText */: + case 11 /* JsxText */: return visitJsxText(node); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitJsxExpression(node); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -67274,14 +70064,14 @@ var ts; if (node === undefined) { return ts.createTrue(); } - else if (node.kind === 9 /* StringLiteral */) { + else if (node.kind === 10 /* StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); return ts.setTextRange(literal, node); } - else if (node.kind === 268 /* JsxExpression */) { + else if (node.kind === 270 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } @@ -67375,7 +70165,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 258 /* JsxElement */) { + if (node.kind === 260 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -67681,7 +70471,7 @@ var ts; return node; } switch (node.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67689,9 +70479,9 @@ var ts; } function visitBinaryExpression(node) { switch (node.operatorToken.kind) { - case 62 /* AsteriskAsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: return visitExponentiationAssignmentExpression(node); - case 40 /* AsteriskAsteriskToken */: + case 41 /* AsteriskAsteriskToken */: return visitExponentiationExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67741,6 +70531,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67914,14 +70709,14 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 228 /* ReturnStatement */ + && node.kind === 230 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -67939,104 +70734,104 @@ var ts; return node; } function callExpressionVisitor(node) { - if (node.kind === 97 /* SuperKeyword */) { + if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); } return visitor(node); } function visitJavaScript(node) { switch (node.kind) { - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: return undefined; // elide static keyword - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return visitClassExpression(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitParameter(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 71 /* Identifier */: + case 72 /* Identifier */: return visitIdentifier(node); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitCaseBlock(node); - case 216 /* Block */: + case 218 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitExpressionStatement(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node, /*needsDestructuringValue*/ true); - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: return visitTemplateLiteral(node); - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return visitTemplateExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return visitSpreadElement(node); - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return visitThisKeyword(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return visitMetaProperty(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return visitAccessorDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -68123,14 +70918,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 227 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 227 /* BreakStatement */) { + if (node.kind === 229 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -68141,7 +70936,7 @@ var ts; } } else { - if (node.kind === 227 /* BreakStatement */) { + if (node.kind === 229 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -68160,10 +70955,10 @@ var ts; expr = copyExpr; } else { - expr = ts.createBinary(expr, 26 /* CommaToken */, copyExpr); + expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr); } } - returnExpression = ts.createBinary(expr, 26 /* CommaToken */, returnExpression); + returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression); } return ts.createReturn(returnExpression); } @@ -68297,7 +71092,7 @@ var ts; addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); // Create a synthetic text range for the return statement. - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18 /* CloseBraceToken */); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */); var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -68402,7 +71197,7 @@ var ts; } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); // The last statement expression was replaced. Skip it. if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { @@ -68441,11 +71236,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 228 /* ReturnStatement */) { + if (statement.kind === 230 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 220 /* IfStatement */) { + else if (statement.kind === 222 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -68453,7 +71248,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 216 /* Block */) { + else if (statement.kind === 218 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -68511,7 +71306,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -68519,10 +71314,10 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 202 /* BinaryExpression */ - || superCallExpression.left.kind !== 189 /* CallExpression */) { + if (superCallExpression.kind !== 204 /* BinaryExpression */ + || superCallExpression.left.kind !== 191 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } // Shift comments from the original super call to the return statement. @@ -68590,7 +71385,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68667,7 +71462,7 @@ var ts; * synthesized call to `super` */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 71 /* Identifier */ && !inConstructorWithSynthesizedSuper; + return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; } /** * Adds statements to the body of a function-like node if it contains a rest parameter. @@ -68719,7 +71514,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68738,25 +71533,25 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return statements; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = ts.createVoidZero(); break; - case 155 /* Constructor */: + case 157 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. - newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); break; default: return ts.Debug.failBadSyntaxKind(node); @@ -68784,20 +71579,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 155 /* Constructor */: + case 157 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -68907,7 +71702,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -68989,7 +71784,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 237 /* FunctionDeclaration */ || node.kind === 194 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); @@ -69034,7 +71829,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 195 /* ArrowFunction */); + ts.Debug.assert(node.kind === 197 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -69072,7 +71867,7 @@ var ts; ts.setEmitFlags(block, 1 /* SingleLine */); } if (closeBraceLocation) { - ts.setTokenSourceMapRange(block, 18 /* CloseBraceToken */, closeBraceLocation); + ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -69102,9 +71897,9 @@ var ts; function visitExpressionStatement(node) { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); @@ -69123,9 +71918,9 @@ var ts; // expression. If we are in a state where we do not need the destructuring value, // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } @@ -69160,7 +71955,7 @@ var ts; assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); } else { - assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); @@ -69197,19 +71992,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69257,8 +72060,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69326,14 +72129,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -69513,11 +72316,11 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 147 /* ComputedPropertyName */) { + if (property.name.kind === 149 /* ComputedPropertyName */) { numInitialProperties = i; break; } @@ -69544,7 +72347,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69556,7 +72375,7 @@ var ts; } visit(node.name); function visit(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { state.hoistedLocalVariables.push(node); } else { @@ -69570,7 +72389,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69586,14 +72405,76 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 236 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 238 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -69603,165 +72484,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // 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 - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.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 = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.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'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 58 /* EqualsToken */, source); + return ts.createBinary(target, 59 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69769,38 +72761,38 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); } if (state.nonLocalJumps & 2 /* Break */) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69840,21 +72832,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69873,20 +72873,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -69994,10 +72994,10 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -70173,15 +73173,15 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || - node.expression.kind === 97 /* SuperKeyword */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70210,7 +73210,7 @@ var ts; resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { var actualThis = ts.createThis(); ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); var initializer = ts.createLogicalOr(resultingCall, actualThis); @@ -70228,7 +73228,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70275,7 +73275,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 185 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -70392,7 +73392,7 @@ var ts; // thus we need to remove those characters. // First template piece starts with "`", others with "}" // Last template piece ends with "`", others with "${" - var isLast = node.kind === 13 /* NoSubstitutionTemplateLiteral */ || node.kind === 16 /* TemplateTail */; + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; text = text.substring(1, text.length - (isLast ? 1 : 2)); // Newline normalization: // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's @@ -70490,7 +73490,7 @@ var ts; : ts.createFileLevelUniqueName("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") { + if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { if (hierarchyFacts & 8192 /* ComputedPropertyName */) { hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; } @@ -70527,7 +73527,7 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } /** @@ -70537,14 +73537,14 @@ var ts; function enableSubstitutionsForCapturedThis() { if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; - context.enableSubstitution(99 /* ThisKeyword */); - context.enableEmitNotification(155 /* Constructor */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(195 /* ArrowFunction */); - context.enableEmitNotification(194 /* FunctionExpression */); - context.enableEmitNotification(237 /* FunctionDeclaration */); + context.enableSubstitution(100 /* ThisKeyword */); + context.enableEmitNotification(157 /* Constructor */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(197 /* ArrowFunction */); + context.enableEmitNotification(196 /* FunctionExpression */); + context.enableEmitNotification(239 /* FunctionDeclaration */); } } /** @@ -70585,10 +73585,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 237 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -70601,9 +73601,9 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return substituteThisKeyword(node); } return node; @@ -70670,19 +73670,19 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 219 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 189 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 97 /* SuperKeyword */) { + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) { return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 206 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -70710,7 +73710,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -70735,15 +73735,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(260 /* JsxOpeningElement */); - context.enableEmitNotification(261 /* JsxClosingElement */); - context.enableEmitNotification(259 /* JsxSelfClosingElement */); + context.enableEmitNotification(262 /* JsxOpeningElement */); + context.enableEmitNotification(263 /* JsxClosingElement */); + context.enableEmitNotification(261 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(273 /* PropertyAssignment */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(275 /* PropertyAssignment */); return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -70762,9 +73762,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -70821,7 +73821,7 @@ var ts; */ function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { + if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -71096,13 +74096,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitWhileStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -71115,30 +74115,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return visitAccessorDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return visitBreakStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return visitContinueStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71153,21 +74153,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return visitConditionalExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -71180,9 +74180,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -71341,7 +74341,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71381,23 +74381,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 59 /* FirstCompoundAssignment */ - && kind <= 70 /* LastCompoundAssignment */; + return kind >= 60 /* FirstCompoundAssignment */ + && kind <= 71 /* LastCompoundAssignment */; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 59 /* PlusEqualsToken */: return 37 /* PlusToken */; - case 60 /* MinusEqualsToken */: return 38 /* MinusToken */; - case 61 /* AsteriskEqualsToken */: return 39 /* AsteriskToken */; - case 62 /* AsteriskAsteriskEqualsToken */: return 40 /* AsteriskAsteriskToken */; - case 63 /* SlashEqualsToken */: return 41 /* SlashToken */; - case 64 /* PercentEqualsToken */: return 42 /* PercentToken */; - case 65 /* LessThanLessThanEqualsToken */: return 45 /* LessThanLessThanToken */; - case 66 /* GreaterThanGreaterThanEqualsToken */: return 46 /* GreaterThanGreaterThanToken */; - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanGreaterThanToken */; - case 68 /* AmpersandEqualsToken */: return 48 /* AmpersandToken */; - case 69 /* BarEqualsToken */: return 49 /* BarToken */; - case 70 /* CaretEqualsToken */: return 50 /* CaretToken */; + case 60 /* PlusEqualsToken */: return 38 /* PlusToken */; + case 61 /* MinusEqualsToken */: return 39 /* MinusToken */; + case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */; + case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */; + case 64 /* SlashEqualsToken */: return 42 /* SlashToken */; + case 65 /* PercentEqualsToken */: return 43 /* PercentToken */; + case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */; + case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */; + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */; + case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */; + case 70 /* BarEqualsToken */: return 50 /* BarToken */; + case 71 /* CaretEqualsToken */: return 51 /* CaretToken */; } } /** @@ -71410,7 +74410,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -71422,7 +74422,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -71454,7 +74454,7 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 26 /* CommaToken */) { + else if (node.operatorToken.kind === 27 /* CommaToken */) { return visitCommaExpression(node); } // [source] @@ -71465,10 +74465,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71509,7 +74509,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { // Logical `&&` shortcuts when the left-hand operand is falsey. emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); } @@ -71540,7 +74540,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { visit(node.left); visit(node.right); } @@ -71729,10 +74729,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -71798,35 +74798,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 216 /* Block */: + case 218 /* Block */: return transformAndEmitBlock(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return transformAndEmitIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return transformAndEmitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return transformAndEmitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return transformAndEmitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -72256,7 +75256,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 270 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -72269,7 +75269,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 269 /* CaseClause */) { + if (clause.kind === 271 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -72399,7 +75399,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72431,10 +75431,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -72581,7 +75581,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = []; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } renamedCatchVariables.set(text, true); renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -73497,12 +76497,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -73516,7 +76516,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +76573,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +76604,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73824,23 +76830,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 308 /* MergeDeclarationMarker */: + case 310 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 309 /* EndOfDeclarationMarker */: + case 311 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -73849,7 +76855,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73867,24 +76873,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -73916,7 +76922,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74362,7 +77368,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -74417,10 +77423,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -74602,8 +77608,8 @@ var ts; function modifierVisitor(node) { // Elide module-specific modifiers. switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: return undefined; } return node; @@ -74619,7 +77625,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -74681,12 +77687,12 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return substituteBinaryExpression(node); - case 201 /* PostfixUnaryExpression */: - case 200 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -74707,7 +77713,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -74775,15 +77781,15 @@ var ts; // - We do not substitute identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only substitute identifiers that are exported at the top level. - if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 /* PostfixUnaryExpression */ - ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { @@ -74857,12 +77863,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -74881,7 +77887,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75083,7 +78089,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 253 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -75108,7 +78114,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 253 /* ExportDeclaration */) { + if (externalImport.kind !== 255 /* ExportDeclaration */) { continue; } if (!externalImport.exportClause) { @@ -75186,19 +78192,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -75248,15 +78254,15 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: // ExportDeclarations are elided as they are handled via // `appendExportsOfDeclaration`. return undefined; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -75432,7 +78438,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 277 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -75496,7 +78502,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -75558,10 +78564,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -75741,43 +78747,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitWhileStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return visitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitCaseBlock(node); - case 269 /* CaseClause */: + case 271 /* CaseClause */: return visitCaseClause(node); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return visitDefaultClause(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return visitTryStatement(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); - case 216 /* Block */: + case 218 /* Block */: return visitBlock(node); - case 308 /* MergeDeclarationMarker */: + case 310 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 309 /* EndOfDeclarationMarker */: + case 311 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -75960,13 +78966,13 @@ var ts; */ function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 202 /* BinaryExpression */) { + && node.kind === 204 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76025,7 +79031,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 277 /* SourceFile */; + return container !== undefined && container.kind === 279 /* SourceFile */; } else { return false; @@ -76041,8 +79047,8 @@ var ts; */ function modifierVisitor(node) { switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: return undefined; } return node; @@ -76058,7 +79064,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -76106,7 +79112,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -76140,12 +79146,12 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return substituteBinaryExpression(node); - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -76231,22 +79237,22 @@ var ts; // - We do not substitute identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only substitute identifiers that are exported at the top level. - if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 /* PostfixUnaryExpression */ + var expression = node.kind === 203 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 201 /* PostfixUnaryExpression */) { - expression = node.operator === 43 /* PlusPlusToken */ + if (node.kind === 203 /* PostfixUnaryExpression */) { + expression = node.operator === 44 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); } @@ -76267,7 +79273,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -76306,8 +79312,8 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(277 /* SourceFile */); - context.enableSubstitution(71 /* Identifier */); + context.enableEmitNotification(279 /* SourceFile */); + context.enableSubstitution(72 /* Identifier */); var currentSourceFile; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { @@ -76335,10 +79341,10 @@ var ts; } function visitor(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); } return node; @@ -76445,7 +79451,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* 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 : @@ -76474,7 +79480,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -76521,7 +79527,7 @@ var ts; return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { 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 : @@ -76530,8 +79536,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 152 /* PropertyDeclaration */ || node.kind === 151 /* PropertySignature */ || - (node.kind === 149 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -76540,7 +79546,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */ || node.kind === 149 /* Parameter */) { + else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -76565,7 +79571,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 157 /* SetAccessor */) { + if (node.kind === 159 /* SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.hasModifier(node, 32 /* Static */)) { @@ -76604,26 +79610,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named 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 158 /* CallSignature */: + case 160 /* CallSignature */: // Interfaces cannot have return types that cannot be named 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 160 /* IndexSignature */: + case 162 /* IndexSignature */: // Interfaces cannot have return types that cannot be named 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 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -76631,7 +79637,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* 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 : @@ -76645,7 +79651,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 237 /* FunctionDeclaration */: + case 239 /* 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 : @@ -76670,30 +79676,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 155 /* Constructor */: + case 157 /* 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 159 /* ConstructSignature */: - case 164 /* ConstructorType */: + case 161 /* ConstructSignature */: + case 166 /* ConstructorType */: // Interfaces cannot have parameter types that cannot be named 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 158 /* CallSignature */: + case 160 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named 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 160 /* IndexSignature */: + case 162 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -76701,7 +79707,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 240 /* 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 : @@ -76714,8 +79720,8 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 237 /* FunctionDeclaration */: - case 163 /* FunctionType */: + case 239 /* FunctionDeclaration */: + case 165 /* FunctionType */: 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 : @@ -76729,34 +79735,34 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 158 /* CallSignature */: + case 160 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node.parent, 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 === 238 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 240 /* 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 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -76771,9 +79777,9 @@ var ts; function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + if (node.parent.parent.kind === 240 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ? 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; } @@ -76808,11 +79814,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +79844,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76849,6 +79855,7 @@ var ts; reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode @@ -76856,6 +79863,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +79873,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76936,16 +79944,22 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } - if (node.kind === 278 /* Bundle */) { + if (node.kind === 280 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,23 +79971,25 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280 /* InputFiles */) { + if (prepend.kind === 282 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +80008,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +80021,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77038,7 +80058,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77046,13 +80066,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,12 +80087,21 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { return name; } else { - if (name.kind === 183 /* ArrayBindingPattern */) { + if (name.kind === 185 /* ArrayBindingPattern */) { return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -77075,7 +80109,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 208 /* OmittedExpression */) { + if (elem.kind === 210 /* OmittedExpression */) { return elem; } return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -77088,7 +80122,7 @@ var ts; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } var newParam = ts.updateParameter(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -77100,7 +80134,7 @@ var ts; } function ensureNoInitializer(node) { if (shouldPrintWithInitializer(node)) { - return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe } return undefined; } @@ -77113,19 +80147,19 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 149 /* Parameter */ && + var shouldUseResolverType = node.kind === 151 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { return ts.visitNode(type, visitDeclarationSubtree); } if (!ts.getParseTreeNode(node)) { - return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */); } - if (node.kind === 157 /* SetAccessor */) { + if (node.kind === 159 /* SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } errorNameNode = node.name; var oldDiag; @@ -77133,12 +80167,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 149 /* Parameter */ - || node.kind === 152 /* PropertyDeclaration */ - || node.kind === 151 /* PropertySignature */) { + if (node.kind === 151 /* Parameter */ + || node.kind === 154 /* PropertyDeclaration */ + || node.kind === 153 /* PropertySignature */) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -77149,26 +80183,26 @@ var ts; if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } - return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */); + return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */); } } function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: return false; } return false; @@ -77222,7 +80256,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -77242,7 +80276,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 257 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return ts.updateImportEqualsDeclaration(decl, @@ -77269,7 +80303,7 @@ var ts; return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -77374,68 +80408,68 @@ var ts; checkEntityNameVisibility(input.exprName, enclosingDeclaration); } var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 /* TypeLiteral */ || input.kind === 179 /* MappedType */) && input.parent.kind !== 240 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */); if (shouldEnterSuppressNewDiagnosticsContextContext) { // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. suppressNewDiagnosticContexts = true; } if (isProcessedComponent(input)) { switch (input.kind) { - case 209 /* ExpressionWithTypeArguments */: { + case 211 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); } - case 162 /* TypeReference */: { + case 164 /* TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); } - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 155 /* Constructor */: { + case 157 /* Constructor */: { var isPrivate = ts.hasModifier(input, 8 /* Private */); // A constructor declaration may not have a type annotation - var ctor = ts.createSignatureDeclaration(155 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), // TODO: GH#18217 isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), /*type*/ undefined); ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); return cleanup(ctor); } - case 154 /* MethodDeclaration */: { - var sig = ts.createSignatureDeclaration(153 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + case 156 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); sig.name = input.name; sig.modifiers = ts.createNodeArray(ensureModifiers(input)); sig.questionToken = input.questionToken; return cleanup(sig); } - case 156 /* GetAccessor */: { + case 158 /* GetAccessor */: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 157 /* SetAccessor */: { + case 159 /* SetAccessor */: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return cleanup(ts.updateProperty(input, /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 153 /* MethodSignature */: { + case 155 /* MethodSignature */: { return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); } - case 158 /* CallSignature */: { + case 160 /* CallSignature */: { return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 160 /* IndexSignature */: { + case 162 /* IndexSignature */: { return cleanup(ts.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */))); } - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -77443,13 +80477,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); } - case 148 /* TypeParameter */: { + case 150 /* TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 173 /* ConditionalType */: { + case 175 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -77461,13 +80495,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 163 /* FunctionType */: { + case 165 /* FunctionType */: { return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 164 /* ConstructorType */: { + case 166 /* ConstructorType */: { return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 181 /* ImportType */: { + case 183 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -77496,7 +80530,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 154 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -77506,7 +80540,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 253 /* ExportDeclaration */: { + case 255 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; @@ -77515,13 +80549,13 @@ var ts; // Rewrite external module names if necessary return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 252 /* ExportAssignment */: { + case 254 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; } - if (input.expression.kind === 71 /* Identifier */) { + if (input.expression.kind === 72 /* Identifier */) { return input; } else { @@ -77531,7 +80565,7 @@ var ts; errorNode: input }); }; var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } @@ -77545,10 +80579,10 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 246 /* ImportEqualsDeclaration */: { + case 248 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 247 /* ImportDeclaration */: { + case 249 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -77569,24 +80603,39 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 240 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(ts.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 239 /* InterfaceDeclaration */: { + case 241 /* InterfaceDeclaration */: { return cleanup(ts.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 237 /* FunctionDeclaration */: { + case 239 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } - case 242 /* ModuleDeclaration */: { + case 244 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 243 /* ModuleBlock */) { + if (inner && inner.kind === 245 /* ModuleBlock */) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; @@ -77607,7 +80656,7 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 238 /* ClassDeclaration */: { + case 240 /* ClassDeclaration */: { var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -77618,7 +80667,7 @@ var ts; if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); - if (param.name.kind === 71 /* Identifier */) { + if (param.name.kind === 72 /* Identifier */) { return preserveJsDoc(ts.createProperty( /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } @@ -77648,7 +80697,7 @@ var ts; } var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); - if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 getSymbolAccessibilityDiagnostic = function () { return ({ @@ -77657,16 +80706,16 @@ var ts; typeName: input.name }); }; var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { - if (clause.token === 85 /* ExtendsKeyword */) { + if (clause.token === 86 /* ExtendsKeyword */) { var oldDiag_2 = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); getSymbolAccessibilityDiagnostic = oldDiag_2; return newClause; } - return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree)); })); return [statement, cleanup(ts.updateClassDeclaration(input, /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 @@ -77677,10 +80726,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { return cleanup(transformVariableStatement(input, isPrivate)); } - case 241 /* EnumDeclaration */: { + case 243 /* EnumDeclaration */: { return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -77699,7 +80748,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242 /* ModuleDeclaration */) { + if (input.kind === 244 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -77720,7 +80769,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 208 /* OmittedExpression */) { + if (e.kind === 210 /* OmittedExpression */) { return; } if (e.name) { @@ -77783,7 +80832,7 @@ var ts; function ensureModifierFlags(node, privateDeclaration) { var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 277 /* SourceFile */; + var parentIsFile = node.parent.kind === 279 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; @@ -77804,7 +80853,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77818,20 +80867,20 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; } function transformHeritageClauses(nodes) { return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { - return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */); + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */); })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); } } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 239 /* InterfaceDeclaration */) { + if (node.kind === 241 /* InterfaceDeclaration */) { return true; } return false; @@ -77856,7 +80905,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 156 /* GetAccessor */ + return accessor.kind === 158 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -77865,51 +80914,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: - case 217 /* VariableStatement */: - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 219 /* VariableStatement */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 159 /* ConstructSignature */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 160 /* IndexSignature */: - case 235 /* VariableDeclaration */: - case 148 /* TypeParameter */: - case 209 /* ExpressionWithTypeArguments */: - case 162 /* TypeReference */: - case 173 /* ConditionalType */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 181 /* ImportType */: + case 161 /* ConstructSignature */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 237 /* VariableDeclaration */: + case 150 /* TypeParameter */: + case 211 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 175 /* ConditionalType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 183 /* ImportType */: return true; } return false; @@ -77974,6 +81024,14 @@ var ts; return transformers; } ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -77985,7 +81043,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(310 /* Count */); + var enabledSyntaxKindFeatures = new Array(312 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -77993,8 +81051,8 @@ var ts; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; - var onSubstituteNode = function (_, node) { return node; }; - var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; var state = 0 /* Uninitialized */; var diagnostics = []; // The transformation context is provided to each transformer as part of transformer @@ -78243,825 +81301,11 @@ var ts; } ts.transformNodes = transformNodes; })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans - var defaultLastEncodedSourceMapSpan = { - emittedLine: 0, - emittedColumn: 0, - sourceLine: 0, - sourceColumn: 0, - sourceIndex: 0 - }; - function createSourceMapWriter(host, writer, compilerOptions) { - if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } - var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSource; - var currentSourceText; - var sourceMapDir; // The directory in which sourcemap will be - // 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; - var sourceMapDataList; - var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); - return { - initialize: initialize, - reset: reset, - setSourceFile: setSourceFile, - emitPos: emitPos, - emitNodeWithSourceMap: emitNodeWithSourceMap, - emitTokenWithSourceMap: emitTokenWithSourceMap, - getText: getText, - getSourceMappingURL: getSourceMappingURL, - }; - /** - * Skips trivia such as comments and white-space that can optionally overriden by the source map source - */ - function skipSourceTrivia(pos) { - return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); - } - /** - * Initialize the SourceMapWriter for a new output file. - * - * @param filePath The path to the generated output file. - * @param sourceMapFilePath The path to the output source map file. - * @param sourceFileOrBundle The input source file or bundle for the program. - */ - function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) { - return; - } - if (sourceMapData) { - reset(); - } - sourceMapDataList = outputSourceMapDataList; - currentSource = undefined; - currentSourceText = 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, - }; - // 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 (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file - // 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(sourceFileOrBundle.fileName, 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)); - } - } - /** - * Reset the SourceMapWriter to an empty state. - */ - function reset() { - if (disabled) { - return; - } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMapData); - } - currentSource = undefined; - sourceMapDir = undefined; - sourceMapSourceIndex = undefined; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = undefined; - lastEncodedNameIndex = undefined; - sourceMapData = undefined; - sourceMapDataList = undefined; - } - function captureSection() { - return { - version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent, - }; - } - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - ts.Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative"); - 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 = 0; - } - // 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; - } - /** - * Emits a mapping. - * - * If the position is synthetic (undefined or a negative value), no mapping will be - * created. - * - * @param pos The position. - */ - function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); - 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 - }; - } - 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; - } - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } - } - function isPossiblySourceMap(x) { - return typeof x === "object" && !!x.mappings && typeof x.mappings === "string" && !!x.sources; - } - /** - * Emits a node with possible leading and trailing source maps. - * - * @param hint A hint as to the intended usage of the node. - * @param node The node to emit. - * @param emitCallback The callback used to emit the node. - */ - function emitNodeWithSourceMap(hint, node, emitCallback) { - var _a; - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(hint, node); - } - if (node) { - if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { - var text = node.sourceMapText; - var parsed = void 0; - try { - parsed = JSON.parse(text); - } - catch (_b) { - // empty - } - if (!parsed || !isPossiblySourceMap(parsed)) { - return emitCallback(hint, node); - } - var offsetLine = writer.getLine(); - var firstLineColumnOffset = writer.getColumn(); - // First, decode the old component sourcemap - var originalMap = parsed; - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var resolvedPathCache = ts.createMap(); - var absolutePathCache = ts.createMap(); - var sourcemapIterator = ts.sourcemaps.decodeMappings(originalMap); - for (var _c = sourcemapIterator.next(), raw = _c.value, done = _c.done; !done; _a = sourcemapIterator.next(), raw = _a.value, done = _a.done, _a) { - var pathCacheKey = "" + raw.sourceIndex; - // Apply offsets to each position and fixup source entries - if (!resolvedPathCache.has(pathCacheKey)) { - var rawPath = originalMap.sources[raw.sourceIndex]; - var relativePath = originalMap.sourceRoot ? ts.combinePaths(originalMap.sourceRoot, rawPath) : rawPath; - var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath); - var resolvedPath_1 = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - resolvedPathCache.set(pathCacheKey, resolvedPath_1); - absolutePathCache.set(pathCacheKey, ts.getNormalizedAbsolutePath(resolvedPath_1, sourcesDirectoryPath)); - } - var resolvedPath = resolvedPathCache.get(pathCacheKey); - var absolutePath = absolutePathCache.get(pathCacheKey); - // tslint:disable-next-line:no-null-keyword - setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); // TODO: Lookup content for inlining? - var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath); - // Then reencode all the updated spans into the overall map - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = __assign({}, raw, { emittedLine: raw.emittedLine + offsetLine, emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, sourceIndex: newIndex }); - } - // And actually emit the text these sourcemaps are for - return emitCallback(hint, node); - } - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0 /* None */; - var range = emitNode && emitNode.sourceMapRange; - var _d = range || node, pos = _d.pos, end = _d.end; - var source = range && range.source; - var oldSource = currentSource; - if (source === oldSource) - source = undefined; - if (source) - setSourceFile(source); - if (node.kind !== 305 /* NotEmittedStatement */ - && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && pos >= 0) { - emitPos(skipSourceTrivia(pos)); - } - if (source) - setSourceFile(oldSource); - if (emitFlags & 64 /* NoNestedSourceMaps */) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - if (source) - setSourceFile(source); - if (node.kind !== 305 /* NotEmittedStatement */ - && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && end >= 0) { - emitPos(end); - } - if (source) - setSourceFile(oldSource); - } - } - /** - * Emits a token of a node with possible leading and trailing source maps. - * - * @param node The node containing the token. - * @param token The token to emit. - * @param tokenStartPos The start pos of the token. - * @param emitCallback The callback used to emit the token. - */ - function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(token, writer, tokenPos); - } - var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0 /* None */; - var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); - if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - tokenPos = emitCallback(token, writer, tokenPos); - if (range) - tokenPos = range.end; - if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - return tokenPos; - } - function isJsonSourceMapSource(sourceFile) { - return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); - } - /** - * Set the current source file. - * - * @param sourceFile The source file. - */ - function setSourceFile(sourceFile) { - if (disabled) { - return; - } - currentSource = sourceFile; - currentSourceText = currentSource.text; - if (isJsonSourceMapSource(sourceFile)) { - return; - } - setupSourceEntry(sourceFile.fileName, sourceFile.text); - } - function setupSourceEntry(fileName, content, source) { - if (!source) { - // 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; - source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(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(fileName); - if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(content); - } - } - } - /** - * Gets the text for the source map. - */ - function getText() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; // TODO: GH#18217 - } - encodeLastRecordedSourceMapSpan(); - return JSON.stringify(captureSection()); - } - /** - * Gets the SourceMappingURL for the source map. - */ - function getSourceMappingURL() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; // TODO: GH#18217 - } - if (compilerOptions.inlineSourceMap) { - // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.base64encode(ts.sys, 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 createCommentWriter(printerOptions, emitPos) { - var extendedDiagnostics = printerOptions.extendedDiagnostics; - var newLine = ts.getNewLineCharacter(printerOptions); - var writer; - var containerPos = -1; - var containerEnd = -1; - var declarationListContainerEnd = -1; - var currentSourceFile; - var currentText; - var currentLineMap; - var detachedCommentsInfo; - var hasWrittenComment = false; - var disabled = !!printerOptions.removeComments; - return { - reset: reset, - setWriter: setWriter, - setSourceFile: setSourceFile, - emitNodeWithComments: emitNodeWithComments, - emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, - emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, - }; - function emitNodeWithComments(hint, node, emitCallback) { - if (disabled) { - emitCallback(hint, node); - return; - } - if (node) { - hasWrittenComment = false; - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0; - var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; - if ((pos < 0 && end < 0) || (pos === end)) { - // Both pos and end are synthesized, so just emit the node without comments. - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - } - else { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithComment"); - } - var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */; - // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. - // It is expensive to walk entire tree just to set one kind of node to have no comments. - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; - var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 10 /* JsxText */; - // Emit leading comments if the position is not synthesized and the node - // has not opted out from emitting leading comments. - if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); - } - // Save current container state on the stack. - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { - // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. - containerPos = pos; - } - if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { - // As above. - containerEnd = end; - // To avoid invalid comment emit in a down-level binding pattern, we - // keep track of the last declaration list container's end - if (node.kind === 236 /* VariableDeclarationList */) { - declarationListContainerEnd = end; - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithComment"); - } - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithComment"); - } - // Restore previous container state. - containerPos = savedContainerPos; - containerEnd = savedContainerEnd; - declarationListContainerEnd = savedDeclarationListContainerEnd; - // Emit trailing comments if the position is not synthesized and the node - // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { - emitTrailingComments(end); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithComment"); - } - } - } - } - function emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback) { - var leadingComments = emitNode && emitNode.leadingComments; - if (ts.some(leadingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithSynthesizedComments"); - } - ts.forEach(leadingComments, emitLeadingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithSynthesizedComments"); - } - } - emitNodeWithNestedComments(hint, node, emitFlags, emitCallback); - var trailingComments = emitNode && emitNode.trailingComments; - if (ts.some(trailingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithSynthesizedComments"); - } - ts.forEach(trailingComments, emitTrailingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithSynthesizedComments"); - } - } - } - function emitLeadingSynthesizedComment(comment) { - if (comment.kind === 2 /* SingleLineCommentTrivia */) { - writer.writeLine(); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function emitTrailingSynthesizedComment(comment) { - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - } - function writeSynthesizedComment(comment) { - var text = formatSynthesizedComment(comment); - var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; - ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); - } - function formatSynthesizedComment(comment) { - return comment.kind === 3 /* MultiLineCommentTrivia */ - ? "/*" + comment.text + "*/" - : "//" + comment.text; - } - function emitNodeWithNestedComments(hint, node, emitFlags, emitCallback) { - if (emitFlags & 2048 /* NoNestedComments */) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - } - function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitBodyWithDetachedComments"); - } - var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = ts.getEmitFlags(node); - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; - if (!skipLeadingComments) { - emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); - } - if (emitFlags & 2048 /* NoNestedComments */ && !disabled) { - disabled = true; - emitCallback(node); - disabled = false; - } - else { - emitCallback(node); - } - if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); - } - if (!skipTrailingComments) { - emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); - if (hasWrittenComment && !writer.isAtStartOfLine()) { - writer.writeLine(); - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); - } - } - function emitLeadingComments(pos, isEmittedNode) { - hasWrittenComment = false; - if (isEmittedNode) { - forEachLeadingCommentToEmit(pos, emitLeadingComment); - } - else if (pos === 0) { - // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, - // unless it is a triple slash comment at the top of the file. - // For Example: - // /// - // declare var x; - // /// - // interface F {} - // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted - forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); - } - } - function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (isTripleSlashComment(commentPos, commentEnd)) { - emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); - } - } - function shouldWriteComment(text, pos) { - if (printerOptions.onlyPrintJsDocStyle) { - return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); - } - return true; - } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (!hasWrittenComment) { - ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); - hasWrittenComment = true; - } - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else if (kind === 3 /* MultiLineCommentTrivia */) { - writer.write(" "); - } - } - function emitLeadingCommentsOfPosition(pos) { - if (disabled || pos === -1) { - return; - } - emitLeadingComments(pos, /*isEmittedNode*/ true); - } - function emitTrailingComments(pos) { - forEachTrailingCommentToEmit(pos, emitTrailingComment); - } - function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - } - function emitTrailingCommentsOfPosition(pos, prefixSpace) { - if (disabled) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); - } - forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); - } - } - function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { - // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function forEachLeadingCommentToEmit(pos, cb) { - // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments - if (containerPos === -1 || pos !== containerPos) { - if (hasDetachedComments(pos)) { - forEachLeadingCommentWithoutDetachedComments(cb); - } - else { - ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - } - } - function forEachTrailingCommentToEmit(end, cb) { - // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments - if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { - ts.forEachTrailingCommentRange(currentText, end, cb); - } - } - function reset() { - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - detachedCommentsInfo = undefined; - } - function setWriter(output) { - writer = output; - } - function setSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = currentSourceFile.text; - currentLineMap = ts.getLineStarts(currentSourceFile); - detachedCommentsInfo = undefined; - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; - } - function forEachLeadingCommentWithoutDetachedComments(cb) { - // get the leading comments from detachedPos - var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - function emitDetachedCommentsAndUpdateCommentsInfo(range) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - } - /** - * Determine if the given comment is a triple-slash - * - * @return true if the comment is a triple-slash comment else false - */ - function isTripleSlashComment(commentPos, commentEnd) { - return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); - } - } - ts.createCommentWriter = createCommentWriter; -})(ts || (ts = {})); var ts; (function (ts) { var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ /** * Iterates over the source files that are expected to have an emit output. @@ -79099,21 +81343,26 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + if (sourceFile.kind === 280 /* Bundle */) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79136,7 +81385,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79156,22 +81405,16 @@ var ts; var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var newLine = host.getNewLine(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); var writer = ts.createTextWriter(newLine); - var sourceMap = ts.createSourceMapWriter(host, writer); - var declarationSourceMap = ts.createSourceMapWriter(host, writer, { - sourceMap: compilerOptions.declarationMap, - sourceRoot: compilerOptions.sourceRoot, - mapRoot: compilerOptions.mapRoot, - extendedDiagnostics: compilerOptions.extendedDiagnostics, - }); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; var exportedModulesFromDeclarationEmit; // Emit each output file - ts.performance.mark("beforePrint"); + enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); - ts.performance.measure("printTime", "beforePrint"); + exit(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -79185,56 +81428,66 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; // Create a printer to print the nodes - var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { + var printer = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, // transform hooks onEmitNode: transform.emitNodeWithNotification, substituteNode: transform.substituteNode, - // sourcemap hooks - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - // emitter hooks - onSetSourceFile: setSourceFile, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79248,14 +81501,20 @@ var ts; emitterDiagnostics.add(diagnostic); } } - var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true, noEmitHelpers: true }), { + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, - // sourcemap hooks - onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: declarationSourceMap.emitPos, - onSetSourceFile: setSourceFileForDeclarationSourceMaps, // transform hooks onEmitNode: declarationTransform.emitNodeWithNotification, substituteNode: declarationTransform.substituteNode, @@ -79264,8 +81523,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); - if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -79274,7 +81538,7 @@ var ts; } function collectLinkedAliases(node) { if (ts.isExportAssignment(node)) { - if (node.expression.kind === 71 /* Identifier */) { + if (node.expression.kind === 72 /* Identifier */) { resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); } return; @@ -79285,25 +81549,41 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { - var bundle = sourceFileOrBundle.kind === 278 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 277 /* SourceFile */ ? sourceFileOrBundle : undefined; + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } if (bundle) { - printer.writeBundle(bundle, writer, bundleInfo); + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); } else { - printer.writeFile(sourceFile, writer); + printer.writeFile(sourceFile, writer, sourceMapGenerator); } - writer.writeLine(); - var sourceMappingURL = mapRecorder.getSourceMappingURL(); - if (sourceMappingURL) { - writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } } - // Write the source map - if (sourceMapFilePath) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); + else { + writer.writeLine(); } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); @@ -79313,32 +81593,84 @@ var ts; ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); } // Reset state - mapRecorder.reset(); writer.clear(); bundleInfo = createDefaultBundleInfo(); } - function setSourceFile(node) { - sourceMap.setSourceFile(node); + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } - function setSourceFileForDeclarationSourceMaps(node) { - declarationSourceMap.setSourceFile(node); + function getSourceRoot(mapOptions) { + // 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 + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; } } ts.emitFiles = emitFiles; var PipelinePhase; (function (PipelinePhase) { PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; - PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; - PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; - PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); - var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); var currentSourceFile; var nodeIdToGeneratedName; // Map of generated names for specific nodes. var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. @@ -79348,19 +81680,23 @@ var ts; var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; - var ownWriter; + var ownWriter; // Reusable `EmitTextWriter` for basic printing. var write = writeBase; - var commitPendingSemicolon = ts.noop; - var writeSemicolon = writeSemicolonInternal; - var pendingSemicolon = false; - if (printerOptions.omitTrailingSemicolon) { - commitPendingSemicolon = commitPendingSemicolonInternal; - writeSemicolon = deferWriteSemicolon; - } - var syntheticParent = { pos: -1, end: -1 }; - var moduleKind = ts.getEmitModuleKind(printerOptions); - var bundledHelpers = ts.createMap(); var isOwnFileEmit; + // Source Maps + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + // Comments + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; reset(); return { // public API @@ -79387,9 +81723,9 @@ var ts; break; } switch (node.kind) { - case 277 /* SourceFile */: return printFile(node); - case 278 /* Bundle */: return printBundle(node); - case 279 /* UnparsedSource */: return printUnparsedSource(node); + case 279 /* SourceFile */: return printFile(node); + case 280 /* Bundle */: return printBundle(node); + case 281 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -79399,11 +81735,11 @@ var ts; return endPrint(); } function printBundle(bundle) { - writeBundle(bundle, beginPrint()); + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printFile(sourceFile) { - writeFile(sourceFile, beginPrint()); + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printUnparsedSource(unparsed) { @@ -79412,14 +81748,14 @@ var ts; } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(hint, node, sourceFile); reset(); writer = previousWriter; } function writeList(format, nodes, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); if (sourceFile) { setSourceFile(sourceFile); } @@ -79427,18 +81763,18 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output, bundleInfo) { + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { isOwnFileEmit = false; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { var prepend = _b[_a]; - print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); writeLine(); + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); } if (bundleInfo) { bundleInfo.originalOffset = writer.getTextPos(); @@ -79452,15 +81788,15 @@ var ts; } function writeUnparsedSource(unparsed, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); reset(); writer = previousWriter; } - function writeFile(sourceFile, output) { + function writeFile(sourceFile, output, sourceMapGenerator) { isOwnFileEmit = true; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(sourceFile); emitPrologueDirectivesIfNeeded(sourceFile); print(0 /* SourceFile */, sourceFile, sourceFile); @@ -79479,19 +81815,24 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - var pipelinePhase = getPipelinePhase(0 /* Notification */, hint); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; - comments.setSourceFile(sourceFile); - if (onSetSourceFile) { - onSetSourceFile(sourceFile); + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); } } - function setWriter(output) { - writer = output; // TODO: GH#18217 - comments.setWriter(output); + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; } function reset() { nodeIdToGeneratedName = []; @@ -79500,68 +81841,66 @@ var ts; tempFlagsStack = []; tempFlags = 0 /* Auto */; reservedNamesStack = []; - comments.reset(); - setWriter(/*output*/ undefined); + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } function emit(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(4 /* Unspecified */, node); } function emitIdentifierName(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(2 /* IdentifierName */, node); } function emitExpression(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(1 /* Expression */, node); } - function getPipelinePhase(phase, hint) { + function getPipelinePhase(phase, node) { switch (phase) { case 0 /* Notification */: - if (onEmitNode) { + if (onEmitNode !== ts.noEmitNotification) { return pipelineEmitWithNotification; } // falls through - case 1 /* Comments */: - if (emitNodeWithComments && hint !== 0 /* SourceFile */) { + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { return pipelineEmitWithComments; } - return pipelineEmitWithoutComments; - case 2 /* SourceMaps */: - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */) { + // falls through + case 3 /* SourceMaps */: + if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { return pipelineEmitWithSourceMap; } // falls through - case 3 /* Emit */: + case 4 /* Emit */: return pipelineEmitWithHint; default: - return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + return ts.Debug.assertNever(phase); } } - function getNextPipelinePhase(currentPhase, hint) { - return getPipelinePhase(currentPhase + 1, hint); + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); - } - function pipelineEmitWithComments(hint, node) { - ts.Debug.assertDefined(emitNodeWithComments); - ts.Debug.assert(hint !== 0 /* SourceFile */); - emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint)); - } - function pipelineEmitWithoutComments(hint, node) { - var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint); - pipelinePhase(hint, trySubstituteNode(hint, node)); - } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(hint !== 0 /* SourceFile */); - ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node); + onEmitNode(hint, node, pipelinePhase); } function pipelineEmitWithHint(hint, node) { if (hint === 0 /* SourceFile */) @@ -79570,254 +81909,285 @@ var ts; return emitIdentifier(ts.cast(node, ts.isIdentifier)); if (hint === 3 /* MappedTypeParameter */) return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } if (hint === 4 /* Unspecified */) { if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); switch (node.kind) { // Pseudo-literals - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: return emitLiteral(node); - case 279 /* UnparsedSource */: + case 281 /* UnparsedSource */: return emitUnparsedSource(node); // Identifiers - case 71 /* Identifier */: + case 72 /* Identifier */: return emitIdentifier(node); // Parse tree nodes // Names - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return emitQualifiedName(node); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return emitTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return emitParameter(node); - case 150 /* Decorator */: + case 152 /* Decorator */: return emitDecorator(node); // Type members - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return emitPropertySignature(node); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 153 /* MethodSignature */: + case 155 /* MethodSignature */: return emitMethodSignature(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return emitConstructor(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return emitAccessorDeclaration(node); - case 158 /* CallSignature */: + case 160 /* CallSignature */: return emitCallSignature(node); - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return emitConstructSignature(node); - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return emitIndexSignature(node); // Types - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return emitTypePredicate(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return emitTypeReference(node); - case 163 /* FunctionType */: + case 165 /* FunctionType */: return emitFunctionType(node); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return emitJSDocFunctionType(node); - case 164 /* ConstructorType */: + case 166 /* ConstructorType */: return emitConstructorType(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return emitTypeQuery(node); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return emitTypeLiteral(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return emitArrayType(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return emitTupleType(node); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return emitOptionalType(node); - case 171 /* UnionType */: + case 173 /* UnionType */: return emitUnionType(node); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return emitIntersectionType(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return emitConditionalType(node); - case 174 /* InferType */: + case 176 /* InferType */: return emitInferType(node); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return emitParenthesizedType(node); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 176 /* ThisType */: + case 178 /* ThisType */: return emitThisType(); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return emitTypeOperator(node); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return emitMappedType(node); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return emitLiteralType(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return emitImportTypeNode(node); - case 282 /* JSDocAllType */: - write("*"); + case 284 /* JSDocAllType */: + writePunctuation("*"); return; - case 283 /* JSDocUnknownType */: - write("?"); + case 285 /* JSDocUnknownType */: + writePunctuation("?"); return; - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return emitJSDocNullableType(node); - case 285 /* JSDocNonNullableType */: + case 287 /* JSDocNonNullableType */: return emitJSDocNonNullableType(node); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return emitJSDocOptionalType(node); - case 170 /* RestType */: - case 288 /* JSDocVariadicType */: + case 172 /* RestType */: + case 290 /* JSDocVariadicType */: return emitRestOrJSDocVariadicType(node); // Binding patterns - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return emitBindingElement(node); // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return emitTemplateSpan(node); - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 216 /* Block */: + case 218 /* Block */: return emitBlock(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return emitVariableStatement(node); - case 218 /* EmptyStatement */: - return emitEmptyStatement(); - case 219 /* ExpressionStatement */: + case 220 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 221 /* ExpressionStatement */: return emitExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return emitIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return emitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return emitWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return emitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return emitForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return emitForOfStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return emitContinueStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return emitBreakStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return emitReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return emitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return emitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return emitLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return emitThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return emitTryStatement(node); - case 234 /* DebuggerStatement */: + case 236 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return emitClassDeclaration(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return emitModuleBlock(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return emitCaseBlock(node); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return emitImportDeclaration(node); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return emitImportClause(node); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return emitNamespaceImport(node); - case 250 /* NamedImports */: + case 252 /* NamedImports */: return emitNamedImports(node); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return emitImportSpecifier(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return emitExportAssignment(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return emitExportDeclaration(node); - case 254 /* NamedExports */: + case 256 /* NamedExports */: return emitNamedExports(node); - case 255 /* ExportSpecifier */: + case 257 /* ExportSpecifier */: return emitExportSpecifier(node); - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return; // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) - case 10 /* JsxText */: + case 11 /* JsxText */: return emitJsxText(node); - case 260 /* JsxOpeningElement */: - case 263 /* JsxOpeningFragment */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 261 /* JsxClosingElement */: - case 264 /* JsxClosingFragment */: + case 263 /* JsxClosingElement */: + case 266 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return emitJsxAttribute(node); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return emitJsxAttributes(node); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: return emitCaseClause(node); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return emitDefaultClause(node); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return emitHeritageClause(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: return emitEnumMember(node); - // JSDoc nodes (ignored) + // JSDoc nodes (only used in codefixes currently) + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return emitJSDocSimpleTypedTag(node); + case 295 /* JSDocAugmentsTag */: + return emitJSDocAugmentsTag(node); + case 303 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 304 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 297 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 293 /* JSDocSignature */: + return emitJSDocSignature(node); + case 292 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 296 /* JSDocClassTag */: + case 294 /* JSDocTag */: + return emitJSDocSimpleTag(node); + case 291 /* JSDocComment */: + return emitJSDoc(node); // Transformation nodes (ignored) } if (ts.isExpression(node)) { hint = 1 /* Expression */; - node = trySubstituteNode(1 /* Expression */, node); + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } } else if (ts.isToken(node)) { return writeTokenNode(node, writePunctuation); @@ -79827,89 +82197,90 @@ var ts; switch (node.kind) { // Literals case 8 /* NumericLiteral */: - return emitNumericLiteral(node); - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return emitLiteral(node); // Identifiers - case 71 /* Identifier */: + case 72 /* Identifier */: return emitIdentifier(node); // Reserved words - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 101 /* TrueKeyword */: - case 99 /* ThisKeyword */: - case 91 /* ImportKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 102 /* TrueKeyword */: + case 100 /* ThisKeyword */: + case 92 /* ImportKeyword */: writeTokenNode(node, writeKeyword); return; // Expressions - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return emitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return emitNewExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return emitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return emitArrowFunction(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return emitDeleteExpression(node); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return emitVoidExpression(node); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return emitAwaitExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return emitBinaryExpression(node); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return emitConditionalExpression(node); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return emitTemplateExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return emitYieldExpression(node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return emitSpreadExpression(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return emitClassExpression(node); - case 208 /* OmittedExpression */: + case 210 /* OmittedExpression */: return; - case 210 /* AsExpression */: + case 212 /* AsExpression */: return emitAsExpression(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return emitNonNullExpression(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return emitMetaProperty(node); // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: return emitJsxElement(node); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return emitCommaList(node); } } @@ -79921,12 +82292,13 @@ var ts; writeSpace(); emit(node.constraint); } - function trySubstituteNode(hint, node) { - return node && substituteNode && substituteNode(hint, node) || node; + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); + pipelinePhase(hint, substituteNode(hint, node)); } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 278 /* Bundle */ ? node : undefined; + var bundle = node.kind === 280 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -79963,7 +82335,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79975,7 +82347,8 @@ var ts; // Literals/Pseudo-literals // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } // SyntaxKind.StringLiteral @@ -79985,9 +82358,9 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) - && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); } else { @@ -80005,7 +82378,7 @@ var ts; function emitIdentifier(node) { var writeText = node.symbol ? writeSymbol : write; writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); - emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments + emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names @@ -80016,7 +82389,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -80052,7 +82425,7 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 287 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { @@ -80074,7 +82447,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -80084,7 +82457,7 @@ var ts; emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); - writeSemicolon(); + writeTrailingSemicolon(); } function emitMethodSignature(node) { pushNameGenerationScope(node); @@ -80095,7 +82468,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -80114,7 +82487,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 156 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -80126,7 +82499,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -80138,7 +82511,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -80146,10 +82519,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // // Types @@ -80176,22 +82549,22 @@ var ts; popNameGenerationScope(node); } function emitJSDocFunctionType(node) { - write("function"); + writeKeyword("function"); emitParameters(node, node.parameters); - write(":"); + writePunctuation(":"); emit(node.type); } function emitJSDocNullableType(node) { - write("?"); + writePunctuation("?"); emit(node.type); } function emitJSDocNonNullableType(node) { - write("!"); + writePunctuation("!"); emit(node.type); } function emitJSDocOptionalType(node) { emit(node.type); - write("="); + writePunctuation("="); } function emitConstructorType(node) { pushNameGenerationScope(node); @@ -80212,8 +82585,8 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */; - emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); writePunctuation("}"); } function emitArrayType(node) { @@ -80222,23 +82595,23 @@ var ts; writePunctuation("]"); } function emitRestOrJSDocVariadicType(node) { - write("..."); + writePunctuation("..."); emit(node.type); } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 272 /* TupleTypeElements */); + emitList(node, node.elementTypes, 528 /* TupleTypeElements */); writePunctuation("]"); } function emitOptionalType(node) { emit(node.type); - write("?"); + writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 260 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */); } function emitIntersectionType(node) { - emitList(node, node.types, 264 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */); } function emitConditionalType(node) { emit(node.checkType); @@ -80291,25 +82664,25 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) { + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { writeKeyword("readonly"); } writeSpace(); } writePunctuation("["); - var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter); pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); - if (node.questionToken.kind !== 55 /* QuestionToken */) { + if (node.questionToken.kind !== 56 /* QuestionToken */) { writePunctuation("?"); } } writePunctuation(":"); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); if (emitFlags & 1 /* SingleLine */) { writeSpace(); } @@ -80342,12 +82715,12 @@ var ts; // function emitObjectBindingPattern(node) { writePunctuation("{"); - emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); writePunctuation("}"); } function emitArrayBindingPattern(node) { writePunctuation("["); - emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); writePunctuation("]"); } function emitBindingElement(node) { @@ -80365,8 +82738,8 @@ var ts; // function emitArrayLiteralExpression(node) { var elements = node.elements; - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -80374,9 +82747,9 @@ var ts; if (indentedFlag) { increaseIndent(); } - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */; - emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); } @@ -80387,20 +82760,20 @@ var ts; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = ts.createToken(23 /* DotToken */); + var dotToken = ts.createToken(24 /* DotToken */); dotToken.pos = dotRangeStart; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); - increaseIndentIf(indentBeforeDot); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); if (shouldEmitDotDot) { writePunctuation("."); } - emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node); - increaseIndentIf(indentAfterDot); + emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); } @@ -80410,9 +82783,9 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); + && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -80425,21 +82798,21 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); } function emitNewExpression(node) { - emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); @@ -80454,9 +82827,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node); + var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { generateNameIfNeeded(node.name); @@ -80475,22 +82848,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -80515,24 +82888,24 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 200 /* PrefixUnaryExpression */ - && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) - || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); + return operand.kind === 202 /* PrefixUnaryExpression */ + && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */)) + || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; + var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); - increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + increaseIndentIf(indentBeforeOperator, isCommaOperator); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, writeOperator); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - increaseIndentIf(indentAfterOperator, " "); + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); } @@ -80542,28 +82915,28 @@ var ts; var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); - increaseIndentIf(indentBeforeQuestion, " "); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); - increaseIndentIf(indentAfterQuestion, " "); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); - increaseIndentIf(indentBeforeColon, " "); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); - increaseIndentIf(indentAfterColon, " "); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); } function emitTemplateExpression(node) { emit(node.head); - emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - writePunctuation("..."); + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); emitExpression(node.expression); } function emitClassExpression(node) { @@ -80606,36 +82979,45 @@ var ts; emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); } function emitBlockStatements(node, forceSingleLine) { - emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); - var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; emitList(node, node.statements, format); - emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); + emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - writeSemicolon(); + writeTrailingSemicolon(); } - function emitEmptyStatement() { - writeSemicolon(); + function emitEmptyStatement(isEmbeddedStatement) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { - writeSemicolon(); + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); } } function emitIfStatement(node) { - var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 220 /* IfStatement */) { + emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -80645,14 +83027,14 @@ var ts; } } function emitWhileClause(node, startPos) { - var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node); + var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { - emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -80668,45 +83050,45 @@ var ts; emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.condition); - pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.incrementor); - emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(145 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 236 /* VariableDeclarationList */) { + if (node.kind === 238 /* VariableDeclarationList */) { emit(node); } else { @@ -80715,14 +83097,14 @@ var ts; } } function emitContinueStatement(node) { - emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitBreakStatement(node) { - emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { var node = ts.getParseTreeNode(contextNode); @@ -80748,40 +83130,40 @@ var ts; return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitWithStatement(node) { - var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node); + emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTryStatement(node) { - emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -80790,14 +83172,14 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); - writeSemicolon(); + writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); } // // Declarations @@ -80810,7 +83192,7 @@ var ts; function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); writeSpace(); - emitList(node, node.declarations, 272 /* VariableDeclarationList */); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { emitFunctionDeclarationOrExpression(node); @@ -80858,7 +83240,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -80910,7 +83292,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -80922,7 +83304,7 @@ var ts; emitHelpers(body); if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { decreaseIndent(); - emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); increaseIndent(); } else { @@ -80949,7 +83331,7 @@ var ts; emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65 /* ClassMembers */); + emitList(node, node.members, 129 /* ClassMembers */); writePunctuation("}"); if (indentedFlag) { decreaseIndent(); @@ -80962,10 +83344,10 @@ var ts; writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256 /* HeritageClauses */); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65 /* InterfaceMembers */); + emitList(node, node.members, 129 /* InterfaceMembers */); writePunctuation("}"); } function emitTypeAliasDeclaration(node) { @@ -80979,7 +83361,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -80988,7 +83370,7 @@ var ts; emit(node.name); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 81 /* EnumMembers */); + emitList(node, node.members, 145 /* EnumMembers */); writePunctuation("}"); } function emitModuleDeclaration(node) { @@ -81000,8 +83382,8 @@ var ts; emit(node.name); var body = node.body; if (!body) - return writeSemicolon(); - while (body.kind === 242 /* ModuleDeclaration */) { + return writeTrailingSemicolon(); + while (body.kind === 244 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); body = body.body; @@ -81016,23 +83398,23 @@ var ts; popNameGenerationScope(node); } function emitCaseBlock(node) { - emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node); - emitList(node, node.clauses, 65 /* CaseBlockClauses */); - emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node); + emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); - writeSemicolon(); + writeTrailingSemicolon(); } function emitModuleReference(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81041,29 +83423,29 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - emitTokenWithComment(143 /* FromKeyword */, node.importClause.end, writeKeyword, node); + emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); - writeSemicolon(); + writeTrailingSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); + var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node); writeSpace(); - emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node); + emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -81074,45 +83456,45 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node); + emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node); } else { - emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node); + emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitExportDeclaration(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node); + nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); var fromPos = node.exportClause ? node.exportClause.end : nextPos; - emitTokenWithComment(143 /* FromKeyword */, fromPos, writeKeyword, node); + emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamespaceExportDeclaration(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node); writeSpace(); emit(node.name); - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -81122,14 +83504,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -81148,7 +83530,7 @@ var ts; // function emitJsxElement(node) { emit(node.openingElement); - emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); emit(node.closingElement); } function emitJsxSelfClosingElement(node) { @@ -81160,7 +83542,7 @@ var ts; } function emitJsxFragment(node) { emit(node.openingFragment); - emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { @@ -81175,7 +83557,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { @@ -81186,7 +83567,7 @@ var ts; writePunctuation(">"); } function emitJsxAttributes(node) { - emitList(node, node.properties, 131328 /* JsxElementAttributes */); + emitList(node, node.properties, 262656 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); @@ -81206,7 +83587,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81217,13 +83598,13 @@ var ts; // Clauses // function emitCaseClause(node) { - emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node); + var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node); emitCaseOrDefaultClauseRest(node, node.statements, pos); } function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { @@ -81233,14 +83614,14 @@ var ts; ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); - var format = 81985 /* CaseOrDefaultClauseStatements */; + var format = 163969 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode); writeSpace(); - format &= ~(1 /* MultiLine */ | 64 /* Indented */); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); } else { - emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode); } emitList(parentNode, statements, format); } @@ -81248,15 +83629,15 @@ var ts; writeSpace(); writeTokenText(node.token, writeKeyword); writeSpace(); - emitList(node, node.types, 272 /* HeritageClauseTypes */); + emitList(node, node.types, 528 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -81293,7 +83674,7 @@ var ts; } function emitSpreadAssignment(node) { if (node.expression) { - writePunctuation("..."); + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); emitExpression(node.expression); } } @@ -81305,6 +83686,142 @@ var ts; emitInitializer(node.initializer, node.name.end, node); } // + // JSDoc + // + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // // Top-level nodes // function emitSourceFile(node) { @@ -81324,41 +83841,46 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.moduleName) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.amdDependencies) { for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { var dep = _b[_a]; if (dep.name) { - write("/// "); + writeComment("/// "); } else { - write("/// "); + writeComment("/// "); } writeLine(); } } for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { var directive = files_1[_c]; - write("/// "); + writeComment("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; - write("/// "); + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); writeLine(); } } @@ -81377,7 +83899,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 272 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -81417,13 +83939,14 @@ var ts; setSourceFile(sourceFile); emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); } + setSourceFile(undefined); } } function emitShebangIfNeeded(sourceFileOrBundle) { if (ts.isSourceFile(sourceFileOrBundle)) { var shebang = ts.getShebang(sourceFileOrBundle.text); if (shebang) { - write(shebang); + writeComment(shebang); writeLine(); return true; } @@ -81451,7 +83974,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328 /* Modifiers */); + emitList(node, modifiers, 262656 /* Modifiers */); writeSpace(); } } @@ -81465,7 +83988,7 @@ var ts; function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -81502,30 +84025,37 @@ var ts; else { writeLine(); increaseIndent(); - emit(node); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(5 /* EmbeddedStatement */, node); + } + else { + emit(node); + } decreaseIndent(); } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 24577 /* Decorators */); + emitList(parentNode, decorators, 49153 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26896 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures return emitTypeArguments(parentNode, parentNode.typeArguments); } - emitList(parentNode, typeParameters, 26896 /* TypeParameters */); + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1296 /* Parameters */); + emitList(parentNode, parameters, 2576 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81539,14 +84069,14 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); } else { emitParameters(parentNode, parameters); } } function emitParametersForIndexSignature(parentNode, parameters) { - emitList(parentNode, parameters, 4432 /* IndexSignatureParameters */); + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } function emitList(parentNode, children, format, start, count) { emitNodeList(emit, parentNode, children, format, start, count); @@ -81555,7 +84085,7 @@ var ts; emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 } function writeDelimiter(format) { - switch (format & 28 /* DelimitersMask */) { + switch (format & 60 /* DelimitersMask */) { case 0 /* None */: break; case 16 /* CommaDelimited */: @@ -81565,6 +84095,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8 /* AmpersandDelimited */: writeSpace(); writePunctuation("&"); @@ -81575,11 +84110,11 @@ var ts; if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; - if (isUndefined && format & 8192 /* OptionalIfUndefined */) { + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { return; } var isEmpty = children === undefined || start >= children.length || count === 0; - if (isEmpty && format & 16384 /* OptionalIfEmpty */) { + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); } @@ -81588,7 +84123,7 @@ var ts; } return; } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { // TODO: GH#18217 @@ -81603,23 +84138,23 @@ var ts; if (format & 1 /* MultiLine */) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { + else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { writeSpace(); } } else { // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; + var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 writeLine(); shouldEmitInterveningComments = false; } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 256 /* SpaceBetweenBraces */) { writeSpace(); } // Increase the indent, if requested. - if (format & 64 /* Indented */) { + if (format & 128 /* Indented */) { increaseIndent(); } // Emit each child. @@ -81628,14 +84163,19 @@ var ts; for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. - if (previousSibling) { + if (format & 32 /* AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { // i.e // function commentedParameters( // /* Parameter a */ // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -81643,14 +84183,14 @@ var ts; if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new // line, we should increase the indent. - if ((format & (3 /* LinesMask */ | 64 /* Indented */)) === 0 /* SingleLine */) { + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { increaseIndent(); shouldDecreaseIndentAfterEmit = true; } writeLine(); shouldEmitInterveningComments = false; } - else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { + else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { writeSpace(); } } @@ -81672,7 +84212,7 @@ var ts; previousSibling = child; } // Write a trailing comma, if requested. - var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; + var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { writePunctuation(","); } @@ -81682,25 +84222,25 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. - if (format & 64 /* Indented */) { + if (format & 128 /* Indented */) { decreaseIndent(); } // Write the closing line terminator or closing whitespace. if (shouldWriteClosingLineTerminator(parentNode, children, format)) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 256 /* SpaceBetweenBraces */) { writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { if (isEmpty && !isUndefined) { // TODO: GH#18217 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists @@ -81708,73 +84248,55 @@ var ts; writePunctuation(getClosingBracket(format)); } } - function commitPendingSemicolonInternal() { - if (pendingSemicolon) { - writeSemicolonInternal(); - pendingSemicolon = false; - } - } + // Writers function writeLiteral(s) { - commitPendingSemicolon(); writer.writeLiteral(s); } function writeStringLiteral(s) { - commitPendingSemicolon(); writer.writeStringLiteral(s); } function writeBase(s) { - commitPendingSemicolon(); writer.write(s); } function writeSymbol(s, sym) { - commitPendingSemicolon(); writer.writeSymbol(s, sym); } function writePunctuation(s) { - commitPendingSemicolon(); writer.writePunctuation(s); } - function deferWriteSemicolon() { - pendingSemicolon = true; - } - function writeSemicolonInternal() { - writer.writePunctuation(";"); + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); } function writeKeyword(s) { - commitPendingSemicolon(); writer.writeKeyword(s); } function writeOperator(s) { - commitPendingSemicolon(); writer.writeOperator(s); } function writeParameter(s) { - commitPendingSemicolon(); writer.writeParameter(s); } + function writeComment(s) { + writer.writeComment(s); + } function writeSpace() { - commitPendingSemicolon(); writer.writeSpace(" "); } function writeProperty(s) { - commitPendingSemicolon(); writer.writeProperty(s); } function writeLine() { - commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { - commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { - commitPendingSemicolon(); writer.decreaseIndent(); } function writeToken(token, pos, writer, contextNode) { - return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) : writeTokenText(token, writer, pos); } function writeTokenNode(node, writer) { @@ -81802,23 +84324,23 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = ts.guessIndentation(lines); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var lineText = lines_2[_a]; + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); - writeLine(); + writer.rawWrite(newLine); } } } - function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + function increaseIndentIf(value, writeSpaceIfNotIndenting) { if (value) { increaseIndent(); writeLine(); } - else if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); + else if (writeSpaceIfNotIndenting) { + writeSpace(); } } // Helper function to decrease the indent if we previously indented. Allows multiple @@ -81838,7 +84360,7 @@ var ts; return true; } if (format & 2 /* PreserveLines */) { - if (format & 32768 /* PreferNewLine */) { + if (format & 65536 /* PreferNewLine */) { return true; } var firstChild = children[0]; @@ -81877,10 +84399,10 @@ var ts; } function shouldWriteClosingLineTerminator(parentNode, children, format) { if (format & 1 /* MultiLine */) { - return (format & 65536 /* NoTrailingNewLine */) === 0; + return (format & 131072 /* NoTrailingNewLine */) === 0; } else if (format & 2 /* PreserveLines */) { - if (format & 32768 /* PreferNewLine */) { + if (format & 65536 /* PreferNewLine */) { return true; } var lastChild = ts.lastOrUndefined(children); @@ -81902,11 +84424,11 @@ var ts; if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { - return (format & 32768 /* PreferNewLine */) !== 0; + return (format & 65536 /* PreferNewLine */) !== 0; } return startsOnNewLine; } - return (format & 32768 /* PreferNewLine */) !== 0; + return (format & 65536 /* PreferNewLine */) !== 0; } function needsIndentation(parent, node1, node2) { parent = skipSynthesizedParentheses(parent); @@ -81926,7 +84448,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -81938,7 +84460,7 @@ var ts; else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } - else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); } else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { @@ -81946,19 +84468,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { - if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -81991,81 +84513,81 @@ var ts; if (!node) return; switch (node.kind) { - case 216 /* Block */: + case 218 /* Block */: ts.forEach(node.statements, generateNames); break; - case 231 /* LabeledStatement */: - case 229 /* WithStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 233 /* LabeledStatement */: + case 231 /* WithStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: generateNames(node.statement); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 272 /* CatchClause */: + case 274 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: generateNames(node.declarationList); break; - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: generateNames(node.importClause); break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -82074,12 +84596,12 @@ var ts; if (!node) return; switch (node.kind) { - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: generateNameIfNeeded(node.name); break; } @@ -82137,7 +84659,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +84738,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82259,23 +84781,23 @@ var ts; */ function generateNameForNode(node, flags) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 252 /* ExportAssignment */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 254 /* ExportAssignment */: return generateNameForExportDefault(); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return generateNameForClassExpression(); - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0 /* Auto */); @@ -82316,21 +84838,396 @@ var ts; // otherwise, return the original node for the source; return node; } + // Comments + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 238 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + // Source Maps + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, + /*nameIndex*/ undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } } ts.createPrinter = createPrinter; function createBracketsMap() { var brackets = []; - brackets[512 /* Braces */] = ["{", "}"]; - brackets[1024 /* Parenthesis */] = ["(", ")"]; - brackets[2048 /* AngleBrackets */] = ["<", ">"]; - brackets[4096 /* SquareBrackets */] = ["[", "]"]; + brackets[1024 /* Braces */] = ["{", "}"]; + brackets[2048 /* Parenthesis */] = ["(", ")"]; + brackets[4096 /* AngleBrackets */] = ["<", ">"]; + brackets[8192 /* SquareBrackets */] = ["[", "]"]; return brackets; } function getOpeningBracket(format) { - return brackets[format & 7680 /* BracketsMask */][0]; + return brackets[format & 15360 /* BracketsMask */][0]; } function getClosingBracket(format) { - return brackets[format & 7680 /* BracketsMask */][1]; + return brackets[format & 15360 /* BracketsMask */][1]; } // Flags enum to track count of temp variables and a few dedicated names var TempFlags; @@ -82730,17 +85627,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +85660,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +85670,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +85678,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +85690,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +85702,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +85718,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(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); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +85752,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +85779,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +85867,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +85883,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83021,7 +85922,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -83034,7 +85935,7 @@ var ts; result = cache.get(name); } else { - cache.set(name, result = loader(name, containingFile)); + cache.set(name, result = loader(name, containingFile, redirectedReference)); } resolutions.push(result); } @@ -83044,7 +85945,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +85954,11 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + var seenResolvedRefs; + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,9 +85979,39 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || + return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolution(sourceFile.path); } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + // If child project references are upto date, this project reference is uptodate + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { @@ -83084,21 +86020,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83121,7 +86053,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var modifiedFilePaths; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -83149,16 +86081,15 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; - var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; @@ -83170,16 +86101,16 @@ var ts; } else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217 - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; } else { - var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217 - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). @@ -83195,30 +86126,34 @@ var ts; // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files - var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; if (projectReferences) { - for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { - var ref = projectReferences_1[_i]; - var parsedRef = parseProjectReferenceConfigFile(ref); - resolvedProjectReferences.push(parsedRef); - if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); - processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); } } } ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); @@ -83232,7 +86167,7 @@ var ts; // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. - if (!skipDefaultLib) { + if (rootNames.length && !skipDefaultLib) { // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file var defaultLibraryFileName = getDefaultLibraryFileName(); @@ -83257,10 +86192,18 @@ var ts; var oldSourceFiles = oldProgram.getSourceFiles(); for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { var oldSourceFile = oldSourceFiles_1[_a]; - if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { - host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); } // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; @@ -83299,7 +86242,12 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +86281,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83362,13 +86310,13 @@ var ts; } return classifiableNames; } - function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, // the best we can do is fallback to the default logic. - return resolveModuleNamesWorker(moduleNames, containingFile); + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); } - var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { // `file` was created for the new program. // @@ -83378,13 +86326,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83431,7 +86379,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -83442,7 +86390,7 @@ var ts; } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) : ts.emptyArray; // Combine results of resolutions and predicted results if (!result) { @@ -83468,9 +86416,9 @@ var ts; return result; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,24 +86426,35 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); - if (!firstUnmodifiedFile) { + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { return false; } if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); } return true; } } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + // If array of references is changed, we cant resue old program + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return 0 /* Not */; @@ -83516,36 +86475,14 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); - if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } - for (var i = 0; i < projectReferences.length; i++) { - var oldRef = oldRefs[i]; - if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); - if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { - // Resolved project reference has gone missing or changed - return oldProgram.structureIsReused = 0 /* Not */; - } - } - else { - // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { - return oldProgram.structureIsReused = 0 /* Not */; - } - } - } + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0 /* Not */; } - else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; - var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2 /* Completely */; // If the missing file paths are now present, it can change the progam structure, @@ -83564,7 +86501,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,8 +86528,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; - filePaths.push(newSourceFile.path); + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { // If there are 2 different source files for the same package name and at least one of them changes, @@ -83653,15 +86593,23 @@ var ts; if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } - modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } // try to verify results of module resolution - for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { - var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { @@ -83673,8 +86621,9 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -83694,28 +86643,29 @@ var ts; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping - for (var i = 0; i < newSourceFiles.length; i++) { - filesByName.set(filePaths[i], newSourceFiles[i]); + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); // Set the file as found during node modules search if it was found that way in old progra, - if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { - sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { - var modifiedFile = modifiedSourceFiles_2[_c]; + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +86676,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +86691,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +86754,7 @@ var ts; // get any preEmit diagnostics, not just the ones 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) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +86820,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +86911,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -83969,22 +86921,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } // falls through - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 235 /* VariableDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 237 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -83992,41 +86944,41 @@ var ts; } } switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: var heritageClause = node; - if (heritageClause.token === 108 /* ImplementsKeyword */) { + if (heritageClause.token === 109 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 210 /* AsExpression */: + case 212 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; @@ -84039,51 +86991,51 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, 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)); } switch (parent.kind) { - case 238 /* ClassDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 240 /* ClassDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } // falls through - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 217 /* VariableStatement */); + return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */); } break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 115 /* StaticKeyword */) { + if (modifier.kind !== 116 /* StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } return; } break; - case 149 /* Parameter */: + case 151 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 209 /* ExpressionWithTypeArguments */: - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -84100,24 +87052,24 @@ var ts; for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { var modifier = modifiers_1[_i]; switch (modifier.kind) { - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: if (isConstValid) { continue; } // to report error, // falls through - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 124 /* DeclareKeyword */: - case 117 /* AbstractKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 125 /* DeclareKeyword */: + case 118 /* AbstractKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. - case 115 /* StaticKeyword */: - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 116 /* StaticKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: } } } @@ -84165,10 +87117,22 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; } function getGlobalDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; } function getConfigFileParsingDiagnostics() { return configFileParsingDiagnostics || ts.emptyArray; @@ -84180,15 +87144,15 @@ var ts; return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 71 /* Identifier */ - ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText - : b.kind === 9 /* StringLiteral */ && a.text === b.text; + return a.kind === 72 /* Identifier */ + ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 10 /* StringLiteral */ && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84210,12 +87174,9 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, /*inAmbientModule*/ false); - if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(node); - } } if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(file.endOfFileToken); + collectDynamicImportOrRequireCalls(file); } file.imports = imports || ts.emptyArray; file.moduleAugmentations = moduleAugmentations || ts.emptyArray; @@ -84263,24 +87224,37 @@ var ts; } } } - function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { - imports = ts.append(imports, node.arguments[0]); - } - // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. - else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { - imports = ts.append(imports, node.arguments[0]); - } - else if (ts.isLiteralImportTypeNode(node)) { - imports = ts.append(imports, node.argument.literal); - } - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } } } - function collectDynamicImportOrRequireCallsForEachChild(node) { - ts.forEachChild(node, collectDynamicImportOrRequireCalls); + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } } } function getLibFileFromReference(ref) { @@ -84296,7 +87270,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84352,11 +87326,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84371,6 +87348,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84436,9 +87414,9 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); - filesByName.set(path, dupFile); + addFileToFilesByName(dupFile, path, redirectedPath); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); return dupFile; @@ -84449,14 +87427,12 @@ var ts; sourceFileToPackageName.set(path, packageId.name); } } - filesByName.set(path, file); - if (redirectedPath) { - filesByName.set(redirectedPath, file); - } + addFileToFilesByName(file, path, redirectedPath); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84485,25 +87461,90 @@ var ts; } return file; } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { - return undefined; - } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); }); - return result; + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + // Visit project references first + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +87554,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84531,6 +87572,8 @@ var ts; } var saveResolution = true; if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 @@ -84555,6 +87598,8 @@ var ts; processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; } else { fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 @@ -84599,8 +87644,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +87653,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +87673,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,61 +87693,61 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } return allFilesBelongToPath; } function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); return undefined; } - sourceFile.path = toPath(refPath); + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); - return { commandLine: commandLine, sourceFile: sourceFile }; - } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84731,41 +87775,18 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); } } - if (projectReferences) { - for (var i = 0; i < projectReferences.length; i++) { - var ref = projectReferences[i]; - var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; - if (resolvedRefOpts === undefined) { - createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); - continue; - } - if (!resolvedRefOpts.composite) { - createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - } - if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); - } - } - else { - createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); - } - } - } - } + verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +87836,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84833,12 +87854,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -84850,7 +87871,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84863,9 +87884,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84876,19 +87897,19 @@ var ts; // 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; })) { + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -84946,6 +87967,35 @@ var ts; } } } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { var needCompilerDiagnostic = true; var pathsSyntax = getOptionPathsSyntax(); @@ -84996,10 +88046,10 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } - function createDiagnosticForReference(index, message, arg0, arg1) { - var referencesSyntax = getProjectReferencesSyntax(); + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); if (referencesSyntax && referencesSyntax.elements.length > index) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); } else { programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); @@ -85013,22 +88063,6 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } - function getProjectReferencesSyntax() { - if (_referencesArrayLiteralSyntax === undefined) { - _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile) { - var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217 - for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { - var prop = _a[_i]; - if (ts.isArrayLiteralExpression(prop.initializer)) { - _referencesArrayLiteralSyntax = prop.initializer; - break; - } - } - } - } - return _referencesArrayLiteralSyntax; - } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword @@ -85079,7 +88113,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,25 +88130,26 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85153,7 +88188,7 @@ var ts; var res = imports.map(function (i) { return i.text; }); for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9 /* StringLiteral */) { + if (aug.kind === 10 /* StringLiteral */) { res.push(aug.text); } // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. @@ -85184,7 +88219,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +88229,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +88258,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,11 +88269,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85338,6 +88413,11 @@ var ts; var latestSignature; if (sourceFile.isDeclarationFile) { latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } } else { var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); @@ -85403,7 +88483,7 @@ var ts; return getAllFileNames(state, programOfThisState); } // If this is non module emit, or its a global file, it depends on all the source files - if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { return getAllFileNames(state, programOfThisState); } // Get the references, traversing deep from the referenceMap @@ -85462,6 +88542,20 @@ var ts; } return true; } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } /** * Gets all files of the program excluding the default library file */ @@ -85502,7 +88596,7 @@ var ts; * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { - if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } var compilerOptions = programOfThisState.getCompilerOptions(); @@ -85552,8 +88646,9 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && - !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { @@ -85568,6 +88663,8 @@ var ts; // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -85585,6 +88682,13 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } // Unchanged file copy diagnostics var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { @@ -85668,18 +88772,31 @@ var ts; // If there are no more diagnostics from old cache, done return; } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } // If there was change in signature for the changed file, // then delete the semantic diagnostics for files that are affected by using exports of this module if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { return; } ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { return exportedModules && exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); })) { return; } @@ -85687,16 +88804,44 @@ var ts; ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); }); } /** * removes the semantic diagnostics of files referencing referencedPath and * returns true if there are no more semantic diagnostics from old state */ - function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { - return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); }); } /** @@ -85705,7 +88850,7 @@ var ts; */ function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -85752,7 +88897,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +88910,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +89091,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -85971,6 +89123,10 @@ var ts; /*@internal*/ var ts; (function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; ts.maxNumberOfFilesToIterateForInvalidation = 256; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; @@ -85984,11 +89140,11 @@ var ts; // The key in the map is source file's path. // The values are Map of resolutions with key being name lookedup. var resolvedModuleNames = ts.createMap(); - var perDirectoryResolvedModuleNames = ts.createMap(); - var nonRelaticeModuleNameCache = ts.createMap(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); var resolvedTypeReferenceDirectives = ts.createMap(); - var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -86012,6 +89168,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -86073,7 +89230,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -86089,15 +89246,15 @@ var ts; } }); } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { return primaryResult; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86108,10 +89265,11 @@ var ts; // Default return the result from the first pass return primaryResult; } - function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { var path = resolutionHost.toPath(containingFile); var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); var perDirectoryResolution = perDirectoryCache.get(dirPath); if (!perDirectoryResolution) { perDirectoryResolution = ts.createMap(); @@ -86120,22 +89278,28 @@ var ts; var resolvedModules = []; var compilerOptions = resolutionHost.getCompilationSettings(); var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; var seenNamesInFile = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { var name = names_2[_i]; var resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { var existingResolution = resolution; var resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { resolution = resolutionInDirectory; } else { - resolution = loader(name, containingFile, compilerOptions, resolutionHost); + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); @@ -86151,7 +89315,7 @@ var ts; } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217 + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); } // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { @@ -86179,12 +89343,14 @@ var ts; return oldResult.resolvedFileName === newResult.resolvedFileName; } } - function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { - return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, /*reusedNames*/ undefined, /*logChanges*/ false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); } function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); @@ -86227,15 +89393,10 @@ var ts; } return true; } - function filterFSRootDirectoriesToWatch(watchPath, dirPath) { - if (!canWatchDirectory(dirPath)) { - watchPath.ignore = true; - } - return watchPath; - } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86251,13 +89412,13 @@ var ts; } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // If directory path contains node module, get the most parent node_modules directory for watching - while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { + while (ts.pathContainsNodeModules(dirPath)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } // If the directory is node_modules use it to watch, always watch it recursively if (isNodeModulesDirectory(dirPath)) { - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -86275,7 +89436,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive }, dirPath); + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -86304,8 +89465,9 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, nonRecursive = _a.nonRecursive, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; // If the failed lookup location path is not one of the supported extensions, // store it in the custom path if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { @@ -86358,8 +89520,9 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { if (refCount === 1) { @@ -86407,6 +89570,22 @@ var ts; cache.delete(filePath); } } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + // If this file is input file for the referenced project, get it + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } function removeResolutionsOfFile(filePath) { removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); @@ -86468,6 +89647,9 @@ var ts; isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; } else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; // Some file or directory in the watching directory is created // Return early if it does not have any of the watching extension or not the custom failed lookup path var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); @@ -86508,8 +89690,8 @@ var ts; if (isInDirectoryPath(rootPath, typeRootPath)) { return rootPath; } - var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info @@ -86575,121 +89757,118 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +89932,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +89949,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +89970,30 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86827,20 +90002,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86855,12 +90028,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86923,13 +90098,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +90166,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,13 +90174,12 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } return false; } - /** @internal */ ts.screenStartingMessageCodes = [ ts.Diagnostics.Starting_compilation_in_watch_mode.code, ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, @@ -87028,10 +90220,27 @@ var ts; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +90256,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87066,7 +90275,7 @@ var ts; } } if (reportSummary) { - reportSummary(diagnostics.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length); + reportSummary(getErrorCountForSummary(diagnostics)); } if (emitSkipped && diagnostics.length > 0) { // If the emitter didn't emit anything, then pass that value along. @@ -87081,6 +90290,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +90321,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +90335,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87133,15 +90354,7 @@ var ts; function emitFilesAndReportErrorUsingBuilder(builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - var reportSummary = function (errorCount) { - if (errorCount === 1) { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions); - } - else { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions); - } - }; - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); } } /** @@ -87166,18 +90379,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,9 +90414,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87215,7 +90430,8 @@ var ts; fileExists: function (path) { return host.fileExists(path); }, readFile: readFile, getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); @@ -87273,7 +90489,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87282,11 +90499,11 @@ var ts; /*logChangesWhenResolvingModule*/ false); // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names compilerHost.resolveModuleNames = host.resolveModuleNames ? - (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : - (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? - (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : - (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; synchronizeProgram(); // Update the wild card directory watch @@ -87311,9 +90528,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +90555,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87460,8 +90677,8 @@ var ts; var hostSourceFile = sourceFilesCache.get(path); return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); } - function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { - var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); // If this is the source file thats in the cache and new program doesnt need it, // remove the cached entry. // Note we arent deleting entry if file became missing in new program or @@ -87475,8 +90692,10 @@ var ts; if (hostSourceFileInfo.fileWatcher) { hostSourceFileInfo.fileWatcher.close(); } - sourceFilesCache.delete(oldSourceFile.path); - resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } } } } @@ -87519,12 +90738,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87550,7 +90764,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87559,6 +90775,7 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { resolutionCache.invalidateResolutionOfFile(path); } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program scheduleProgramUpdate(); @@ -87599,6 +90816,8 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { @@ -87637,6 +90856,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +90878,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +90896,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +90967,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +90982,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,808 +91003,827 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects - }; - } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } - } - ts.performBuild = performBuild; /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +91859,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +91871,144 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +92016,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88684,7 +92045,6 @@ var ts; : undefined; } server.findArgument = findArgument; - /*@internal*/ function nowString() { // E.g. "12:34:56.789" var d = new Date(); @@ -88698,13 +92058,11 @@ var ts; (function (ts) { var JsTyping; (function (JsTyping) { - /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; - /* @internal */ JsTyping.nodeCoreModuleList = [ "assert", "async_hooks", @@ -88743,7 +92101,6 @@ var ts; "vm", "zlib" ]; - /* @internal */ JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); @@ -88776,7 +92133,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +92218,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +92256,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +92347,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89085,12 +92377,6 @@ var ts; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); /* @internal */ ts.emptyOptions = {}; - var TextChange = /** @class */ (function () { - function TextChange() { - } - return TextChange; - }()); - ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { HighlightSpanKind["none"] = "none"; @@ -89104,6 +92390,32 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + function getDefaultFormatCodeSettings(newLineCharacter) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: newLineCharacter || "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + /* @internal */ + ts.testFormatSettings = getDefaultFormatCodeSettings("\n"); var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89165,8 +92477,9 @@ var ts; TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; - TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; - TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; + TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral"; + TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral"; })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); var ScriptElementKind; (function (ScriptElementKind) { @@ -89249,6 +92562,12 @@ var ts; ScriptElementKindModifier["staticModifier"] = "static"; ScriptElementKindModifier["abstractModifier"] = "abstract"; ScriptElementKindModifier["optionalModifier"] = "optional"; + ScriptElementKindModifier["dtsModifier"] = ".d.ts"; + ScriptElementKindModifier["tsModifier"] = ".ts"; + ScriptElementKindModifier["tsxModifier"] = ".tsx"; + ScriptElementKindModifier["jsModifier"] = ".js"; + ScriptElementKindModifier["jsxModifier"] = ".jsx"; + ScriptElementKindModifier["jsonModifier"] = ".json"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); var ClassificationTypeNames; (function (ClassificationTypeNames) { @@ -89256,6 +92575,7 @@ var ts; ClassificationTypeNames["identifier"] = "identifier"; ClassificationTypeNames["keyword"] = "keyword"; ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["bigintLiteral"] = "bigint"; ClassificationTypeNames["operator"] = "operator"; ClassificationTypeNames["stringLiteral"] = "string"; ClassificationTypeNames["whiteSpace"] = "whitespace"; @@ -89302,6 +92622,7 @@ var ts; ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral"; })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); })(ts || (ts = {})); // These utilities are common to multiple language service features. @@ -89319,36 +92640,37 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 272 /* CatchClause */: - case 265 /* JsxAttribute */: + case 237 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 274 /* CatchClause */: + case 267 /* JsxAttribute */: return 1 /* Value */; - case 148 /* TypeParameter */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 166 /* TypeLiteral */: + case 150 /* TypeParameter */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 168 /* TypeLiteral */: return 2 /* Type */; - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 276 /* EnumMember */: - case 238 /* ClassDeclaration */: + case 278 /* EnumMember */: + case 240 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -89358,26 +92680,26 @@ var ts; else { return 4 /* Namespace */; } - case 241 /* EnumDeclaration */: - case 250 /* NamedImports */: - case 251 /* ImportSpecifier */: - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: - case 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 243 /* EnumDeclaration */: + case 252 /* NamedImports */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89409,11 +92731,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 146 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 246 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + var name = node.kind === 148 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 248 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 146 /* QualifiedName */) { + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -89425,27 +92747,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 146 /* QualifiedName */) { - while (root.parent && root.parent.kind === 146 /* QualifiedName */) { + if (root.parent.kind === 148 /* QualifiedName */) { + while (root.parent && root.parent.kind === 148 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 162 /* TypeReference */ && !isLastClause; + return root.parent.kind === 164 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 187 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 187 /* PropertyAccessExpression */) { + if (root.parent.kind === 189 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 189 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 209 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 271 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 211 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 273 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 238 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || - (decl.kind === 239 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); + return (decl.kind === 240 /* ClassDeclaration */ && root.parent.parent.token === 109 /* ImplementsKeyword */) || + (decl.kind === 241 /* InterfaceDeclaration */ && root.parent.parent.token === 86 /* ExtendsKeyword */); } return false; } @@ -89454,17 +92776,17 @@ var ts; node = node.parent; } switch (node.kind) { - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 176 /* ThisType */: + case 178 /* ThisType */: return true; } switch (node.parent.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return true; - case 181 /* ImportType */: + case 183 /* ImportType */: return !node.parent.isTypeOf; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; @@ -89491,7 +92813,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 231 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 233 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -89499,53 +92821,64 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { - return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; + return node.kind === 72 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; + return node.kind === 72 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; } ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; function isLabelName(node) { return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } ts.isLabelName = isLabelName; + function isTagName(node) { + return ts.isJSDocTag(node.parent) && node.parent.tagName === node; + } + ts.isTagName = isTagName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 242 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 244 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { - return node.kind === 71 /* Identifier */ && + return node.kind === 72 /* Identifier */ && ts.isFunctionLike(node.parent) && node.parent.name === node; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 273 /* PropertyAssignment */: - case 276 /* EnumMember */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 242 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 278 /* EnumMember */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 244 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return true; - case 180 /* LiteralType */: - return node.parent.parent.kind === 178 /* IndexedAccessType */; + case 182 /* LiteralType */: + return node.parent.parent.kind === 180 /* IndexedAccessType */; default: return false; } @@ -89569,17 +92902,17 @@ var ts; return undefined; } switch (node.kind) { - case 277 /* SourceFile */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: return node; } } @@ -89587,51 +92920,54 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return "class" /* classElement */; - case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 240 /* TypeAliasDeclaration */: - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 242 /* TypeAliasDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 241 /* EnumDeclaration */: return "enum" /* enumElement */; - case 235 /* VariableDeclaration */: + case 243 /* EnumDeclaration */: return "enum" /* enumElement */; + case 237 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return "function" /* functionElement */; - case 156 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 157 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 158 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 159 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return "method" /* memberFunctionElement */; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return "property" /* memberVariableElement */; - case 160 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 159 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 158 /* CallSignature */: return "call" /* callSignatureElement */; - case 155 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 148 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 276 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 149 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 246 /* ImportEqualsDeclaration */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: - case 249 /* NamespaceImport */: + case 162 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 161 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 160 /* CallSignature */: return "call" /* callSignatureElement */; + case 157 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 150 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 278 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 151 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + case 251 /* NamespaceImport */: return "alias" /* alias */; - case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: case 0 /* None */: return "" /* unknown */; case 1 /* ExportsProperty */: @@ -89652,7 +92988,7 @@ var ts; return "" /* unknown */; } } - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; @@ -89668,12 +93004,12 @@ var ts; ts.getNodeKind = getNodeKind; function isThis(node) { switch (node.kind) { - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: // case SyntaxKind.ThisType: TODO: GH#9267 return true; - case 71 /* Identifier */: + case 72 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 149 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 151 /* Parameter */; default: return false; } @@ -89738,42 +93074,42 @@ var ts; return false; } switch (n.kind) { - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 186 /* ObjectLiteralExpression */: - case 182 /* ObjectBindingPattern */: - case 166 /* TypeLiteral */: - case 216 /* Block */: - case 243 /* ModuleBlock */: - case 244 /* CaseBlock */: - case 250 /* NamedImports */: - case 254 /* NamedExports */: - return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile); - case 272 /* CatchClause */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 168 /* TypeLiteral */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 246 /* CaseBlock */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); + case 274 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 190 /* NewExpression */: + case 192 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 189 /* CallExpression */: - case 193 /* ParenthesizedExpression */: - case 175 /* ParenthesizedType */: - return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 191 /* CallExpression */: + case 195 /* ParenthesizedExpression */: + case 177 /* ParenthesizedType */: + return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 159 /* ConstructSignature */: - case 158 /* CallSignature */: - case 195 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 197 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -89782,66 +93118,66 @@ var ts; } // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. - return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); - case 242 /* ModuleDeclaration */: + return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); + case 244 /* ModuleDeclaration */: return !!n.body && isCompletedNode(n.body, sourceFile); - case 220 /* IfStatement */: + case 222 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile); - case 185 /* ArrayLiteralExpression */: - case 183 /* ArrayBindingPattern */: - case 188 /* ElementAccessExpression */: - case 147 /* ComputedPropertyName */: - case 168 /* TupleType */: - return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile); - case 160 /* IndexSignature */: + hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); + case 187 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 190 /* ElementAccessExpression */: + case 149 /* ComputedPropertyName */: + case 170 /* TupleType */: + return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); + case 162 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 221 /* DoStatement */: + case 223 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile) - ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile) + return hasChildOfKind(n, 107 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 197 /* TypeOfExpression */: - case 196 /* DeleteExpression */: - case 198 /* VoidExpression */: - case 205 /* YieldExpression */: - case 206 /* SpreadElement */: + case 199 /* TypeOfExpression */: + case 198 /* DeleteExpression */: + case 200 /* VoidExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 253 /* ExportDeclaration */: - case 247 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -89858,7 +93194,7 @@ var ts; if (lastChild.kind === expectedLastToken) { return true; } - else if (lastChild.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -89993,7 +93329,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +93347,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); 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, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +93356,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90084,25 +93418,25 @@ var ts; if (!token) { return false; } - if (token.kind === 10 /* JsxText */) { + if (token.kind === 11 /* JsxText */) { return true; } //
Hello |
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 10 /* JsxText */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) { return true; } //
{ |
or
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 268 /* JsxExpression */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 270 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 268 /* JsxExpression */) { + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 270 /* JsxExpression */) { return true; } //
|
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 261 /* JsxClosingElement */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 263 /* JsxClosingElement */) { return true; } return false; @@ -90116,6 +93450,20 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; + function isInJSXText(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (ts.isJsxText(token)) { + return true; + } + if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + if (token.kind === 28 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + return false; + } + ts.isInJSXText = isInJSXText; function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { var tokenKind = token.kind; var remainingMatchingTokens = 0; @@ -90162,7 +93510,7 @@ var ts; var nTypeArguments = 0; while (token) { switch (token.kind) { - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // Found the beginning of the generic argument expression token = findPrecedingToken(token.getFullStart(), sourceFile); if (!token || !ts.isIdentifier(token)) @@ -90172,53 +93520,54 @@ var ts; } remainingLessThanTokens--; break; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: remainingLessThanTokens = +3; break; - case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: remainingLessThanTokens = +2; break; - case 29 /* GreaterThanToken */: + case 30 /* GreaterThanToken */: remainingLessThanTokens++; break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); + token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile); if (!token) return undefined; break; - case 20 /* CloseParenToken */: + case 21 /* CloseParenToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); + token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile); if (!token) return undefined; break; - case 22 /* CloseBracketToken */: + case 23 /* CloseBracketToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); + token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile); if (!token) return undefined; break; // Valid tokens in a type name. Skip. - case 26 /* CommaToken */: + case 27 /* CommaToken */: nTypeArguments++; break; - case 36 /* EqualsGreaterThanToken */: - case 71 /* Identifier */: - case 9 /* StringLiteral */: + case 37 /* EqualsGreaterThanToken */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 103 /* TypeOfKeyword */: - case 85 /* ExtendsKeyword */: - case 128 /* KeyOfKeyword */: - case 23 /* DotToken */: - case 49 /* BarToken */: - case 55 /* QuestionToken */: - case 56 /* ColonToken */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 104 /* TypeOfKeyword */: + case 86 /* ExtendsKeyword */: + case 129 /* KeyOfKeyword */: + case 24 /* DotToken */: + case 50 /* BarToken */: + case 56 /* QuestionToken */: + case 57 /* ColonToken */: break; default: if (ts.isTypeNode(token)) { @@ -90250,7 +93599,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90273,10 +93622,10 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 162 /* TypeReference */ || node.kind === 189 /* CallExpression */) { + if (node.kind === 164 /* TypeReference */ || node.kind === 191 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 238 /* ClassDeclaration */ || node.kind === 239 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 240 /* ClassDeclaration */ || node.kind === 241 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -90287,8 +93636,8 @@ var ts; } ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { - if (kind === 9 /* StringLiteral */ - || kind === 12 /* RegularExpressionLiteral */ + if (kind === 10 /* StringLiteral */ + || kind === 13 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; } @@ -90296,7 +93645,7 @@ var ts; } ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; function isPunctuation(kind) { - return 17 /* FirstPunctuation */ <= kind && kind <= 70 /* LastPunctuation */; + return 18 /* FirstPunctuation */ <= kind && kind <= 71 /* LastPunctuation */; } ts.isPunctuation = isPunctuation; function isInsideTemplateLiteral(node, position, sourceFile) { @@ -90306,9 +93655,9 @@ var ts; ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: return true; } return false; @@ -90321,18 +93670,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 185 /* ArrayLiteralExpression */ || - node.kind === 186 /* ObjectLiteralExpression */) { + if (node.kind === 187 /* ArrayLiteralExpression */ || + node.kind === 188 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 202 /* BinaryExpression */ && + if (node.parent.kind === 204 /* BinaryExpression */ && node.parent.left === node && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { + node.parent.operatorToken.kind === 59 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 225 /* ForOfStatement */ && + if (node.parent.kind === 227 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -90340,7 +93689,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 273 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 275 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -90364,7 +93713,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +93721,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90384,21 +93733,22 @@ var ts; } ts.createTextChange = createTextChange; ts.typeKeywords = [ - 119 /* AnyKeyword */, - 122 /* BooleanKeyword */, - 86 /* FalseKeyword */, - 128 /* KeyOfKeyword */, - 131 /* NeverKeyword */, - 95 /* NullKeyword */, - 134 /* NumberKeyword */, - 135 /* ObjectKeyword */, - 137 /* StringKeyword */, - 138 /* SymbolKeyword */, - 101 /* TrueKeyword */, - 105 /* VoidKeyword */, - 140 /* UndefinedKeyword */, - 141 /* UniqueKeyword */, - 142 /* UnknownKeyword */, + 120 /* AnyKeyword */, + 146 /* BigIntKeyword */, + 123 /* BooleanKeyword */, + 87 /* FalseKeyword */, + 129 /* KeyOfKeyword */, + 132 /* NeverKeyword */, + 96 /* NullKeyword */, + 135 /* NumberKeyword */, + 136 /* ObjectKeyword */, + 138 /* StringKeyword */, + 139 /* SymbolKeyword */, + 102 /* TrueKeyword */, + 106 /* VoidKeyword */, + 141 /* UndefinedKeyword */, + 142 /* UniqueKeyword */, + 143 /* UnknownKeyword */, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); @@ -90434,7 +93784,7 @@ var ts; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { - return name.kind === 147 /* ComputedPropertyName */ + return name.kind === 149 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.getTextOfIdentifierOrLiteral(name); @@ -90510,19 +93860,20 @@ var ts; } return ts.firstDefined(symbol.declarations, function (decl) { var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined; + return name && name.kind === 72 /* Identifier */ ? name.escapedText : undefined; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { - // See GH#16922 - ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); - return propSymbol.target; - } - return propSymbol; + return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; /** @@ -90575,7 +93926,6 @@ var ts; return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); } ts.findModifier = findModifier; - /* @internal */ function insertImport(changes, sourceFile, importDecl) { var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); if (lastImportDeclaration) { @@ -90599,7 +93949,7 @@ var ts; /* @internal */ (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 149 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 151 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -90625,6 +93975,7 @@ var ts; writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, @@ -90633,7 +93984,7 @@ var ts; writeSymbol: writeSymbol, writeLine: writeLine, write: unknownWrite, - writeTextOfNode: unknownWrite, + writeComment: unknownWrite, getText: function () { return ""; }, getTextPos: function () { return 0; }, getColumn: function () { return 0; }, @@ -90784,7 +94135,6 @@ var ts; return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; - /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -90818,9 +94168,7 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { - return !!location.parent && - (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && - location.parent.propertyName === location; + return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; /** @@ -90866,6 +94214,13 @@ var ts; return position; } ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; + function getPrecedingNonSpaceCharacterPosition(text, position) { + while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) { + position -= 1; + } + return position + 1; + } + ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition; /** * Creates a deep, memberwise clone of a node with no source map location. * @@ -90883,7 +94238,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +94246,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -90906,14 +94261,14 @@ var ts; ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_7 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_7)) { - clone_7.textSourceNode = node; + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_7)) { - clone_7.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_7, node); + return ts.setTextRange(clone_8, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -90932,7 +94287,6 @@ var ts; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - /* @internal */ function suppressLeadingAndTrailingTrivia(node) { suppressLeadingTrivia(node); suppressTrailingTrivia(node); @@ -90941,7 +94295,6 @@ var ts; /** * Sets EmitFlags to suppress leading trivia on the node. */ - /* @internal */ function suppressLeadingTrivia(node) { addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); } @@ -90949,7 +94302,6 @@ var ts; /** * Sets EmitFlags to suppress trailing trivia on the node. */ - /* @internal */ function suppressTrailingTrivia(node) { addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } @@ -90963,7 +94315,6 @@ var ts; function getFirstChild(node) { return node.forEachChild(function (child) { return child; }); } - /* @internal */ function getUniqueName(baseName, sourceFile) { var nameText = baseName; for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { @@ -90977,7 +94328,6 @@ var ts; * to be on the reference, rather than the declaration, because it's closer to where the * user was before extracting it. */ - /* @internal */ function getRenameLocation(edits, renameFilename, name, preferLastLocation) { var delta = 0; var lastPos = -1; @@ -91031,6 +94381,72 @@ var ts; idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 192 /* NewExpression */: + return checker.getContextualType(parent); + case 204 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 271 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + ts.getContextualTypeFromParent = getContextualTypeFromParent; + function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } + } + ts.quote = quote; + function isEqualityOperatorKind(kind) { + switch (kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return true; + default: + return false; + } + } + ts.isEqualityOperatorKind = isEqualityOperatorKind; + function isStringLiteralOrTemplate(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + return true; + default: + return false; + } + } + ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate; + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + ts.hasIndexSignature = hasIndexSignature; + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } + ts.getSwitchedType = getSwitchedType; })(ts || (ts = {})); var ts; (function (ts) { @@ -91069,7 +94485,7 @@ var ts; text = prefix + text; var offset = prefix.length; if (pushTemplate) { - templateStack.push(14 /* TemplateHead */); + templateStack.push(15 /* TemplateHead */); } scanner.setText(text); var endOfLineState = 0 /* None */; @@ -91111,65 +94527,65 @@ var ts; } while (token !== 1 /* EndOfFileToken */); function handleToken() { switch (token) { - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 12 /* RegularExpressionLiteral */) { - token = 12 /* RegularExpressionLiteral */; + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + token = 13 /* RegularExpressionLiteral */; } break; - case 27 /* LessThanToken */: - if (lastNonTriviaToken === 71 /* Identifier */) { + case 28 /* LessThanToken */: + if (lastNonTriviaToken === 72 /* Identifier */) { // Could be the start of something generic. Keep track of that by bumping // up the current count of generic contexts we may be in. angleBracketStack++; } break; - case 29 /* GreaterThanToken */: + case 30 /* GreaterThanToken */: if (angleBracketStack > 0) { // If we think we're currently in something generic, then mark that that // generic entity is complete. angleBracketStack--; } break; - case 119 /* AnyKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: + case 120 /* AnyKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* 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, // causing a noisy experience for the user. - token = 71 /* Identifier */; + token = 72 /* Identifier */; } break; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: templateStack.push(token); break; - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { templateStack.push(token); } break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 14 /* TemplateHead */) { + if (lastTemplateStackToken === 15 /* TemplateHead */) { token = scanner.reScanTemplateToken(); // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. - if (token === 16 /* TemplateTail */) { + if (token === 17 /* TemplateTail */) { templateStack.pop(); } else { - ts.Debug.assertEqual(token, 15 /* TemplateMiddle */, "Should have been a template middle."); + ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle."); } } else { - ts.Debug.assertEqual(lastTemplateStackToken, 17 /* OpenBraceToken */, "Should have been an open brace"); + ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace"); templateStack.pop(); } } @@ -91178,15 +94594,15 @@ var ts; if (!ts.isKeyword(token)) { break; } - if (lastNonTriviaToken === 23 /* DotToken */) { - token = 71 /* Identifier */; + if (lastNonTriviaToken === 24 /* DotToken */) { + token = 72 /* Identifier */; } else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { // We have two keywords in a row. Only treat the second as a keyword if // it's a sequence that could legally occur in the language. Otherwise // treat it as an identifier. This way, if someone writes "private var" // we recognize that 'var' is actually an identifier here. - token = 71 /* Identifier */; + token = 72 /* Identifier */; } } } @@ -91200,22 +94616,23 @@ var ts; /// we have a series of divide operator. this list allows us to be more accurate by ruling out /// locations where a regexp cannot exist. var noRegexTable = ts.arrayToNumericMap([ - 71 /* Identifier */, - 9 /* StringLiteral */, + 72 /* Identifier */, + 10 /* StringLiteral */, 8 /* NumericLiteral */, - 12 /* RegularExpressionLiteral */, - 99 /* ThisKeyword */, - 43 /* PlusPlusToken */, - 44 /* MinusMinusToken */, - 20 /* CloseParenToken */, - 22 /* CloseBracketToken */, - 18 /* CloseBraceToken */, - 101 /* TrueKeyword */, - 86 /* FalseKeyword */, + 9 /* BigIntLiteral */, + 13 /* RegularExpressionLiteral */, + 100 /* ThisKeyword */, + 44 /* PlusPlusToken */, + 45 /* MinusMinusToken */, + 21 /* CloseParenToken */, + 23 /* CloseBracketToken */, + 19 /* CloseBraceToken */, + 102 /* TrueKeyword */, + 87 /* FalseKeyword */, ], function (token) { return token; }, function () { return true; }); function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { switch (token) { - case 9 /* StringLiteral */: { + case 10 /* StringLiteral */: { // Check to see if we finished up on a multiline string literal. if (!scanner.isUnterminated()) return undefined; @@ -91239,15 +94656,15 @@ var ts; return undefined; } switch (token) { - case 16 /* TemplateTail */: + case 17 /* TemplateTail */: return 5 /* InTemplateMiddleOrTail */; - case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; default: return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } - return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; } } function pushEncodedClassification(start, end, offset, classification, result) { @@ -91273,7 +94690,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +94699,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -91296,6 +94713,7 @@ var ts; case 1 /* comment */: return ts.TokenClass.Comment; case 3 /* keyword */: return ts.TokenClass.Keyword; case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral; case 5 /* operator */: return ts.TokenClass.Operator; case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; @@ -91322,10 +94740,10 @@ var ts; return true; } switch (keyword2) { - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 123 /* ConstructorKeyword */: - case 115 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 124 /* ConstructorKeyword */: + case 116 /* StaticKeyword */: return true; // Allow things like "public get", "public constructor" and "public static". default: return false; // Any other keyword following "public" is actually an identifier, not a real keyword. @@ -91358,43 +94776,43 @@ var ts; } function isBinaryExpressionOperatorToken(token) { switch (token) { - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 48 /* AmpersandToken */: - case 50 /* CaretToken */: - case 49 /* BarToken */: - case 53 /* AmpersandAmpersandToken */: - case 54 /* BarBarToken */: - case 69 /* BarEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 58 /* EqualsToken */: - case 26 /* CommaToken */: + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 49 /* AmpersandToken */: + case 51 /* CaretToken */: + case 50 /* BarToken */: + case 54 /* AmpersandAmpersandToken */: + case 55 /* BarBarToken */: + case 70 /* BarEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 59 /* EqualsToken */: + case 27 /* CommaToken */: return true; default: return false; @@ -91402,12 +94820,12 @@ var ts; } function isPrefixUnaryExpressionOperatorToken(token) { switch (token) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: return true; default: return false; @@ -91420,15 +94838,17 @@ var ts; else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { return 5 /* operator */; } - else if (token >= 17 /* FirstPunctuation */ && token <= 70 /* LastPunctuation */) { + else if (token >= 18 /* FirstPunctuation */ && token <= 71 /* LastPunctuation */) { return 10 /* punctuation */; } switch (token) { case 8 /* NumericLiteral */: return 4 /* numericLiteral */; - case 9 /* StringLiteral */: + case 9 /* BigIntLiteral */: + return 25 /* bigintLiteral */; + case 10 /* StringLiteral */: return 6 /* stringLiteral */; - case 12 /* RegularExpressionLiteral */: + case 13 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; case 7 /* ConflictMarkerTrivia */: case 3 /* MultiLineCommentTrivia */: @@ -91437,7 +94857,7 @@ var ts; case 5 /* WhitespaceTrivia */: case 4 /* NewLineTrivia */: return 8 /* whiteSpace */; - case 71 /* Identifier */: + case 72 /* Identifier */: default: if (ts.isTemplateLiteralKind(token)) { return 6 /* stringLiteral */; @@ -91462,10 +94882,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 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -91540,6 +94960,7 @@ var ts; case 2 /* identifier */: return "identifier" /* identifier */; case 3 /* keyword */: return "keyword" /* keyword */; case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */; case 5 /* operator */: return "operator" /* operator */; case 6 /* stringLiteral */: return "string" /* stringLiteral */; case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; @@ -91673,22 +95094,22 @@ var ts; if (tag.pos !== pos) { pushCommentRange(pos, tag.pos - pos); } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); // "@" + pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 297 /* JSDocParameterTag */: + case 299 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; break; - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; break; - case 298 /* JSDocReturnTag */: + case 300 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; break; @@ -91759,10 +95180,10 @@ var ts; return true; } var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 10 /* JsxText */ && classifiedElementName === undefined) { + if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) { return false; } - var tokenStart = node.kind === 10 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { @@ -91775,22 +95196,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -91807,7 +95228,7 @@ var ts; } // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. - if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { + if (tokenKind === 28 /* LessThanToken */ || tokenKind === 30 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { @@ -91817,19 +95238,19 @@ var ts; if (ts.isPunctuation(tokenKind)) { if (token) { var parent = token.parent; - if (tokenKind === 58 /* EqualsToken */) { + if (tokenKind === 59 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (parent.kind === 235 /* VariableDeclaration */ || - parent.kind === 152 /* PropertyDeclaration */ || - parent.kind === 149 /* Parameter */ || - parent.kind === 265 /* JsxAttribute */) { + if (parent.kind === 237 /* VariableDeclaration */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 151 /* Parameter */ || + parent.kind === 267 /* JsxAttribute */) { return 5 /* operator */; } } - if (parent.kind === 202 /* BinaryExpression */ || - parent.kind === 200 /* PrefixUnaryExpression */ || - parent.kind === 201 /* PostfixUnaryExpression */ || - parent.kind === 203 /* ConditionalExpression */) { + if (parent.kind === 204 /* BinaryExpression */ || + parent.kind === 202 /* PrefixUnaryExpression */ || + parent.kind === 203 /* PostfixUnaryExpression */ || + parent.kind === 205 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -91838,11 +95259,14 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 265 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + else if (tokenKind === 9 /* BigIntLiteral */) { + return 25 /* bigintLiteral */; } - else if (tokenKind === 12 /* RegularExpressionLiteral */) { + else if (tokenKind === 10 /* StringLiteral */) { + // TODO: GH#18217 + return token.parent.kind === 267 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + } + else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */; } @@ -91850,38 +95274,38 @@ var ts; // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } - else if (tokenKind === 10 /* JsxText */) { + else if (tokenKind === 11 /* JsxText */) { return 23 /* jsxText */; } - else if (tokenKind === 71 /* Identifier */) { + else if (tokenKind === 72 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 149 /* Parameter */: + case 151 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -91915,37 +95339,245 @@ var ts; (function (ts) { var Completions; (function (Completions) { - var PathCompletions; - (function (PathCompletions) { - function nameAndKind(name, kind) { - return { name: name, kind: kind }; + var StringCompletions; + (function (StringCompletions) { + function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + if (ts.isInReferenceComment(sourceFile, position)) { + var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host), sourceFile, checker, log, preferences); + } + } + StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + if (completion === undefined) { + return undefined; + } + switch (completion.kind) { + case 0 /* Paths */: + return convertPathCompletions(completion.paths); + case 1 /* Properties */: { + var entries = []; + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; + } + case 2 /* Types */: { + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; + } + default: + return ts.Debug.assertNever(completion); + } + } + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + if (!contextToken || !ts.isStringLiteralLike(contextToken)) + return undefined; + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); + } + StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function convertPathCompletions(pathCompletions) { + var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. + var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. + var entries = pathCompletions.map(function (_a) { + var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension; + return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span }); + }); + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function kindModifiersFromExtension(extension) { + switch (extension) { + case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */; + case ".js" /* Js */: return ".js" /* jsModifier */; + case ".json" /* Json */: return ".json" /* jsonModifier */; + case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */; + case ".ts" /* Ts */: return ".ts" /* tsModifier */; + case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */; + case undefined: return "" /* none */; + default: + return ts.Debug.assertNever(extension); + } + } + var StringLiteralCompletionKind; + (function (StringLiteralCompletionKind) { + StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; + })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + var parent = node.parent; + switch (parent.kind) { + case 182 /* LiteralType */: + switch (parent.parent.kind) { + case 164 /* TypeReference */: + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; + case 180 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); + case 183 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 173 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } + default: + return undefined; + } + case 275 /* PropertyAssignment */: + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); + } + return fromContextualType(); + case 190 /* ElementAccessExpression */: { + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return undefined; + } + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through (is `require("")` or `import("")`) + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 259 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + default: + return fromContextualType(); + } + function fromContextualType() { + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; + } + } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } + function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { + var isNewIdentifier = false; + var uniques = ts.createMap(); + var candidates = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + var types = ts.flatMap(candidates, function (candidate) { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + return; + var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); + return getStringLiteralTypes(type, uniques); + }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; + } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: ts.hasIndexSignature(type) }; + } + function getStringLiteralTypes(type, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } + if (!type) + return ts.emptyArray; + type = ts.skipConstraint(type); + return type.isUnion() + ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) + : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) + ? [type] + : ts.emptyArray; + } + function nameAndKind(name, kind, extension) { + return { name: name, kind: kind, extension: extension }; + } + function directoryResult(name) { + return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined); } function addReplacementSpans(text, textStart, names) { var span = getDirectoryFragmentTextSpan(text, textStart); return names.map(function (_a) { - var name = _a.name, kind = _a.kind; - return ({ name: name, kind: kind, span: span }); + var name = _a.name, kind = _a.kind, extension = _a.extension; + return ({ name: name, kind: kind, extension: extension, span: span }); }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); } - PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { - var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); - if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); - } - else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); - } + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + } + function getExtensionOptions(compilerOptions, includeExtensions) { + if (includeExtensions === void 0) { includeExtensions = false; } + return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; + } + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { + var extensionOptions = getExtensionOptions(compilerOptions); + if (compilerOptions.rootDirs) { + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); } } function getSupportedExtensionsForModuleResolution(compilerOptions) { @@ -91958,31 +95590,27 @@ var ts; * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option */ - function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { // Make all paths absolute/normalized if they are not already rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { - return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; + return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined; }); // TODO: GH#18217 // Now find a path for each potential directory that is to be merged with the one containing the script - return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); - var result = []; - for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { - var baseDirectory = baseDirectories_1[_i]; - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); - } - return result; + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); + return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); } /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) { + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { + var extensions = _a.extensions, includeExtensions = _a.includeExtensions; if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; @@ -92003,46 +95631,77 @@ var ts; var absolutePath = ts.resolvePath(scriptPath, fragment); var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - if (tryDirectoryExists(host, baseDirectory)) { - // Enumerate the available files if possible - var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); - if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - var foundFiles = ts.createMap(); - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var filePath = files_3[_i]; - filePath = ts.normalizePath(filePath); - if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { - continue; - } - var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.has(foundFileName)) { - foundFiles.set(foundFileName, true); - } + if (!tryDirectoryExists(host, baseDirectory)) + return result; + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ + var foundFiles = ts.createMap(); // maps file to its extension + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { + continue; } - ts.forEachKey(foundFiles, function (foundFile) { - result.push(nameAndKind(foundFile, "script" /* scriptElement */)); - }); + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); } - // If possible, get folder completion as well - var directories = tryGetDirectories(host, baseDirectory); - if (directories) { - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var directory = directories_1[_a]; - var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - if (directoryName !== "@types") { - result.push(nameAndKind(directoryName, "directory" /* directory */)); - } + foundFiles.forEach(function (ext, foundFile) { + result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext)); + }); + } + // If possible, get folder completion as well + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var directory = directories_1[_b]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + if (directoryName !== "@types") { + result.push(directoryResult(directoryName)); + } + } + } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); } } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind, extension) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind, extension)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; + _loop_10(name, kind, extension); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92053,60 +95712,51 @@ var ts; function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; - var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); + var extensionOptions = getExtensionOptions(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); } } - var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; - result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); + var fragmentDirectory = getFragmentDirectory(fragment); + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; + result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined)); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_11 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; - result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); } } if (!foundGlobal) { ts.forEachAncestorDirectory(scriptPath, function (ancestor) { var nodeModules = ts.combinePaths(ancestor, "node_modules"); if (tryDirectoryExists(host, nodeModules)) { - getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result); } }); } } return result; } + function getFragmentDirectory(fragment) { + return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + } function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. @@ -92118,7 +95768,7 @@ var ts; return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); function justPathMappingName(name) { - return ts.startsWith(name, fragment) ? [{ name: name, kind: "directory" /* directory */ }] : ts.emptyArray; + return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; } } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { @@ -92146,15 +95796,20 @@ var ts; // that encodes the suffix, but we would have to escape the character "?" which readDirectory // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]).map(function (name) { return ({ name: name, kind: "script" /* scriptElement */ }); }); - var directories = tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }).map(function (name) { return ({ name: name, kind: "directory" /* directory */ }); }); - // Trim away prefix and suffix - return ts.mapDefined(ts.concatenate(matches, directories), function (_a) { - var name = _a.name, kind = _a.kind; - var normalizedMatch = ts.normalizePath(name); - var inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix); - return inner !== undefined ? { name: removeLeadingDirectorySeparator(ts.removeFileExtension(inner)), kind: kind } : undefined; + var matches = ts.mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var extension = ts.tryGetExtensionFromPath(match); + var name = trimPrefixAndSuffix(match); + return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension); }); + var directories = ts.mapDefined(tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { + var name = trimPrefixAndSuffix(dir); + return name === undefined ? undefined : directoryResult(name); + }); + return matches.concat(directories); + function trimPrefixAndSuffix(path) { + var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); + return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner); + } } function withoutStartAndEnd(s, start, end) { return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; @@ -92189,62 +95844,48 @@ var ts; } var prefix = match[1], kind = match[2], toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) - : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) - : undefined; - return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) + : ts.Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, names); } - PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; - function getCompletionEntriesFromTypings(host, options, scriptPath, result) { + function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options var seen = ts.createMap(); - if (options.types) { - for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); - pushResult(moduleName); - } + var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; + for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) { + var root = typeRoots_2[_i]; + getCompletionEntriesFromDirectories(root); } - else if (host.getDirectories) { - var typeRoots = void 0; - try { - typeRoots = ts.getEffectiveTypeRoots(options, host); - } - catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ } - if (typeRoots) { - for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { - var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(root); - } - } - // Also get all @types typings installed in visible node_modules directories - for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { - var packageJson = _e[_d]; - var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(typesDir); - } + // Also get all @types typings installed in visible node_modules directories + for (var _a = 0, _b = findPackageJsons(scriptPath, host); _a < _b.length; _a++) { + var packageJson = _b[_a]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); } return result; function getCompletionEntriesFromDirectories(directory) { - ts.Debug.assert(!!host.getDirectories); - if (tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); - pushResult(moduleName); + if (!tryDirectoryExists(host, directory)) + return; + for (var _i = 0, _a = tryGetDirectories(host, directory); _i < _a.length; _i++) { + var typeDirectoryName = _a[_i]; + var packageName = ts.unmangleScopedPackageName(typeDirectoryName); + if (options.types && !ts.contains(options.types, packageName)) + continue; + if (fragmentDirectory === undefined) { + if (!seen.has(packageName)) { + result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + seen.set(packageName, true); + } + } + else { + var baseDirectory = ts.combinePaths(directory, typeDirectoryName); + var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host)); + if (remainingFragment !== undefined) { + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result); } } - } - } - function pushResult(moduleName) { - if (!seen.has(moduleName)) { - result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); - seen.set(moduleName, true); } } } @@ -92259,6 +95900,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92322,27 +95975,27 @@ var ts; return tryIOAndConsumeErrors(host, host.fileExists, path); } function tryDirectoryExists(host, path) { - try { - return ts.directoryProbablyExists(path, host); - } - catch ( /*ignore*/_a) { /*ignore*/ } - return false; + return tryAndIgnoreErrors(function () { return ts.directoryProbablyExists(path, host); }) || false; } function tryIOAndConsumeErrors(host, toApply) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } + return tryAndIgnoreErrors(function () { return toApply && toApply.apply(host, args); }); + } + function tryAndIgnoreErrors(cb) { try { - return toApply && toApply.apply(host, args); + return cb(); + } + catch (_a) { + return undefined; } - catch ( /*ignore*/_a) { /*ignore*/ } - return undefined; } function containsSlash(fragment) { return ts.stringContains(fragment, ts.directorySeparator); } - })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); + })(StringCompletions = Completions.StringCompletions || (Completions.StringCompletions = {})); })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -92366,11 +96019,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92381,20 +96035,15 @@ var ts; function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); - if (ts.isInReferenceComment(sourceFile, position)) { - var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries && convertPathCompletions(entries); - } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; - if (ts.isInString(sourceFile, position, contextToken)) { - return !contextToken || !ts.isStringLiteralLike(contextToken) - ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); + var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); + if (stringCompletions) { + return stringCompletions; } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) - && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { + && (contextToken.kind === 73 /* BreakKeyword */ || contextToken.kind === 78 /* ContinueKeyword */ || contextToken.kind === 72 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined); @@ -92417,35 +96066,6 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { - if (completion === undefined) { - return undefined; - } - switch (completion.kind) { - case 0 /* Paths */: - return convertPathCompletions(completion.paths); - case 1 /* Properties */: { - var entries = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; - } - case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; - } - default: - return ts.Debug.assertNever(completion); - } - } - function convertPathCompletions(pathCompletions) { - var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. - var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. - var entries = pathCompletions.map(function (_a) { - var name = _a.name, kind = _a.kind, span = _a.span; - return ({ name: name, kind: kind, kindModifiers: "" /* none */, sortText: "0", replacementSpan: span }); - }); - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - } function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } @@ -92459,7 +96079,7 @@ var ts; // The completion list at "1" will contain "div>" with type any // And at `
` (with a closing `>`), the completion list will contain "div". var tagName = location.parent.parent.openingElement.tagName; - var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile); + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 30 /* GreaterThanToken */, sourceFile); var entry = { name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), kind: "class" /* classElement */, @@ -92471,7 +96091,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +96099,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +96127,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92523,7 +96144,9 @@ var ts; } }); } - var completionNameForLiteral = JSON.stringify; + var completionNameForLiteral = function (literal) { + return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); + }; function createCompletionEntryForLiteral(literal) { return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" }; } @@ -92536,13 +96159,13 @@ var ts; var insertText; var replacementSpan; if (origin && origin.kind === 0 /* ThisType */) { - insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; + insertText = needsConvertPropertyAccess ? "this[" + ts.quote(name, preferences) + "]" : "this." + name; } // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { - insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]"; - var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); + insertText = needsConvertPropertyAccess ? "[" + ts.quote(name, preferences) + "]" : "[" + name + "]"; + var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); @@ -92577,18 +96200,6 @@ var ts; replacementSpan: replacementSpan, }; } - function quote(text, preferences) { - var quoted = JSON.stringify(text); - switch (preferences.quotePreference) { - case undefined: - case "double": - return quoted; - case "single": - return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; - default: - return ts.Debug.assertNever(preferences.quotePreference); - } - } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; @@ -92626,6 +96237,7 @@ var ts; log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniques; } + Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { var entries = getLabelStatementCompletions(node); if (entries.length) { @@ -92656,120 +96268,6 @@ var ts; } return entries; } - var StringLiteralCompletionKind; - (function (StringLiteralCompletionKind) { - StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; - StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; - StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; - })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); - function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { - case 180 /* LiteralType */: - switch (node.parent.parent.kind) { - case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; - case 178 /* IndexedAccessType */: - // Get all apparent property names - // i.e. interface Foo { - // foo: string; - // bar: string; - // } - // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); - case 181 /* ImportType */: - return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; - default: - return undefined; - } - case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); - } - return fromContextualType(); - case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; - if (node === argumentExpression) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); - } - return undefined; - } - case 189 /* CallExpression */: - case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { - var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); - } - // falls through (is `require("")` or `import("")`) - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 257 /* ExternalModuleReference */: - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - default: - return fromContextualType(); - } - function fromContextualType() { - // Get completion for string literal from string literal type - // i.e. var x: "hi" | "hello" = "/*completion position*/" - return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; - } - } - function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { - var isNewIdentifier = false; - var uniques = ts.createMap(); - var candidates = []; - checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); - var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) - return; - var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); - isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); - return getStringLiteralTypes(type, uniques); - }); - return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; - } - function stringLiteralCompletionsFromProperties(type) { - return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; - } - function getStringLiteralTypes(type, uniques) { - if (uniques === void 0) { uniques = ts.createMap(); } - if (!type) - return ts.emptyArray; - type = ts.skipConstraint(type); - return type.isUnion() - ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) - : type.isStringLiteral() && !(type.flags & 512 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) - ? [type] - : ts.emptyArray; - } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { var compilerOptions = program.getCompilerOptions(); var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); @@ -92808,10 +96306,7 @@ var ts; var name = entryId.name; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { - var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) - ? undefined - : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); - return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); @@ -92855,25 +96350,11 @@ var ts; }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } - function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { - switch (completion.kind) { - case 0 /* Paths */: { - var match = ts.find(completion.paths, function (p) { return p.name === name; }); - return match && createCompletionDetails(name, "" /* none */, match.kind, [ts.textPart(name)]); - } - case 1 /* Properties */: { - var match = ts.find(completion.symbols, function (s) { return s.name === name; }); - return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); - } - case 2 /* Types */: - return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; - default: - return ts.Debug.assertNever(completion); - } - } + Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; } + Completions.createCompletionDetails = createCompletionDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { @@ -92904,7 +96385,7 @@ var ts; CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; CompletionKind[CompletionKind["String"] = 4] = "String"; CompletionKind[CompletionKind["None"] = 5] = "None"; - })(CompletionKind || (CompletionKind = {})); + })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {})); function getRecommendedCompletion(previousToken, contextualType, checker) { // For a union, return the first one with a recommended completion. return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { @@ -92918,56 +96399,36 @@ var ts; function getContextualType(previousToken, position, sourceFile, checker) { var parent = previousToken.parent; switch (previousToken.kind) { - case 71 /* Identifier */: - return getContextualTypeFromParent(previousToken, checker); - case 58 /* EqualsToken */: + case 72 /* Identifier */: + return ts.getContextualTypeFromParent(previousToken, checker); + case 59 /* EqualsToken */: switch (parent.kind) { - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return checker.getContextualType(parent.initializer); // TODO: GH#18217 - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; } - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: return checker.getContextualType(parent); - case 73 /* CaseKeyword */: - return getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); - case 17 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 258 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + case 74 /* CaseKeyword */: + return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); + case 18 /* OpenBraceToken */: + return ts.isJsxExpression(parent) && parent.parent.kind !== 260 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo // At `,`, treat this as the next argument after the comma. - ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 26 /* CommaToken */ ? 1 : 0)) - : isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) + : ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) // completion at `x ===/**/` should be for the right side ? checker.getTypeAtLocation(parent.left) : checker.getContextualType(previousToken); } } - function getContextualTypeFromParent(node, checker) { - var parent = node.parent; - switch (parent.kind) { - case 190 /* NewExpression */: - return checker.getContextualType(parent); - case 202 /* BinaryExpression */: { - var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; - return isEqualityOperatorKind(operatorToken.kind) - ? checker.getTypeAtLocation(node === right ? left : right) - : checker.getContextualType(node); - } - case 269 /* CaseClause */: - return parent.expression === node ? getSwitchedType(parent, checker) : undefined; - default: - return checker.getContextualType(node); - } - } - function getSwitchedType(caseClause, checker) { - return checker.getTypeAtLocation(caseClause.parent.parent.expression); - } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); if (chain) @@ -92975,7 +96436,7 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 277 /* SourceFile */; }); + return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; }); } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { var typeChecker = program.getTypeChecker(); @@ -93026,11 +96487,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 281 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 303 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -93056,9 +96517,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.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { - var start_4 = ts.timestamp(); + var start_3 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 - log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -93077,21 +96538,21 @@ var ts; return undefined; } var parent = contextToken.parent; - if (contextToken.kind === 23 /* DotToken */) { + if (contextToken.kind === 24 /* DotToken */) { isRightOfDot = true; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; break; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: node = parent.left; break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: node = parent.name; break; - case 181 /* ImportType */: - case 212 /* MetaProperty */: + case 183 /* ImportType */: + case 214 /* MetaProperty */: node = parent; break; default: @@ -93104,53 +96565,56 @@ var ts; // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 187 /* PropertyAccessExpression */) { + if (parent && parent.kind === 189 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } // Fix location if (currentToken.parent === location) { switch (currentToken.kind) { - case 29 /* GreaterThanToken */: - if (currentToken.parent.kind === 258 /* JsxElement */ || currentToken.parent.kind === 260 /* JsxOpeningElement */) { + case 30 /* GreaterThanToken */: + if (currentToken.parent.kind === 260 /* JsxElement */ || currentToken.parent.kind === 262 /* JsxOpeningElement */) { location = currentToken; } break; - case 41 /* SlashToken */: - if (currentToken.parent.kind === 259 /* JsxSelfClosingElement */) { + case 42 /* SlashToken */: + if (currentToken.parent.kind === 261 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 261 /* JsxClosingElement */: - if (contextToken.kind === 41 /* SlashToken */) { + case 263 /* JsxClosingElement */: + if (contextToken.kind === 42 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 259 /* JsxSelfClosingElement */: - case 258 /* JsxElement */: - case 260 /* JsxOpeningElement */: - if (contextToken.kind === 27 /* LessThanToken */) { + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + case 262 /* JsxOpeningElement */: + if (contextToken.kind === 28 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: switch (previousToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: isJsxInitializer = true; break; - case 71 /* Identifier */: + case 72 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 59 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +96636,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +96645,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93196,11 +96662,11 @@ var ts; return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: - case 298 /* JSDocReturnTag */: - case 300 /* JSDocTypeTag */: - case 302 /* JSDocTypedefTag */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 304 /* JSDocTypedefTag */: return true; default: return false; @@ -93240,15 +96706,15 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 277 /* SourceFile */ && d.kind !== 242 /* ModuleDeclaration */ && d.kind !== 241 /* EnumDeclaration */; })) { + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; } } } - if (ts.isMetaProperty(node) && (node.keywordToken === 94 /* NewKeyword */ || node.keywordToken === 91 /* ImportKeyword */)) { - var completion = (node.keywordToken === 94 /* NewKeyword */) ? "target" : "meta"; + if (ts.isMetaProperty(node) && (node.keywordToken === 95 /* NewKeyword */ || node.keywordToken === 92 /* ImportKeyword */)) { + var completion = (node.keywordToken === 95 /* NewKeyword */) ? "target" : "meta"; symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); return; } @@ -93269,7 +96735,7 @@ var ts; else { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 181 /* ImportType */ ? node : node.parent, type, symbol)) { + if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 183 /* ImportType */ ? node : node.parent, type, symbol)) { addPropertySymbol(symbol); } } @@ -93317,24 +96783,22 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { var jsxContainer = tryGetContainingJsxElement(contextToken); // Cursor is inside a JSX self-closing element or opening element - var attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); if (!attrsType) return 0 /* Continue */; - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties); completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,10 +96835,11 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var isTypeOnly = isTypeOnlyCompletion(); + var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode); if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { @@ -93399,31 +96864,31 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 277 /* SourceFile */: - case 204 /* TemplateExpression */: - case 268 /* JsxExpression */: - case 216 /* Block */: + case 279 /* SourceFile */: + case 206 /* TemplateExpression */: + case 270 /* JsxExpression */: + case 218 /* Block */: return true; default: return ts.isStatement(scopeNode); } } function filterGlobalCompletion(symbols) { - var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); - if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + var isTypeOnly = isTypeOnlyCompletion(); + var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); + if (isTypeOnly) + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93438,52 +96903,49 @@ var ts; if (allowTypes) { // Its a type, but you can reach it by namespace.type as well var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); - if (symbolAllowedAsType || isTypeOnlyCompletion) { + if (symbolAllowedAsType || isTypeOnly) { return symbolAllowedAsType; } } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } + function isTypeOnlyCompletion() { + return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 103 /* TypeOfKeyword */ && - (contextToken.parent.kind === 165 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + contextToken.kind === 104 /* TypeOfKeyword */ && + (contextToken.parent.kind === 167 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { - case 56 /* ColonToken */: - return parentKind === 152 /* PropertyDeclaration */ || - parentKind === 151 /* PropertySignature */ || - parentKind === 149 /* Parameter */ || - parentKind === 235 /* VariableDeclaration */ || + case 57 /* ColonToken */: + return parentKind === 154 /* PropertyDeclaration */ || + parentKind === 153 /* PropertySignature */ || + parentKind === 151 /* Parameter */ || + parentKind === 237 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); - case 58 /* EqualsToken */: - return parentKind === 240 /* TypeAliasDeclaration */; - case 118 /* AsKeyword */: - return parentKind === 210 /* AsExpression */; + case 59 /* EqualsToken */: + return parentKind === 242 /* TypeAliasDeclaration */; + case 119 /* AsKeyword */: + return parentKind === 212 /* AsExpression */; } } return false; } - function symbolCanBeReferencedAtTypeLocation(symbol) { - symbol = symbol.exportSymbol || symbol; - // This is an alias, follow what it aliases - symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { - return true; - } - if (symbol.flags & 1536 /* Module */) { - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - // If the exported symbols contains type, - // symbol can be referenced at locations where type is allowed - return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); - } - return false; + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { + if (seenModules === void 0) { seenModules = ts.createMap(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); + return !!(sym.flags & 67897832 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { var tokenTextLowerCase = tokenText.toLowerCase(); @@ -93498,19 +96960,29 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details. // This is just to avoid adding duplicate completion entries. // - // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. - // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + // If `symbol.parent !== ...`, this is an `export * from "foo"` re-export. Those don't create new symbols. if (typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol - || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + || ts.some(symbol.declarations, function (d) { + // If `!!d.name.originalKeywordKind`, this is `export { _break as break };` -- skip this and prefer the keyword completion. + // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + return ts.isExportSpecifier(d) && (d.propertyName ? ts.isIdentifierANonContextualKeyword(d.name) : !!d.parent.parent.moduleSpecifier); + })) { continue; } - var isDefaultExport = symbol.name === "default" /* Default */; + var isDefaultExport = symbol.escapedName === "default" /* Default */; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } @@ -93564,15 +97036,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 10 /* JsxText */) { + if (contextToken.kind === 11 /* JsxText */) { return true; } - if (contextToken.kind === 29 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 260 /* JsxOpeningElement */) { + if (contextToken.kind === 30 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 262 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 261 /* JsxClosingElement */ || contextToken.parent.kind === 259 /* JsxSelfClosingElement */) { - return !!contextToken.parent.parent && contextToken.parent.parent.kind === 258 /* JsxElement */; + if (contextToken.parent.kind === 263 /* JsxClosingElement */ || contextToken.parent.kind === 261 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 260 /* JsxElement */; } } return false; @@ -93582,41 +97054,41 @@ var ts; var containingNodeKind = previousToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(previousToken)) { - case 26 /* CommaToken */: - return containingNodeKind === 189 /* CallExpression */ // func( a, | - || containingNodeKind === 155 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 190 /* NewExpression */ // new C(a, | - || containingNodeKind === 185 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 202 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 163 /* FunctionType */; // var x: (s: string, list| - case 19 /* OpenParenToken */: - return containingNodeKind === 189 /* CallExpression */ // func( | - || containingNodeKind === 155 /* Constructor */ // constructor( | - || containingNodeKind === 190 /* NewExpression */ // new C(a| - || containingNodeKind === 193 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 175 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ - case 21 /* OpenBracketToken */: - return containingNodeKind === 185 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 160 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 147 /* ComputedPropertyName */; // [ | /* this can become an index signature */ - case 129 /* ModuleKeyword */: // module | - case 130 /* NamespaceKeyword */: // namespace | + case 27 /* CommaToken */: + return containingNodeKind === 191 /* CallExpression */ // func( a, | + || containingNodeKind === 157 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 192 /* NewExpression */ // new C(a, | + || containingNodeKind === 187 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 204 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 165 /* FunctionType */; // var x: (s: string, list| + case 20 /* OpenParenToken */: + return containingNodeKind === 191 /* CallExpression */ // func( | + || containingNodeKind === 157 /* Constructor */ // constructor( | + || containingNodeKind === 192 /* NewExpression */ // new C(a| + || containingNodeKind === 195 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 177 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 22 /* OpenBracketToken */: + return containingNodeKind === 187 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 162 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 149 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 130 /* ModuleKeyword */: // module | + case 131 /* NamespaceKeyword */: // namespace | return true; - case 23 /* DotToken */: - return containingNodeKind === 242 /* ModuleDeclaration */; // module A.| - case 17 /* OpenBraceToken */: - return containingNodeKind === 238 /* ClassDeclaration */; // class A{ | - case 58 /* EqualsToken */: - return containingNodeKind === 235 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 202 /* BinaryExpression */; // x = a| - case 14 /* TemplateHead */: - return containingNodeKind === 204 /* TemplateExpression */; // `aa ${| - case 15 /* TemplateMiddle */: - return containingNodeKind === 214 /* TemplateSpan */; // `aa ${10} dd ${| - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - return containingNodeKind === 152 /* PropertyDeclaration */; // class A{ public | + case 24 /* DotToken */: + return containingNodeKind === 244 /* ModuleDeclaration */; // module A.| + case 18 /* OpenBraceToken */: + return containingNodeKind === 240 /* ClassDeclaration */; // class A{ | + case 59 /* EqualsToken */: + return containingNodeKind === 237 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 204 /* BinaryExpression */; // x = a| + case 15 /* TemplateHead */: + return containingNodeKind === 206 /* TemplateExpression */; // `aa ${| + case 16 /* TemplateMiddle */: + return containingNodeKind === 216 /* TemplateSpan */; // `aa ${10} dd ${| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */; // class A{ public | } } return false; @@ -93643,16 +97115,16 @@ var ts; completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 186 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 188 /* ObjectLiteralExpression */) { var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return 2 /* Fail */; - isNewIdentifierLocation = hasIndexSignature(typeForObject); + isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker); existingMembers = objectLikeContainer.properties; } else { - ts.Debug.assert(objectLikeContainer.kind === 182 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 184 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -93663,12 +97135,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 225 /* ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 149 /* Parameter */) { + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 227 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 151 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 154 /* MethodDeclaration */ || rootDeclaration.parent.kind === 157 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 156 /* MethodDeclaration */ || rootDeclaration.parent.kind === 159 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -93704,13 +97176,13 @@ var ts; */ function tryGetImportOrExportClauseCompletionSymbols() { // `import { |` or `import { a as 0, | }` - var namedImportsOrExports = contextToken && (contextToken.kind === 17 /* OpenBraceToken */ || contextToken.kind === 26 /* CommaToken */) + var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; if (!namedImportsOrExports) return 0 /* Continue */; // cursor is in an import clause // try to show exported member for imported module - var moduleSpecifier = (namedImportsOrExports.kind === 250 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifier = (namedImportsOrExports.kind === 252 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -93733,14 +97205,15 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 40 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; var classElement = contextToken.parent; var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; // If this is context token is not something we are editing now, consider if this would lead to be modifier - if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + if (contextToken.kind === 72 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { switch (contextToken.getText()) { case "private": classElementModifierFlags = classElementModifierFlags | 8 /* Private */; @@ -93767,14 +97240,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { - case 17 /* OpenBraceToken */: // const x = { | - case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; + case 18 /* OpenBraceToken */: // const x = { | + case 27 /* CommaToken */: // const x = { a: 0, | if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 40 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 72 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93791,8 +97269,8 @@ var ts; if (contextToken) { var parent = contextToken.parent; switch (contextToken.kind) { - case 19 /* OpenParenToken */: - case 26 /* CommaToken */: + case 20 /* OpenParenToken */: + case 27 /* CommaToken */: return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; default: if (isConstructorParameterCompletion(contextToken)) { @@ -93822,17 +97300,23 @@ var ts; if (contextToken) { var parent = contextToken.parent; switch (contextToken.kind) { - case 28 /* LessThanSlashToken */: - case 41 /* SlashToken */: - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: - case 266 /* JsxAttributes */: - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 259 /* JsxSelfClosingElement */ || parent.kind === 260 /* JsxOpeningElement */)) { + case 30 /* GreaterThanToken */: // End of a type argument list + case 29 /* LessThanSlashToken */: + case 42 /* SlashToken */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 268 /* JsxAttributes */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) { + if (contextToken.kind === 30 /* GreaterThanToken */) { + var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); + if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */)) + break; + } return parent; } - else if (parent.kind === 265 /* JsxAttribute */) { + else if (parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93843,8 +97327,8 @@ var ts; // 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 && ((parent.kind === 265 /* JsxAttribute */) || (parent.kind === 267 /* JsxSpreadAttribute */))) { + case 10 /* StringLiteral */: + if (parent && ((parent.kind === 267 /* JsxAttribute */) || (parent.kind === 269 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93852,10 +97336,10 @@ var ts; return parent.parent.parent; } break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: if (parent && - parent.kind === 268 /* JsxExpression */ && - parent.parent && parent.parent.kind === 265 /* JsxAttribute */) { + parent.kind === 270 /* JsxExpression */ && + parent.parent && parent.parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93863,7 +97347,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 267 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 269 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93882,67 +97366,66 @@ var ts; var parent = contextToken.parent; var containingNodeKind = parent.kind; switch (contextToken.kind) { - case 26 /* CommaToken */: - return containingNodeKind === 235 /* VariableDeclaration */ || - containingNodeKind === 236 /* VariableDeclarationList */ || - containingNodeKind === 217 /* VariableStatement */ || - containingNodeKind === 241 /* EnumDeclaration */ || // enum a { foo, | + case 27 /* CommaToken */: + return containingNodeKind === 237 /* VariableDeclaration */ || + containingNodeKind === 238 /* VariableDeclarationList */ || + containingNodeKind === 219 /* VariableStatement */ || + containingNodeKind === 243 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A= contextToken.pos); - case 23 /* DotToken */: - return containingNodeKind === 183 /* ArrayBindingPattern */; // var [.| - case 56 /* ColonToken */: - return containingNodeKind === 184 /* BindingElement */; // var {x :html| - case 21 /* OpenBracketToken */: - return containingNodeKind === 183 /* ArrayBindingPattern */; // var [x| - case 19 /* OpenParenToken */: - return containingNodeKind === 272 /* CatchClause */ || + case 24 /* DotToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [.| + case 57 /* ColonToken */: + return containingNodeKind === 186 /* BindingElement */; // var {x :html| + case 22 /* OpenBracketToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [x| + case 20 /* OpenParenToken */: + return containingNodeKind === 274 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); - case 17 /* OpenBraceToken */: - return containingNodeKind === 241 /* EnumDeclaration */; // enum a { | - case 27 /* LessThanToken */: - return containingNodeKind === 238 /* ClassDeclaration */ || // class A< | - containingNodeKind === 207 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 240 /* TypeAliasDeclaration */ || // type List< | + case 18 /* OpenBraceToken */: + return containingNodeKind === 243 /* EnumDeclaration */; // enum a { | + case 28 /* LessThanToken */: + return containingNodeKind === 240 /* ClassDeclaration */ || // class A< | + containingNodeKind === 209 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 242 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); - case 115 /* StaticKeyword */: - return containingNodeKind === 152 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); - case 24 /* DotDotDotToken */: - return containingNodeKind === 149 /* Parameter */ || - (!!parent.parent && parent.parent.kind === 183 /* ArrayBindingPattern */); // var [...z| - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - return containingNodeKind === 149 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); - case 118 /* AsKeyword */: - return containingNodeKind === 251 /* ImportSpecifier */ || - containingNodeKind === 255 /* ExportSpecifier */ || - containingNodeKind === 249 /* NamespaceImport */; - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 109 /* InterfaceKeyword */: - case 89 /* FunctionKeyword */: - case 104 /* VarKeyword */: - case 91 /* ImportKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 116 /* YieldKeyword */: - case 139 /* TypeKeyword */: // type htm| + case 116 /* StaticKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + case 25 /* DotDotDotToken */: + return containingNodeKind === 151 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 185 /* ArrayBindingPattern */); // var [...z| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 151 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + case 119 /* AsKeyword */: + return containingNodeKind === 253 /* ImportSpecifier */ || + containingNodeKind === 257 /* ExportSpecifier */ || + containingNodeKind === 251 /* NamespaceImport */; + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return !isFromObjectTypeDeclaration(contextToken); + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 110 /* InterfaceKeyword */: + case 90 /* FunctionKeyword */: + case 105 /* VarKeyword */: + case 92 /* ImportKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 117 /* YieldKeyword */: + case 140 /* TypeKeyword */: // type htm| return true; + case 40 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93962,22 +97445,23 @@ var ts; } // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 75 /* ClassKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 83 /* EnumKeyword */: - case 89 /* FunctionKeyword */: - case 109 /* InterfaceKeyword */: - case 110 /* LetKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 115 /* StaticKeyword */: - case 104 /* VarKeyword */: - case 116 /* YieldKeyword */: + case 118 /* AbstractKeyword */: + case 76 /* ClassKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 90 /* FunctionKeyword */: + case 110 /* InterfaceKeyword */: + case 111 /* LetKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 116 /* StaticKeyword */: + case 105 /* VarKeyword */: + case 117 /* YieldKeyword */: return true; + case 121 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -93986,7 +97470,7 @@ var ts; && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 155 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 157 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -94009,12 +97493,12 @@ 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 !== 273 /* PropertyAssignment */ && - m.kind !== 274 /* ShorthandPropertyAssignment */ && - m.kind !== 184 /* BindingElement */ && - m.kind !== 154 /* MethodDeclaration */ && - m.kind !== 156 /* GetAccessor */ && - m.kind !== 157 /* SetAccessor */) { + if (m.kind !== 275 /* PropertyAssignment */ && + m.kind !== 276 /* ShorthandPropertyAssignment */ && + m.kind !== 186 /* BindingElement */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -94024,7 +97508,7 @@ var ts; var existingName = void 0; if (ts.isBindingElement(m) && m.propertyName) { // include only identifiers in completion list - if (m.propertyName.kind === 71 /* Identifier */) { + if (m.propertyName.kind === 72 /* Identifier */) { existingName = m.propertyName.escapedText; } } @@ -94049,10 +97533,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 152 /* PropertyDeclaration */ && - m.kind !== 154 /* MethodDeclaration */ && - m.kind !== 156 /* GetAccessor */ && - m.kind !== 157 /* SetAccessor */) { + if (m.kind !== 154 /* PropertyDeclaration */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -94092,7 +97576,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 265 /* JsxAttribute */) { + if (attr.kind === 267 /* JsxAttribute */) { seenNames.set(attr.name.escapedText, true); } } @@ -94136,7 +97620,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 72 /* FirstKeyword */; i <= 145 /* LastKeyword */; i++) { + for (var i = 73 /* FirstKeyword */; i <= 147 /* LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -94151,17 +97635,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 121 /* AsyncKeyword */ || 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 125 /* DeclareKeyword */ || kind === 130 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 141 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94169,37 +97655,26 @@ var ts; })); } function isInterfaceOrTypeLiteralCompletionKeyword(kind) { - return kind === 132 /* ReadonlyKeyword */; + return kind === 133 /* ReadonlyKeyword */; } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 117 /* AbstractKeyword */: - case 123 /* ConstructorKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 120 /* AsyncKeyword */: + case 118 /* AbstractKeyword */: + case 124 /* ConstructorKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 121 /* AsyncKeyword */: return true; default: return ts.isClassMemberModifier(kind); } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 121 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } - function isEqualityOperatorKind(kind) { - switch (kind) { - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - return true; - default: - return false; - } - } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { var jsdoc = ts.findAncestor(node, ts.isJSDoc); @@ -94209,7 +97684,7 @@ var ts; return contextualType.isUnion() ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. - return !(memberType.flags & 32764 /* Primitive */ || + return !(memberType.flags & 131068 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker) || checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); @@ -94232,31 +97707,31 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 304 /* SyntaxList */: + case 306 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); - if (cls && !ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile)) { + if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) { return cls; } } if (!contextToken) return undefined; switch (contextToken.kind) { - case 25 /* SemicolonToken */: // class c {getValue(): number; | } - case 18 /* CloseBraceToken */: // class c { method() { } | } + case 26 /* SemicolonToken */: // class c {getValue(): number; | } + case 19 /* CloseBraceToken */: // class c { method() { } | } // class c { method() { } b| } return isFromObjectTypeDeclaration(location) && location.parent.name === location ? location.parent.parent : ts.tryCast(location, ts.isObjectTypeDeclaration); - case 17 /* OpenBraceToken */: // class c { | - case 26 /* CommaToken */: // class c {getValue(): number, | } + case 18 /* OpenBraceToken */: // class c { | + case 27 /* CommaToken */: // class c {getValue(): number, | } return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); default: if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 40 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94264,9 +97739,6 @@ var ts; function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); } - function hasIndexSignature(type) { - return !!type.getStringIndexType() || !!type.getNumberIndexType(); - } function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { case ".": @@ -94276,14 +97748,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 28 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 42 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94292,17 +97764,6 @@ var ts; var left = _a.left; return ts.nodeIsMissing(left); } - function isStringLiteralOrTemplate(node) { - switch (node.kind) { - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 191 /* TaggedTemplateExpression */: - return true; - default: - return false; - } - } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -94355,40 +97816,40 @@ var ts; } function getHighlightSpans(node, sourceFile) { switch (node.kind) { - case 90 /* IfKeyword */: - case 82 /* ElseKeyword */: + case 91 /* IfKeyword */: + case 83 /* ElseKeyword */: return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; - case 96 /* ReturnKeyword */: + case 97 /* ReturnKeyword */: return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); - case 100 /* ThrowKeyword */: + case 101 /* ThrowKeyword */: return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); - case 102 /* TryKeyword */: - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: - var tryStatement = node.kind === 74 /* CatchKeyword */ ? node.parent.parent : node.parent; + case 103 /* TryKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + var tryStatement = node.kind === 75 /* CatchKeyword */ ? node.parent.parent : node.parent; return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); - case 98 /* SwitchKeyword */: + case 99 /* SwitchKeyword */: return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); - case 73 /* CaseKeyword */: - case 79 /* DefaultKeyword */: + case 74 /* CaseKeyword */: + case 80 /* DefaultKeyword */: return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); - case 72 /* BreakKeyword */: - case 77 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 78 /* ContinueKeyword */: return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); - case 88 /* ForKeyword */: - case 106 /* WhileKeyword */: - case 81 /* DoKeyword */: + case 89 /* ForKeyword */: + case 107 /* WhileKeyword */: + case 82 /* DoKeyword */: return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); - case 123 /* ConstructorKeyword */: - return getFromAllDeclarations(ts.isConstructorDeclaration, [123 /* ConstructorKeyword */]); - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]); - case 121 /* AwaitKeyword */: + case 124 /* ConstructorKeyword */: + return getFromAllDeclarations(ts.isConstructorDeclaration, [124 /* ConstructorKeyword */]); + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return getFromAllDeclarations(ts.isAccessor, [126 /* GetKeyword */, 137 /* SetKeyword */]); + case 122 /* AwaitKeyword */: return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: return highlightSpans(getAsyncAndAwaitOccurrences(node)); - case 116 /* YieldKeyword */: + case 117 /* YieldKeyword */: return highlightSpans(getYieldOccurrences(node)); default: return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) @@ -94431,7 +97892,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 277 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -94463,16 +97924,16 @@ var ts; function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 230 /* SwitchStatement */: - if (statement.kind === 226 /* ContinueStatement */) { + case 232 /* SwitchStatement */: + if (statement.kind === 228 /* ContinueStatement */) { return false; } // falls through - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. @@ -94488,11 +97949,11 @@ var ts; // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 243 /* ModuleBlock */: - case 277 /* SourceFile */: - case 216 /* Block */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 218 /* Block */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return declaration.members.concat([declaration]); @@ -94500,12 +97961,12 @@ var ts; else { return container.statements; } - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 237 /* FunctionDeclaration */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: var 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. @@ -94536,12 +97997,12 @@ var ts; } function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) { + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 89 /* ForKeyword */, 107 /* WhileKeyword */, 82 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 221 /* DoStatement */) { + if (loopNode.kind === 223 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) { + if (pushKeywordIf(keywords, loopTokens[i], 107 /* WhileKeyword */)) { break; } } @@ -94549,7 +98010,7 @@ var ts; } ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) { if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */, 77 /* ContinueKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */, 78 /* ContinueKeyword */); } }); return keywords; @@ -94558,13 +98019,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -94572,13 +98033,13 @@ var ts; } function getSwitchCaseDefaultOccurrences(switchStatement) { var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 98 /* SwitchKeyword */); + pushKeywordIf(keywords, switchStatement.getFirstToken(), 99 /* SwitchKeyword */); // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 73 /* CaseKeyword */, 79 /* DefaultKeyword */); + pushKeywordIf(keywords, clause.getFirstToken(), 74 /* CaseKeyword */, 80 /* DefaultKeyword */); ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) { if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */); } }); }); @@ -94586,13 +98047,13 @@ var ts; } function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 102 /* TryKeyword */); + pushKeywordIf(keywords, tryStatement.getFirstToken(), 103 /* TryKeyword */); if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 74 /* CatchKeyword */); + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 75 /* CatchKeyword */); } if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 87 /* FinallyKeyword */); + var finallyKeyword = ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 88 /* FinallyKeyword */); } return keywords; } @@ -94603,13 +98064,13 @@ var ts; } var keywords = []; ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - keywords.push(ts.findChildOfKind(throwStatement, 100 /* ThrowKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); }); // If the "owner" is a function, then we equate 'return' and 'throw' statements in their // ability to "jump out" of the function, and include occurrences for both. if (ts.isFunctionBlock(owner)) { ts.forEachReturnStatement(owner, function (returnStatement) { - keywords.push(ts.findChildOfKind(returnStatement, 96 /* ReturnKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); }); } return keywords; @@ -94621,11 +98082,11 @@ var ts; } var keywords = []; ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { - keywords.push(ts.findChildOfKind(returnStatement, 96 /* ReturnKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); }); // Include 'throw' statements that do not occur within a try block. ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - keywords.push(ts.findChildOfKind(throwStatement, 100 /* ThrowKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); }); return keywords; } @@ -94637,13 +98098,13 @@ var ts; var keywords = []; if (func.modifiers) { func.modifiers.forEach(function (modifier) { - pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */); + pushKeywordIf(keywords, modifier, 121 /* AsyncKeyword */); }); } ts.forEachChild(func, function (child) { traverseWithoutCrossingFunction(child, function (node) { if (ts.isAwaitExpression(node)) { - pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */); + pushKeywordIf(keywords, node.getFirstToken(), 122 /* AwaitKeyword */); } }); }); @@ -94658,7 +98119,7 @@ var ts; ts.forEachChild(func, function (child) { traverseWithoutCrossingFunction(child, function (node) { if (ts.isYieldExpression(node)) { - pushKeywordIf(keywords, node.getFirstToken(), 116 /* YieldKeyword */); + pushKeywordIf(keywords, node.getFirstToken(), 117 /* YieldKeyword */); } }); }); @@ -94677,7 +98138,7 @@ var ts; // We'd like to highlight else/ifs together if they are only separated by whitespace // (i.e. the keywords are separated by no comments, no newlines). for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 82 /* ElseKeyword */ && i < keywords.length - 1) { + if (keywords[i].kind === 83 /* ElseKeyword */ && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. var shouldCombineElseAndIf = true; @@ -94712,10 +98173,10 @@ var ts; // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. while (true) { var children = ifStatement.getChildren(sourceFile); - pushKeywordIf(keywords, children[0], 90 /* IfKeyword */); + pushKeywordIf(keywords, children[0], 91 /* IfKeyword */); // Generally the 'else' keyword is second-to-last, so we traverse backwards. for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 82 /* ElseKeyword */)) { + if (pushKeywordIf(keywords, children[i], 83 /* ElseKeyword */)) { break; } } @@ -94748,16 +98209,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } - function getBucketForCompilationSettings(key, createIfMissing) { - var bucket = buckets.get(key); - if (!bucket && createIfMissing) { - buckets.set(key, bucket = ts.createMap()); - } - return bucket; // TODO: GH#18217 - } function reportStats() { var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = buckets.get(name); @@ -94793,9 +98244,9 @@ var ts; return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); + var bucket = ts.getOrUpdate(buckets, key, ts.createMap); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +98260,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94847,8 +98298,7 @@ var ts; return releaseDocumentWithKey(path, key); } function releaseDocumentWithKey(path, key) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); - ts.Debug.assert(bucket !== undefined); + var bucket = ts.Debug.assertDefined(buckets.get(key)); var entry = bucket.get(path); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); @@ -94876,6 +98326,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -94939,12 +98392,12 @@ var ts; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 235 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 237 /* VariableDeclaration */) { var name = parent.name; - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { directImports.push(name); break; } @@ -94953,22 +98406,22 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; - case 71 /* Identifier */: // for 'const x = require("y"); + case 72 /* Identifier */: // for 'const x = require("y"); break; // TODO: GH#23879 - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 251 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); @@ -94978,7 +98431,7 @@ var ts; directImports.push(direct); } break; - case 181 /* ImportType */: + case 183 /* ImportType */: directImports.push(direct); break; default: @@ -94995,7 +98448,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 277 /* SourceFile */ || sourceFileLike.kind === 242 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -95050,17 +98503,17 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 246 /* ImportEqualsDeclaration */) { + if (decl.kind === 248 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } return; } - if (decl.kind === 71 /* Identifier */) { + if (decl.kind === 72 /* Identifier */) { handleNamespaceImportLike(decl); return; } - if (decl.kind === 181 /* ImportType */) { + if (decl.kind === 183 /* ImportType */) { if (decl.qualifier) { if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { singleReferences.push(decl.qualifier); @@ -95072,20 +98525,20 @@ var ts; return; } // Ignore if there's a grammar error - if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) { + if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { return; } - if (decl.kind === 253 /* ExportDeclaration */) { + if (decl.kind === 255 /* ExportDeclaration */) { searchForNamedImport(decl.exportClause); return; } var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: handleNamespaceImportLike(namedBindings.name); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: // 'default' might be accessed as a named import `{ default as foo }`. if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { searchForNamedImport(namedBindings); @@ -95135,7 +98588,7 @@ var ts; } } else { - var localSymbol = element.kind === 255 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 257 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -95161,10 +98614,10 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 277 /* SourceFile */) { + if (searchSourceFile.kind === 279 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -95192,8 +98645,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95212,7 +98665,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 277 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -95227,15 +98680,15 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 253 /* ExportDeclaration */: - case 247 /* ImportDeclaration */: { + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 246 /* ImportEqualsDeclaration */: { + case 248 /* ImportEqualsDeclaration */: { var decl = statement; if (isExternalModuleImportEquals(decl)) { action(decl, decl.moduleReference.expression); @@ -95259,7 +98712,7 @@ var ts; var parent = node.parent; var grandParent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 187 /* PropertyAccessExpression */) { + if (parent.kind === 189 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) @@ -95279,7 +98732,7 @@ var ts; return undefined; } var lhsSymbol = checker.getSymbolAtLocation(exportNode.name); - return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false }; + return { kind: 0 /* Import */, symbol: lhsSymbol }; } else { return exportInfo(symbol, getExportKindForDeclaration(exportNode)); @@ -95312,7 +98765,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95349,7 +98802,7 @@ var ts; // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { - return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); + return { kind: 0 /* Import */, symbol: importedSymbol }; } } function exportInfo(symbol, kind) { @@ -95381,10 +98834,10 @@ var ts; // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent, node) { - if (parent.kind === 235 /* VariableDeclaration */) { + if (parent.kind === 237 /* VariableDeclaration */) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 272 /* CatchClause */ ? undefined : p.parent.parent.kind === 217 /* VariableStatement */ ? p.parent.parent : undefined; + p.parent.kind === 274 /* CatchClause */ ? undefined : p.parent.parent.kind === 219 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -95393,19 +98846,17 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 246 /* ImportEqualsDeclaration */: - return parent.name === node && isExternalModuleImportEquals(parent) - ? { isNamedImport: false } - : undefined; - case 251 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + return parent.name === node && isExternalModuleImportEquals(parent); + case 253 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. - return parent.propertyName ? undefined : { isNamedImport: true }; - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: + return !parent.propertyName; + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: ts.Debug.assert(parent.name === node); - return { isNamedImport: false }; + return true; default: - return undefined; + return false; } } function getExportInfo(exportSymbol, exportKind, checker) { @@ -95434,21 +98885,21 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 277 /* SourceFile */) { + if (parent.kind === 279 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 243 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 245 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; + return node.kind === 244 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; } function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 257 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */; + return eq.moduleReference.kind === 259 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95457,8 +98908,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95483,18 +98951,18 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } - else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" var symbol = checker.getSymbolAtLocation(node); @@ -95505,10 +98973,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95521,28 +98989,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95556,28 +99024,67 @@ var ts; } function getDefinitionKindAndDisplayParts(symbol, checker, node) { var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); - var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node; + var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode, checker) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), - isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + isDefinition: node.kind === 80 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode, checker) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + var prefixColon = { prefixText: name + ": " }; + var suffixColon = { suffixText: ": " + name }; + return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon + : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : isShorthandAssignment ? suffixColon : prefixColon; + } + else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + // If the original symbol was using this alias, just rename the alias. + var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); + return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions; + } + else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name }; + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95592,16 +99099,16 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 186 /* ObjectLiteralExpression */) { + else if (node.kind === 188 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, - displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] }; } - else if (node.kind === 207 /* ClassExpression */) { + else if (node.kind === 209 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, - displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] }; } else { @@ -95609,17 +99116,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95627,7 +99134,7 @@ var ts; function getTextSpan(node, sourceFile) { var start = node.getStart(sourceFile); var end = node.getEnd(); - if (node.kind === 9 /* StringLiteral */) { + if (node.kind === 10 /* StringLiteral */) { start += 1; end -= 1; } @@ -95635,7 +99142,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 80 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 204 /* BinaryExpression */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 80 /* DefaultKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 257 /* ExportSpecifier */: + case 250 /* ImportClause */: // default import + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 241 /* InterfaceDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 267 /* JsxAttribute */: + case 244 /* ModuleDeclaration */: + case 247 /* NamespaceExportDeclaration */: + case 251 /* NamespaceImport */: + case 151 /* Parameter */: + case 276 /* ShorthandPropertyAssignment */: + case 242 /* TypeAliasDeclaration */: + case 150 /* TypeParameter */: + return true; + case 275 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return !!decl.body; + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 155 /* MethodSignature */: + case 153 /* PropertySignature */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95668,6 +99230,9 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } + if (symbol.escapedName === "export=" /* ExportEquals */) { + return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } var moduleReferences = ts.emptyArray; var moduleSourceFile = isModuleSymbol(symbol); var referencedNode = node; @@ -95699,11 +99264,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95712,12 +99277,12 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95725,7 +99290,23 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + var exported = symbol.exports.get("export=" /* ExportEquals */); + if (exported) { + for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { + var decl = _c[_b]; + var sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + // At `module.exports = ...`, reference node is `module` + var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) + ? decl.left.expression + : ts.isExportAssignment(decl) + ? ts.Debug.assertDefined(ts.findChildOfKind(decl, 85 /* ExportKeyword */, sourceFile)) + : ts.getNameOfDeclaration(decl) || decl; + references.push(FindAllReferences.nodeEntry(node)); + } + } + } + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95746,24 +99327,29 @@ var ts; if (ts.isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); } - if (node.kind === 97 /* SuperKeyword */) { + if (node.kind === 98 /* SuperKeyword */) { return getReferencesForSuperKeyword(node); } return undefined; } /** Core find-all-references algorithm for a normal symbol. */ - function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; // Compute the meaning from the location and the symbol it references var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - if (node && node.kind === 79 /* DefaultKeyword */) { + var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + if (exportSpecifier) { + // When renaming at an export specifier, rename the export and not the thing being exported. + getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); + } + else if (node && node.kind === 80 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -95783,9 +99369,9 @@ var ts; } function getSpecialSearchKind(node) { switch (node.kind) { - case 123 /* ConstructorKeyword */: + case 124 /* ConstructorKeyword */: return 1 /* Constructor */; - case 71 /* Identifier */: + case 72 /* Identifier */: if (ts.isClassLike(node.parent)) { ts.Debug.assert(node.parent.name === node); return 2 /* Class */; @@ -95796,15 +99382,11 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { var parent = node.parent; - if (ts.isExportSpecifier(parent)) { + if (ts.isExportSpecifier(parent) && !isForRename) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); } - if (ts.isImportSpecifier(parent) && parent.propertyName === node) { - // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. - return checker.getImmediateAliasedSymbol(symbol); - } // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. return ts.firstDefined(symbol.declarations, function (decl) { if (!decl.parent) { @@ -95894,15 +99476,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -95967,7 +99549,8 @@ var ts; var indirectUser = indirectUsers_2[_b]; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; - if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) { + // Import specifiers should be handled by importSearches + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { cb(node); } } @@ -95983,7 +99566,7 @@ var ts; if (!ts.isIdentifier(singleRef)) return false; // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */); } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { @@ -96005,19 +99588,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -96030,7 +99600,7 @@ 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 declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 194 /* FunctionExpression */ || valueDeclaration.kind === 207 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 196 /* FunctionExpression */ || valueDeclaration.kind === 209 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -96040,14 +99610,14 @@ var ts; if (flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 238 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 240 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -96062,14 +99632,14 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -96090,7 +99660,9 @@ var ts; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { - var symbol = checker.getSymbolAtLocation(definition); + var symbol = ts.isParameterPropertyDeclaration(definition.parent) + ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) + : checker.getSymbolAtLocation(definition); if (!symbol) return undefined; for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { @@ -96112,8 +99684,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,21 +99742,21 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node.text.length === searchSymbolName.length; - case 9 /* StringLiteral */: { + case 10 /* StringLiteral */: { var str = node; - return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && str.text.length === searchSymbolName.length; } case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; - case 79 /* DefaultKeyword */: + case 80 /* DefaultKeyword */: return "default".length === searchSymbolName.length; default: return false; @@ -96197,7 +99769,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96248,7 +99820,7 @@ var ts; return; } if (ts.isExportSpecifier(parent)) { - ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */); + ts.Debug.assert(referenceLocation.kind === 72 /* Identifier */); getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); return; } @@ -96273,16 +99845,16 @@ var ts; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) { + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); - if (!search.includes(localSymbol)) { + if (!alwaysGetReferences && !search.includes(localSymbol)) { return; } if (!propertyName) { // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) - if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) { + if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) { addRef(); } } @@ -96293,7 +99865,7 @@ var ts; addRef(); } if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { - addReference(name, referenceSymbol, state); + addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state); } } else { @@ -96302,15 +99874,14 @@ var ts; } } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!(referenceLocation === propertyName && state.options.isForRename)) { - var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; - var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); - if (!exportInfo) - return ts.Debug.fail(); - searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); + if (!state.options.isForRename || alwaysGetReferences) { + var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; + var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); + var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. - if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) { + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (imported) searchForImportedSymbol(imported, state); @@ -96342,12 +99913,11 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0 /* Import */) { - if (!state.options.isForRename || importOrExport.isNamedImport) { + if (!state.options.isForRename) { searchForImportedSymbol(symbol, state); } } else { - // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching. searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); } } @@ -96367,12 +99937,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96382,7 +99953,7 @@ var ts; } var pusher = function () { return state.referenceAdder(search.symbol); }; if (ts.isClassLike(referenceLocation.parent)) { - ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); + ts.Debug.assert(referenceLocation.kind === 80 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. findOwnConstructorReferences(search.symbol, sourceFile, pusher()); } @@ -96408,7 +99979,7 @@ var ts; } if (member.body) { member.body.forEachChild(function cb(node) { - if (node.kind === 99 /* ThisKeyword */) { + if (node.kind === 100 /* ThisKeyword */) { addRef(node); } else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { @@ -96425,16 +99996,16 @@ var ts; function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 155 /* Constructor */ && !!ctrKeyword); + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 154 /* MethodDeclaration */) { + if (decl && decl.kind === 156 /* MethodDeclaration */) { var body = decl.body; if (body) { - forEachDescendantOfKind(body, 99 /* ThisKeyword */, function (thisKeyword) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { if (ts.isNewExpressionTarget(thisKeyword)) { addNode(thisKeyword); } @@ -96451,10 +100022,10 @@ var ts; } for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 155 /* Constructor */); + ts.Debug.assert(decl.kind === 157 /* Constructor */); var body = decl.body; if (body) { - forEachDescendantOfKind(body, 97 /* SuperKeyword */, function (node) { + forEachDescendantOfKind(body, 98 /* SuperKeyword */, function (node) { if (ts.isCallExpressionTarget(node)) { addNode(node); } @@ -96468,10 +100039,10 @@ var ts; addReference(refNode); return; } - if (refNode.kind !== 71 /* Identifier */) { + if (refNode.kind !== 72 /* Identifier */) { return; } - if (refNode.parent.kind === 274 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 276 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -96491,7 +100062,7 @@ var ts; } else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { var body = typeHavingNode.body; - if (body.kind === 216 /* Block */) { + if (body.kind === 218 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression) addIfImplementation(returnStatement.expression); @@ -96519,13 +100090,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 195 /* ArrowFunction */: - case 194 /* FunctionExpression */: - case 186 /* ObjectLiteralExpression */: - case 207 /* ClassExpression */: - case 185 /* ArrayLiteralExpression */: + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 187 /* ArrayLiteralExpression */: return true; default: return false; @@ -96578,13 +100149,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -96593,7 +100164,7 @@ var ts; } var sourceFile = searchSpaceNode.getSourceFile(); var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) { - if (node.kind !== 97 /* SuperKeyword */) { + if (node.kind !== 98 /* SuperKeyword */) { return; } var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); @@ -96602,41 +100173,41 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // falls through - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // falls through - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* 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. default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 277 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -96644,24 +100215,25 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: return searchSpaceNode.symbol === container.symbol; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; - case 277 /* SourceFile */: - return container.kind === 277 /* SourceFile */ && !ts.isExternalModule(container); + case 279 /* SourceFile */: + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96669,39 +100241,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // 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 - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96713,8 +100271,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // 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 + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96727,11 +100303,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96739,19 +100317,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96777,8 +100355,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_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +100418,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96855,7 +100433,7 @@ var ts; function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); return function (path) { - var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 }); var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); return originalPath ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) @@ -96874,7 +100452,7 @@ var ts; var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); return combinePathsSafe(ts.getDirectoryPath(a1), rel); } - function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; if (!configFile) return; @@ -96892,7 +100470,8 @@ var ts; var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); // If there isn't some include for this, add a new one. - if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if (ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); } } @@ -96943,9 +100522,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_12 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +100550,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_12(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +100580,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +100610,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +100652,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97078,7 +100664,7 @@ var ts; else { var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; // For a 'super()' call, put the signature first, else put the variable first. - return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); + return node.kind === 98 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -97086,7 +100672,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; } @@ -97239,18 +100825,18 @@ var ts; // (2) when the aliased symbol is originating from an import. // function shouldSkipAlias(node, declaration) { - if (node.kind !== 71 /* Identifier */) { + if (node.kind !== 72 /* Identifier */) { return false; } if (node.parent === declaration) { return true; } switch (declaration.kind) { - case 248 /* ImportClause */: - case 246 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: return true; - case 251 /* ImportSpecifier */: - return declaration.parent.kind === 250 /* NamedImports */; + case 253 /* ImportSpecifier */: + return declaration.parent.kind === 252 /* NamedImports */; default: return false; } @@ -97260,7 +100846,7 @@ var ts; function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */)) { + if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 124 /* ConstructorKeyword */)) { var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } @@ -97332,6 +100918,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97444,11 +101040,11 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: return [declaration]; - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -97469,16 +101065,16 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return withNode(tag.class); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 303 /* JSDocPropertyTag */: - case 297 /* JSDocParameterTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -97542,7 +101138,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +101171,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +101234,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97655,7 +101251,7 @@ var ts; function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { return parameters.map(function (_a, i) { var name = _a.name, dotDotDotToken = _a.dotDotDotToken; - var paramName = name.kind === 71 /* Identifier */ ? name.text : "param" + i; + var paramName = name.kind === 72 /* Identifier */ ? name.text : "param" + i; var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; return indentationStr + " * @param " + type + paramName + newLine; }).join(""); @@ -97665,23 +101261,23 @@ var ts; } function getCommentOwnerInfoWorker(commentOwner) { switch (commentOwner.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 155 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return getCommentOwnerInfoWorker(commentOwner.initializer); - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 151 /* PropertySignature */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 240 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 153 /* PropertySignature */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 242 /* TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer @@ -97689,16 +101285,16 @@ var ts; : undefined; return { commentOwner: commentOwner, parameters: parameters_1 }; } - case 277 /* SourceFile */: + case 279 /* SourceFile */: return "quit"; - case 242 /* ModuleDeclaration */: + case 244 /* 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 { }'. - return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 202 /* BinaryExpression */: { + return commentOwner.parent.kind === 244 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 204 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97715,14 +101311,14 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 193 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 195 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return rightHandSide.parameters; - case 207 /* ClassExpression */: { + case 209 /* ClassExpression */: { var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); return ctr ? ctr.parameters : ts.emptyArray; } @@ -97741,7 +101337,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +101347,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +101362,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -97784,9 +101380,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 248 /* ImportClause */: - case 251 /* ImportSpecifier */: - case 246 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -97796,7 +101392,7 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - return !!name && (pushLiteral(name, containers) || name.kind === 147 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + return !!name && (pushLiteral(name, containers) || name.kind === 149 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // @@ -97813,7 +101409,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + if (name && name.kind === 149 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } // Don't include the last portion. @@ -97982,7 +101578,7 @@ var ts; return; } switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -97994,21 +101590,21 @@ var ts; } } break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 155 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -98020,7 +101616,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings.kind === 251 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -98031,8 +101627,8 @@ var ts; } } break; - case 184 /* BindingElement */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); @@ -98053,12 +101649,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -98068,9 +101664,9 @@ var ts; } endNode(); break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -98078,19 +101674,19 @@ var ts; } endNode(); break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 255 /* ExportSpecifier */: - case 246 /* ImportEqualsDeclaration */: - case 160 /* IndexSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 240 /* TypeAliasDeclaration */: + case 257 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 162 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 242 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: { + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98101,6 +101697,9 @@ var ts; case 4 /* ThisProperty */: case 5 /* Property */: case 0 /* None */: + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: break; default: ts.Debug.assertNever(special); @@ -98168,12 +101767,12 @@ var ts; return false; } switch (a.kind) { - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return areSameModule(a, b); default: return true; @@ -98189,7 +101788,7 @@ var ts; // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { // TODO: GH#18217 - return a.body.kind === b.body.kind && (a.body.kind !== 242 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 244 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { @@ -98219,7 +101818,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 242 /* ModuleDeclaration */) { + if (node.kind === 244 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -98227,16 +101826,16 @@ var ts; return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 207 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: return getFunctionOrClassName(node); default: return undefined; } } function getItemName(node, name) { - if (node.kind === 242 /* ModuleDeclaration */) { + if (node.kind === 244 /* ModuleDeclaration */) { return getModuleName(node); } if (name) { @@ -98246,16 +101845,16 @@ var ts; } } switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -98263,13 +101862,13 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the // navigation bar. return getFunctionOrClassName(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return "constructor"; - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return "new()"; - case 158 /* CallSignature */: + case 160 /* CallSignature */: return "()"; - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return "[]"; default: return ""; @@ -98293,25 +101892,25 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 241 /* EnumDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 277 /* SourceFile */: - case 240 /* TypeAliasDeclaration */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 242 /* TypeAliasDeclaration */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return true; - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 235 /* VariableDeclaration */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 237 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -98321,10 +101920,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 243 /* ModuleBlock */: - case 277 /* SourceFile */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: return true; default: return hasSomeImportantChild(item); @@ -98333,7 +101932,7 @@ var ts; function hasSomeImportantChild(item) { return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 235 /* VariableDeclaration */ && childKind !== 184 /* BindingElement */; + return childKind !== 237 /* VariableDeclaration */ && childKind !== 186 /* BindingElement */; }); } } @@ -98390,7 +101989,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -98404,47 +102003,68 @@ var ts; return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 147 /* ComputedPropertyName */; + return !member.name || member.name.kind === 149 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 277 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 235 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 195 /* ArrowFunction */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: return true; default: return false; @@ -98571,7 +102191,7 @@ var ts; ? specifier.text : undefined; } - /* @internal */ // Internal for testing + // Internal for testing /** * @param importGroup a list of ImportDeclarations, all with the same module name. */ @@ -98670,7 +102290,7 @@ var ts; } } OrganizeImports.coalesceImports = coalesceImports; - /* @internal */ // Internal for testing + // Internal for testing /** * @param exportGroup a list of ExportDeclarations, all with the same module name. */ @@ -98773,7 +102393,7 @@ var ts; } var lastImport = current - 1; if (lastImport !== firstImport) { - out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 92 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); } } function visitNonImportNode(n) { @@ -98880,31 +102500,31 @@ var ts; } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(n)) { - return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 195 /* ArrowFunction */); + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 197 /* ArrowFunction */); } // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { - case 221 /* DoStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 220 /* IfStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 272 /* CatchClause */: + case 223 /* DoStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 274 /* CatchClause */: return spanForNode(n.parent); - case 233 /* TryStatement */: + case 235 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { return spanForNode(n.parent); } else if (tryStatement.finallyBlock === n) { - return spanForNode(ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile)); + return spanForNode(ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile)); } // falls through default: @@ -98912,21 +102532,21 @@ var ts; // the span of the block, independent of any parent span. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return spanForNode(n.parent); - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 244 /* CaseBlock */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 246 /* CaseBlock */: return spanForNode(n); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 185 /* ArrayLiteralExpression */: - return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); - case 258 /* JsxElement */: + case 187 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); + case 260 /* JsxElement */: return spanForJSXElement(n); - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); } function spanForJSXElement(node) { @@ -98942,7 +102562,7 @@ var ts; return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } function spanForObjectOrArrayLiteral(node, open) { - if (open === void 0) { open = 17 /* OpenBraceToken */; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } // If the block has no leading keywords and is inside an array literal, // we only want to collapse the span of the block. // Otherwise, the collapsed section will include the end of the previous line. @@ -98951,9 +102571,9 @@ var ts; function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { if (autoCollapse === void 0) { autoCollapse = false; } if (useFullStart === void 0) { useFullStart = true; } - if (open === void 0) { open = 17 /* OpenBraceToken */; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } var openToken = ts.findChildOfKind(n, open, sourceFile); - var close = open === 17 /* OpenBraceToken */ ? 18 /* CloseBraceToken */ : 22 /* CloseBracketToken */; + var close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; var closeToken = ts.findChildOfKind(n, close, sourceFile); if (!openToken || !closeToken) { return undefined; @@ -99248,13 +102868,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_14 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_14(start); if (typeof state_3 === "object") return state_3.value; } @@ -99312,11 +102932,11 @@ var ts; characterSpans: breakIntoCharacterSpans(text) }; } - /* @internal */ function breakIntoCharacterSpans(identifier) { + function breakIntoCharacterSpans(identifier) { return breakIntoSpans(identifier, /*word:*/ false); } ts.breakIntoCharacterSpans = breakIntoCharacterSpans; - /* @internal */ function breakIntoWordSpans(identifier) { + function breakIntoWordSpans(identifier) { return breakIntoSpans(identifier, /*word:*/ true); } ts.breakIntoWordSpans = breakIntoWordSpans; @@ -99456,10 +103076,10 @@ var ts; function nextToken() { lastToken = currentToken; currentToken = ts.scanner.scan(); - if (currentToken === 17 /* OpenBraceToken */) { + if (currentToken === 18 /* OpenBraceToken */) { braceNesting++; } - else if (currentToken === 18 /* CloseBraceToken */) { + else if (currentToken === 19 /* CloseBraceToken */) { braceNesting--; } return currentToken; @@ -99489,12 +103109,12 @@ var ts; */ function tryConsumeDeclare() { var token = ts.scanner.getToken(); - if (token === 124 /* DeclareKeyword */) { + if (token === 125 /* DeclareKeyword */) { // declare module "mod" token = nextToken(); - if (token === 129 /* ModuleKeyword */) { + if (token === 130 /* ModuleKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { recordAmbientExternalModule(); } } @@ -99506,42 +103126,42 @@ var ts; * Returns true if at least one token was consumed from the stream */ function tryConsumeImport() { - if (lastToken === 23 /* DotToken */) { + if (lastToken === 24 /* DotToken */) { return false; } var token = ts.scanner.getToken(); - if (token === 91 /* ImportKeyword */) { + if (token === 92 /* ImportKeyword */) { token = nextToken(); - if (token === 19 /* OpenParenToken */) { + if (token === 20 /* OpenParenToken */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import("mod"); recordModuleName(); return true; } } - else if (token === 9 /* StringLiteral */) { + else if (token === 10 /* StringLiteral */) { // import "mod"; recordModuleName(); return true; } else { - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import d from "mod"; recordModuleName(); return true; } } - else if (token === 58 /* EqualsToken */) { + else if (token === 59 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } - else if (token === 26 /* CommaToken */) { + else if (token === 27 /* CommaToken */) { // consume comma and keep going token = nextToken(); } @@ -99550,18 +103170,18 @@ var ts; return true; } } - if (token === 17 /* OpenBraceToken */) { + if (token === 18 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure that it stops on EOF - while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import {a as A} from "mod"; // import d, {a, b as B} from "mod" recordModuleName(); @@ -99569,15 +103189,15 @@ var ts; } } } - else if (token === 39 /* AsteriskToken */) { + else if (token === 40 /* AsteriskToken */) { token = nextToken(); - if (token === 118 /* AsKeyword */) { + if (token === 119 /* AsKeyword */) { token = nextToken(); - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import * as NS from "mod" // import d, * as NS from "mod" recordModuleName(); @@ -99593,21 +103213,21 @@ var ts; } function tryConsumeExport() { var token = ts.scanner.getToken(); - if (token === 84 /* ExportKeyword */) { + if (token === 85 /* ExportKeyword */) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 17 /* OpenBraceToken */) { + if (token === 18 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure it stops on EOF - while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // export {a as A} from "mod"; // export {a, b as B} from "mod" recordModuleName(); @@ -99615,21 +103235,21 @@ var ts; } } } - else if (token === 39 /* AsteriskToken */) { + else if (token === 40 /* AsteriskToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // export * from "mod" recordModuleName(); } } } - else if (token === 91 /* ImportKeyword */) { + else if (token === 92 /* ImportKeyword */) { token = nextToken(); - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 58 /* EqualsToken */) { + if (token === 59 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } @@ -99642,11 +103262,11 @@ var ts; } function tryConsumeRequireCall(skipCurrentToken) { var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); - if (token === 133 /* RequireKeyword */) { + if (token === 134 /* RequireKeyword */) { token = nextToken(); - if (token === 19 /* OpenParenToken */) { + if (token === 20 /* OpenParenToken */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // require("mod"); recordModuleName(); } @@ -99657,16 +103277,16 @@ var ts; } function tryConsumeDefine() { var token = ts.scanner.getToken(); - if (token === 71 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + if (token === 72 /* Identifier */ && ts.scanner.getTokenValue() === "define") { token = nextToken(); - if (token !== 19 /* OpenParenToken */) { + if (token !== 20 /* OpenParenToken */) { return true; } token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // looks like define ("modname", ... - skip string literal and comma token = nextToken(); - if (token === 26 /* CommaToken */) { + if (token === 27 /* CommaToken */) { token = nextToken(); } else { @@ -99675,15 +103295,15 @@ var ts; } } // should be start of dependency list - if (token !== 21 /* OpenBracketToken */) { + if (token !== 22 /* OpenBracketToken */) { return true; } // skip open bracket token = nextToken(); // scan until ']' or EOF - while (token !== 22 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { // record string literals as module names - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { recordModuleName(); } token = nextToken(); @@ -99791,47 +103411,61 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; - if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + if (ts.isIdentifier(node) && node.originalKeywordKind === 80 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); var width = node.getWidth(sourceFile); - if (node.kind === 9 /* StringLiteral */) { + if (node.kind === 10 /* StringLiteral */) { // Exclude the quotes start += 1; width -= 2; @@ -99840,9 +103474,9 @@ var ts; } function nodeIsEligibleForRename(node) { switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 99 /* ThisKeyword */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: return true; case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); @@ -99877,22 +103511,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // 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. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +103545,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99921,19 +103569,19 @@ var ts; return false; var invocationChildren = node.getChildren(sourceFile); switch (startingToken.kind) { - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return ts.contains(invocationChildren, startingToken); - case 26 /* CommaToken */: { + case 27 /* CommaToken */: { var containingList = ts.findContainingList(startingToken); return !!containingList && ts.contains(invocationChildren, containingList); } - case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + case 28 /* LessThanToken */: + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +103598,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -99973,7 +103621,7 @@ var ts; return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; } function getArgumentOrParameterListAndIndex(node, sourceFile) { - if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { + if (node.kind === 28 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; @@ -100026,10 +103674,10 @@ var ts; } return undefined; } - else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) { + else if (ts.isTemplateHead(node) && parent.parent.kind === 193 /* TaggedTemplateExpression */) { var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 204 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 206 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } @@ -100092,24 +103740,24 @@ var ts; return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) { - if (startingToken.kind !== 19 /* OpenParenToken */ && startingToken.kind !== 26 /* CommaToken */) + if (startingToken.kind !== 20 /* OpenParenToken */ && startingToken.kind !== 27 /* CommaToken */) return undefined; var parent = startingToken.parent; switch (parent.kind) { - case 193 /* ParenthesizedExpression */: - case 154 /* MethodDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ParenthesizedExpression */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: var info = getArgumentOrParameterListInfo(startingToken, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var highestBinary = getHighestBinary(parent); var contextualType_1 = checker.getContextualType(highestBinary); - var argumentIndex_1 = startingToken.kind === 19 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; + var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; var argumentCount_1 = countBinaryExpressionParameters(highestBinary); return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) }; } @@ -100141,7 +103789,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 26 /* CommaToken */) { + if (child.kind !== 27 /* CommaToken */) { argumentIndex++; } } @@ -100160,8 +103808,8 @@ var ts; // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. var listChildren = argumentsList.getChildren(); - var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 26 /* CommaToken */; }); - if (listChildren.length > 0 && ts.last(listChildren).kind === 26 /* CommaToken */) { + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; }); + if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -100230,7 +103878,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 === 204 /* TemplateExpression */) { + if (template.kind === 206 /* TemplateExpression */) { var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -100238,8 +103886,8 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100248,8 +103896,8 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +103912,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } - var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +103929,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(28 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(30 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100307,9 +103975,9 @@ var ts; var parameterParts = ts.mapToDisplayParts(function (writer) { var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); + printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer); }); - return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(27 /* LessThanToken */)], suffix: [ts.punctuationPart(29 /* GreaterThanToken */)].concat(parameterParts) }; + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { var isVariadic = candidateSignature.hasRestParameter; @@ -100317,11 +103985,11 @@ var ts; var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); - printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); + printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); - return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(19 /* OpenParenToken */)]), suffix: [ts.punctuationPart(20 /* CloseParenToken */)] }; + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] }; } function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { @@ -100336,60 +104004,53 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); /* @internal */ var ts; (function (ts) { - // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) - var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; - var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) { + function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var sourcemappedFileCache; - return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + var mappedFile = sourcemappedFileCache.get(toPath(fileName)); if (!mappedFile) { return; } - var starts = ts.getLineStarts(mappedFile); - for (var index = starts.length - 1; index >= 0; index--) { - var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); - var comment = sourceMapCommentRegExp.exec(lineText); - if (comment) { - return comment[1]; - } - // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file - else if (!lineText.match(whitespaceOrMapCommentRegExp)) { - break; - } - } + return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); } function convertDocumentToSourceMapper(file, contents, mapFileName) { - var maps; - try { - maps = JSON.parse(contents); - } - catch (_a) { - // swallow error - } - if (!maps || !maps.sources || !maps.file || !maps.mappings) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { // obviously invalid map - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } - return file.sourceMapper = ts.sourcemaps.decode({ - readFile: function (s) { return host.readFile(s); }, - fileExists: function (s) { return host.fileExists(s); }, + var program = getProgram(); + return file.sourceMapper = ts.createDocumentPositionMapper({ + getSourceFileLike: function (s) { + // Lookup file in program, if provided + var file = program && program.getSourceFileByPath(s); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (file === undefined || file.resolvedPath !== s) { + // Otherwise check the cache (which may hit disk) + return sourcemappedFileCache.get(s); + } + return file; + }, getCanonicalFileName: getCanonicalFileName, log: log, - }, mapFileName, maps, getProgram(), sourcemappedFileCache); + }, map, mapFileName); } function getSourceMapper(fileName, file) { if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } if (file.sourceMapper) { return file.sourceMapper; @@ -100418,20 +104079,24 @@ var ts; return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 } } - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } - function tryGetOriginalLocation(info) { + function tryGetSourcePosition(info) { if (!ts.isDeclarationFileName(info.fileName)) return undefined; var file = getFile(info.fileName); if (!file) return undefined; - var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); - return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); + return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; } - function tryGetGeneratedLocation(info) { + function tryGetGeneratedPosition(info) { var program = getProgram(); - var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + var options = program.getCompilerOptions(); + var outPath = options.outFile || options.out; + var declarationPath = outPath ? + ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : + ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); if (declarationPath === undefined) return undefined; var declarationFile = getFile(declarationPath); @@ -100441,18 +104106,45 @@ var ts; return newLoc === info ? undefined : newLoc; } function getFile(fileName) { - return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + var path = toPath(fileName); + var file = getProgram().getSourceFileByPath(path); + if (file && file.resolvedPath === path) { + return file; + } + return sourcemappedFileCache.get(path); } function toLineColumnOffset(fileName, position) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 + var file = getFile(fileName); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } function clearCache() { - sourcemappedFileCache = ts.createSourceFileLikeCache(host); + sourcemappedFileCache = createSourceFileLikeCache(host); } } ts.getSourceMapper = getSourceMapper; + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } })(ts || (ts = {})); /* @internal */ var ts; @@ -100460,13 +104152,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100488,8 +104180,8 @@ var ts; function check(node) { if (isJsFile) { switch (node.kind) { - case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + case 196 /* FunctionExpression */: + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100498,7 +104190,7 @@ var ts; } } // falls through if no diagnostic was created - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: var symbol = node.symbol; if (symbol.members && (symbol.members.size > 0)) { diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); @@ -100531,15 +104223,15 @@ var ts; function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 - case 219 /* ExpressionStatement */: { + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 221 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100552,66 +104244,74 @@ var ts; } function importNameForConvertToDefaultImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 249 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 251 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node.name; default: return undefined; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { - return; + if (!ts.isAsyncFunction(node) && + node.body && + ts.isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker)) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } + } + function returnsPromise(node, checker) { + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; - if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { - return; - } - // collect all the return statements - // check that a property access expression exists in there and that it is a handler - var returnStatements = getReturnStatementsWithPromiseHandlers(node); - if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); - } + return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - /** @internal */ - function getReturnStatementsWithPromiseHandlers(node) { - var returnStatements = []; - if (ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - else { - visit(node); - } - function visit(child) { - if (ts.isFunctionLike(child)) { - return; - } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } - } - ts.forEachChild(child, visit); - } - return returnStatements; + function hasReturnStatementWithPromiseHandler(body) { + return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); } - ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + function isReturnStatementWithFixablePromiseHandler(node) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + } + ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + ts.isFixablePromiseHandler = isFixablePromiseHandler; function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100627,7 +104327,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -100664,7 +104364,7 @@ var ts; if (typeChecker.isArgumentsSymbol(symbol)) { return "local var" /* localVariableElement */; } - if (location.kind === 99 /* ThisKeyword */ && ts.isExpression(location)) { + if (location.kind === 100 /* ThisKeyword */ && ts.isExpression(location)) { return "parameter" /* parameterElement */; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); @@ -100715,11 +104415,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 260 /* JsxOpeningElement */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 265 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + return location.kind === 72 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 267 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -100744,13 +104444,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 100 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 100 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(100 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100759,7 +104462,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 187 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 189 /* 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)) { @@ -100780,7 +104483,7 @@ var ts; if (callExpressionLike) { var candidateSignatures = []; signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 - var useConstructSignatures = callExpressionLike.kind === 190 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 192 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 98 /* 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 @@ -100798,7 +104501,7 @@ var ts; pushSymbolKind(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addFullSymbolName(symbol); @@ -100815,14 +104518,14 @@ var ts; case "parameter" /* parameterElement */: case "local var" /* localVariableElement */: // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(56 /* ColonToken */)); + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); displayParts.push(ts.spacePart()); if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); @@ -100835,29 +104538,29 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 155 /* Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 124 /* ConstructorKeyword */ && location.parent.kind === 157 /* Constructor */)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { - return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + return declaration === (location.kind === 124 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 155 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 157 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 155 /* Constructor */) { + if (functionDeclaration_1.kind === 157 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 158 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 160 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -100867,7 +104570,7 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 209 /* 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 @@ -100875,7 +104578,7 @@ var ts; } else { // Class declaration has name which is not local. - displayParts.push(ts.keywordPart(75 /* ClassKeyword */)); + displayParts.push(ts.keywordPart(76 /* ClassKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -100883,45 +104586,45 @@ var ts; } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); + displayParts.push(ts.keywordPart(110 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { - displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); + displayParts.push(ts.keywordPart(77 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } - displayParts.push(ts.keywordPart(83 /* EnumKeyword */)); + displayParts.push(ts.keywordPart(84 /* EnumKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 242 /* ModuleDeclaration */); - var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 130 /* NamespaceKeyword */ : 129 /* ModuleKeyword */)); + var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 131 /* NamespaceKeyword */ : 130 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); if (symbol.parent) { @@ -100932,7 +104635,7 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 148 /* TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 150 /* TypeParameter */); if (decl === undefined) return ts.Debug.fail(); var declaration = decl.parent; @@ -100940,21 +104643,21 @@ var ts; if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 - if (declaration.kind === 159 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + if (declaration.kind === 161 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 158 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 160 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 240 /* TypeAliasDeclaration */) { + else if (declaration.kind === 242 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path addInPrefix(); - displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -100966,11 +104669,11 @@ var ts; symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 276 /* EnumMember */) { + if (declaration.kind === 278 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } @@ -100996,41 +104699,41 @@ var ts; } } switch (symbol.declarations[0].kind) { - case 245 /* NamespaceExportDeclaration */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 247 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(130 /* NamespaceKeyword */)); + displayParts.push(ts.keywordPart(131 /* NamespaceKeyword */)); break; - case 252 /* ExportAssignment */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 254 /* ExportAssignment */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 59 /* EqualsToken */ : 80 /* DefaultKeyword */)); break; - case 255 /* ExportSpecifier */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 257 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); break; default: - displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); + displayParts.push(ts.keywordPart(92 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 246 /* ImportEqualsDeclaration */) { + if (declaration.kind === 248 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(133 /* RequireKeyword */)); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.keywordPart(134 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); } else { var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(internalAliasSymbol, enclosingDeclaration); } @@ -101044,7 +104747,7 @@ var ts; if (type) { if (isThisExpression) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); + displayParts.push(ts.keywordPart(100 /* ThisKeyword */)); } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); @@ -101055,7 +104758,7 @@ var ts; symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || isThisExpression) { - displayParts.push(ts.punctuationPart(56 /* ColonToken */)); + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); displayParts.push(ts.spacePart()); // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { @@ -101093,10 +104796,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 277 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 202 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -101118,7 +104821,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101139,7 +104842,7 @@ var ts; } function addInPrefix() { displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(92 /* InKeyword */)); + displayParts.push(ts.keywordPart(93 /* InKeyword */)); displayParts.push(ts.spacePart()); } function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { @@ -101149,7 +104852,7 @@ var ts; var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); if (symbol.flags & 16777216 /* Optional */) { - displayParts.push(ts.punctuationPart(55 /* QuestionToken */)); + displayParts.push(ts.punctuationPart(56 /* QuestionToken */)); } } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { @@ -101172,9 +104875,9 @@ var ts; displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); return; } } @@ -101183,20 +104886,21 @@ var ts; ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); - displayParts.push(ts.operatorPart(37 /* PlusToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(38 /* PlusToken */)); displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); displayParts.push(ts.spacePart()); displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); - getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -101208,16 +104912,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 194 /* FunctionExpression */) { + if (declaration.kind === 196 /* FunctionExpression */) { return true; } - if (declaration.kind !== 235 /* VariableDeclaration */ && declaration.kind !== 237 /* FunctionDeclaration */) { + if (declaration.kind !== 237 /* VariableDeclaration */ && declaration.kind !== 239 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 277 /* SourceFile */ || parent.kind === 243 /* ModuleBlock */) { + if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) { return false; } } @@ -101257,6 +104961,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +105035,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_16 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +105054,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_16(opt); } return options; } @@ -101376,16 +105081,11 @@ var ts; this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { - ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); - ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); - ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); - ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); - ts.Debug.assert(commonParent !== undefined, "commonParent is null"); - this.currentTokenSpan = currentRange; - this.currentTokenParent = currentTokenParent; - this.nextTokenSpan = nextRange; - this.nextTokenParent = nextTokenParent; - this.contextNode = commonParent; + this.currentTokenSpan = ts.Debug.assertDefined(currentRange); + this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent); + this.nextTokenSpan = ts.Debug.assertDefined(nextRange); + this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent); + this.contextNode = ts.Debug.assertDefined(commonParent); // drop cached results this.contextNodeAllOnSameLine = undefined; this.nextNodeAllOnSameLine = undefined; @@ -101431,8 +105131,8 @@ var ts; return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 17 /* OpenBraceToken */, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 18 /* CloseBraceToken */, this.sourceFile); + var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile); if (openBrace && closeBrace) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; @@ -101514,11 +105214,11 @@ var ts; } function shouldRescanGreaterThanToken(node) { switch (node.kind) { - case 31 /* GreaterThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 46 /* GreaterThanGreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: return true; } return false; @@ -101526,28 +105226,28 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 265 /* JsxAttribute */: - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 267 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. - return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; + return ts.isKeyword(node.kind) || node.kind === 72 /* Identifier */; } } return false; } function shouldRescanJsxText(node) { - return node.kind === 10 /* JsxText */; + return node.kind === 11 /* JsxText */; } function shouldRescanSlashToken(container) { - return container.kind === 12 /* RegularExpressionLiteral */; + return container.kind === 13 /* RegularExpressionLiteral */; } function shouldRescanTemplateToken(container) { - return container.kind === 15 /* TemplateMiddle */ || - container.kind === 16 /* TemplateTail */; + return container.kind === 16 /* TemplateMiddle */ || + container.kind === 17 /* TemplateTail */; } function startsWithSlashToken(t) { - return t === 41 /* SlashToken */ || t === 63 /* SlashEqualsToken */; + return t === 42 /* SlashToken */ || t === 64 /* SlashEqualsToken */; } function readTokenInfo(n) { ts.Debug.assert(isOnToken()); @@ -101617,7 +105317,7 @@ var ts; lastScanAction = 0 /* Scan */; switch (expectedScanAction) { case 1 /* RescanGreaterThanToken */: - if (token === 29 /* GreaterThanToken */) { + if (token === 30 /* GreaterThanToken */) { lastScanAction = 1 /* RescanGreaterThanToken */; var newToken = scanner.reScanGreaterToken(); ts.Debug.assert(n.kind === newToken); @@ -101633,7 +105333,7 @@ var ts; } break; case 3 /* RescanTemplateToken */: - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { lastScanAction = 3 /* RescanTemplateToken */; return scanner.reScanTemplateToken(); } @@ -101706,7 +105406,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 145 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 147 /* LastToken */; token++) { allTokens.push(token); } function anyTokenExcept() { @@ -101718,255 +105418,255 @@ var ts; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); - var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 145 /* LastKeyword */); - var binaryOperators = tokenRangeFromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 145 /* OfKeyword */, 118 /* AsKeyword */, 127 /* IsKeyword */]; - var unaryPrefixOperators = [43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]; + var keywords = tokenRangeFromRange(73 /* FirstKeyword */, 147 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(28 /* FirstBinaryOperator */, 71 /* LastBinaryOperator */); + var binaryKeywordOperators = [93 /* InKeyword */, 94 /* InstanceOfKeyword */, 147 /* OfKeyword */, 119 /* AsKeyword */, 128 /* IsKeyword */]; + var unaryPrefixOperators = [44 /* PlusPlusToken */, 45 /* MinusMinusToken */, 53 /* TildeToken */, 52 /* ExclamationToken */]; var unaryPrefixExpressions = [ - 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, - 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 72 /* Identifier */, 20 /* OpenParenToken */, + 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */ ]; - var unaryPreincrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; - var unaryPostincrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; - var unaryPredecrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; - var unaryPostdecrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; + var unaryPreincrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostincrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var unaryPredecrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostdecrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; - var typeNames = [71 /* Identifier */].concat(ts.typeKeywords); + var typeNames = [72 /* Identifier */].concat(ts.typeKeywords); // Place a space before open brace in a function declaration // TypeScript: Function can have return types, which can be made of tons of different token kinds var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) - var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([72 /* Identifier */, 3 /* MultiLineCommentTrivia */, 76 /* ClassKeyword */, 85 /* ExportKeyword */, 92 /* ImportKeyword */]); // Place a space before open brace in a control flow construct - var controlOpenBraceLeftTokenRange = tokenRangeFrom([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); + var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 82 /* DoKeyword */, 103 /* TryKeyword */, 88 /* FinallyKeyword */, 83 /* ElseKeyword */]); // These rules are higher in priority than user-configurable var highPriorityCommonRules = [ // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), - rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), - rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), - rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NotSpaceBeforeColon", anyToken, 57 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), + rule("SpaceAfterColon", 57 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 56 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // insert space after '?' only when it is used in conditional operator - rule("SpaceAfterQuestionMarkInConditionalOperator", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + rule("SpaceAfterQuestionMarkInConditionalOperator", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), // in other cases there should be no space between '?' and next token - rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), + rule("NoSpaceAfterQuestionMark", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 92 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), - rule("NoSpaceAfterUnaryPreincrementOperator", 43 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterUnaryPredecrementOperator", 44 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 44 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 45 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 45 /* MinusMinusToken */, [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 - rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterPostincrementWhenFollowedByAdd", 44 /* PlusPlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 38 /* PlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 38 /* PlusToken */, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 45 /* MinusMinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 39 /* MinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 39 /* MinusToken */, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // For functions and control block place } on a new line [multi-line rule] - rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), // Space/new line after }. - rule("SpaceAfterCloseBrace", 18 /* CloseBraceToken */, anyTokenExcept(20 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, 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 // Also should not apply to }) - rule("SpaceBetweenCloseBraceAndElse", 18 /* CloseBraceToken */, 82 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenCloseBraceAndWhile", 18 /* CloseBraceToken */, 106 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 83 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 107 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' - rule("SpaceAfterConditionalClosingParen", 20 /* CloseParenToken */, 21 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), - rule("NoSpaceBetweenFunctionKeywordAndStar", 89 /* FunctionKeyword */, 39 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), - rule("SpaceAfterStarInGeneratorDeclaration", 39 /* AsteriskToken */, [71 /* Identifier */, 19 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), - rule("SpaceAfterFunctionInFuncDecl", 89 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 90 /* FunctionKeyword */, 40 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 40 /* AsteriskToken */, [72 /* Identifier */, 20 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 90 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), // Insert new line after { and before } in multi-line contexts. - rule("NewLineAfterOpenBraceInBlockContext", 17 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: // get x() {} // set x(val) {} - rule("SpaceAfterGetSetInMember", [125 /* GetKeyword */, 136 /* SetKeyword */], 71 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceBetweenYieldKeywordAndStar", 116 /* YieldKeyword */, 39 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), - rule("SpaceBetweenYieldOrYieldStarAndOperand", [116 /* YieldKeyword */, 39 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), - rule("NoSpaceBetweenReturnAndSemicolon", 96 /* ReturnKeyword */, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterCertainKeywords", [104 /* VarKeyword */, 100 /* ThrowKeyword */, 94 /* NewKeyword */, 80 /* DeleteKeyword */, 96 /* ReturnKeyword */, 103 /* TypeOfKeyword */, 121 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceAfterLetConstInVariableDeclaration", [110 /* LetKeyword */, 76 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), - rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), + rule("SpaceAfterGetSetInMember", [126 /* GetKeyword */, 137 /* SetKeyword */], 72 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 117 /* YieldKeyword */, 40 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [117 /* YieldKeyword */, 40 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 97 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [105 /* VarKeyword */, 101 /* ThrowKeyword */, 95 /* NewKeyword */, 81 /* DeleteKeyword */, 97 /* ReturnKeyword */, 104 /* TypeOfKeyword */, 122 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [111 /* LetKeyword */, 77 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterVoidOperator", 105 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 106 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), // Async-await - rule("SpaceBetweenAsyncAndOpenParen", 120 /* AsyncKeyword */, 19 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 120 /* AsyncKeyword */, 89 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndOpenParen", 121 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 121 /* AsyncKeyword */, 90 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), // Template string - rule("NoSpaceBetweenTagAndTemplateString", [71 /* Identifier */, 20 /* CloseParenToken */], [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenTagAndTemplateString", [72 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // JSX opening elements - rule("SpaceBeforeJsxAttribute", anyToken, 71 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 41 /* SlashToken */, 29 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 58 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterEqualInJsxAttribute", 58 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeJsxAttribute", anyToken, 72 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 42 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 42 /* SlashToken */, 30 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 59 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 59 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), // TypeScript-specific rules // Use of module as a function call. e.g.: import m2 = module("m2"); - rule("NoSpaceAfterModuleImport", [129 /* ModuleKeyword */, 133 /* RequireKeyword */], 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterModuleImport", [130 /* ModuleKeyword */, 134 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Add a space around certain TypeScript keywords rule("SpaceAfterCertainTypeScriptKeywords", [ - 117 /* AbstractKeyword */, - 75 /* ClassKeyword */, - 124 /* DeclareKeyword */, - 79 /* DefaultKeyword */, - 83 /* EnumKeyword */, - 84 /* ExportKeyword */, - 85 /* ExtendsKeyword */, - 125 /* GetKeyword */, - 108 /* ImplementsKeyword */, - 91 /* ImportKeyword */, - 109 /* InterfaceKeyword */, - 129 /* ModuleKeyword */, - 130 /* NamespaceKeyword */, - 112 /* PrivateKeyword */, - 114 /* PublicKeyword */, - 113 /* ProtectedKeyword */, - 132 /* ReadonlyKeyword */, - 136 /* SetKeyword */, - 115 /* StaticKeyword */, - 139 /* TypeKeyword */, - 143 /* FromKeyword */, - 128 /* KeyOfKeyword */, - 126 /* InferKeyword */, + 118 /* AbstractKeyword */, + 76 /* ClassKeyword */, + 125 /* DeclareKeyword */, + 80 /* DefaultKeyword */, + 84 /* EnumKeyword */, + 85 /* ExportKeyword */, + 86 /* ExtendsKeyword */, + 126 /* GetKeyword */, + 109 /* ImplementsKeyword */, + 92 /* ImportKeyword */, + 110 /* InterfaceKeyword */, + 130 /* ModuleKeyword */, + 131 /* NamespaceKeyword */, + 113 /* PrivateKeyword */, + 115 /* PublicKeyword */, + 114 /* ProtectedKeyword */, + 133 /* ReadonlyKeyword */, + 137 /* SetKeyword */, + 116 /* StaticKeyword */, + 140 /* TypeKeyword */, + 144 /* FromKeyword */, + 129 /* KeyOfKeyword */, + 127 /* InferKeyword */, ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 143 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [86 /* ExtendsKeyword */, 109 /* ImplementsKeyword */, 144 /* FromKeyword */], [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" { - rule("SpaceAfterModuleName", 9 /* StringLiteral */, 17 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), + rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), // Lambda expressions - rule("SpaceBeforeArrow", anyToken, 36 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceAfterArrow", 36 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeArrow", anyToken, 37 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 37 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Optional parameters and let args - rule("NoSpaceAfterEllipsis", 24 /* DotDotDotToken */, 71 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOptionalParameters", 55 /* QuestionToken */, [20 /* CloseParenToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 72 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 56 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // Remove spaces in empty interface literals. e.g.: x: {} - rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), // generics and type assertions - rule("NoSpaceBeforeOpenAngularBracket", typeNames, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceBetweenCloseParenAndAngularBracket", 20 /* CloseParenToken */, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterOpenAngularBracket", 27 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 28 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 30 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 30 /* GreaterThanToken */, [20 /* OpenParenToken */, 22 /* OpenBracketToken */, 30 /* GreaterThanToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), // decorators - rule("SpaceBeforeAt", [20 /* CloseParenToken */, 71 /* Identifier */], 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeAt", [21 /* CloseParenToken */, 72 /* Identifier */], 58 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 58 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after @ in decorator rule("SpaceAfterDecorator", anyToken, [ - 117 /* AbstractKeyword */, - 71 /* Identifier */, - 84 /* ExportKeyword */, - 79 /* DefaultKeyword */, - 75 /* ClassKeyword */, - 115 /* StaticKeyword */, - 114 /* PublicKeyword */, - 112 /* PrivateKeyword */, - 113 /* ProtectedKeyword */, - 125 /* GetKeyword */, - 136 /* SetKeyword */, - 21 /* OpenBracketToken */, - 39 /* AsteriskToken */, + 118 /* AbstractKeyword */, + 72 /* Identifier */, + 85 /* ExportKeyword */, + 80 /* DefaultKeyword */, + 76 /* ClassKeyword */, + 116 /* StaticKeyword */, + 115 /* PublicKeyword */, + 113 /* PrivateKeyword */, + 114 /* ProtectedKeyword */, + 126 /* GetKeyword */, + 137 /* SetKeyword */, + 22 /* OpenBracketToken */, + 40 /* AsteriskToken */, ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), - rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 51 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterNewKeywordOnConstructorSignature", 94 /* NewKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 52 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 95 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), ]; // These rules are applied after high priority var userConfigurableRules = [ // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses - rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), - rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), + rule("SpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), // Insert space after function keyword for anonymous functions - rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), + rule("SpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), // Insert space after keywords in control flow statements - rule("SpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), - rule("NoSpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), + rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), // Insert space after opening and before closing nonempty parenthesis - rule("SpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenOpenParens", 19 /* OpenParenToken */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenParens", 19 /* OpenParenToken */, 20 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing nonempty brackets - rule("SpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenBrackets", 21 /* OpenBracketToken */, 22 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - rule("SpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), - rule("SpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), - rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), - rule("NoSpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing template string braces - rule("SpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // No space after { and before } in JSX expression - rule("SpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), - rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), - rule("NoSpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), // Insert space after semicolon in for statement - rule("SpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), - rule("NoSpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), // Insert space before and after binary operators rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), - rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), // Open Brace braces after control block - rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), // Open Brace braces after function // TypeScript: Function can have return types, which can be made of tons of different token kinds - rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), // Open Brace braces after TypeScript module/class/interface - rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), - rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), - rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), - rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), - rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), ]; // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. var lowPriorityCommonRules = [ // Space after keyword but not before ; or : or ? - rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // No space before and after indexer `x[]` - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), - rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(121 /* AsyncKeyword */, 74 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Remove extra space between for and await - rule("SpaceBetweenForAndAwaitKeyword", 88 /* ForKeyword */, 121 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenForAndAwaitKeyword", 89 /* ForKeyword */, 122 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), // 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] - rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), + rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 82 /* DoKeyword */, 83 /* ElseKeyword */, 74 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterTryFinally", [103 /* TryKeyword */, 88 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), ]; return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); } @@ -102010,45 +105710,45 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 223 /* ForStatement */; + return context.contextNode.kind === 225 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 202 /* BinaryExpression */: - case 203 /* ConditionalExpression */: - case 173 /* ConditionalType */: - case 210 /* AsExpression */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 161 /* TypePredicate */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 175 /* ConditionalType */: + case 212 /* AsExpression */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 163 /* TypePredicate */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 184 /* BindingElement */: + case 186 /* BindingElement */: // equals in type X = ... - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: // equal in p = 0; - case 149 /* Parameter */: - case 276 /* EnumMember */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; + case 151 /* Parameter */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] - case 148 /* TypeParameter */: - return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; + case 150 /* TypeParameter */: + return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 225 /* ForOfStatement */: - return context.currentTokenSpan.kind === 145 /* OfKeyword */ || context.nextTokenSpan.kind === 145 /* OfKeyword */; + case 227 /* ForOfStatement */: + return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */; } return false; } @@ -102060,22 +105760,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 152 /* PropertyDeclaration */ || - contextKind === 151 /* PropertySignature */ || - contextKind === 149 /* Parameter */ || - contextKind === 235 /* VariableDeclaration */ || + return contextKind === 154 /* PropertyDeclaration */ || + contextKind === 153 /* PropertySignature */ || + contextKind === 151 /* Parameter */ || + contextKind === 237 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 203 /* ConditionalExpression */ || - context.contextNode.kind === 173 /* ConditionalType */; + return context.contextNode.kind === 205 /* ConditionalExpression */ || + context.contextNode.kind === 175 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 182 /* ObjectBindingPattern */ || - context.contextNode.kind === 179 /* MappedType */ || + return context.contextNode.kind === 184 /* ObjectBindingPattern */ || + context.contextNode.kind === 181 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -102101,31 +105801,31 @@ var ts; return true; } switch (node.kind) { - case 216 /* Block */: - case 244 /* CaseBlock */: - case 186 /* ObjectLiteralExpression */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 188 /* ObjectLiteralExpression */: + case 245 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // case SyntaxKind.MethodSignature: - case 158 /* CallSignature */: - case 194 /* FunctionExpression */: - case 155 /* Constructor */: - case 195 /* ArrowFunction */: + case 160 /* CallSignature */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 197 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 239 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 241 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -102134,40 +105834,40 @@ var ts; return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 237 /* FunctionDeclaration */ || context.contextNode.kind === 194 /* FunctionExpression */; + return context.contextNode.kind === 239 /* FunctionDeclaration */ || context.contextNode.kind === 196 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 166 /* TypeLiteral */: - case 242 /* ModuleDeclaration */: - case 253 /* ExportDeclaration */: - case 254 /* NamedExports */: - case 247 /* ImportDeclaration */: - case 250 /* NamedImports */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 168 /* TypeLiteral */: + case 244 /* ModuleDeclaration */: + case 255 /* ExportDeclaration */: + case 256 /* NamedExports */: + case 249 /* ImportDeclaration */: + case 252 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 272 /* CatchClause */: - case 243 /* ModuleBlock */: - case 230 /* SwitchStatement */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 274 /* CatchClause */: + case 245 /* ModuleBlock */: + case 232 /* SwitchStatement */: return true; - case 216 /* Block */: { + case 218 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 195 /* ArrowFunction */ && blockParent.kind !== 194 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 197 /* ArrowFunction */ && blockParent.kind !== 196 /* FunctionExpression */) { return true; } } @@ -102176,64 +105876,64 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 220 /* IfStatement */: - case 230 /* SwitchStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: - case 233 /* TryStatement */: - case 221 /* DoStatement */: - case 229 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 231 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 272 /* CatchClause */: + case 274 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 186 /* ObjectLiteralExpression */; + return context.contextNode.kind === 188 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 189 /* CallExpression */; + return context.contextNode.kind === 191 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 190 /* NewExpression */; + return context.contextNode.kind === 192 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); } function isPreviousTokenNotComma(context) { - return context.currentTokenSpan.kind !== 26 /* CommaToken */; + return context.currentTokenSpan.kind !== 27 /* CommaToken */; } function isNextTokenNotCloseBracket(context) { - return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; + return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 195 /* ArrowFunction */; + return context.contextNode.kind === 197 /* ArrowFunction */; } function isImportTypeContext(context) { - return context.contextNode.kind === 181 /* ImportType */; + return context.contextNode.kind === 183 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; + return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 258 /* JsxElement */ && context.contextNode.kind !== 262 /* JsxFragment */; + return context.contextNode.kind !== 260 /* JsxElement */ && context.contextNode.kind !== 264 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 268 /* JsxExpression */ || context.contextNode.kind === 267 /* JsxSpreadAttribute */; + return context.contextNode.kind === 270 /* JsxExpression */ || context.contextNode.kind === 269 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 265 /* JsxAttribute */; + return context.nextTokenParent.kind === 267 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 265 /* JsxAttribute */; + return context.contextNode.kind === 267 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 259 /* JsxSelfClosingElement */; + return context.contextNode.kind === 261 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -102248,45 +105948,45 @@ var ts; while (ts.isExpressionNode(node)) { node = node.parent; } - return node.kind === 150 /* Decorator */; + return node.kind === 152 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 236 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 238 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 242 /* ModuleDeclaration */; + return context.contextNode.kind === 244 /* ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 166 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 168 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 159 /* ConstructSignature */; + return context.contextNode.kind === 161 /* ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { - if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { + if (token.kind !== 28 /* LessThanToken */ && token.kind !== 30 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 162 /* TypeReference */: - case 192 /* TypeAssertionExpression */: - case 240 /* TypeAliasDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 209 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 194 /* TypeAssertionExpression */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -102297,16 +105997,16 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 192 /* TypeAssertionExpression */; + return context.contextNode.kind === 194 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 198 /* VoidExpression */; + return context.currentTokenSpan.kind === 106 /* VoidKeyword */ && context.currentTokenParent.kind === 200 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 205 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 207 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 211 /* NonNullExpression */; + return context.contextNode.kind === 213 /* NonNullExpression */; } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -102357,12 +106057,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 145 /* LastKeyword */ && column <= 145 /* LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 147 /* LastKeyword */ && column <= 147 /* LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 145 /* LastToken */ + 1; + var mapRowLength = 147 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; @@ -102451,12 +106151,12 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, formatContext) { - var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25 /* SemicolonToken */, sourceFile); + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; function formatOnOpeningCurly(position, sourceFile, formatContext) { - var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17 /* OpenBraceToken */, sourceFile); + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile); if (!openingCurly) { return []; } @@ -102482,7 +106182,7 @@ var ts; } formatting.formatOnOpeningCurly = formatOnOpeningCurly; function formatOnClosingCurly(position, sourceFile, formatContext) { - var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18 /* CloseBraceToken */, sourceFile); + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; @@ -102540,17 +106240,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 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: var body = parent.body; - return !!body && body.kind === 243 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 277 /* SourceFile */: - case 216 /* Block */: - case 243 /* ModuleBlock */: + return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 279 /* SourceFile */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -102663,7 +106363,6 @@ var ts; } return 0; } - /* @internal */ function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { var range = { pos: 0, end: sourceFileLike.text.length }; return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors @@ -102693,7 +106392,7 @@ var ts; var previousParent; var previousRangeStartLine; var lastIndentedLine; - var indentationOnLastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -102707,7 +106406,7 @@ var ts; if (!formattingScanner.isOnToken()) { var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); // TODO: GH#18217 + indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); trimTrailingWhitespacesForRemainingRange(); } } @@ -102752,7 +106451,7 @@ var ts; }; } else if (inheritedIndentation === -1 /* Unknown */) { - if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) { + if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) { // the is used for chaining methods formatting // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; @@ -102773,19 +106472,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 238 /* ClassDeclaration */: return 75 /* ClassKeyword */; - case 239 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; - case 237 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; - case 241 /* EnumDeclaration */: return 241 /* EnumDeclaration */; - case 156 /* GetAccessor */: return 125 /* GetKeyword */; - case 157 /* SetAccessor */: return 136 /* SetKeyword */; - case 154 /* MethodDeclaration */: + case 240 /* ClassDeclaration */: return 76 /* ClassKeyword */; + case 241 /* InterfaceDeclaration */: return 110 /* InterfaceKeyword */; + case 239 /* FunctionDeclaration */: return 90 /* FunctionKeyword */; + case 243 /* EnumDeclaration */: return 243 /* EnumDeclaration */; + case 158 /* GetAccessor */: return 126 /* GetKeyword */; + case 159 /* SetAccessor */: return 137 /* SetKeyword */; + case 156 /* MethodDeclaration */: if (node.asteriskToken) { - return 39 /* AsteriskToken */; + return 40 /* AsteriskToken */; } // falls through - case 152 /* PropertyDeclaration */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: var name = ts.getNameOfDeclaration(node); if (name) { return name.kind; @@ -102800,15 +106499,25 @@ var ts; // .. { // // comment // } - case 18 /* CloseBraceToken */: - case 22 /* CloseBracketToken */: - case 20 /* CloseParenToken */: + case 19 /* CloseBraceToken */: + case 23 /* CloseBracketToken */: + case 21 /* CloseParenToken */: return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind, container) { - return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; + // if list end token is LessThanToken '>' then its delta should be explicitly suppressed + // so that LessThanToken as a binary operator can still be indented. + // foo.then + // < + // number, + // string, + // >(); + // vs + // var a = xValue + // > yValue; + getIndentationForToken: function (line, kind, container, suppressDelta) { + return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, getDelta: getDelta, @@ -102822,26 +106531,25 @@ var ts; function shouldAddDelta(line, kind, container) { switch (kind) { // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 17 /* OpenBraceToken */: - case 18 /* CloseBraceToken */: - case 19 /* OpenParenToken */: - case 20 /* CloseParenToken */: - case 82 /* ElseKeyword */: - case 106 /* WhileKeyword */: - case 57 /* AtToken */: + case 18 /* OpenBraceToken */: + case 19 /* CloseBraceToken */: + case 21 /* CloseParenToken */: + case 83 /* ElseKeyword */: + case 107 /* WhileKeyword */: + case 58 /* AtToken */: return false; - case 41 /* SlashToken */: - case 29 /* GreaterThanToken */: + case 42 /* SlashToken */: + case 30 /* GreaterThanToken */: switch (container.kind) { - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: return false; } break; - case 21 /* OpenBracketToken */: - case 22 /* CloseBracketToken */: - if (container.kind !== 179 /* MappedType */) { + case 22 /* OpenBracketToken */: + case 23 /* CloseBracketToken */: + if (container.kind !== 181 /* MappedType */) { return false; } break; @@ -102926,22 +106634,22 @@ var ts; return inheritedIndentation; } // JSX text shouldn't affect indenting - if (ts.isToken(child) && child.kind !== 10 /* JsxText */) { + if (ts.isToken(child) && child.kind !== 11 /* JsxText */) { // 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, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 150 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 152 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); - if (child.kind === 10 /* JsxText */) { + if (child.kind === 11 /* JsxText */) { var range = { pos: child.getStart(), end: child.getEnd() }; indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); } childContextNode = node; - if (isFirstListItem && parent.kind === 185 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 187 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -102962,9 +106670,20 @@ var ts; else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta); - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + var indentationOnListStartToken = void 0; + if (indentationOnLastIndentedLine !== -1 /* Unknown */) { + // scanner just processed list start token so consider last indentation as list indentation + // function foo(): { // last indentation was 0, list item will be indented based on this value + // foo: number; + // }: {}; + indentationOnListStartToken = indentationOnLastIndentedLine; + } + else { + var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile); + indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options); + } + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217 } else { // consume any tokens that precede the list as child elements of 'node' using its indentation scope @@ -102980,21 +106699,21 @@ var ts; var listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); - if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true); } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -103026,32 +106745,12 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : -1 /* Unknown */; var indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); - for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { - var triviaItem = _a[_i]; - var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); - switch (triviaItem.kind) { - case 3 /* MultiLineCommentTrivia */: - if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); - } - indentNextTokenOrTrivia = false; - break; - case 2 /* SingleLineCommentTrivia */: - if (indentNextTokenOrTrivia && triviaInRange) { - insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); - } - indentNextTokenOrTrivia = false; - break; - case 4 /* NewLineTrivia */: - indentNextTokenOrTrivia = true; - break; - } - } + var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); }); } // indent token only if is it is in target range and does not overlap with any error ranges if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { @@ -103064,16 +106763,39 @@ var ts; childContextNode = parent; } } - function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) { for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { var triviaItem = trivia_1[_i]; + var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); + switch (triviaItem.kind) { + case 3 /* MultiLineCommentTrivia */: + if (triviaInRange) { + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + } + indentNextTokenOrTrivia = false; + break; + case 2 /* SingleLineCommentTrivia */: + if (indentNextTokenOrTrivia && triviaInRange) { + indentSingleLine(triviaItem); + } + indentNextTokenOrTrivia = false; + break; + case 4 /* NewLineTrivia */: + indentNextTokenOrTrivia = true; + break; + } + } + return indentNextTokenOrTrivia; + } + function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) { + var triviaItem = trivia_2[_i]; if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); } } } - // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAction = 0 /* None */; @@ -103245,7 +106967,10 @@ var ts; * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - var startPosition = previousRange ? previousRange.end : originalRange.pos; + if (!previousRange) { + return; + } + var startPosition = previousRange.end; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); @@ -103345,41 +107070,46 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 195 /* ArrowFunction */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 197 /* ArrowFunction */: if (node.typeParameters === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } else if (node.parameters === list) { - return 19 /* OpenParenToken */; + return 20 /* OpenParenToken */; } break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: if (node.typeArguments === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } else if (node.arguments === list) { - return 19 /* OpenParenToken */; + return 20 /* OpenParenToken */; } break; - case 162 /* TypeReference */: + case 164 /* TypeReference */: if (node.typeArguments === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } + break; + case 168 /* TypeLiteral */: + return 18 /* OpenBraceToken */; } return 0 /* Unknown */; } function getCloseTokenForOpenToken(kind) { switch (kind) { - case 19 /* OpenParenToken */: - return 20 /* CloseParenToken */; - case 27 /* LessThanToken */: - return 29 /* GreaterThanToken */; + case 20 /* OpenParenToken */: + return 21 /* CloseParenToken */; + case 28 /* LessThanToken */: + return 30 /* GreaterThanToken */; + case 18 /* OpenBraceToken */: + return 19 /* CloseBraceToken */; } return 0 /* Unknown */; } @@ -103484,13 +107214,18 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 202 /* BinaryExpression */) { + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 204 /* 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 */) { return actualIndentation; } } + var containerList = getListByPosition(position, precedingToken.parent, sourceFile); + // use list position if the preceding token is before any list items + if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) { + return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217 + } return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); } SmartIndenter.getIndentation = getIndentation; @@ -103501,12 +107236,12 @@ var ts; if (previousLine <= commentStartLine) { return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); } - var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); - var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; if (column === 0) { return column; } - var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; } function getBlockIndent(sourceFile, position, options) { @@ -103539,14 +107274,13 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 } // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); + // do not consider parent-child line sharing yet: + // function foo(a + // | preceding node 'a' does share line with its parent but indentation is expected + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } - actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); - if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; // TODO: GH#18217 - } previous = current; current = current.parent; } @@ -103573,23 +107307,17 @@ var ts; var start = current.getStart(sourceFile); useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; } - if (useActualIndentation) { - // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); - if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + indentationDelta; - } - } var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { - // try to fetch actual indentation for current node from source text - var actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); + // check if current node is a list item - if yes, take indentation from it + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } - actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + // try to fetch actual indentation for current node from source text + actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -103640,7 +107368,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.isStatementButNotDeclaration(current)) && - (parent.kind === 277 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -103657,11 +107385,11 @@ var ts; if (!nextToken) { return 0 /* Unknown */; } - if (nextToken.kind === 17 /* OpenBraceToken */) { + if (nextToken.kind === 18 /* OpenBraceToken */) { // open braces are always indented at the parent level return 1 /* OpenBrace */; } - else if (nextToken.kind === 18 /* CloseBraceToken */) { + else if (nextToken.kind === 19 /* CloseBraceToken */) { // close braces are indented at the parent level if they are located on the same line with cursor // this means that if new line will be added at $ position, this case will be indented // class A { @@ -103688,8 +107416,8 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 220 /* IfStatement */ && parent.elseStatement === child) { - var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile); + if (parent.kind === 222 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 83 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; @@ -103697,103 +107425,87 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; - function getListIfStartEndIsInListRange(list, start, end) { - return list && ts.rangeContainsStartEnd(list, start, end) ? list : undefined; - } function getContainingList(node, sourceFile) { - if (node.parent) { - var end = node.end; - switch (node.parent.kind) { - case 162 /* TypeReference */: - return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); - case 186 /* ObjectLiteralExpression */: - return node.parent.properties; - case 185 /* ArrayLiteralExpression */: - return node.parent.elements; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 155 /* Constructor */: - case 164 /* ConstructorType */: - case 159 /* ConstructSignature */: { - var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || - getListIfStartEndIsInListRange(node.parent.parameters, start, end); - } - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: { - var typeParameters = node.parent.typeParameters; - return getListIfStartEndIsInListRange(typeParameters, node.getStart(sourceFile), end); - } - case 190 /* NewExpression */: - case 189 /* CallExpression */: { - var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || - getListIfStartEndIsInListRange(node.parent.arguments, start, end); - } - case 236 /* VariableDeclarationList */: - return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); - case 250 /* NamedImports */: - case 254 /* NamedExports */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); - } - } - return undefined; + return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile); } SmartIndenter.getContainingList = getContainingList; - function getActualIndentationForListItem(node, sourceFile, options) { + function getListByPosition(pos, node, sourceFile) { + return node && getListByRange(pos, pos, node, sourceFile); + } + function getListByRange(start, end, node, sourceFile) { + switch (node.kind) { + case 164 /* TypeReference */: + return getList(node.typeArguments); + case 188 /* ObjectLiteralExpression */: + return getList(node.properties); + case 187 /* ArrayLiteralExpression */: + return getList(node.elements); + case 168 /* TypeLiteral */: + return getList(node.members); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return getList(node.typeParameters) || getList(node.parameters); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + return getList(node.typeParameters); + case 192 /* NewExpression */: + case 191 /* CallExpression */: + return getList(node.typeArguments) || getList(node.arguments); + case 238 /* VariableDeclarationList */: + return getList(node.declarations); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return getList(node.elements); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return getList(node.elements); + } + function getList(list) { + return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined; + } + } + function getVisualListRange(node, list, sourceFile) { + var children = node.getChildren(sourceFile); + for (var i = 1; i < children.length - 1; i++) { + if (children[i].pos === list.pos && children[i].end === list.end) { + return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) }; + } + } + return list; + } + function getActualIndentationForListStartLine(list, sourceFile, options) { + if (!list) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); + } + function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { + if (node.parent && node.parent.kind === 238 /* VariableDeclarationList */) { + // VariableDeclarationList has no wrapping tokens + return -1 /* Unknown */; + } var containingList = getContainingList(node, sourceFile); if (containingList) { var index = containingList.indexOf(node); if (index !== -1) { - return deriveActualIndentationFromList(containingList, index, sourceFile, options); - } - } - return -1 /* Unknown */; - } - function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { - // actual indentation should not be used when: - // - node is close parenthesis - this is the end of the expression - if (node.kind === 20 /* CloseParenToken */) { - return -1 /* Unknown */; - } - if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { - var fullCallOrNewExpression = node.parent.expression; - var startingExpression = getStartingExpression(fullCallOrNewExpression); - if (fullCallOrNewExpression === startingExpression) { - return -1 /* Unknown */; - } - var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); - var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); - if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { - return -1 /* Unknown */; - } - return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); - } - return -1 /* Unknown */; - function getStartingExpression(node) { - while (true) { - switch (node.kind) { - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - node = node.expression; - break; - default: - return node; + var result = deriveActualIndentationFromList(containingList, index, sourceFile, options); + if (result !== -1 /* Unknown */) { + return result; } } + return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217 } + return -1 /* Unknown */; } function deriveActualIndentationFromList(list, index, sourceFile, options) { ts.Debug.assert(index >= 0 && index < list.length); @@ -103802,7 +107514,7 @@ var ts; // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for (var i = index - 1; i >= 0; i--) { - if (list[i].kind === 26 /* CommaToken */) { + if (list[i].kind === 27 /* CommaToken */) { continue; } // skip list items that ends on the same line with the current list element @@ -103851,83 +107563,83 @@ var ts; function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 219 /* ExpressionStatement */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 185 /* ArrayLiteralExpression */: - case 216 /* Block */: - case 243 /* ModuleBlock */: - case 186 /* ObjectLiteralExpression */: - case 166 /* TypeLiteral */: - case 179 /* MappedType */: - case 168 /* TupleType */: - case 244 /* CaseBlock */: - case 270 /* DefaultClause */: - case 269 /* CaseClause */: - case 193 /* ParenthesizedExpression */: - case 187 /* PropertyAccessExpression */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 217 /* VariableStatement */: - case 252 /* ExportAssignment */: - case 228 /* ReturnStatement */: - case 203 /* ConditionalExpression */: - case 183 /* ArrayBindingPattern */: - case 182 /* ObjectBindingPattern */: - case 260 /* JsxOpeningElement */: - case 263 /* JsxOpeningFragment */: - case 259 /* JsxSelfClosingElement */: - case 268 /* JsxExpression */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 149 /* Parameter */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 175 /* ParenthesizedType */: - case 191 /* TaggedTemplateExpression */: - case 199 /* AwaitExpression */: - case 254 /* NamedExports */: - case 250 /* NamedImports */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 152 /* PropertyDeclaration */: + case 221 /* ExpressionStatement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 187 /* ArrayLiteralExpression */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 181 /* MappedType */: + case 170 /* TupleType */: + case 246 /* CaseBlock */: + case 272 /* DefaultClause */: + case 271 /* CaseClause */: + case 195 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 219 /* VariableStatement */: + case 254 /* ExportAssignment */: + case 230 /* ReturnStatement */: + case 205 /* ConditionalExpression */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + case 261 /* JsxSelfClosingElement */: + case 270 /* JsxExpression */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 151 /* Parameter */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 177 /* ParenthesizedType */: + case 193 /* TaggedTemplateExpression */: + case 201 /* AwaitExpression */: + case 256 /* NamedExports */: + case 252 /* NamedImports */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 154 /* PropertyDeclaration */: return true; - case 235 /* VariableDeclaration */: - case 273 /* PropertyAssignment */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 186 /* ObjectLiteralExpression */) { // TODO: GH#18217 + case 237 /* VariableDeclaration */: + case 275 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 188 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } return true; - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 220 /* IfStatement */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 195 /* ArrowFunction */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return childKind !== 216 /* Block */; - case 253 /* ExportDeclaration */: - return childKind !== 254 /* NamedExports */; - case 247 /* ImportDeclaration */: - return childKind !== 248 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 250 /* NamedImports */); - case 258 /* JsxElement */: - return childKind !== 261 /* JsxClosingElement */; - case 262 /* JsxFragment */: - return childKind !== 264 /* JsxClosingFragment */; - case 172 /* IntersectionType */: - case 171 /* UnionType */: - if (childKind === 166 /* TypeLiteral */) { + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return childKind !== 218 /* Block */; + case 255 /* ExportDeclaration */: + return childKind !== 256 /* NamedExports */; + case 249 /* ImportDeclaration */: + return childKind !== 250 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 252 /* NamedImports */); + case 260 /* JsxElement */: + return childKind !== 263 /* JsxClosingElement */; + case 264 /* JsxFragment */: + return childKind !== 266 /* JsxClosingFragment */; + case 174 /* IntersectionType */: + case 173 /* UnionType */: + if (childKind === 168 /* TypeLiteral */) { return false; } // falls through @@ -103938,11 +107650,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: - return parent.kind !== 216 /* Block */; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return parent.kind !== 218 /* Block */; default: return false; } @@ -104070,7 +107782,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 186 /* ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 188 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -104099,7 +107811,6 @@ var ts; }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); - return this; }; ChangeTracker.prototype.delete = function (sourceFile, node) { this.deletedNodes.push({ sourceFile: sourceFile, node: node }); @@ -104112,7 +107823,6 @@ var ts; var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - return this; }; ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { if (options === void 0) { options = {}; } @@ -104123,11 +107833,10 @@ var ts; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); - return this; }; ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } @@ -104136,31 +107845,33 @@ var ts; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); - return this; }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + }; + ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) { + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); - return next && next.kind === 26 /* CommaToken */ ? next : undefined; + return next && next.kind === 27 /* CommaToken */ ? next : undefined; }; ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); - return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); + this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -104175,7 +107886,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -104190,17 +107909,32 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) { + var fnStart = node.getStart(sourceFile); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsdoc = _a[_i]; + this.deleteRange(sourceFile, { + pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + }); + } + } + var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); + var indent = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { var endNode; if (ts.isFunctionLike(node)) { - endNode = ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile); + endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) return; // Function missing parentheses, give up @@ -104209,13 +107943,13 @@ var ts; } } else { - endNode = node.kind !== 235 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + endNode = node.kind !== 237 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter - var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); }; ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { @@ -104256,30 +107990,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +108043,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104314,18 +108055,18 @@ var ts; }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - case 235 /* VariableDeclaration */: - case 9 /* StringLiteral */: - case 71 /* Identifier */: + case 237 /* VariableDeclaration */: + case 10 /* StringLiteral */: + case 72 /* Identifier */: return { prefix: ", " }; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return { suffix: "," + this.newLineCharacter }; - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: return { prefix: " " }; - case 149 /* Parameter */: + case 151 /* Parameter */: return {}; default: ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it @@ -104334,28 +108075,28 @@ var ts; }; ChangeTracker.prototype.insertName = function (sourceFile, node, name) { ts.Debug.assert(!node.name); - if (node.kind === 195 /* ArrowFunction */) { - var arrow = ts.findChildOfKind(node, 36 /* EqualsGreaterThanToken */, sourceFile); - var lparen = ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile); + if (node.kind === 197 /* ArrowFunction */) { + var arrow = ts.findChildOfKind(node, 37 /* EqualsGreaterThanToken */, sourceFile); + var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); if (lparen) { // `() => {}` --> `function f() {}` - this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(89 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(90 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); deleteNode(this, sourceFile, arrow); } else { // `x => {}` -> `function f(x) {}` this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` - this.replaceRange(sourceFile, arrow, ts.createToken(20 /* CloseParenToken */)); + this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */)); } - if (node.body.kind !== 216 /* Block */) { + if (node.body.kind !== 218 /* Block */) { // `() => 0` => `function f() { return 0; }` - this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(17 /* OpenBraceToken */), ts.createToken(96 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); - this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(25 /* SemicolonToken */), ts.createToken(18 /* CloseBraceToken */)], { joiner: " " }); + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(97 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); + this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " }); } } else { - var pos = ts.findChildOfKind(node, node.kind === 194 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end; + var pos = ts.findChildOfKind(node, node.kind === 196 /* FunctionExpression */ ? 90 /* FunctionKeyword */ : 76 /* ClassKeyword */, sourceFile).end; this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } }; @@ -104371,11 +108112,11 @@ var ts; if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } if (!containingList) { ts.Debug.fail("node is not a list element"); - return this; + return; } var index = ts.indexOfNode(containingList, after); if (index < 0) { - return this; + return; } var end = after.getEnd(); if (index !== containingList.length - 1) { @@ -104427,7 +108168,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104443,12 +108184,12 @@ var ts; // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise // i.e. var x = 1 // this is x // | new element will be inserted at this position - separator = 26 /* CommaToken */; + separator = 27 /* CommaToken */; } else { // element has more than one element, pick separator from the list var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile); - separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 26 /* CommaToken */; + separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */; // determine if list is multiline by checking lines of after element and element that precedes it. var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile); multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition; @@ -104459,7 +108200,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +108208,28 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } - return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; - var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var _loop_17 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +108242,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_17(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +108281,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { - return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; + function getClassOrObjectBraceEnds(cls, sourceFile) { + return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +108299,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +108316,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes) + newLineCharacter; + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,9 +108365,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -104698,6 +108450,9 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeComment = function (s) { + this.writer.writeComment(s); + }; Writer.prototype.writeKeyword = function (s) { this.writer.writeKeyword(s); this.setLastNonTriviaPosition(s, /*force*/ false); @@ -104710,6 +108465,10 @@ var ts; this.writer.writePunctuation(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeTrailingSemicolon = function (s) { + this.writer.writeTrailingSemicolon(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; Writer.prototype.writeParameter = function (s) { this.writer.writeParameter(s); this.setLastNonTriviaPosition(s, /*force*/ false); @@ -104730,9 +108489,6 @@ var ts; this.writer.writeSymbol(s, sym); this.setLastNonTriviaPosition(s, /*force*/ false); }; - Writer.prototype.writeTextOfNode = function (text, node) { - this.writer.writeTextOfNode(text, node); - }; Writer.prototype.writeLine = function () { this.writer.writeLine(); }; @@ -104774,10 +108530,25 @@ var ts; }; return Writer; }()); - function getInsertionPositionAtSourceFileTop(_a) { - var text = _a.text; - var shebang = ts.getShebang(text); + function getInsertionPositionAtSourceFileTop(sourceFile) { + var lastPrologue; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + if (ts.isPrologueDirective(node)) { + lastPrologue = node; + } + else { + break; + } + } var position = 0; + var text = sourceFile.text; + if (lastPrologue) { + position = lastPrologue.end; + advancePastLineBreak(); + return position; + } + var shebang = ts.getShebang(text); if (shebang !== undefined) { position = shebang.length; advancePastLineBreak(); @@ -104793,8 +108564,8 @@ var ts; ranges = ranges.slice(1); } // As well as any triple slash references - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; + for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) { + var range = ranges_1[_b]; if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { position = range.end; advancePastLineBreak(); @@ -104816,45 +108587,40 @@ var ts; } } function isValidLocationToAddComment(sourceFile, position) { - return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position); } textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; function needSemicolonBetween(a, b) { - return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 147 /* ComputedPropertyName */ + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 149 /* ComputedPropertyName */ || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` } var deleteDeclaration; (function (deleteDeclaration_1) { function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { switch (node.kind) { - case 149 /* Parameter */: { + case 151 /* Parameter */: { var oldFunction = node.parent; - if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + if (ts.isArrowFunction(oldFunction) && + oldFunction.parameters.length === 1 && + !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the // case if the parameter is simply removed (e.g. in `x => 1`). - var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, - /*parameters*/ undefined, // TODO: GH#18217 - oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); - // Drop leading and trailing trivia of the new function because we're only going - // to replace the span (vs the full span) of the old function - the old leading - // and trailing trivia will remain. - ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction); + changes.replaceNodeWithText(sourceFile, node, "()"); } else { deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; } - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: deleteNode(changes, sourceFile, node, // For first import, leave header comment in place node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: var pattern = node.parent; - var preserveComma = pattern.kind === 183 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + var preserveComma = pattern.kind === 185 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); if (preserveComma) { deleteNode(changes, sourceFile, node); } @@ -104862,13 +108628,13 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { deleteImportBinding(changes, sourceFile, namedImports); @@ -104877,7 +108643,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; default: @@ -104888,7 +108654,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } else { - deleteNode(changes, sourceFile, node, node.kind === 25 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); } } } @@ -104902,7 +108668,7 @@ var ts; // import |d,| * as ns from './file' var start = importClause.name.getStart(sourceFile); var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { + if (nextToken && nextToken.kind === 27 /* CommaToken */) { // shift first non-whitespace position after comma to the start position of the node var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); changes.deleteRange(sourceFile, { pos: start, end: end }); @@ -104924,15 +108690,15 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(node, 247 /* ImportDeclaration */); + var importDecl = ts.getAncestor(node, 249 /* ImportDeclaration */); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { var parent = node.parent; - if (parent.kind === 272 /* CatchClause */) { + if (parent.kind === 274 /* CatchClause */) { // TODO: There's currently no unused diagnostic for this, could be a suggestion - changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 19 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 20 /* CloseParenToken */, sourceFile)); + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); return; } if (parent.declarations.length !== 1) { @@ -104941,14 +108707,14 @@ var ts; } var gp = parent.parent; switch (gp.kind) { - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: deleteNode(changes, sourceFile, parent); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: deleteNode(changes, sourceFile, gp); break; default: @@ -105093,6 +108859,32 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addConvertToUnknownForNonOverlappingTypes"; + var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var assertion = ts.Debug.assertDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); })); + var replacement = ts.isAsExpression(assertion) + ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(143 /* UnknownKeyword */)) + : ts.createTypeAssertion(ts.createKeywordTypeNode(143 /* UnknownKeyword */), assertion.expression); + changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -105160,9 +108952,9 @@ var ts; if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } - var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile); if (needParens) - changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(19 /* OpenParenToken */)); + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */)); for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { var param = _a[_i]; if (!param.type) { @@ -105172,7 +108964,7 @@ var ts; } } if (needParens) - changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(20 /* CloseParenToken */)); + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */)); if (!decl.type) { var returnType = ts.getJSDocReturnType(decl); if (returnType) @@ -105187,26 +108979,26 @@ var ts; } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 235 /* VariableDeclaration */ || - node.kind === 151 /* PropertySignature */ || - node.kind === 152 /* PropertyDeclaration */; + node.kind === 237 /* VariableDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 154 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 285 /* JSDocNonNullableType */: + case 287 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return transformJSDocFunctionType(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return transformJSDocTypeReference(node); default: var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 @@ -105228,9 +109020,9 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 288 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); - var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; + var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); } function transformJSDocTypeReference(node) { @@ -105268,8 +109060,8 @@ var ts; var index = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s", - /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []), + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "number" : "string", []), /*initializer*/ undefined); var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); ts.setEmitFlags(indexSignature, 1 /* SingleLine */); @@ -105279,6 +109071,784 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var token = ts.getTokenAtPosition(sourceFile, start); + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var markSeen = ts.nodeSeenTracker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + }); + }, + }); + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; + default: + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode) { + switch (errorCode) { + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 72 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 100 /* ThisKeyword */) { + return undefined; + } + var parent = token.parent; + errorCode = mapSuggestionDiagnostic(errorCode); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags + var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ ""); + addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + } + return parent; + } + return undefined; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + return symbol.valueDeclaration; + } + return undefined; + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + return param; + } + return undefined; + // Get Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: + case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + return containingFunction; + } + return undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + return undefined; + default: + return ts.Debug.fail(String(errorCode)); + } + } + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + } + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + return true; + case 196 /* FunctionExpression */: + var parent = declaration.parent; + return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) || !!declaration.name; + } + return false; + } + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return; + } + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } + } + } + } + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } + } + } + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) { + var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; + if (!parent) { + return; + } + var typeExpression = ts.createJSDocTypeExpression(typeNode); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } + } + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + var paramTags = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + // only infer parameters that have (1) no type and (2) an accessible inferred type + if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name)) + return; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + var name = ts.getSynthesizedClone(param.name); + ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), ""); + }); + addJSDocTags(changes, sourceFile, signature, paramTags); + } + function addJSDocTags(changes, sourceFile, parent, newTags) { + var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags))); + changes.insertJsdocCommentBefore(sourceFile, parent, tag); + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 299 /* JSDocParameterTag */: { + var oldParam = oldTag; + var newParam = newTag; + return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + : undefined; + } + case 300 /* JSDocReturnTag */: + return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); + } + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } + }); + return typeIsAccessible ? res : undefined; + } + function getReferences(token, program, cancellationToken) { + // Position shouldn't matter since token is not a SourceFile. + return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + }); + } + function inferTypeForVariableFromUsage(token, program, cancellationToken) { + var references = getReferences(token, program, cancellationToken); + var checker = program.getTypeChecker(); + var types = InferFromReference.inferTypesFromReferences(references, checker, cancellationToken); + return InferFromReference.unifyFromContext(types, checker); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + var searchToken; + switch (containingFunction.kind) { + case 157 /* Constructor */: + searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); + break; + case 196 /* FunctionExpression */: + var parent = containingFunction.parent; + searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + searchToken = containingFunction.name; + break; + } + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypesFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return inferFromContext(usageContext, checker); + } + InferFromReference.inferTypesFromReferences = inferTypesFromReferences; + function inferTypeForParametersFromReferences(references, declaration, program, cancellationToken) { + var checker = program.getTypeChecker(); + if (references.length === 0) { + return undefined; + } + if (!declaration.parameters) { + return undefined; + } + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []); + return declaration.parameters.map(function (parameter, parameterIndex) { + var types = []; + var isRest = ts.isRestParameter(parameter); + var isOptional = false; + for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { + var callContext = callContexts_1[_i]; + if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); + types.push(checker.getUndefinedType()); + } + else if (isRest) { + for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + } + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + if (ts.isIdentifier(parameter.name)) { + var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken); + types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); + } + var type = unifyFromContext(types, checker); + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; + }); + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 203 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 202 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 204 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 189 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 190 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + case 237 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + usageContext.isNumber = true; + break; + case 38 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + // case SyntaxKind.ExclamationToken: + // no inferences here; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 41 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + // ShiftOperator + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 49 /* AmpersandToken */: + case 50 /* BarToken */: + case 51 /* CaretToken */: + // CompoundAssignmentOperator + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 70 /* BarEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 39 /* MinusToken */: + // RelationalOperator + case 28 /* LessThanToken */: + case 31 /* LessThanEqualsToken */: + case 30 /* GreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 60 /* PlusEqualsToken */: + case 38 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 296 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 132 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 59 /* EqualsToken */: + case 33 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 93 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 55 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 237 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + case 94 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 191 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent.argumentExpression); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 296 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function removeLowPriorityInferences(inferences, priorities) { + var toRemove = []; + for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) { + var i = inferences_2[_i]; + for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) { + var _b = priorities_1[_a], high = _b.high, low = _b.low; + if (high(i)) { + ts.Debug.assert(!low(i)); + toRemove.push(low); + } + } + } + return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); }); + } + function unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + // 1. string or number individually override string | number + // 2. non-any, non-void overrides any or void + // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types + var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); + var priorities = [ + { + high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); }, + low: function (t) { return t === stringNumber; } + }, + { + high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); }, + low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); } + }, + { + high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); }, + low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); } + } + ]; + var good = removeLowPriorityInferences(inferences, priorities); + var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + if (anons.length) { + good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + good.push(unifyAnonymousTypes(anons, checker)); + } + return checker.getWidenedType(checker.getUnionType(good)); + } + InferFromReference.unifyFromContext = unifyFromContext; + function unifyAnonymousTypes(anons, checker) { + if (anons.length === 1) { + return anons[0]; + } + var calls = []; + var constructs = []; + var stringIndices = []; + var numberIndices = []; + var stringIndexReadonly = false; + var numberIndexReadonly = false; + var props = ts.createMultiMap(); + for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) { + var anon = anons_1[_i]; + for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { + var p = _b[_a]; + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); + constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } + } + var members = ts.mapEntries(props, function (name, types) { + var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; + var s = checker.createSymbol(4 /* Property */ | isOptional, name); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + function inferFromContext(usageContext, checker) { + var types = []; + if (usageContext.isNumber) { + types.push(checker.getNumberType()); + } + if (usageContext.isString) { + types.push(checker.getStringType()); + } + if (usageContext.isNumberOrString) { + types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); + } + types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 + var types_19 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + types_19.push(checker.createPromiseType(types_19.length ? checker.getUnionType(types_19, 2 /* Subtype */) : checker.getAnyType())); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker))); + } + if (usageContext.numberIndexContext) { + types.push(checker.createArrayType(recur(usageContext.numberIndexContext))); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { + var members_6 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = recur(context); + members_6.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); + } + types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 + } + return types; + function recur(innerContext) { + return unifyFromContext(inferFromContext(innerContext, checker), checker); + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = unifyFromContext(inferFromContext(callContext.returnType, checker), checker, checker.getVoidType()); + // TODO: GH#18217 + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return !!usageContext && !!usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -105303,12 +109873,12 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: precedingNode = ctorDeclaration; changes.delete(sourceFile, ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: precedingNode = ctorDeclaration.parent.parent; newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { @@ -105340,7 +109910,7 @@ var ts; // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); + var memberElement = createClassElement(member, [ts.createToken(116 /* StaticKeyword */)]); if (memberElement) { memberElements.push(memberElement); } @@ -105363,7 +109933,7 @@ var ts; return; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 219 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 221 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentBinaryExpression.right) { @@ -105371,27 +109941,27 @@ var ts; /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 194 /* FunctionExpression */: { + case 196 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); ts.copyComments(assignmentBinaryExpression, method, sourceFile); return method; } - case 195 /* ArrowFunction */: { + case 197 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 216 /* Block */) { + if (arrowFunctionBody.kind === 218 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] else { bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); } - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); ts.copyComments(assignmentBinaryExpression, method, sourceFile); @@ -105399,7 +109969,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105412,17 +109982,17 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 194 /* FunctionExpression */) { + if (!initializer || initializer.kind !== 196 /* FunctionExpression */) { return undefined; } - if (node.name.kind !== 71 /* Identifier */) { + if (node.name.kind !== 72 /* Identifier */) { return undefined; } var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */); + var modifiers = getModifierKindFromSource(precedingNode, 85 /* ExportKeyword */); var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place @@ -105433,7 +110003,7 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); } - var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */); + var modifiers = getModifierKindFromSource(node, 85 /* ExportKeyword */); var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place @@ -105452,59 +110022,73 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); - var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 121 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_19(statement); } } + function getReturnStatementsWithPromiseHandlers(body) { + var res = []; + ts.forEachReturnStatement(body, function (ret) { + if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + res.push(ret); + }); + return res; + } // Returns the identifiers that are never reassigned in the refactor function getConstIdentifiers(synthNamesMap) { var constIdentifiers = []; @@ -105549,7 +110133,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +110147,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +110161,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +110187,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +110210,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +110220,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,7 +110254,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105670,17 +110270,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +110297,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +110313,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,100 +110326,134 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 96 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 72 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; - if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } + if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; - var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); + var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105837,12 +110474,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +110481,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105912,10 +110541,10 @@ var ts; } var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); } @@ -105941,7 +110570,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -105961,29 +110590,29 @@ var ts; sourceFile.forEachChild(function recur(node) { if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { var parent = node.parent; - cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 59 /* EqualsToken */); } node.forEachChild(recur); }); } function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 219 /* ExpressionStatement */: { + case 221 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 189 /* CallExpression */: { + case 191 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var operatorToken = expression.operatorToken; - return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); + return operatorToken.kind === 59 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); } } } @@ -106023,8 +110652,8 @@ var ts; /** Converts `const name = require("moduleSpecifier").propertyName` */ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ @@ -106032,7 +110661,7 @@ var ts; makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } - case 71 /* Identifier */: + case 72 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; default: @@ -106058,7 +110687,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106075,16 +110704,16 @@ var ts; function tryChangeModuleExportsObject(object) { var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. - case 274 /* ShorthandPropertyAssignment */: - case 275 /* SpreadAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 277 /* SpreadAssignment */: return undefined; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); - case 154 /* MethodDeclaration */: - return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); + case 156 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(85 /* ExportKeyword */)], prop); default: ts.Debug.assertNever(prop); } @@ -106133,23 +110762,23 @@ var ts; var name = left.name.text; if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) { // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. - changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(84 /* ExportKeyword */), { suffix: " " }); + changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(85 /* ExportKeyword */), { suffix: " " }); if (!right.name) changes.insertName(sourceFile, right, name); - var semi = ts.findChildOfKind(parent, 25 /* SemicolonToken */, sourceFile); + var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile); if (semi) changes.delete(sourceFile, semi); } else { // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` - changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 23 /* DotToken */, sourceFile), [ts.createToken(84 /* ExportKeyword */), ts.createToken(76 /* ConstKeyword */)], { joiner: " ", suffix: " " }); + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(85 /* ExportKeyword */), ts.createToken(77 /* ConstKeyword */)], { joiner: " ", suffix: " " }); } } // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node. function convertExportsDotXEquals_replaceNode(name, exported) { - var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + var modifiers = [ts.createToken(85 /* ExportKeyword */)]; switch (exported.kind) { - case 194 /* FunctionExpression */: { + case 196 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -106157,10 +110786,10 @@ var ts; } } // falls through - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported); default: @@ -106178,7 +110807,7 @@ var ts; */ function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: { + case 184 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined @@ -106189,7 +110818,7 @@ var ts; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 183 /* ArrayBindingPattern */: { + case 185 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; @@ -106200,7 +110829,7 @@ var ts; makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } - case 71 /* Identifier */: + case 72 /* Identifier */: return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); default: return ts.Debug.assertNever(name); @@ -106272,11 +110901,11 @@ var ts; function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return parent.name !== node; - case 184 /* BindingElement */: + case 186 /* BindingElement */: return parent.propertyName !== node; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -106544,33 +111173,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106608,21 +111244,21 @@ var ts; function tryAddToExistingImport(existingImports) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind !== 247 /* ImportDeclaration */) + if (declaration.kind !== 249 /* ImportDeclaration */) return undefined; var importClause = declaration.importClause; if (!importClause) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; - return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */) + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 252 /* NamedImports */) ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } : undefined; }); } function getNamespaceImportName(declaration) { - if (declaration.kind === 247 /* ImportDeclaration */) { + if (declaration.kind === 249 /* ImportDeclaration */) { var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 249 /* NamespaceImport */ ? namedBindings.name : undefined; + return namedBindings && namedBindings.kind === 251 /* NamespaceImport */ ? namedBindings.name : undefined; } else { return declaration.name; @@ -106631,24 +111267,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) + return (i.kind === 249 /* ImportDeclaration */ || i.kind === 248 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return ts.sort(choicesForEachExportingModule, function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106656,9 +111292,9 @@ var ts; } function newImportInfoFromExistingSpecifier(_a) { var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 247 /* ImportDeclaration */ + var expression = declaration.kind === 249 /* ImportDeclaration */ ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 257 /* ExternalModuleReference */ + : declaration.moduleReference.kind === 259 /* ExternalModuleReference */ ? declaration.moduleReference.expression : undefined; return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; @@ -106690,7 +111326,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106738,17 +111374,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +111390,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +111413,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -106975,12 +111622,12 @@ var ts; var checker = context.program.getTypeChecker(); var suggestion; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71 /* Identifier */); + ts.Debug.assert(node.kind === 72 /* Identifier */); var containingType = checker.getTypeAtLocation(node.parent.expression); suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); } else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71 /* Identifier */); + ts.Debug.assert(node.kind === 72 /* Identifier */); var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { @@ -107009,10 +111656,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107035,6 +111682,9 @@ var ts; var errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code ]; var fixId = "addMissingMember"; codefix.registerCodeFix({ @@ -107051,7 +111701,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +111730,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_20 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +111757,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_20(info); } }); })); @@ -107151,7 +111801,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,14 +111811,14 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { - if (classDeclaration.kind === 207 /* ClassExpression */) { + if (classDeclaration.kind === 209 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -107194,13 +111844,17 @@ var ts; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 202 /* BinaryExpression */) { + if (token.parent.parent.kind === 204 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } - return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); + else { + var contextualType = checker.getContextualType(token.parent); + typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + } + return typeNode || ts.createKeywordTypeNode(120 /* AnyKeyword */); } function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); @@ -107209,7 +111863,7 @@ var ts; function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); var lastProp = getNodeToInsertPropertyAfter(classDeclaration); @@ -107233,7 +111887,7 @@ var ts; } function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. - var stringTypeNode = ts.createKeywordTypeNode(137 /* StringKeyword */); + var stringTypeNode = ts.createKeywordTypeNode(138 /* StringKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -107253,7 +111907,7 @@ var ts; } function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); - var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */); + var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); } @@ -107269,7 +111923,7 @@ var ts; */ var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { var type = checker.getTypeAtLocation(member); - return !!(type && type.flags & 68 /* StringLike */); + return !!(type && type.flags & 132 /* StringLike */); }); var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); @@ -107281,7 +111935,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +111947,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -107406,7 +112172,7 @@ var ts; } function getNodes(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - if (token.kind !== 99 /* ThisKeyword */) + if (token.kind !== 100 /* ThisKeyword */) return undefined; var constructor = ts.getContainingFunction(token); var superCall = findSuperCall(constructor.body); @@ -107445,7 +112211,7 @@ var ts; }); function getNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */); + ts.Debug.assert(token.kind === 124 /* ConstructorKeyword */); return token.parent; } function doChange(changes, sourceFile, ctr) { @@ -107483,17 +112249,17 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); var heritageClauses = ts.getContainingClass(token).heritageClauses; var extendsToken = heritageClauses[0].getFirstToken(); - return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + return extendsToken.kind === 86 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; } function doChanges(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); + changes.replaceNode(sourceFile, extendsToken, ts.createToken(109 /* ImplementsKeyword */)); // If there is already an implements clause, replace the implements keyword with a comma. if (heritageClauses.length === 2 && - heritageClauses[0].token === 85 /* ExtendsKeyword */ && - heritageClauses[1].token === 108 /* ImplementsKeyword */) { + heritageClauses[0].token === 86 /* ExtendsKeyword */ && + heritageClauses[1].token === 109 /* ImplementsKeyword */) { var implementsToken = heritageClauses[1].getFirstToken(); var implementsFullStart = implementsToken.getFullStart(); - changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(26 /* CommaToken */)); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */)); // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. // (Trailing because leading might be indentation, which is more sensitive.) var text = sourceFile.text; @@ -107577,7 +112343,7 @@ var ts; if (ts.isJSDocTemplateTag(token)) { return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; } - if (token.kind === 27 /* LessThanToken */) { + if (token.kind === 28 /* LessThanToken */) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; } @@ -107597,7 +112363,7 @@ var ts; return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; } var result = []; - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); @@ -107629,7 +112395,7 @@ var ts; tryPrefixDeclaration(changes, diag.code, sourceFile, token); break; case fixIdDelete: { - if (token.kind === 126 /* InferKeyword */) + if (token.kind === 127 /* InferKeyword */) break; // Can't delete var importDecl = tryGetFullImport(token); if (importDecl) { @@ -107638,7 +112404,7 @@ var ts; else if (ts.isJSDocTemplateTag(token)) { changes.delete(sourceFile, token); } - else if (token.kind === 27 /* LessThanToken */) { + else if (token.kind === 28 /* LessThanToken */) { deleteTypeParameters(changes, sourceFile, token); } else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && @@ -107648,7 +112414,7 @@ var ts; break; } case fixIdInfer: - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { changeInferToUnknown(changes, sourceFile, token); } break; @@ -107659,7 +112425,7 @@ var ts; }, }); function changeInferToUnknown(changes, sourceFile, token) { - changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(142 /* UnknownKeyword */)); + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(143 /* UnknownKeyword */)); } function createDeleteFix(changes, diag) { return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); @@ -107669,13 +112435,13 @@ var ts; } // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(token) { - return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; + return token.kind === 92 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; } function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { - if (token.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) + if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) return false; var decl = token.parent.parent; - if (decl.kind === 149 /* Parameter */) { + if (decl.kind === 151 /* Parameter */) { tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); } else { @@ -107686,7 +112452,7 @@ var ts; function tryDeleteFullVariableStatement(sourceFile, token, changes) { var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { - changes.delete(sourceFile, declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList); + changes.delete(sourceFile, declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList); return true; } return false; @@ -107695,7 +112461,7 @@ var ts; // Don't offer to prefix a property. if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) return; - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; } if (ts.isIdentifier(token) && canPrefix(token)) { @@ -107704,14 +112470,14 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 149 /* Parameter */: - case 148 /* TypeParameter */: + case 151 /* Parameter */: + case 150 /* TypeParameter */: return true; - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: return true; } } @@ -107725,9 +112491,9 @@ var ts; } function deleteAssignments(changes, sourceFile, token, checker) { ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { - if (ref.parent.kind === 187 /* PropertyAccessExpression */) + if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent; - if (ref.parent.kind === 202 /* BinaryExpression */ && ref.parent.parent.kind === 219 /* ExpressionStatement */) { + if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) { changes.delete(sourceFile, ref.parent.parent); } }); @@ -107743,33 +112509,41 @@ var ts; } function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { if (mayDeleteParameter(p, checker, isFixAll)) { - changes.delete(sourceFile, p); - deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + if (p.modifiers && p.modifiers.length > 0 + && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + p.modifiers.forEach(function (modifier) { + changes.deleteModifier(sourceFile, modifier); + }); + } + else { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + } } } function mayDeleteParameter(p, checker, isFixAll) { var parent = p.parent; switch (parent.kind) { - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // Don't remove a parameter if this overrides something. var symbol = checker.getSymbolAtLocation(parent.name); if (ts.isMemberSymbolInBaseType(symbol, checker)) return false; // falls through - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: return true; - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. var parameters = parent.parameters; var index = parameters.indexOf(p); ts.Debug.assert(index !== -1); return isFixAll - ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 71 /* Identifier */ && !p.symbol.isReferenced; }) + ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 72 /* Identifier */ && !p.symbol.isReferenced; }) : index === parameters.length - 1; } - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: // Setter must have a parameter return false; default: @@ -107809,7 +112583,7 @@ var ts; var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { switch (container.kind) { - case 220 /* IfStatement */: + case 222 /* IfStatement */: if (container.elseStatement) { if (ts.isBlock(statement.parent)) { break; @@ -107820,8 +112594,8 @@ var ts; return; } // falls through - case 222 /* WhileStatement */: - case 223 /* ForStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: changes.delete(sourceFile, container); return; } @@ -107870,7 +112644,7 @@ var ts; var statementPos = labeledStatement.statement.getStart(sourceFile); // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos - : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 57 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); changes.deleteRange(sourceFile, { pos: pos, end: end }); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -107894,10 +112668,10 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 284 /* JSDocNullableType */) { + if (typeNode.kind === 286 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - actions.push(fix(checker.getNullableType(type, 8192 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); + actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; function fix(type, fixId, fixAllDescription) { @@ -107914,7 +112688,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 284 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type; + var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -107931,22 +112705,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 210 /* AsExpression */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 237 /* FunctionDeclaration */: - case 156 /* GetAccessor */: - case 160 /* IndexSignature */: - case 179 /* MappedType */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 157 /* SetAccessor */: - case 240 /* TypeAliasDeclaration */: - case 192 /* TypeAssertionExpression */: - case 235 /* VariableDeclaration */: + case 212 /* AsExpression */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 239 /* FunctionDeclaration */: + case 158 /* GetAccessor */: + case 162 /* IndexSignature */: + case 181 /* MappedType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 194 /* TypeAssertionExpression */: + case 237 /* VariableDeclaration */: return true; default: return false; @@ -108000,15 +112774,15 @@ var ts; } var insertBefore; switch (containingFunction.kind) { - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 90 /* FunctionKeyword */, sourceFile); break; - case 195 /* ArrowFunction */: - insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + case 197 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: return; @@ -108022,11 +112796,11 @@ var ts; var insertBefore = _a.insertBefore, returnType = _a.returnType; if (returnType) { var entityName = ts.getEntityNameFromTypeNode(returnType); - if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") { + if (!entityName || entityName.kind !== 72 /* Identifier */ || entityName.text !== "Promise") { changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); } } - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore); + changes.insertModifierBefore(sourceFile, 121 /* AsyncKeyword */, insertBefore); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -108045,7 +112819,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108116,17 +112890,17 @@ var ts; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 151 /* PropertySignature */: - case 152 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 153 /* PropertySignature */: + case 154 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); out(ts.createProperty( - /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, + /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 153 /* MethodSignature */: - case 154 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 156 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -108144,8 +112918,8 @@ var ts; outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } - for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { - var signature = signatures_8[_i]; + for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) { + var signature = signatures_7[_i]; // Need to ensure nodes are fresh each time so they can have different positions. outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); } @@ -108166,43 +112940,40 @@ var ts; } } function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 154 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); if (!signatureDeclaration) { return undefined; } signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; signatureDeclaration.name = name; - signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; + signatureDeclaration.questionToken = optional ? ts.createToken(56 /* QuestionToken */) : undefined; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, - /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(39 /* AsteriskToken */) : undefined, methodName, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(40 /* AsteriskToken */) : undefined, methodName, /*questionToken*/ undefined, /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108213,8 +112984,8 @@ var ts; /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || "arg" + i, - /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, - /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(119 /* AnyKeyword */), + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(120 /* AnyKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -108228,8 +112999,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { - var sig = signatures_9[_i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var sig = signatures_8[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -108242,11 +113013,11 @@ var ts; var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { - var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); + var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(120 /* AnyKeyword */)); var restParameter = ts.createParameter( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", - /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, anyArrayType, + /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", + /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, anyArrayType, /*initializer*/ undefined); parameters.push(restParameter); } @@ -108257,7 +113028,7 @@ var ts; function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { return ts.createMethod( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); + /*asteriskToken*/ undefined, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); } function createStubbedMethodBody(preferences) { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), @@ -108266,10 +113037,10 @@ var ts; } function createVisibilityModifier(flags) { if (flags & 4 /* Public */) { - return ts.createToken(114 /* PublicKeyword */); + return ts.createToken(115 /* PublicKeyword */); } else if (flags & 16 /* Protected */) { - return ts.createToken(113 /* ProtectedKeyword */); + return ts.createToken(114 /* ProtectedKeyword */); } return undefined; } @@ -108277,561 +113048,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - var codefix; - (function (codefix) { - var fixId = "inferFromUsage"; - var errorCodes = [ - // Variable declarations - ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, - ]; - codefix.registerCodeFix({ - errorCodes: errorCodes, - getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } - var token = ts.getTokenAtPosition(sourceFile, start); - var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); - var name = declaration && ts.getNameOfDeclaration(declaration); - return !name || changes.length === 0 ? undefined - : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; - }, - fixIds: [fixId], - getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; - var markSeen = ts.nodeSeenTracker(); - return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); - }); - }, - }); - function getDiagnostic(errorCode, token) { - switch (errorCode) { - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return ts.Diagnostics.Infer_parameter_types_from_usage; - default: - return ts.Diagnostics.Infer_type_of_0_from_usage; - } - } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { - return undefined; - } - var parent = token.parent; - switch (errorCode) { - // Variable and Property declarations - case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: - case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); - return parent; - } - return undefined; - case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { - var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); - return symbol.valueDeclaration; - } - return undefined; - } - } - var containingFunction = ts.getContainingFunction(token); - if (containingFunction === undefined) { - return undefined; - } - switch (errorCode) { - // Parameter declarations - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); - return containingFunction; - } - // falls through - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (markSeen(containingFunction)) { - var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); - return param; - } - return undefined; - // Get Accessor declarations - case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: - case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); - return containingFunction; - } - return undefined; - // Set Accessor declarations - case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); - return containingFunction; - } - return undefined; - default: - return ts.Debug.fail(String(errorCode)); - } - } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { - if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); - } - } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - return true; - case 194 /* FunctionExpression */: - return !!declaration.name; - } - return false; - } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return; - } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; - } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); - } - }); - } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { - var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); - if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || - inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); - } - } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); - } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { - var typeIsAccessible = true; - var notAccessible = function () { typeIsAccessible = false; }; - var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { - trackSymbol: function (symbol, declaration, meaning) { - // TODO: GH#18217 - typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; - }, - reportInaccessibleThisError: notAccessible, - reportPrivateInBaseOfClassExpression: notAccessible, - reportInaccessibleUniqueSymbolError: notAccessible, - }); - return typeIsAccessible ? res : undefined; - } - function getReferences(token, program, cancellationToken) { - // Position shouldn't matter since token is not a SourceFile. - return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; - }); - } - function inferTypeForVariableFromUsage(token, program, cancellationToken) { - return InferFromReference.inferTypeFromReferences(getReferences(token, program, cancellationToken), program.getTypeChecker(), cancellationToken); - } - function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { - switch (containingFunction.kind) { - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - var isConstructor = containingFunction.kind === 155 /* Constructor */; - var searchToken = isConstructor ? - ts.findChildOfKind(containingFunction, 123 /* ConstructorKeyword */, sourceFile) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); - } - } - } - var InferFromReference; - (function (InferFromReference) { - function inferTypeFromReferences(references, checker, cancellationToken) { - var usageContext = {}; - for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { - var reference = references_1[_i]; - cancellationToken.throwIfCancellationRequested(); - inferTypeFromContext(reference, checker, usageContext); - } - return getTypeFromUsageContext(usageContext, checker); - } - InferFromReference.inferTypeFromReferences = inferTypeFromReferences; - function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { - if (references.length === 0) { - return undefined; - } - if (!declaration.parameters) { - return undefined; - } - var usageContext = {}; - for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { - var reference = references_2[_i]; - cancellationToken.throwIfCancellationRequested(); - inferTypeFromContext(reference, checker, usageContext); - } - var isConstructor = declaration.kind === 155 /* Constructor */; - var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; - return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { - var types = []; - var isRest = ts.isRestParameter(parameter); - for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { - var callContext = callContexts_1[_i]; - if (callContext.argumentTypes.length <= parameterIndex) { - continue; - } - if (isRest) { - for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); - } - } - else { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); - } - } - if (!types.length) { - return undefined; - } - var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; - }); - } - InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; - function inferTypeFromContext(node, checker, usageContext) { - while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { - node = node.parent; - } - switch (node.parent.kind) { - case 201 /* PostfixUnaryExpression */: - usageContext.isNumber = true; - break; - case 200 /* PrefixUnaryExpression */: - inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); - break; - case 202 /* BinaryExpression */: - inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); - break; - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); - break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: - if (node.parent.expression === node) { - inferTypeFromCallExpressionContext(node.parent, checker, usageContext); - } - else { - inferTypeFromContextualType(node, checker, usageContext); - } - break; - case 187 /* PropertyAccessExpression */: - inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); - break; - case 188 /* ElementAccessExpression */: - inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); - break; - case 235 /* VariableDeclaration */: { - var _a = node.parent, name = _a.name, initializer = _a.initializer; - if (node === name) { - if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. - addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); - } - break; - } - } - // falls through - default: - return inferTypeFromContextualType(node, checker, usageContext); - } - } - function inferTypeFromContextualType(node, checker, usageContext) { - if (ts.isExpressionNode(node)) { - addCandidateType(usageContext, checker.getContextualType(node)); - } - } - function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { - switch (node.operator) { - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - usageContext.isNumber = true; - break; - case 37 /* PlusToken */: - usageContext.isNumberOrString = true; - break; - // case SyntaxKind.ExclamationToken: - // no inferences here; - } - } - function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { - switch (parent.operatorToken.kind) { - // ExponentiationOperator - case 40 /* AsteriskAsteriskToken */: - // MultiplicativeOperator - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - // ShiftOperator - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - // BitwiseOperator - case 48 /* AmpersandToken */: - case 49 /* BarToken */: - case 50 /* CaretToken */: - // CompoundAssignmentOperator - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 69 /* BarEqualsToken */: - case 70 /* CaretEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - // AdditiveOperator - case 38 /* MinusToken */: - // RelationalOperator - case 27 /* LessThanToken */: - case 30 /* LessThanEqualsToken */: - case 29 /* GreaterThanToken */: - case 31 /* GreaterThanEqualsToken */: - var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (operandType.flags & 544 /* EnumLike */) { - addCandidateType(usageContext, operandType); - } - else { - usageContext.isNumber = true; - } - break; - case 59 /* PlusEqualsToken */: - case 37 /* PlusToken */: - var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (otherOperandType.flags & 544 /* EnumLike */) { - addCandidateType(usageContext, otherOperandType); - } - else if (otherOperandType.flags & 168 /* NumberLike */) { - usageContext.isNumber = true; - } - else if (otherOperandType.flags & 68 /* StringLike */) { - usageContext.isString = true; - } - else { - usageContext.isNumberOrString = true; - } - break; - // AssignmentOperators - case 58 /* EqualsToken */: - case 32 /* EqualsEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); - break; - case 92 /* InKeyword */: - if (node === parent.left) { - usageContext.isString = true; - } - break; - // LogicalOperator - case 54 /* BarBarToken */: - if (node === parent.left && - (node.parent.parent.kind === 235 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { - // var x = x || {}; - // TODO: use getFalsyflagsOfType - addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); - } - break; - case 53 /* AmpersandAmpersandToken */: - case 26 /* CommaToken */: - case 93 /* InstanceOfKeyword */: - // nothing to infer here - break; - } - } - function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { - addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); - } - function inferTypeFromCallExpressionContext(parent, checker, usageContext) { - var callContext = { - argumentTypes: [], - returnType: {} - }; - if (parent.arguments) { - for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); - } - } - inferTypeFromContext(parent, checker, callContext.returnType); - if (parent.kind === 189 /* CallExpression */) { - (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); - } - else { - (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); - } - } - function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { - var name = ts.escapeLeadingUnderscores(parent.name.text); - if (!usageContext.properties) { - usageContext.properties = ts.createUnderscoreEscapedMap(); - } - var propertyUsageContext = usageContext.properties.get(name) || {}; - inferTypeFromContext(parent, checker, propertyUsageContext); - usageContext.properties.set(name, propertyUsageContext); - } - function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { - if (node === parent.argumentExpression) { - usageContext.isNumberOrString = true; - return; - } - else { - var indexType = checker.getTypeAtLocation(parent.argumentExpression); - var indexUsageContext = {}; - inferTypeFromContext(parent, checker, indexUsageContext); - if (indexType.flags & 168 /* NumberLike */) { - usageContext.numberIndexContext = indexUsageContext; - } - else { - usageContext.stringIndexContext = indexUsageContext; - } - } - } - function getTypeFromUsageContext(usageContext, checker) { - if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { - return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); - } - else if (usageContext.isNumber) { - return checker.getNumberType(); - } - else if (usageContext.isString) { - return checker.getStringType(); - } - else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); - } - else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { - var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 - var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); - return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); - } - else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { - return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); - } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { - var members_6 = ts.createUnderscoreEscapedMap(); - var callSignatures = []; - var constructSignatures = []; - var stringIndexInfo = void 0; - var numberIndexInfo = void 0; - if (usageContext.properties) { - usageContext.properties.forEach(function (context, name) { - var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); - members_6.set(name, symbol); - }); - } - if (usageContext.callContexts) { - for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { - var callContext = _a[_i]; - callSignatures.push(getSignatureFromCallContext(callContext, checker)); - } - } - if (usageContext.constructContexts) { - for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { - var constructContext = _c[_b]; - constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); - } - } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } - if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 - } - else { - return undefined; - } - } - function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { - var types = []; - if (callContexts) { - for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { - var callContext = callContexts_2[_i]; - if (callContext.argumentTypes.length > parameterIndex) { - if (isRestParameter) { - types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); - } - else { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); - } - } - } - } - if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRestParameter ? checker.createArrayType(type) : type; - } - return undefined; - } - function getSignatureFromCallContext(callContext, checker) { - var parameters = []; - for (var i = 0; i < callContext.argumentTypes.length; i++) { - var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); - symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); - parameters.push(symbol); - } - var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); - // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - } - function addCandidateType(context, type) { - if (type && !(type.flags & 1 /* Any */) && !(type.flags & 32768 /* Never */)) { - (context.candidateTypes || (context.candidateTypes = [])).push(type); - } - } - function hasCallContext(usageContext) { - return !!usageContext && !!usageContext.callContexts; - } - })(InferFromReference || (InferFromReference = {})); - })(codefix = ts.codefix || (ts.codefix = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var codefix; (function (codefix) { @@ -108864,7 +113080,7 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 189 /* CallExpression */ : 190 /* NewExpression */; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 191 /* CallExpression */ : 192 /* NewExpression */; var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); if (!node) { return []; @@ -108975,7 +113191,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { - var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(52 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, propertyDeclaration) { @@ -108983,7 +113199,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { - var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + var undefinedTypeNode = ts.createKeywordTypeNode(141 /* UndefinedKeyword */); var type = propertyDeclaration.type; // TODO: GH#18217 var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); @@ -109004,8 +113220,8 @@ var ts; return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 } function getDefaultValueFromType(checker, type) { - if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + if (type.flags & 512 /* BooleanLiteral */) { + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109029,6 +113245,234 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, 0 /* ExportEquals */); + } + ts.generateTypesForModule = generateTypesForModule; + function generateTypesForGlobal(name, globalValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, 3 /* Global */); + } + ts.generateTypesForGlobal = generateTypesForGlobal; + function generateTypesForModuleOrGlobal(name, globalValue, formatSettings, outputKind) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, globalValue), formatSettings, outputKind); + } + /* @internal */ + function valueInfoToDeclarationFileText(valueInfo, formatSettings, outputKind) { + if (outputKind === void 0) { outputKind = 0 /* ExportEquals */; } + return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + OutputKind[OutputKind["Global"] = 3] = "Global"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(85 /* ExportKeyword */), ts.createModifier(80 /* DefaultKeyword */)] + : kind === 3 /* Global */ || kind === 0 /* ExportEquals */ ? [ts.createModifier(125 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(85 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members, hasNontrivialPrototype = info.hasNontrivialPrototype; + if (!hasNontrivialPrototype) { + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var protoOrInstanceMembers = ts.createMap(); + if (typeof fnAst === "object") + getConstructorFunctionInstanceProperties(fnAst, protoOrInstanceMembers); + for (var _i = 0, prototypeMembers_1 = prototypeMembers; _i < prototypeMembers_1.length; _i++) { + var p = prototypeMembers_1[_i]; + // ignore non-functions on the prototype + if (p.kind === 2 /* FunctionOrClass */) { + var m = tryGetMethod(p); + if (m) { + protoOrInstanceMembers.set(p.name, m); + } + } + } + var classStaticMembers = protoOrInstanceMembers.size !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(116 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(116 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + break; + default: + ts.Debug.assertNever(info); + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), ts.arrayFrom(protoOrInstanceMembers.values()))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + function toPropertyName(name) { + return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name); + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst, members) { + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { + var name_6 = node.left.name.text; + if (!ts.isJsPrivate(name_6)) { + ts.getOrUpdate(members, name_6, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_6, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + } + } + }); + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 200 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(106 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -109125,8 +113569,8 @@ var ts; }); function getImportTypeNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 91 /* ImportKeyword */); - ts.Debug.assert(token.parent.kind === 181 /* ImportType */); + ts.Debug.assert(token.kind === 92 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 183 /* ImportType */); return token.parent; } function doChange(changes, sourceFile, importType) { @@ -109178,7 +113622,7 @@ var ts; var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); var parameter = ts.first(indexSignature.parameters); var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); - var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(133 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ mappedIntersectionType ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); @@ -109198,7 +113642,7 @@ var ts; getAvailableActions: function (context) { var info = getInfo(context); if (!info) - return undefined; + return ts.emptyArray; var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; @@ -109225,16 +113669,16 @@ var ts; return undefined; } switch (exportNode.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: { var node = exportNode; return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { var vs = exportNode; // Must be `export const x = something;`. if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { @@ -109257,17 +113701,17 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 79 /* DefaultKeyword */))); + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 80 /* DefaultKeyword */))); } else { - var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* ExportKeyword */)); + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 85 /* ExportKeyword */)); switch (exportNode.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(79 /* DefaultKeyword */)); + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(80 /* DefaultKeyword */)); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { // We checked in `getInfo` that an initializer exists. @@ -109275,9 +113719,9 @@ var ts; break; } // falls through - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // `export type T = number;` -> `type T = number; export default T;` changes.deleteModifier(exportingSourceFile, exportKeyword); changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); @@ -109304,18 +113748,18 @@ var ts; function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { var parent = ref.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // `a.default` --> `a.foo` changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: { + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: { var spec = parent; // `default as foo` --> `foo`, `default as bar` --> `foo as bar` changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); break; } - case 248 /* ImportClause */: { + case 250 /* ImportClause */: { var clause = parent; ts.Debug.assert(clause.name === ref); var spec = makeImportSpecifier(exportName, ref.text); @@ -109324,7 +113768,7 @@ var ts; // `import foo from "./a";` --> `import { foo } from "./a";` changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); } - else if (namedBindings.kind === 249 /* NamespaceImport */) { + else if (namedBindings.kind === 251 /* NamespaceImport */) { // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; @@ -109345,36 +113789,33 @@ var ts; function changeNamedToDefaultImport(importingSourceFile, ref, changes) { var parent = ref.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // `a.foo` --> `a.default` changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: { - var spec = parent; - if (spec.kind === 251 /* ImportSpecifier */) { - // `import { foo } from "./a";` --> `import foo from "./a";` - // `import { foo as bar } from "./a";` --> `import bar from "./a";` - var defaultImport = ts.createIdentifier(spec.name.text); - if (spec.parent.elements.length === 1) { - changes.replaceNode(importingSourceFile, spec.parent, defaultImport); - } - else { - changes.delete(importingSourceFile, spec); - changes.insertNodeBefore(importingSourceFile, spec.parent, defaultImport); - } + case 253 /* ImportSpecifier */: { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(parent.name.text); + if (parent.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent.parent, defaultImport); } else { - // `export { foo } from "./a";` --> `export { default as foo } from "./a";` - // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` - // `export { foo as default } from "./a";` --> `export { default } from "./a";` - // (Because `export foo from "./a";` isn't valid syntax.) - changes.replaceNode(importingSourceFile, spec, makeExportSpecifier("default", spec.name.text)); + changes.delete(importingSourceFile, parent); + changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport); } break; } + case 257 /* ExportSpecifier */: { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text)); + break; + } default: - ts.Debug.failBadSyntaxKind(parent); + ts.Debug.assertNever(parent); } } function makeImportSpecifier(propertyName, name) { @@ -109397,9 +113838,9 @@ var ts; getAvailableActions: function (context) { var i = getImportToConvert(context); if (!i) - return undefined; - var description = i.kind === 249 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; - var actionName = i.kind === 249 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return ts.emptyArray; + var description = i.kind === 251 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 251 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; }, getEditsForAction: function (context, actionName) { @@ -109421,7 +113862,7 @@ var ts; } function doChange(sourceFile, program, changes, toConvert) { var checker = program.getTypeChecker(); - if (toConvert.kind === 249 /* NamespaceImport */) { + if (toConvert.kind === 251 /* NamespaceImport */) { doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { @@ -109481,7 +113922,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_21 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +113941,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_21(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -109529,12 +113970,12 @@ var ts; var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { - return undefined; + return ts.emptyArray; } var extractions = getPossibleExtractions(targetRange, context); if (extractions === undefined) { // No extractions possible - return undefined; + return ts.emptyArray; } var functionActions = []; var usedFunctionNames = ts.createMap(); @@ -109590,7 +114031,7 @@ var ts; actions: constantActions }); } - return infos.length ? infos : undefined; + return infos.length ? infos : ts.emptyArray; } extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ @@ -109764,20 +114205,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 152 /* PropertyDeclaration */) { + if (current.kind === 154 /* PropertyDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 149 /* Parameter */) { + else if (current.kind === 151 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 155 /* Constructor */) { + if (ctorOrMethod.kind === 157 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 154 /* MethodDeclaration */) { + else if (current.kind === 156 /* MethodDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -109820,7 +114261,7 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 235 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 237 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! @@ -109832,13 +114273,13 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 189 /* CallExpression */) { + if (node.parent.kind === 191 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { @@ -109853,8 +114294,8 @@ var ts; } if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); @@ -109866,20 +114307,20 @@ var ts; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 220 /* IfStatement */: + case 222 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 216 /* Block */: - if (node.parent && node.parent.kind === 233 /* TryStatement */ && node.parent.finallyBlock === node) { + case 218 /* Block */: + if (node.parent && node.parent.kind === 235 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 269 /* CaseClause */: + case 271 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -109891,11 +114332,11 @@ var ts; break; } switch (node.kind) { - case 176 /* ThisType */: - case 99 /* ThisKeyword */: + case 178 /* ThisType */: + case 100 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -109903,8 +114344,8 @@ var ts; seenLabels.pop(); break; } - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: { var label = node.label; if (label) { @@ -109914,20 +114355,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 227 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -109981,7 +114422,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 149 /* Parameter */) { + if (current.kind === 151 /* Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -109992,7 +114433,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 277 /* SourceFile */) { + if (current.kind === 279 /* SourceFile */) { return scopes; } } @@ -110082,32 +114523,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: return "constructor"; - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : "anonymous function"; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return "arrow function"; - case 154 /* MethodDeclaration */: - return "method '" + scope.name.getText(); - case 156 /* GetAccessor */: + case 156 /* MethodDeclaration */: + return "method '" + scope.name.getText() + "'"; + case 158 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: throw ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 238 /* ClassDeclaration */ + return scope.kind === 240 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 243 /* ModuleBlock */ + return scope.kind === 245 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -110126,7 +114567,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110173,20 +114614,20 @@ var ts; var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files - var modifiers = isJS ? [] : [ts.createToken(112 /* PrivateKeyword */)]; + var modifiers = isJS ? [] : [ts.createToken(113 /* PrivateKeyword */)]; if (range.facts & RangeFacts.InStaticRegion) { - modifiers.push(ts.createToken(115 /* StaticKeyword */)); + modifiers.push(ts.createToken(116 /* StaticKeyword */)); } if (range.facts & RangeFacts.IsAsyncFunction) { - modifiers.push(ts.createToken(120 /* AsyncKeyword */)); + modifiers.push(ts.createToken(121 /* AsyncKeyword */)); } newFunction = ts.createMethod( - /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { newFunction = ts.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(121 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; @@ -110203,7 +114644,7 @@ var ts; var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference callArguments); if (range.facts & RangeFacts.IsGenerator) { - call = ts.createYield(ts.createToken(39 /* AsteriskToken */), call); + call = ts.createYield(ts.createToken(40 /* AsteriskToken */), call); } if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); @@ -110327,9 +114768,9 @@ var ts; while (ts.isParenthesizedTypeNode(withoutParens)) { withoutParens = withoutParens.type; } - return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 140 /* UndefinedKeyword */; }) + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 141 /* UndefinedKeyword */; }) ? clone - : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(140 /* UndefinedKeyword */)]); + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(141 /* UndefinedKeyword */)]); } } /** @@ -110342,7 +114783,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110352,11 +114793,11 @@ var ts; if (ts.isClassLike(scope)) { ts.Debug.assert(!isJS); // See CannotExtractToJSClass var modifiers = []; - modifiers.push(ts.createToken(112 /* PrivateKeyword */)); + modifiers.push(ts.createToken(113 /* PrivateKeyword */)); if (rangeFacts & RangeFacts.InStaticRegion) { - modifiers.push(ts.createToken(115 /* StaticKeyword */)); + modifiers.push(ts.createToken(116 /* StaticKeyword */)); } - modifiers.push(ts.createToken(132 /* ReadonlyKeyword */)); + modifiers.push(ts.createToken(133 /* ReadonlyKeyword */)); var newVariable = ts.createProperty( /*decorators*/ undefined, modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); @@ -110385,7 +114826,7 @@ var ts; var localReference = ts.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 219 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 221 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.createVariableStatement( @@ -110404,7 +114845,7 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 219 /* ExpressionStatement */) { + if (node.parent.kind === 221 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. changeTracker.delete(context.file, node.parent); } @@ -110491,7 +114932,7 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 228 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + if (!ignoreReturns && node.kind === 230 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { @@ -110661,7 +115102,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { + else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -110669,14 +115110,14 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 237 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 239 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +115173,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_22 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +115213,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_22(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -110985,30 +115426,30 @@ var ts; function isExtractableExpression(node) { var parent = node.parent; switch (parent.kind) { - case 276 /* EnumMember */: + case 278 /* EnumMember */: return false; } switch (node.kind) { - case 9 /* StringLiteral */: - return parent.kind !== 247 /* ImportDeclaration */ && - parent.kind !== 251 /* ImportSpecifier */; - case 206 /* SpreadElement */: - case 182 /* ObjectBindingPattern */: - case 184 /* BindingElement */: + case 10 /* StringLiteral */: + return parent.kind !== 249 /* ImportDeclaration */ && + parent.kind !== 253 /* ImportSpecifier */; + case 208 /* SpreadElement */: + case 184 /* ObjectBindingPattern */: + case 186 /* BindingElement */: return false; - case 71 /* Identifier */: - return parent.kind !== 184 /* BindingElement */ && - parent.kind !== 251 /* ImportSpecifier */ && - parent.kind !== 255 /* ExportSpecifier */; + case 72 /* Identifier */: + return parent.kind !== 186 /* BindingElement */ && + parent.kind !== 253 /* ImportSpecifier */ && + parent.kind !== 257 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 216 /* Block */: - case 277 /* SourceFile */: - case 243 /* ModuleBlock */: - case 269 /* CaseClause */: + case 218 /* Block */: + case 279 /* SourceFile */: + case 245 /* ModuleBlock */: + case 271 /* CaseClause */: return true; default: return false; @@ -111029,7 +115470,7 @@ var ts; refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!getConvertibleFieldAtPosition(context)) - return undefined; + return ts.emptyArray; return [{ name: actionName, description: actionDescription, @@ -111046,7 +115487,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111057,10 +115498,10 @@ var ts; var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; var accessorModifiers = isInClassLike ? !modifierFlags || modifierFlags & 8 /* Private */ - ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) + ? getModifiers(isJS, isStatic, 115 /* PublicKeyword */) : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined; - var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined; + var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 113 /* PrivateKeyword */) : undefined; updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); ts.suppressLeadingAndTrailingTrivia(getAccessor); @@ -111069,7 +115510,7 @@ var ts; // readonly modifier only existed in classLikeDeclaration var constructor = ts.getFirstConstructorWithBody(container); if (constructor) { - updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); } } else { @@ -111098,7 +115539,7 @@ var ts; return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); } function getModifiers(isJS, isStatic, accessModifier) { - var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined); + var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(116 /* StaticKeyword */) : undefined); return modifiers && ts.createNodeArray(modifiers); } function startsWithUnderscore(name) { @@ -111121,8 +115562,8 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), - container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent, - originalName: declaration.name, + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name.text, declaration: declaration, fieldName: fieldName, accessorName: accessorName, @@ -111173,22 +115614,23 @@ var ts; ? changeTracker.insertNodeAfterComma(file, declaration, accessor) : changeTracker.insertNodeAfter(file, declaration, accessor); } - function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) { + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { if (!constructor.body) return; - var file = context.file, program = context.program, cancellationToken = context.cancellationToken; - var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; - }); - ts.forEach(referenceEntries, function (entry) { - var parent = entry.parent; - var accessorName = ts.createIdentifier(fieldName.text); - var node = ts.isBinaryExpression(parent) - ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken) - : ts.isPropertyAccessExpression(parent) - ? ts.updatePropertyAccess(parent, parent.expression, accessorName) - : ts.Debug.fail("Unexpected write access token"); - changeTracker.replaceNode(file, parent, node); + constructor.body.forEachChild(function recur(node) { + if (ts.isElementAccessExpression(node) && + node.expression.kind === 100 /* ThisKeyword */ && + ts.isStringLiteral(node.argumentExpression) && + node.argumentExpression.text === originalName && + ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName)); + } + if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName)); + } + if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(recur); + } }); } })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); @@ -111203,7 +115645,7 @@ var ts; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) - return undefined; + return ts.emptyArray; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; }, @@ -111265,11 +115707,11 @@ var ts; } function isPureImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return true; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return !ts.hasModifier(node, 1 /* Export */); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; @@ -111322,10 +115764,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_23 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_24 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,22 +115789,22 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_24(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_23(sourceFile); } } function getNamespaceLikeImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 249 /* NamespaceImport */ ? + case 249 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 251 /* NamespaceImport */ ? node.importClause.namedBindings.name : undefined; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node.name; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: return ts.Debug.assertNever(node); @@ -111393,20 +115835,20 @@ var ts; var newNamespaceId = ts.createIdentifier(newNamespaceName); var newModuleString = ts.createLiteral(newModuleSpecifier); switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); default: return ts.Debug.assertNever(node); } } function moduleSpecifierFromImport(i) { - return (i.kind === 247 /* ImportDeclaration */ ? i.moduleSpecifier - : i.kind === 246 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + return (i.kind === 249 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 248 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]); } function forEachImportInStatement(statement, cb) { @@ -111476,15 +115918,15 @@ var ts; } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { switch (importDecl.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); break; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: if (isUnused(importDecl.name)) { changes.delete(sourceFile, importDecl); } break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: @@ -111497,7 +115939,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 251 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -111509,7 +115951,7 @@ var ts; if (namedBindingsUnused) { changes.delete(sourceFile, namedBindings); } - else if (namedBindings.kind === 250 /* NamedImports */) { + else if (namedBindings.kind === 252 /* NamedImports */) { for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { var element = _b[_i]; if (isUnused(element.name)) @@ -111522,14 +115964,14 @@ var ts; function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { var name = varDecl.name; switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: if (isUnused(name)) { changes.delete(sourceFile, name); } break; - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: break; - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } @@ -111634,13 +116076,13 @@ var ts; // Below should all be utilities function isInImport(decl) { switch (decl.kind) { - case 246 /* ImportEqualsDeclaration */: - case 251 /* ImportSpecifier */: - case 248 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: return true; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return isVariableDeclarationInImport(decl); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); default: return false; @@ -111652,7 +116094,7 @@ var ts; } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 247 /* ImportDeclaration */: { + case 249 /* ImportDeclaration */: { var clause = i.importClause; if (!clause) return undefined; @@ -111662,9 +116104,9 @@ var ts; ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) : undefined; } - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return keep(i.name) ? i : undefined; - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { var name = filterBindingName(i.name, keep); return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } @@ -111673,7 +116115,7 @@ var ts; } } function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings.kind === 251 /* NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : undefined; } else { @@ -111683,11 +116125,11 @@ var ts; } function filterBindingName(name, keep) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return keep(name) ? name : undefined; - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return name; - case 182 /* ObjectBindingPattern */: { + case 184 /* ObjectBindingPattern */: { // We can't handle nested destructurings or property names well here, so just copy them all. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; @@ -111744,13 +116186,13 @@ var ts; } function isNonVariableTopLevelDeclaration(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return true; default: return false; @@ -111758,29 +116200,47 @@ var ts; } function forEachTopLevelDeclaration(statement, cb) { switch (statement.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return cb(statement); - case 217 /* VariableStatement */: - return ts.forEach(statement.declarationList.declarations, cb); - case 219 /* ExpressionStatement */: { + case 219 /* VariableStatement */: + return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); + case 221 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } } } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 72 /* Identifier */: + return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); + default: + return ts.Debug.assertNever(name); + } + } function nameOfTopLevelDeclaration(d) { - return d.kind === 219 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + return ts.isExpressionStatement(d) ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); } function getTopLevelDeclarationStatement(d) { - return ts.isVariableDeclaration(d) ? d.parent.parent : d; + switch (d.kind) { + case 237 /* VariableDeclaration */: + return d.parent.parent; + case 186 /* BindingElement */: + return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); + default: + return d; + } } function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { if (isExported(sourceFile, decl, useEs6Exports)) @@ -111807,25 +116267,25 @@ var ts; return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); } function addEs6Export(d) { - var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers); + var modifiers = ts.concatenate([ts.createModifier(85 /* ExportKeyword */)], d.modifiers); switch (d.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.updateVariableStatement(d, modifiers, d.declarationList); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(d); @@ -111836,18 +116296,18 @@ var ts; } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: return [decl.name.text]; // TODO: GH#18217 - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.emptyArray; - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(decl); @@ -111855,7 +116315,7 @@ var ts; } /** Creates `exports.x = x;` */ function createExportAssignment(name) { - return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name))); + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 59 /* EqualsToken */, ts.createIdentifier(name))); } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); @@ -111877,7 +116337,7 @@ var ts; var file = context.file, startPosition = context.startPosition; var info = getConvertibleArrowFunctionAtPosition(file, startPosition); if (!info) - return undefined; + return ts.emptyArray; return [{ name: refactorName, description: refactorDescription, @@ -111919,7 +116379,7 @@ var ts; return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); } function getConvertibleArrowFunctionAtPosition(file, startPosition) { var node = ts.getTokenAtPosition(file, startPosition); @@ -111955,7 +116415,7 @@ var ts; ts.servicesVersion = "0.8"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : - kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : + kind === 72 /* Identifier */ ? new IdentifierObject(72 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; node.flags = parent.flags & 12679168 /* ContextFlags */; @@ -112028,8 +116488,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 303 /* LastJSDocNode */; }); - return child.kind < 146 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; }); + return child.kind < 148 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -112040,7 +116500,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 146 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 148 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -112086,7 +116546,7 @@ var ts; var token = ts.scanner.scan(); var textPos = ts.scanner.getTextPos(); if (textPos <= end) { - if (token === 71 /* Identifier */) { + if (token === 72 /* Identifier */) { ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); } nodes.push(createNode(token, pos, textPos, parent)); @@ -112098,7 +116558,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(304 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -112230,7 +116690,7 @@ var ts; }); return IdentifierObject; }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 71 /* Identifier */; + IdentifierObject.prototype.kind = 72 /* Identifier */; var TypeObject = /** @class */ (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -112276,25 +116736,25 @@ var ts; return this.checker.getDefaultFromTypeParameter(this); }; TypeObject.prototype.isUnion = function () { - return !!(this.flags & 262144 /* Union */); + return !!(this.flags & 1048576 /* Union */); }; TypeObject.prototype.isIntersection = function () { - return !!(this.flags & 524288 /* Intersection */); + return !!(this.flags & 2097152 /* Intersection */); }; TypeObject.prototype.isUnionOrIntersection = function () { - return !!(this.flags & 786432 /* UnionOrIntersection */); + return !!(this.flags & 3145728 /* UnionOrIntersection */); }; TypeObject.prototype.isLiteral = function () { - return !!(this.flags & 192 /* StringOrNumberLiteral */); + return !!(this.flags & 384 /* StringOrNumberLiteral */); }; TypeObject.prototype.isStringLiteral = function () { - return !!(this.flags & 64 /* StringLiteral */); + return !!(this.flags & 128 /* StringLiteral */); }; TypeObject.prototype.isNumberLiteral = function () { - return !!(this.flags & 128 /* NumberLiteral */); + return !!(this.flags & 256 /* NumberLiteral */); }; TypeObject.prototype.isTypeParameter = function () { - return !!(this.flags & 65536 /* TypeParameter */); + return !!(this.flags & 262144 /* TypeParameter */); }; TypeObject.prototype.isClassOrInterface = function () { return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */); @@ -112344,8 +116804,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112431,10 +116891,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -112454,31 +116914,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 166 /* TypeLiteral */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 168 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 149 /* Parameter */: + case 151 /* Parameter */: // Only consider parameter properties if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // falls through - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: { + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -112489,19 +116949,19 @@ var ts; } } // falls through - case 276 /* EnumMember */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: addDeclaration(node); break; - case 253 /* ExportDeclaration */: + case 255 /* 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 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -112513,7 +116973,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -112522,8 +116982,8 @@ var ts; } } break; - case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112835,7 +117295,7 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; }); + var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -112865,8 +117325,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +117364,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112911,11 +117376,11 @@ var ts; compilerHost.trace = function (message) { return host.trace(message); }; } if (host.resolveModuleNames) { - compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }; + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }; } if (host.resolveTypeReferenceDirectives) { - compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile) { - return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile); + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile, redirectedReference); }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); @@ -112924,7 +117389,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -112949,7 +117414,7 @@ var ts; // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -113039,7 +117504,7 @@ var ts; // 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); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +117547,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113106,15 +117571,15 @@ var ts; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { - case 71 /* Identifier */: - return !ts.isLabelName(node); - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + return !ts.isLabelName(node) && !ts.isTagName(node); + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` return !ts.isInComment(sourceFile, position); - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 97 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 98 /* SuperKeyword */: return true; default: return false; @@ -113152,7 +117617,7 @@ var ts; var normalizedFileName = ts.normalizePath(fileName); ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); synchronizeHostData(); - var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); }); + var sourceFilesToSearch = filesToSearch.map(getValidSourceFile); var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } @@ -113160,29 +117625,27 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position); - if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { + if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113223,16 +117686,16 @@ var ts; return undefined; } switch (node.kind) { - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: - case 9 /* StringLiteral */: - case 86 /* FalseKeyword */: - case 101 /* TrueKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 71 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + case 10 /* StringLiteral */: + case 87 /* FalseKeyword */: + case 102 /* TrueKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 72 /* Identifier */: break; // Cant create the text span default: @@ -113248,7 +117711,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 === 242 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 244 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -113310,10 +117773,10 @@ var ts; return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken); } var braceMatching = ts.createMapFromTemplate((_a = {}, - _a[17 /* OpenBraceToken */] = 18 /* CloseBraceToken */, - _a[19 /* OpenParenToken */] = 20 /* CloseParenToken */, - _a[21 /* OpenBracketToken */] = 22 /* CloseBracketToken */, - _a[29 /* GreaterThanToken */] = 27 /* LessThanToken */, + _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */, + _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */, + _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */, + _a[30 /* GreaterThanToken */] = 28 /* LessThanToken */, _a)); braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); function getBraceMatchingAtPosition(fileName, position) { @@ -113389,19 +117852,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -113441,7 +117916,7 @@ var ts; var token = ts.findPrecedingToken(position, sourceFile); if (!token) return undefined; - var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent + var element = token.kind === 30 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent : ts.isJsxText(token) ? token.parent : undefined; if (element && isUnclosedTag(element)) { return { newText: "" }; @@ -113679,7 +118154,7 @@ var ts; function initializeNameTable(sourceFile) { var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); sourceFile.forEachChild(function walk(node) { - if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { + if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { var text = ts.getEscapedTextOfIdentifierOrLiteral(node); nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } @@ -113700,7 +118175,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 257 /* ExternalModuleReference */ || + node.parent.kind === 259 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -113715,15 +118190,15 @@ var ts; ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; function getContainingObjectLiteralElementWorker(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 147 /* ComputedPropertyName */) { + if (node.parent.kind === 149 /* ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 186 /* ObjectLiteralExpression */ || node.parent.parent.kind === 266 /* JsxAttributes */) && + (node.parent.parent.kind === 188 /* ObjectLiteralExpression */ || node.parent.parent.kind === 268 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -113765,7 +118240,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 188 /* ElementAccessExpression */ && + node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -113845,144 +118320,144 @@ var ts; if (node) { var parent = node.parent; switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 235 /* VariableDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return spanInVariableDeclaration(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return spanInParameterDeclaration(node); - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return spanInBlock(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return spanInBlock(node.block); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 221 /* DoStatement */: + case 223 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 234 /* DebuggerStatement */: + case 236 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 220 /* IfStatement */: + case 222 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return spanInForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 233 /* TryStatement */: + case 235 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 184 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 186 /* BindingElement */: // span on complete node return textSpan(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 150 /* Decorator */: + case 152 /* Decorator */: return spanInNodeArray(parent.decorators); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return undefined; // Tokens: - case 25 /* SemicolonToken */: + case 26 /* SemicolonToken */: case 1 /* EndOfFileToken */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return spanInPreviousNode(node); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return spanInOpenBraceToken(node); - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: return spanInCloseBraceToken(node); - case 22 /* CloseBracketToken */: + case 23 /* CloseBracketToken */: return spanInCloseBracketToken(node); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return spanInOpenParenToken(node); - case 20 /* CloseParenToken */: + case 21 /* CloseParenToken */: return spanInCloseParenToken(node); - case 56 /* ColonToken */: + case 57 /* ColonToken */: return spanInColonToken(node); - case 29 /* GreaterThanToken */: - case 27 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 28 /* LessThanToken */: return spanInGreaterThanOrLessThanToken(node); // Keywords: - case 106 /* WhileKeyword */: + case 107 /* WhileKeyword */: return spanInWhileKeyword(node); - case 82 /* ElseKeyword */: - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 83 /* ElseKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return spanInNextNode(node); - case 145 /* OfKeyword */: + case 147 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -113994,14 +118469,14 @@ var ts; // 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 === 71 /* Identifier */ || - node.kind === 206 /* SpreadElement */ || - node.kind === 273 /* PropertyAssignment */ || - node.kind === 274 /* ShorthandPropertyAssignment */) && + if ((node.kind === 72 /* Identifier */ || + node.kind === 208 /* SpreadElement */ || + node.kind === 275 /* PropertyAssignment */ || + node.kind === 276 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 202 /* BinaryExpression */) { + if (node.kind === 204 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -114010,35 +118485,35 @@ var ts; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); } - if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + if (operatorToken.kind === 59 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.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 (operatorToken.kind === 26 /* CommaToken */) { + if (operatorToken.kind === 27 /* CommaToken */) { return spanInNode(left); } } if (ts.isExpressionNode(node)) { switch (parent.kind) { - case 221 /* DoStatement */: + case 223 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 150 /* Decorator */: + case 152 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: return textSpan(node); - case 202 /* BinaryExpression */: - if (node.parent.operatorToken.kind === 26 /* CommaToken */) { + case 204 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 27 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -114047,21 +118522,21 @@ var ts; } } switch (node.parent.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -114069,7 +118544,7 @@ var ts; } break; } - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -114099,7 +118574,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 224 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 226 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } var parent = variableDeclaration.parent; @@ -114111,7 +118586,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - parent.parent.kind === 225 /* ForOfStatement */) { + parent.parent.kind === 227 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -114152,7 +118627,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 238 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */); + (functionDeclaration.parent.kind === 240 /* ClassDeclaration */ && functionDeclaration.kind !== 157 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -114175,26 +118650,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // falls through // Set on parent if on same line otherwise on first statement - case 222 /* WhileStatement */: - case 220 /* IfStatement */: - case 224 /* ForInStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 226 /* 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 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 227 /* 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(forLikeStatement) { - if (forLikeStatement.initializer.kind === 236 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 238 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -114219,21 +118694,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 184 /* BindingElement */) { + if (bindingPattern.parent.kind === 186 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 183 /* ArrayBindingPattern */ && node.kind !== 182 /* ObjectBindingPattern */); - var elements = node.kind === 185 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 185 /* ArrayBindingPattern */ && node.kind !== 184 /* ObjectBindingPattern */); + var elements = node.kind === 187 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -114241,18 +118716,18 @@ var ts; // 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 === 202 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 204 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -114260,25 +118735,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 241 /* EnumDeclaration */: - case 238 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 272 /* CatchClause */: + case 274 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -114286,7 +118761,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 182 /* ObjectBindingPattern */: + case 184 /* 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); @@ -114302,7 +118777,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 183 /* ArrayBindingPattern */: + case 185 /* 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); @@ -114317,12 +118792,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 221 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 189 /* CallExpression */ || - node.parent.kind === 190 /* NewExpression */) { + if (node.parent.kind === 223 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 191 /* CallExpression */ || + node.parent.kind === 192 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 193 /* ParenthesizedExpression */) { + if (node.parent.kind === 195 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -114331,21 +118806,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 193 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 195 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -114355,20 +118830,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 273 /* PropertyAssignment */ || - node.parent.kind === 149 /* Parameter */) { + node.parent.kind === 275 /* PropertyAssignment */ || + node.parent.kind === 151 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 192 /* TypeAssertionExpression */) { + if (node.parent.kind === 194 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 221 /* DoStatement */) { + if (node.parent.kind === 223 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -114376,7 +118851,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 225 /* ForOfStatement */) { + if (node.parent.kind === 227 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -114474,7 +118949,7 @@ var ts; var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; // TODO: GH#18217 + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -114484,7 +118959,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); }; } } @@ -114593,9 +119068,15 @@ var ts; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } + else { + this.directoryExists = undefined; // TODO: GH#18217 + } if ("realpath" in this.shimHost) { this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 } + else { + this.realpath = undefined; // TODO: GH#18217 + } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 @@ -115231,30 +119712,6 @@ var ts; } Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; })(Errors = server.Errors || (server.Errors = {})); - function getDefaultFormatCodeSettings(host) { - return { - indentSize: 4, - tabSize: 4, - newLineCharacter: host.newLine || "\n", - convertTabsToSpaces: true, - indentStyle: ts.IndentStyle.Smart, - insertSpaceAfterConstructor: false, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceBeforeFunctionParenthesis: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - }; - } - server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; function toNormalizedPath(fileName) { return ts.normalizePath(fileName); } @@ -115384,29 +119841,14 @@ var ts; } } server.removeSorted = removeSorted; - function toSortedArray(arr, comparer) { - arr.sort(comparer); - return arr; - } - server.toSortedArray = toSortedArray; - function toDeduplicatedSortedArray(arr) { - arr.sort(); - ts.filterMutate(arr, isNonDuplicateInSortedArray); - return arr; - } - server.toDeduplicatedSortedArray = toDeduplicatedSortedArray; - function isNonDuplicateInSortedArray(value, index, array) { - return index === 0 || value !== array[index - 1]; - } - /* @internal */ + var indentStr = "\n "; function indent(str) { - return "\n " + str; + return indentStr + str.replace(/\n/g, indentStr); } server.indent = indent; /** Put stringified JSON on the next line, indented. */ - /* @internal */ function stringifyIndented(json) { - return "\n " + JSON.stringify(json); + return indentStr + JSON.stringify(json); } server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); @@ -115545,6 +119987,7 @@ var ts; CommandTypes["GetEditsForFileRename"] = "getEditsForFileRename"; /* @internal */ CommandTypes["GetEditsForFileRenameFull"] = "getEditsForFileRename-full"; + CommandTypes["ConfigurePlugin"] = "configurePlugin"; // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {})); var IndentStyle; @@ -115604,6 +120047,18 @@ var ts; this.host = host; this.fileName = fileName; this.info = info; + /** + * True if the text is for the file thats open in the editor + */ + this.isOpen = false; + /** + * True if the text present is the text from the file on the disk + */ + this.ownFileText = false; + /** + * True when reloading contents of file from the disk is pending + */ + this.pendingReloadFromDisk = false; this.version = initialVersion || { svc: 0, text: 0 }; } TextStorage.prototype.getVersion = function () { @@ -115617,10 +120072,12 @@ var ts; TextStorage.prototype.useScriptVersionCache_TestOnly = function () { this.switchToScriptVersionCache(); }; + /** Public for testing */ TextStorage.prototype.useText = function (newText) { this.svc = undefined; this.text = newText; this.lineMap = undefined; + this.fileSize = undefined; this.version.text++; }; TextStorage.prototype.edit = function (start, end, newText) { @@ -115628,6 +120085,7 @@ var ts; this.ownFileText = false; this.text = undefined; this.lineMap = undefined; + this.fileSize = undefined; }; /** * Set the contents as newText @@ -115648,13 +120106,16 @@ var ts; this.ownFileText = false; return true; } + return false; }; /** * Reads the contents from tempFile(if supplied) or own file and sets it as contents * returns true if text changed */ TextStorage.prototype.reloadWithFileText = function (tempFileName) { - var reloaded = this.reload(this.getFileText(tempFileName)); + var _a = this.getFileTextAndSize(tempFileName), newText = _a.text, fileSize = _a.fileSize; + var reloaded = this.reload(newText); + this.fileSize = fileSize; // NB: after reload since reload clears it this.ownFileText = !tempFileName || tempFileName === this.fileName; return reloaded; }; @@ -115671,6 +120132,22 @@ var ts; TextStorage.prototype.delayReloadFromFileIntoText = function () { this.pendingReloadFromDisk = true; }; + /** + * For telemetry purposes, we would like to be able to report the size of the file. + * However, we do not want telemetry to require extra file I/O so we report a size + * that may be stale (e.g. may not reflect change made on disk since the last reload). + * NB: Will read from disk if the file contents have never been loaded because + * telemetry falsely indicating size 0 would be counter-productive. + */ + TextStorage.prototype.getTelemetryFileSize = function () { + return !!this.fileSize + ? this.fileSize + : !!this.text // Check text before svc because its length is cheaper + ? this.text.length // Could be wrong if this.pendingReloadFromDisk + : !!this.svc + ? this.svc.getSnapshot().getLength() // Could be wrong if this.pendingReloadFromDisk + : this.getSnapshot().getLength(); // Should be strictly correct + }; TextStorage.prototype.getSnapshot = function () { return this.useScriptVersionCacheIfValidOrOpen() ? this.svc.getSnapshot() @@ -115709,23 +120186,23 @@ var ts; } return this.svc.positionToLineOffset(position); }; - TextStorage.prototype.getFileText = function (tempFileName) { + TextStorage.prototype.getFileTextAndSize = function (tempFileName) { var _this = this; var text; var fileName = tempFileName || this.fileName; var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; // Only non typescript files have size limitation - if (!ts.hasTypeScriptFileExtension(this.fileName)) { + if (!ts.hasTSFileExtension(this.fileName)) { var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > server.maxFileSize) { ts.Debug.assert(!!this.info.containingProjects.length); var service = this.info.containingProjects[0].projectService; service.logger.info("Skipped loading contents of large file " + fileName + " for info " + this.info.fileName + ": fileSize: " + fileSize); this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize); - return ""; + return { text: "", fileSize: fileSize }; } } - return getText(); + return { text: getText() }; }; TextStorage.prototype.switchToScriptVersionCache = function () { if (!this.svc || this.pendingReloadFromDisk) { @@ -115791,6 +120268,10 @@ var ts; return this.textStorage.version; }; /*@internal*/ + ScriptInfo.prototype.getTelemetryFileSize = function () { + return this.textStorage.getTelemetryFileSize(); + }; + /*@internal*/ ScriptInfo.prototype.isDynamicOrHasMixedContent = function () { return this.hasMixedContent || this.isDynamic; }; @@ -115941,7 +120422,7 @@ var ts; ScriptInfo.prototype.setOptions = function (formatSettings, preferences) { if (formatSettings) { if (!this.formatSettings) { - this.formatSettings = server.getDefaultFormatCodeSettings(this.host); + this.formatSettings = ts.getDefaultFormatCodeSettings(this.host.newLine); ts.assign(this.formatSettings, formatSettings); } else { @@ -116030,6 +120511,7 @@ var ts; isKnownTypesPackageName: ts.returnFalse, // Should never be called because we never provide a types registry. installPackage: ts.notImplemented, + inspectValue: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -116091,6 +120573,9 @@ var ts; TypingsCache.prototype.installPackage = function (options) { return this.installer.installPackage(options); }; + TypingsCache.prototype.inspectValue = function (options) { + return this.installer.inspectValue(options); + }; TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -116116,7 +120601,7 @@ var ts; } }; TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typeAcquisition, unresolvedImports, newTypings) { - var typings = server.toSortedArray(newTypings); + var typings = ts.sort(newTypings); this.perProjectCache.set(projectName, { compilerOptions: compilerOptions, typeAcquisition: typeAcquisition, @@ -116146,27 +120631,45 @@ var ts; ProjectKind[ProjectKind["External"] = 2] = "External"; })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); /* @internal */ - function countEachFileTypes(infos) { - var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0, deferred: 0 }; + function countEachFileTypes(infos, includeSizes) { + if (includeSizes === void 0) { includeSizes = false; } + var result = { + js: 0, jsSize: 0, + jsx: 0, jsxSize: 0, + ts: 0, tsSize: 0, + tsx: 0, tsxSize: 0, + dts: 0, dtsSize: 0, + deferred: 0, deferredSize: 0, + }; for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { var info = infos_2[_i]; + var fileSize = includeSizes ? info.getTelemetryFileSize() : 0; switch (info.scriptKind) { case 1 /* JS */: result.js += 1; + result.jsSize += fileSize; break; case 2 /* JSX */: result.jsx += 1; + result.jsxSize += fileSize; break; case 3 /* TS */: - ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */) - ? result.dts += 1 - : result.ts += 1; + if (ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */)) { + result.dts += 1; + result.dtsSize += fileSize; + } + else { + result.ts += 1; + result.tsSize += fileSize; + } break; case 4 /* TSX */: result.tsx += 1; + result.tsxSize += fileSize; break; case 7 /* Deferred */: result.deferred += 1; + result.deferredSize += fileSize; break; } } @@ -116199,8 +120702,7 @@ var ts; server.isScriptInfo = isScriptInfo; var Project = /** @class */ (function () { /*@internal*/ - function Project( - /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { + function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { var _this = this; this.projectName = projectName; this.projectKind = projectKind; @@ -116236,6 +120738,7 @@ var ts; * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project */ this.projectStateVersion = 0; + this.isInitialLoadPending = ts.returnFalse; /*@internal*/ this.dirty = false; /*@internal*/ @@ -116301,6 +120804,10 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + /* @internal */ + Project.prototype.inspectValue = function (options) { + return this.typingsCache.inspectValue(options); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -116323,7 +120830,7 @@ var ts; return this.projectStateVersion.toString(); }; Project.prototype.getProjectReferences = function () { - return server.emptyArray; + return undefined; }; Project.prototype.getScriptFileNames = function () { var _this = this; @@ -116385,20 +120892,23 @@ var ts; Project.prototype.readFile = function (fileName) { return this.projectService.host.readFile(fileName); }; + Project.prototype.writeFile = function (fileName, content) { + return this.projectService.host.writeFile(fileName, content); + }; Project.prototype.fileExists = function (file) { // As an optimization, don't hit the disks for files we already know don't exist // (because we're watching for their creation). var path = this.toPath(file); return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); }; - Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { - return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); + Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }; Project.prototype.getResolvedModuleWithFailedLookupLocationsFromCache = function (moduleName, containingFile) { return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile); }; - Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); + Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile, redirectedReference) { + return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }; Project.prototype.directoryExists = function (path) { return this.directoryStructureHost.directoryExists(path); // TODO: GH#18217 @@ -116533,11 +121043,11 @@ var ts; }; Project.prototype.getExternalFiles = function () { var _this = this; - return server.toSortedArray(ts.flatMap(this.plugins, function (plugin) { - if (typeof plugin.getExternalFiles !== "function") + return ts.sort(ts.flatMap(this.plugins, function (plugin) { + if (typeof plugin.module.getExternalFiles !== "function") return; try { - return plugin.getExternalFiles(_this); + return plugin.module.getExternalFiles(_this); } catch (e) { _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); @@ -116568,21 +121078,17 @@ var ts; var f = _a[_i]; this.detachScriptInfoIfNotRoot(f.fileName); } - var projectReferences = this.program.getProjectReferences(); - if (projectReferences) { - for (var _b = 0, projectReferences_2 = projectReferences; _b < projectReferences_2.length; _b++) { - var ref = projectReferences_2[_b]; - if (ref) { - this.detachScriptInfoFromProject(ref.sourceFile.fileName); - } + this.program.forEachResolvedProjectReference(function (ref) { + if (ref) { + _this.detachScriptInfoFromProject(ref.sourceFile.fileName); } - } + }); } // Release external files ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); }); // Always remove root files from the project - for (var _c = 0, _d = this.rootFiles; _c < _d.length; _c++) { - var root = _d[_c]; + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; root.detachFromProject(this); } this.projectService.pendingEnsureProjectForOpenFiles = true; @@ -116639,7 +121145,7 @@ var ts; return this.rootFiles; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { - var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; }); return scriptInfo; }); @@ -116704,7 +121210,7 @@ var ts; return false; }; Project.prototype.containsScriptInfo = function (info) { - return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); + return this.isRoot(info) || (!!this.program && this.program.getSourceFileByPath(info.path) !== undefined); }; Project.prototype.containsFile = function (filename, requireOpen) { var info = this.projectService.getScriptInfoForNormalizedPath(filename); @@ -116757,38 +121263,6 @@ var ts; } }; /* @internal */ - Project.prototype.extractUnresolvedImportsFromSourceFile = function (file, ambientModules) { - var cached = this.cachedUnresolvedImportsPerFile.get(file.path); - if (cached) { - // found cached result, return - return cached; - } - var unresolvedImports; - if (file.resolvedModules) { - file.resolvedModules.forEach(function (resolvedModule, name) { - // pick unresolved non-relative names - if (!resolvedModule && !ts.isExternalModuleNameRelative(name) && !isAmbientlyDeclaredModule(name)) { - // for non-scoped names extract part up-to the first slash - // for scoped names - extract up to the second slash - var trimmed = name.trim(); - var i = trimmed.indexOf("/"); - if (i !== -1 && trimmed.charCodeAt(0) === 64 /* at */) { - i = trimmed.indexOf("/", i + 1); - } - if (i !== -1) { - trimmed = trimmed.substr(0, i); - } - (unresolvedImports || (unresolvedImports = [])).push(trimmed); - } - }); - } - this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || server.emptyArray); - return unresolvedImports || server.emptyArray; - function isAmbientlyDeclaredModule(name) { - return ambientModules.some(function (m) { return m === name; }); - } - }; - /* @internal */ Project.prototype.onFileAddedOrRemoved = function () { this.hasAddedorRemovedFiles = true; }; @@ -116797,7 +121271,6 @@ var ts; * @returns: true if set of files in the project stays the same and false - otherwise. */ Project.prototype.updateGraph = function () { - var _a; this.resolutionCache.startRecordingFilesWithChangedResolutions(); var hasNewProgram = this.updateGraphWorker(); var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; @@ -116818,16 +121291,7 @@ var ts; // (can reuse cached imports for files that were not changed) // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch if (hasNewProgram || changedFiles.length) { - var result = void 0; - var ambientModules = this.program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); - for (var _b = 0, _c = this.program.getSourceFiles(); _b < _c.length; _b++) { - var sourceFile = _c[_b]; - var unResolved = this.extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules); - if (unResolved !== server.emptyArray) { - (_a = (result || (result = []))).push.apply(_a, unResolved); - } - } - this.lastCachedUnresolvedImportsList = result ? server.toDeduplicatedSortedArray(result) : server.emptyArray; + this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile); } this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles); } @@ -116877,12 +121341,18 @@ var ts; if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var f = _a[_i]; - if (this.program.getSourceFileByPath(f.path)) { - continue; + var newFile = this.program.getSourceFileByPath(f.resolvedPath); + if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) { + // new program does not contain this file - detach it from the project + // - remove resolutions only if the new program doesnt contain source file by the path (not resolvedPath since path is used for resolution) + this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path)); } - // new program does not contain this file - detach it from the project - this.detachScriptInfoFromProject(f.fileName); } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !_this.program.getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + _this.detachScriptInfoFromProject(resolvedProjectReference.sourceFile.fileName); + } + }); } // Update the missing file paths watcher ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), @@ -116907,11 +121377,13 @@ var ts; this.writeLog("Finishing updateGraphWorker: Project: " + this.getProjectName() + " Version: " + this.getProjectVersion() + " structureChanged: " + hasNewProgram + " Elapsed: " + elapsed + "ms"); return hasNewProgram; }; - Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName) { + Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName, noRemoveResolution) { var scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); if (scriptInfoToDetach) { scriptInfoToDetach.detachFromProject(this); - this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); + if (!noRemoveResolution) { + this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); + } } }; Project.prototype.addMissingFileWatcher = function (missingFilePath) { @@ -116930,7 +121402,7 @@ var ts; return fileWatcher; }; Project.prototype.isWatchedMissingFile = function (path) { - return this.missingFilesMap && this.missingFilesMap.has(path); + return !!this.missingFilesMap && this.missingFilesMap.has(path); }; Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { var scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName)); @@ -116949,13 +121421,19 @@ var ts; var sourceFiles = this.program.getSourceFiles(); var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; if (writeProjectFileNames) { - for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { - var file = sourceFiles_9[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var file = sourceFiles_7[_i]; strBuilder += "\t" + file.fileName + "\n"; } } return strBuilder; }; + /*@internal*/ + Project.prototype.print = function (counter) { + this.writeLog("Project '" + this.projectName + "' (" + ProjectKind[this.projectKind] + ") " + (counter === undefined ? "" : counter)); + this.writeLog(this.filesToString(this.projectService.logger.hasLevel(server.LogLevel.verbose))); + this.writeLog("-----------------------------------------------"); + }; Project.prototype.setCompilerOptions = function (compilerOptions) { if (compilerOptions) { compilerOptions.allowNonTsExtensions = true; @@ -116973,7 +121451,10 @@ var ts; }; /* @internal */ Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - server.updateProjectIfDirty(this); + // Update the graph only if initial configured project load is not pending + if (!this.isInitialLoadPending()) { + server.updateProjectIfDirty(this); + } var info = { projectName: this.getProjectName(), version: this.projectProgramVersion, @@ -117026,9 +121507,8 @@ var ts; ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); }; - Project.prototype.enableGlobalPlugins = function () { + Project.prototype.enableGlobalPlugins = function (options, pluginConfigOverrides) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117037,7 +121517,7 @@ var ts; // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_26 = function (globalPluginName) { + var _loop_25 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -117046,17 +121526,17 @@ var ts; return "continue"; // Provide global: true so plugins can detect why they can't find their config this_2.projectService.logger.info("Loading global plugin " + globalPluginName); - this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); + this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides); }; var this_2 = this; // Enable global plugins with synthetic configuration entries for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_26(globalPluginName); + _loop_25(globalPluginName); } } }; - Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths) { + Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { var _this = this; this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); var log = function (message) { @@ -117066,16 +121546,19 @@ var ts; return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log); }); if (resolvedModule) { + var configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name); + if (configurationOverride) { + // Preserve the name property since it's immutable + var pluginName = pluginConfigEntry.name; + pluginConfigEntry = configurationOverride; + pluginConfigEntry.name = pluginName; + } this.enableProxy(resolvedModule, pluginConfigEntry); } else { this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); } }; - /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ - Project.prototype.refreshDiagnostics = function () { - this.projectService.sendProjectsUpdatedInBackgroundEvent(); - }; Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) { try { if (typeof pluginModuleFactory !== "function") { @@ -117100,15 +121583,49 @@ var ts; } this.projectService.logger.info("Plugin validation succeded"); this.languageService = newLS; - this.plugins.push(pluginModule); + this.plugins.push({ name: configEntry.name, module: pluginModule }); } catch (e) { this.projectService.logger.info("Plugin activation failed: " + e); } }; + /*@internal*/ + Project.prototype.onPluginConfigurationChanged = function (pluginName, configuration) { + this.plugins.filter(function (plugin) { return plugin.name === pluginName; }).forEach(function (plugin) { + if (plugin.module.onConfigurationChanged) { + plugin.module.onConfigurationChanged(configuration); + } + }); + }; + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ + Project.prototype.refreshDiagnostics = function () { + this.projectService.sendProjectsUpdatedInBackgroundEvent(); + }; return Project; }()); server.Project = Project; + function getUnresolvedImports(program, cachedUnresolvedImportsPerFile) { + var ambientModules = program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); + return ts.sortAndDeduplicate(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + return extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile); + })); + } + function extractUnresolvedImportsFromSourceFile(file, ambientModules, cachedUnresolvedImportsPerFile) { + return ts.getOrUpdate(cachedUnresolvedImportsPerFile, file.path, function () { + if (!file.resolvedModules) + return server.emptyArray; + var unresolvedImports; + file.resolvedModules.forEach(function (resolvedModule, name) { + // pick unresolved non-relative names + if ((!resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) && + !ts.isExternalModuleNameRelative(name) && + !ambientModules.some(function (m) { return m === name; })) { + unresolvedImports = ts.append(unresolvedImports, ts.parsePackageName(name).packageName); + } + }); + return unresolvedImports || server.emptyArray; + }); + } /** * If a file is opened and no tsconfig (or jsconfig) is found, * the file and its imports/references are put into an InferredProject. @@ -117116,7 +121633,7 @@ var ts; var InferredProject = /** @class */ (function (_super) { __extends(InferredProject, _super); /*@internal*/ - function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory) { + function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory, pluginConfigOverrides) { var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, // TODO: GH#18217 /*files*/ undefined, @@ -117127,7 +121644,7 @@ var ts; if (!projectRootPath && !projectService.useSingleInferredProject) { _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory); } - _this.enableGlobalPlugins(); + _this.enableGlobalPlugins(_this.getCompilerOptions(), pluginConfigOverrides); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -117138,10 +121655,10 @@ var ts; }; InferredProject.prototype.setCompilerOptions = function (options) { // Avoid manipulating the given options directly - var newOptions = options ? ts.cloneCompilerOptions(options) : this.getCompilationSettings(); - if (!newOptions) { + if (!options && !this.getCompilationSettings()) { return; } + var newOptions = ts.cloneCompilerOptions(options || this.getCompilationSettings()); if (this._isJsInferredProject && typeof newOptions.maxNodeModuleJsDepth !== "number") { newOptions.maxNodeModuleJsDepth = 2; } @@ -117210,14 +121727,20 @@ var ts; var ConfiguredProject = /** @class */ (function (_super) { __extends(ConfiguredProject, _super); /*@internal*/ - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { - var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; - _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectReferences = projectReferences; + function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, + /*hasExplicitListOfFiles*/ false, + /*lastFileExceededProgramSize*/ undefined, + /*compilerOptions*/ {}, + /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; + /*@internal*/ + _this.canConfigFileJsonReportNoInputFiles = false; /** Ref count to the project when opened from external project */ _this.externalProjectRefCount = 0; + _this.isInitialLoadPending = ts.returnTrue; + /*@internal*/ + _this.sendLoadingProjectFinish = false; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); - _this.enablePlugins(); return _this; } /** @@ -117225,17 +121748,27 @@ var ts; * @returns: true if set of files in the project stays the same and false - otherwise. */ ConfiguredProject.prototype.updateGraph = function () { + this.isInitialLoadPending = ts.returnFalse; var reloadLevel = this.pendingReload; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + var result; switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: - return this.projectService.reloadFileNamesOfConfiguredProject(this); + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; case ts.ConfigFileProgramReloadLevel.Full: - this.projectService.reloadConfiguredProject(this); - return true; + var reason = ts.Debug.assertDefined(this.pendingReloadReason); + this.pendingReloadReason = undefined; + this.projectService.reloadConfiguredProject(this, reason); + result = true; + break; default: - return _super.prototype.updateGraph.call(this); + result = _super.prototype.updateGraph.call(this); } + this.projectService.sendProjectLoadingFinishEvent(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; }; /*@internal*/ ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { @@ -117245,19 +121778,19 @@ var ts; return server.asNormalizedPath(this.getProjectName()); }; ConfiguredProject.prototype.getProjectReferences = function () { - return this.projectReferences || server.emptyArray; + return this.projectReferences; }; ConfiguredProject.prototype.updateReferences = function (refs) { this.projectReferences = refs; }; /*@internal*/ - ConfiguredProject.prototype.getResolvedProjectReferences = function () { + ConfiguredProject.prototype.forEachResolvedProjectReference = function (cb) { var program = this.getCurrentProgram(); - return program && program.getProjectReferences(); + return program && program.forEachResolvedProjectReference(cb); }; - ConfiguredProject.prototype.enablePlugins = function () { + /*@internal*/ + ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117274,10 +121807,10 @@ var ts; if (options.plugins) { for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { var pluginConfigEntry = _a[_i]; - this.enablePlugin(pluginConfigEntry, searchPaths); + this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); } } - this.enableGlobalPlugins(); + this.enableGlobalPlugins(options, pluginConfigOverrides); }; /** * Get the errors that dont have any file name associated @@ -117355,17 +121888,16 @@ var ts; // The project is referenced only if open files impacted by this project are present in this project return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; + /*@internal*/ + ConfiguredProject.prototype.hasExternalProjectRef = function () { + return !!this.externalProjectRefCount; + }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; }; /*@internal*/ - ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (hasFileNames) { - if (hasFileNames) { - ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); // TODO: GH#18217 - } - else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { // TODO: GH#18217 - this.projectErrors.push(ts.getErrorForNoInputFiles(this.configFileSpecs, this.getConfigFilePath())); - } + ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) { + ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); }; return ConfiguredProject; }(Project)); @@ -117385,6 +121917,12 @@ var ts; _this.excludedFiles = []; return _this; } + ExternalProject.prototype.updateGraph = function () { + var result = _super.prototype.updateGraph.call(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; @@ -117412,6 +121950,9 @@ var ts; server.maxFileSize = 4 * 1024 * 1024; // tslint:disable variable-name server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.ProjectLoadingStartEvent = "projectLoadingStart"; + server.ProjectLoadingFinishEvent = "projectLoadingFinish"; + server.SurveyReady = "surveyReady"; server.LargeFileReferencedEvent = "largeFileReferenced"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -117522,6 +122063,12 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; + /*@internal*/ + function convertUserPreferences(preferences) { + var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]); + return userPreferences; + } + server.convertUserPreferences = convertUserPreferences; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -117565,6 +122112,7 @@ var ts; WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; WatchType["TypeRoots"] = "Type root directory"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; })(WatchType = server.WatchType || (server.WatchType = {})); var ConfigFileWatcherStatus; (function (ConfigFileWatcherStatus) { @@ -117582,11 +122130,19 @@ var ts; function getDetailWatchInfo(watchType, project) { return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== undefined; + } /*@internal*/ function updateProjectIfDirty(project) { return project.dirty && project.updateGraph(); } server.updateProjectIfDirty = updateProjectIfDirty; + function setProjectOptionsUsed(project) { + if (project.projectKind === server.ProjectKind.Configured) { + project.projectOptions = true; + } + } var ProjectService = /** @class */ (function () { function ProjectService(opts) { var _this = this; @@ -117594,6 +122150,7 @@ var ts; * Container of all known scripts */ this.filenameToScriptInfo = ts.createMap(); + this.scriptInfoInNodeModulesWatchers = ts.createMap(); /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -117640,10 +122197,14 @@ var ts; */ this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist = ts.createMap(); this.pendingProjectUpdates = ts.createMap(); + /* @internal */ + this.pendingEnsureProjectForOpenFiles = false; /** Tracks projects that we have already sent telemetry for. */ this.seenProjects = ts.createMap(); + /** Tracks projects that we have already sent survey events for. */ + this.seenSurveyProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -117656,7 +122217,7 @@ var ts; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; this.syntaxOnly = opts.syntaxOnly; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); if (this.host.realpath) { @@ -117677,7 +122238,7 @@ var ts; this.typingsInstaller.attach(this); this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { - formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), + formatCodeOptions: ts.getDefaultFormatCodeSettings(this.host.newLine), preferences: ts.emptyOptions, hostInfo: "Unknown host", extraFileExtensions: [] @@ -117745,14 +122306,14 @@ var ts; this.safelist = raw.typesMap; for (var key in raw.simpleMap) { if (raw.simpleMap.hasOwnProperty(key)) { - this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); } } } catch (e) { this.logger.info("Error loading types map: " + e); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist.clear(); } }; ProjectService.prototype.updateTypingsForProject = function (response) { @@ -117819,6 +122380,13 @@ var ts; this.eventHandler(event); }; /* @internal */ + ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } }); + }; + /* @internal */ ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { if (!this.eventHandler) { return; @@ -117830,6 +122398,30 @@ var ts; this.eventHandler(event); }; /* @internal */ + ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + var event = { + eventName: server.ProjectLoadingStartEvent, + data: { project: project, reason: reason } + }; + this.eventHandler(event); + }; + /* @internal */ + ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + project.sendLoadingProjectFinish = false; + var event = { + eventName: server.ProjectLoadingFinishEvent, + data: { project: project } + }; + this.eventHandler(event); + }; + /* @internal */ ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) { this.delayUpdateProjectGraph(project); this.delayEnsureProjectForOpenFiles(); @@ -117888,9 +122480,9 @@ var ts; }; /* @internal */ ProjectService.prototype.forEachProject = function (cb) { - this.inferredProjects.forEach(cb); - this.configuredProjects.forEach(cb); this.externalProjects.forEach(cb); + this.configuredProjects.forEach(cb); + this.inferredProjects.forEach(cb); }; /* @internal */ ProjectService.prototype.forEachEnabledProject = function (cb) { @@ -117915,7 +122507,7 @@ var ts; ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileName) { this.ensureProjectStructuresUptoDate(); var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - return scriptInfo ? scriptInfo.getDefaultProject() : server.Errors.ThrowNoProject(); + return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(fileName), server.Errors.ThrowNoProject()); }; ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { this.ensureProjectStructuresUptoDate(); @@ -117960,15 +122552,20 @@ var ts; if (!info) { this.logger.msg("Error: got watch notification for unknown file: " + fileName); } - else if (eventKind === ts.FileWatcherEventKind.Deleted) { - // File was deleted - this.handleDeletedFile(info); - } - else if (!info.isScriptOpen()) { - // file has been changed which might affect the set of referenced files in projects that include - // this file and set of inferred projects - info.delayReloadNonMixedContentFile(); - this.delayUpdateProjectGraphs(info.containingProjects); + else { + if (info.containingProjects) { + info.containingProjects.forEach(function (project) { return project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path); }); + } + if (eventKind === ts.FileWatcherEventKind.Deleted) { + // File was deleted + this.handleDeletedFile(info); + } + else if (!info.isScriptOpen()) { + // file has been changed which might affect the set of referenced files in projects that include + // this file and set of inferred projects + info.delayReloadNonMixedContentFile(); + this.delayUpdateProjectGraphs(info.containingProjects); + } } }; ProjectService.prototype.handleDeletedFile = function (info) { @@ -117991,6 +122588,8 @@ var ts; return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) { var fileOrDirectoryPath = _this.toPath(fileOrDirectory); project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; var configFilename = project.getConfigFilePath(); // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list @@ -118027,6 +122626,7 @@ var ts; else { this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */); project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = "Change in config file detected"; this.delayUpdateProjectGraph(project); // As we scheduled the update on configured project graph, // we would need to schedule the project reload for only the root of inferred projects @@ -118050,10 +122650,12 @@ var ts; this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); }; ProjectService.prototype.removeProject = function (project) { - this.logger.info("remove project: " + project.getRootFiles().toString()); + var _this = this; + this.logger.info("`remove Project::"); + project.print(); project.close(); if (ts.Debug.shouldAssert(1 /* Normal */)) { - this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project)); }); + this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project), "Found script Info still attached to project", function () { return project.projectName + ": ScriptInfos still attached: " + JSON.stringify(ts.mapDefined(ts.arrayFrom(_this.filenameToScriptInfo.values()), function (info) { return info.isAttached(project) ? info : undefined; })); }); }); } // Remove the project from pending project updates this.pendingProjectUpdates.delete(project.getProjectName()); @@ -118086,7 +122688,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_27 = function (inferredProject) { + var _loop_26 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -118107,7 +122709,7 @@ var ts; // Note that we need to create a copy of the array since the list of project can change for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_27(inferredProject); + _loop_26(inferredProject); } } return project; @@ -118447,20 +123049,9 @@ var ts; } var writeProjectFileNames = this.logger.hasLevel(server.LogLevel.verbose); this.logger.startGroup(); - var counter = 0; - var printProjects = function (projects, counter) { - for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { - var project = projects_3[_i]; - _this.logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); - _this.logger.info(project.filesToString(writeProjectFileNames)); - _this.logger.info("-----------------------------------------------"); - counter++; - } - return counter; - }; - counter = printProjects(this.externalProjects, counter); - counter = printProjects(ts.arrayFrom(this.configuredProjects.values()), counter); - printProjects(this.inferredProjects, counter); + var counter = printProjectsWithCounter(this.externalProjects, 0); + counter = printProjectsWithCounter(ts.arrayFrom(this.configuredProjects.values()), counter); + printProjectsWithCounter(this.inferredProjects, counter); this.logger.info("Open files: "); this.openFiles.forEach(function (projectRootPath, path) { var info = _this.getScriptInfoForPath(path); @@ -118482,35 +123073,6 @@ var ts; ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { return findProjectByName(projectFileName, this.externalProjects); }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { - configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 - var result = ts.parseJsonText(configFilename, configFileContent); - if (!result.endOfFileToken) { - result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; - } - var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), - /*existingOptions*/ {}, configFilename, - /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); - if (parsedCommandLine.errors.length) { - errors.push.apply(errors, parsedCommandLine.errors); - } - ts.Debug.assert(!!parsedCommandLine.fileNames); - var projectOptions = { - files: parsedCommandLine.fileNames, - compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, - configHasFilesProperty: parsedCommandLine.raw.files !== undefined, - configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, - configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, - wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), - typeAcquisition: parsedCommandLine.typeAcquisition, - compileOnSave: parsedCommandLine.compileOnSave, - projectReferences: parsedCommandLine.projectReferences - }; - return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; - }; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { @@ -118523,12 +123085,12 @@ var ts; for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var f = fileNames_2[_i]; var fileName = propertyReader.getFileName(f); - if (ts.hasTypeScriptFileExtension(fileName)) { + if (ts.hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // Keep the size as zero since it's disabled return fileName; } @@ -118540,9 +123102,9 @@ var ts; return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); } function getTop5LargestFiles(_a) { - var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; + var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .filter(function (name) { return hasTypeScriptFileExtension(name); }) + .filter(function (name) { return hasTSFileExtension(name); }) .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217 .sort(function (a, b) { return b.size - a.size; }) .slice(0, 5); @@ -118553,22 +123115,38 @@ var ts; var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); project.excludedFiles = excludedFiles; - this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); - this.sendProjectTelemetry(projectFileName, project); return project; }; - ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { - if (this.seenProjects.has(projectKey)) { + /*@internal*/ + ProjectService.prototype.sendSurveyReady = function (project) { + if (this.seenSurveyProjects.has(project.projectName)) { return; } - this.seenProjects.set(projectKey, true); + if (project.getCompilerOptions().checkJs !== undefined) { + var name = "checkJs"; + this.logger.info("Survey " + name + " is ready"); + this.sendSurveyReadyEvent(name); + this.seenSurveyProjects.set(project.projectName, true); + } + }; + /*@internal*/ + ProjectService.prototype.sendProjectTelemetry = function (project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); + return; + } + this.seenProjects.set(project.projectName, true); if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); return; } + var projectOptions = project.projectKind === server.ProjectKind.Configured ? project.projectOptions : undefined; + setProjectOptionsUsed(project); var data = { - projectId: this.host.createSHA256Hash(projectKey), - fileStats: server.countEachFileTypes(project.getScriptInfos()), + projectId: this.host.createSHA256Hash(project.projectName), + fileStats: server.countEachFileTypes(project.getScriptInfos(), /*includeSizes*/ true), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), extends: projectOptions && projectOptions.configHasExtendsProperty, @@ -118586,8 +123164,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; // TODO: GH#18217 - return server.getBaseConfigFileName(configFilePath) || "other"; + return server.getBaseConfigFileName(project.getConfigFilePath()) || "other"; } function convertTypeAcquisition(_a) { var enable = _a.enable, include = _a.include, exclude = _a.exclude; @@ -118598,34 +123175,88 @@ var ts; }; } }; - ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { + ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) { this.updateNonInferredProjectFiles(project, files, propertyReader); project.setTypeAcquisition(typeAcquisition); - // This doesnt need scheduling since its either creation or reload of the project - project.updateGraph(); }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217 - var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, // TODO: GH#18217 - lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); - project.configFileSpecs = configFileSpecs; + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); // TODO: We probably should also watch the configFiles that are extended project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project); - if (!lastFileExceededProgramSize) { - project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 - } - project.setProjectErrors(configFileErrors); - var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); // TODO: GH#18217 this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); - this.sendProjectTelemetry(configFileName, project, projectOptions); return project; }; + /* @internal */ + ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; + return project; + }; + /* @internal */ + ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project, reason); + return project; + }; + /* @internal */ + ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) { + var project = this.createAndLoadConfiguredProject(configFileName, reason); + project.updateGraph(); + return project; + }; + /** + * Read the config file of the project, and update the project root file names. + */ + /* @internal */ + ProjectService.prototype.loadConfiguredProject = function (project, reason) { + this.sendProjectLoadingStartEvent(project, reason); + // Read updated contents from disk + var configFilename = ts.normalizePath(project.getConfigFilePath()); + var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; + } + var configFileErrors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), + /*existingOptions*/ {}, configFilename, + /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + var compilerOptions = parsedCommandLine.options; + // Update the project + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + }; + } + project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(parsedCommandLine.raw); + project.setProjectErrors(configFileErrors); + project.updateReferences(parsedCommandLine.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + project.stopWatchingWildCards(); + } + else { + project.enableLanguageService(); + project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); // TODO: GH#18217 + } + project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); + var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); // TODO: GH#18217 + }; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = ts.createMap(); @@ -118681,14 +123312,14 @@ var ts; // mark the project as dirty unconditionally project.markAsDirty(); }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { + ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently // therefore if it is undefined, it should not be updated. if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } - this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; /** * Reload the file names from config file specs and update the project graph @@ -118698,37 +123329,24 @@ var ts; var configFileSpecs = project.configFileSpecs; // TODO: GH#18217 var configFileName = project.getConfigFilePath(); var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); - project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); - this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); + project.updateErrorOnNoInputFiles(fileNamesResult); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); }; /** - * Read the config file of the project again and update the project + * Read the config file of the project again by clearing the cache and update the project graph */ /* @internal */ - ProjectService.prototype.reloadConfiguredProject = function (project) { + ProjectService.prototype.reloadConfiguredProject = function (project, reason) { // At this point, there is no reason to not have configFile in the host var host = project.getCachedDirectoryStructureHost(); // Clear the cache since we are reloading the project from disk host.clearCache(); var configFileName = project.getConfigFilePath(); this.logger.info("Reloading configured project " + configFileName); - // Read updated contents from disk - var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; - // Update the project - project.configFileSpecs = configFileSpecs; - project.setProjectErrors(configFileErrors); - project.updateReferences(projectOptions.projectReferences); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 - if (lastFileExceededProgramSize) { - project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - } - else { - project.enableLanguageService(); - project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 - } - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); // TODO: GH#18217 + // Load project from the disk + this.loadConfiguredProject(project, reason); + project.updateGraph(); this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { @@ -118809,8 +123427,8 @@ var ts; return this.createInferredProject(currentDirectory); }; ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) { - var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; - var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory); + var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; // TODO: GH#18217 + var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides); if (isSingleInferredProject) { this.inferredProjects.unshift(project); } @@ -118836,6 +123454,14 @@ var ts; var configProject = this.configuredProjects.get(uncheckedFileName); return configProject && configProject.getCompilerOptions().configFile; }; + /* @internal */ + ProjectService.prototype.logErrorForScriptInfoNotFound = function (fileName) { + var names = ts.arrayFrom(this.filenameToScriptInfo.entries()).map(function (_a) { + var path = _a[0], scriptInfo = _a[1]; + return ({ path: path, fileName: scriptInfo.fileName }); + }); + this.logger.msg("Could not find file " + JSON.stringify(fileName) + ".\nAll files are: " + JSON.stringify(names), server.Msg.Err); + }; /** * Returns the projects that contain script info through SymLink * Note that this does not return projects in info.containingProjects @@ -118853,7 +123479,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_28 = function (project) { + var _loop_27 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && @@ -118870,7 +123496,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_28(project); + _loop_27(project); } } } @@ -118883,10 +123509,82 @@ var ts; if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - var fileName = info.fileName; - info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); + var indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } } }; + ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) { + var _this = this; + // Watch only directory + var existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + var watchDir = dir + "/node_modules"; + var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; + // Has extension + ts.Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + _this.refreshScriptInfosInDirectory(watchDir); + } + else { + var info = _this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + _this.refreshScriptInfo(info); + } + } + // Folder + else if (!ts.hasExtension(fileOrDirectoryPath)) { + _this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, 1 /* Recursive */, "node_modules for closed script infos in them" /* NodeModulesForClosedScriptInfo */); + var result = { + close: function () { + if (result.refCount === 1) { + watcher.close(); + _this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + }; + ProjectService.prototype.getModifiedTime = function (info) { + return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime(); + }; + ProjectService.prototype.refreshScriptInfo = function (info) { + var mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + }; + ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) { + var _this = this; + dir = dir + ts.directorySeparator; + this.filenameToScriptInfo.forEach(function (info) { + if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) { + _this.refreshScriptInfo(info); + } + }); + }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { if (info.fileWatcher) { info.fileWatcher.close(); @@ -118894,7 +123592,18 @@ var ts; } }; ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { - return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + if (ts.isRootedDiskPath(fileName) || server.isDynamicFileName(fileName)) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + } + // This is non rooted path with different current directory than project service current directory + // Only paths recognized are open relative file paths + var info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)); + if (info) { + return info; + } + // This means triple slash references wont be resolved in dynamic and unsaved files + // which is intentional since we dont know what it means to be relative to non disk files + return undefined; }; ProjectService.prototype.getOrCreateScriptInfoOpenedByClientForNormalizedPath = function (fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) { return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ true, fileContent, scriptKind, hasMixedContent); @@ -118909,7 +123618,7 @@ var ts; var info = this.getScriptInfoForPath(path); if (!info) { var isDynamic = server.isDynamicFileName(fileName); - ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info"; }); + ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory"; }); ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); // If the file is not opened by client and the file doesnot exist on the disk, return @@ -118922,7 +123631,7 @@ var ts; if (!openedByClient) { this.watchClosedScriptInfo(info); } - else if (!ts.isRootedDiskPath(fileName) && currentDirectory !== this.currentDirectory) { + else if (!ts.isRootedDiskPath(fileName) && !isDynamic) { // File that is opened by user but isn't rooted disk path this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); } @@ -118952,6 +123661,7 @@ var ts; return this.filenameToScriptInfo.get(fileName); }; ProjectService.prototype.setHostConfiguration = function (args) { + var _this = this; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { @@ -118969,7 +123679,18 @@ var ts; this.logger.info("Format host information updated"); } if (args.preferences) { + var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject; this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences); + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + // Load configured projects for external projects that are pending reload + this.configuredProjects.forEach(function (project) { + if (project.hasExternalProjectRef() && + project.pendingReload === ts.ConfigFileProgramReloadLevel.Full && + !_this.pendingProjectUpdates.has(project.getProjectName())) { + project.updateGraph(); + } + }); + } } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; @@ -118994,7 +123715,7 @@ var ts; // (and would separate out below reloading of projects to be called when immediate reload is needed) // as there is no need to load contents of the files from the disk // Reload Projects - this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue); + this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue, "User requested reload projects"); this.ensureProjectForOpenFiles(); }; ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { @@ -119002,8 +123723,8 @@ var ts; this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, /*delayReload*/ true, ignoreIfNotRootOfInferredProject ? function (isRootOfInferredProject) { return isRootOfInferredProject; } : // Reload open files if they are root of inferred project - ts.returnTrue // Reload all the open files impacted by config file - ); + ts.returnTrue, // Reload all the open files impacted by config file + "Change in config file detected"); this.delayEnsureProjectForOpenFiles(); }; /** @@ -119013,7 +123734,7 @@ var ts; * If the there is no existing project it just opens the configured project for the config file * reloadForInfo provides a way to filter out files to reload configured project for */ - ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor) { + ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) { var _this = this; var updatedProjects = ts.createMap(); // try to reload config file for all open files @@ -119030,18 +123751,16 @@ var ts; // otherwise we create a new one. var configFileName = _this.getConfigFileNameForFile(info); if (configFileName) { - var project = _this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - _this.createConfiguredProject(configFileName); - updatedProjects.set(configFileName, true); - } - else if (!updatedProjects.has(configFileName)) { + var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName); + if (!updatedProjects.has(configFileName)) { if (delayReload) { project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; _this.delayUpdateProjectGraph(project); } else { - _this.reloadConfiguredProject(project); + // reload from the disk + _this.reloadConfiguredProject(project, reason); } updatedProjects.set(configFileName, true); } @@ -119111,7 +123830,7 @@ var ts; }; /*@internal*/ ProjectService.prototype.getOriginalLocationEnsuringConfiguredProject = function (project, location) { - var originalLocation = project.getSourceMapper().tryGetOriginalLocation(location); + var originalLocation = project.getSourceMapper().tryGetSourcePosition(location); if (!originalLocation) return undefined; var fileName = originalLocation.fileName; @@ -119121,7 +123840,8 @@ var ts; var configFileName = this.getConfigFileNameForFile(originalFileInfo); if (!configFileName) return undefined; - var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || + this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName); updateProjectIfDirty(configuredProject); // Keep this configured project as referenced from project addOriginalConfiguredProject(configuredProject); @@ -119165,7 +123885,7 @@ var ts; if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createConfiguredProject(configFileName); + project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open"); // Send the event only if the project got created as part of this open request and info is part of the project if (info.isOrphan()) { // Since the file isnt part of configured project, do not send config file info @@ -119235,18 +123955,14 @@ var ts; } else { // If the configured project for project reference has more than zero references, keep it alive - var resolvedProjectReferences = project.getResolvedProjectReferences(); - if (resolvedProjectReferences) { - for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { - var ref = resolvedProjectReferences_1[_i]; - if (ref) { - var refProject = _this.configuredProjects.get(ref.sourceFile.path); - if (refProject && refProject.hasOpenRef()) { - toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); - } + project.forEachResolvedProjectReference(function (ref) { + if (ref) { + var refProject = _this.configuredProjects.get(ref.sourceFile.path); + if (refProject && refProject.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); } } - } + }); } }); // Remove all the non marked projects @@ -119276,13 +123992,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_29 = function (proj) { + var _loop_28 = function (proj) { var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_29(proj); + _loop_28(proj); } }; /* @internal */ @@ -119362,8 +124078,8 @@ var ts; ts.forEachKey(this.externalProjectToConfiguredProjectMap, function (externalProjectName) { projectsToClose.set(externalProjectName, true); }); - for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { - var externalProject = projects_4[_i]; + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var externalProject = projects_3[_i]; this.openExternalProject(externalProject); // delete project that is present in input list projectsToClose.delete(externalProject.projectFileName); @@ -119392,7 +124108,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_30 = function (name) { + var _loop_29 = function (name) { var rule = this_3.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -119410,7 +124126,7 @@ var ts; } } if (rule.exclude) { - var _loop_32 = function (exclude) { + var _loop_31 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -119437,7 +124153,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_32(exclude); + _loop_31(exclude); } } else { @@ -119453,11 +124169,11 @@ var ts; var this_3 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_30(name); + _loop_29(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_31 = function (i) { + var _loop_30 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -119468,13 +124184,13 @@ var ts; if (ts.fileExtensionIs(baseName, "js")) { var inferredTypingName = ts.removeFileExtension(baseName); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - if (this_4.legacySafelist[cleanedTypingName]) { + var typeName = this_4.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { this_4.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); excludedFiles.push(normalizedNames[i]); // *exclude* it from the project... exclude = true; // ... but *include* it in the list of types to acquire - var typeName = this_4.legacySafelist[cleanedTypingName]; // Same best-effort dedupe as above if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); @@ -119495,7 +124211,7 @@ var ts; }; var this_4 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_31(i); + _loop_30(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -119546,7 +124262,9 @@ var ts; externalProject.enableLanguageService(); } // external project already exists and not config files were added - update the project and return; - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + // The graph update here isnt postponed since any file open operation needs all updated external projects + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + externalProject.updateGraph(); return; } // some config files were added to external project (that previously were not there) @@ -119594,8 +124312,10 @@ var ts; var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { - // errors are stored in the project - project = this.createConfiguredProject(tsconfigFile); + // errors are stored in the project, do not need to update the graph + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? + this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project @@ -119605,8 +124325,11 @@ var ts; } else { // no config files - remove the item from the collection + // Create external project and update its graph, do not delay update since + // any file open operation needs all updated external projects this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); } }; ProjectService.prototype.hasDeferredExtension = function () { @@ -119618,6 +124341,14 @@ var ts; } return false; }; + ProjectService.prototype.configurePlugin = function (args) { + // For any projects that already have the plugin loaded, configure the plugin + this.forEachEnabledProject(function (project) { return project.onPluginConfigurationChanged(args.pluginName, args.configuration); }); + // Also save the current configuration to pass on to any projects that are yet to be loaded. + // If a plugin is configured twice, only the latest configuration will be remembered. + this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || ts.createMap(); + this.currentPluginConfigOverrides.set(args.pluginName, args.configuration); + }; /** Makes a filename safe to insert in a RegExp */ ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; return ProjectService; @@ -119628,6 +124359,14 @@ var ts; return config.kind !== undefined; } server.isConfigFile = isConfigFile; + function printProjectsWithCounter(projects, counter) { + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var project = projects_4[_i]; + project.print(counter); + counter++; + } + return counter; + } })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -119822,17 +124561,15 @@ var ts; /** * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. */ - function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { - var outputs = ts.flatMap(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); + function combineProjectOutput(defaultValue, getValue, projects, action) { + var outputs = ts.flatMapToMutable(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); if (!ts.isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach(function (projects, path) { var value = getValue(path); outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); }); } - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); + return ts.deduplicate(outputs, ts.equateValues); } function combineProjectOutputFromEveryProject(projectService, action, areEqual) { var outputs = []; @@ -119842,10 +124579,10 @@ var ts; }); return outputs; } - function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, projectService, action, getLocation, resultsEqual) { + function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, action, getLocation, resultsEqual) { var outputs = []; combineProjectOutputWorker(projects, defaultProject, - /*initialLocation*/ undefined, projectService, function (_a, tryAddToTodo) { + /*initialLocation*/ undefined, function (_a, tryAddToTodo) { var project = _a.project; for (var _i = 0, _b = action(project); _i < _b.length; _i++) { var output = _b[_i]; @@ -119857,11 +124594,11 @@ var ts; /*getDefinition*/ undefined); return outputs; } - function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, projectService, findInStrings, findInComments) { + function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, tryAddToTodo) { var project = _a.project, location = _a.location; - for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.position, findInStrings, findInComments) || server.emptyArray; _i < _b.length; _i++) { + for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments) || server.emptyArray; _i < _b.length; _i++) { var output = _b[_i]; if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { outputs.push(output); @@ -119871,30 +124608,33 @@ var ts; return outputs; } function getDefinitionLocation(defaultProject, initialLocation) { - var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.position); + var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos); var info = infos && ts.firstOrUndefined(infos); - return info && { fileName: info.fileName, position: info.textSpan.start }; + return info && { fileName: info.fileName, pos: info.textSpan.start }; } - function combineProjectOutputForReferences(projects, defaultProject, initialLocation, projectService) { + function combineProjectOutputForReferences(projects, defaultProject, initialLocation) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, getMappedLocation) { var project = _a.project, location = _a.location; - var _loop_33 = function (outputReferencedSymbol) { - var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, outputReferencedSymbol.definition); }); + var _loop_32 = function (outputReferencedSymbol) { + var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); if (!symbolToAddTo) { - symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + symbolToAddTo = { definition: definition, references: [] }; outputs.push(symbolToAddTo); } for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { var ref = _a[_i]; - if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { symbolToAddTo.references.push(ref); } } }; - for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.position) || server.emptyArray; _i < _b.length; _i++) { + for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _b.length; _i++) { var outputReferencedSymbol = _b[_i]; - _loop_33(outputReferencedSymbol); + _loop_32(outputReferencedSymbol); } }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); return outputs.filter(function (o) { return o.references.length !== 0; }); @@ -119913,12 +124653,13 @@ var ts; }); } } - function combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, cb, getDefinition) { + function combineProjectOutputWorker(projects, defaultProject, initialLocation, cb, getDefinition) { + var projectService = defaultProject.projectService; var toDo; var seenProjects = ts.createMap(); forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) { - // TLocation shoud be either `sourcemaps.SourceMappableLocation` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. - var location = (initialLocation ? { fileName: path, position: initialLocation.position } : undefined); + // TLocation shoud be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. + var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined); toDo = callbackProjectAndLocation({ project: project, location: location }, projectService, toDo, seenProjects, cb); }); // After initial references are collected, go over every other project and see if it has a reference for the symbol definition. @@ -119940,7 +124681,7 @@ var ts; function getDefinitionInProject(definition, definingProject, project) { if (!definition || project.containsFile(server.toNormalizedPath(definition.fileName))) return definition; - var mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedLocation(definition); + var mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(definition); return mappedDefinition && project.containsFile(server.toNormalizedPath(mappedDefinition.fileName)) ? mappedDefinition : undefined; } function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) { @@ -119950,7 +124691,7 @@ var ts; seenProjects.set(projectAndLocation.project.projectName, true); var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); if (!originalLocation) - return false; + return undefined; var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); toDo = toDo || []; for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { @@ -119966,7 +124707,7 @@ var ts; } }); } - return true; + return originalLocation; }); return toDo; } @@ -119976,10 +124717,10 @@ var ts; } function documentSpanLocation(_a) { var fileName = _a.fileName, textSpan = _a.textSpan; - return { fileName: fileName, position: textSpan.start }; + return { fileName: fileName, pos: textSpan.start }; } function getMappedLocation(location, projectService, project) { - var mapsTo = project.getSourceMapper().tryGetOriginalLocation(location); + var mapsTo = project.getSourceMapper().tryGetSourcePosition(location); return mapsTo && projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined; } var Session = /** @class */ (function () { @@ -120290,6 +125031,10 @@ var ts; _a[server.CommandNames.GetEditsForFileRenameFull] = function (request) { return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ false)); }, + _a[server.CommandNames.ConfigurePlugin] = function (request) { + _this.configurePlugin(request.arguments); + return _this.notRequired(); + }, _a)); this.host = opts.host; this.cancellationToken = opts.cancellationToken; @@ -120326,6 +125071,7 @@ var ts; globalPlugins: opts.globalPlugins, pluginProbeLocations: opts.pluginProbeLocations, allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, syntaxOnly: opts.syntaxOnly, }; this.projectService = new server.ProjectService(settings); @@ -120340,21 +125086,33 @@ var ts; var openFiles = event.data.openFiles; this.projectsUpdatedInBackgroundEvent(openFiles); break; + case server.ProjectLoadingStartEvent: + var _a = event.data, project = _a.project, reason = _a.reason; + this.event({ projectName: project.getProjectName(), reason: reason }, server.ProjectLoadingStartEvent); + break; + case server.ProjectLoadingFinishEvent: + var finishProject = event.data.project; + this.event({ projectName: finishProject.getProjectName() }, server.ProjectLoadingFinishEvent); + break; case server.LargeFileReferencedEvent: - var _a = event.data, file = _a.file, fileSize = _a.fileSize, maxFileSize_1 = _a.maxFileSize; - this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, "largeFileReferenced"); + var _b = event.data, file = _b.file, fileSize = _b.fileSize, maxFileSize_1 = _b.maxFileSize; + this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, server.LargeFileReferencedEvent); break; case server.ConfigFileDiagEvent: - var _b = event.data, triggerFile = _b.triggerFile, configFile = _b.configFileName, diagnostics = _b.diagnostics; + var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics; var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ true); }); this.event({ triggerFile: triggerFile, configFile: configFile, diagnostics: bakedDiags - }, "configFileDiag"); + }, server.ConfigFileDiagEvent); + break; + case server.SurveyReady: + var surveyId = event.data.surveyId; + this.event({ surveyId: surveyId }, server.SurveyReady); break; case server.ProjectLanguageServiceStateEvent: { - var eventName = "projectLanguageServiceState"; + var eventName = server.ProjectLanguageServiceStateEvent; this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled @@ -120383,10 +125141,13 @@ var ts; // Send project changed event this.event({ openFiles: openFiles - }, "projectsUpdatedInBackground"); + }, server.ProjectsUpdatedInBackgroundEvent); } }; Session.prototype.logError = function (err, cmd) { + this.logErrorWorker(err, cmd); + }; + Session.prototype.logErrorWorker = function (err, cmd, fileRequest) { var msg = "Exception on executing command " + cmd; if (err.message) { msg += ":\n" + server.indent(err.message); @@ -120394,6 +125155,17 @@ var ts; msg += "\n" + server.indent(err.stack); } } + if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) { + try { + var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + var text = ts.getSnapshotText(scriptInfo.getSnapshot()); + msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + } + } + catch (_b) { } // tslint:disable-line no-empty + } this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { @@ -120422,7 +125194,27 @@ var ts; success: success, }; if (success) { - res.body = info; + var metadata = void 0; + if (ts.isArray(info)) { + res.body = info; + metadata = info.metadata; + delete info.metadata; + } + else if (typeof info === "object") { + if (info.metadata) { + var _a = info, infoMetadata = _a.metadata, body = __rest(_a, ["metadata"]); + res.body = body; + metadata = infoMetadata; + } + else { + res.body = info; + } + } + else { + res.body = info; + } + if (metadata) + res.metadata = metadata; } else { ts.Debug.assert(info === undefined); @@ -120606,7 +125398,7 @@ var ts; kind: info.kind, name: info.name, textSpan: { - start: newLoc.position, + start: newLoc.pos, length: info.textSpan.length }, originalFileName: info.fileName, @@ -120685,7 +125477,7 @@ var ts; kind: info.kind, displayParts: info.displayParts, textSpan: { - start: newLoc.position, + start: newLoc.pos, length: info.textSpan.length }, originalFileName: info.fileName, @@ -120822,7 +125614,10 @@ var ts; this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : this.projectService.getScriptInfo(args.file); if (!scriptInfo) { - return ignoreNoProjectError ? server.emptyArray : server.Errors.ThrowNoProject(); + if (ignoreNoProjectError) + return server.emptyArray; + this.projectService.logErrorForScriptInfoNotFound(args.file); + return server.Errors.ThrowNoProject(); } projects = scriptInfo.containingProjects; symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); @@ -120830,6 +125625,7 @@ var ts; // filter handles case when 'projects' is undefined projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); }); if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { + this.projectService.logErrorForScriptInfoNotFound(args.file); return server.Errors.ThrowNoProject(); } return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; // TODO: GH#18217 @@ -120848,26 +125644,32 @@ var ts; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); - var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, position: position }, this.projectService, !!args.findInStrings, !!args.findInComments); + var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments); if (!simplifiedResult) return locations; var defaultProject = this.getDefaultProject(args); - var renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; - // strips 'triggerSpan' - Session.mapRenameInfo = function (_a) { - var canRename = _a.canRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers; - return { canRename: canRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers }; + Session.prototype.mapRenameInfo = function (info, scriptInfo) { + if (info.canRename) { + var canRename = info.canRename, fileToRename = info.fileToRename, displayName = info.displayName, fullDisplayName = info.fullDisplayName, kind = info.kind, kindModifiers = info.kindModifiers, triggerSpan = info.triggerSpan; + return ts.identity({ canRename: canRename, fileToRename: fileToRename, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }); + } + else { + return info; + } }; Session.prototype.toSpanGroups = function (locations) { var map = ts.createMap(); for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { - var _a = locations_1[_i], fileName = _a.fileName, textSpan = _a.textSpan; + var _a = locations_1[_i]; + var fileName = _a.fileName, textSpan = _a.textSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "originalTextSpan", "originalFileName"]); var group_2 = map.get(fileName); if (!group_2) map.set(fileName, group_2 = { file: fileName, locs: [] }); - group_2.locs.push(this.toLocationTextSpan(textSpan, ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)))); + var scriptInfo = ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)); + group_2.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText)); } return ts.arrayFrom(map.values()); }; @@ -120876,7 +125678,7 @@ var ts; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); var position = this.getPositionInFile(args, file); - var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, position: position }, this.projectService); + var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }); if (simplifiedResult) { var defaultProject = this.getDefaultProject(args); var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); @@ -120884,7 +125686,7 @@ var ts; var symbolDisplayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : ""; var nameSpan = nameInfo && nameInfo.textSpan; var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; - var symbolName_4 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; + var symbolName_3 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; var refs = ts.flatMap(references, function (referencedSymbol) { return referencedSymbol.references.map(function (_a) { var fileName = _a.fileName, textSpan = _a.textSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition; @@ -120895,7 +125697,7 @@ var ts; return __assign({}, toFileSpan(fileName, textSpan, scriptInfo), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition }); }); }); - var result = { refs: refs, symbolName: symbolName_4, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; + var result = { refs: refs, symbolName: symbolName_3, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; return result; } else { @@ -121099,7 +125901,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); if (completions === undefined) return undefined; if (kind === "completions-full" /* CompletionsFull */) @@ -121113,8 +125915,11 @@ var ts; return { name: name, kind: kind_2, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; } }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); - if (kind === "completions" /* Completions */) + if (kind === "completions" /* Completions */) { + if (completions.metadata) + entries.metadata = completions.metadata; return entries; + } var res = __assign({}, completions, { entries: entries }); return res; }; @@ -121323,7 +126128,7 @@ var ts; return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file); } else { - return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), this.projectService, function (project) { + return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), function (project) { return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject()); }, documentSpanLocation, navigateToItemIsEqualTo); } @@ -121352,7 +126157,7 @@ var ts; Session.prototype.isLocation = function (locationOrSpan) { return locationOrSpan.line !== undefined; }; - Session.prototype.extractPositionAndRange = function (args, scriptInfo) { + Session.prototype.extractPositionOrRange = function (args, scriptInfo) { var position; var textRange; if (this.isLocation(args)) { @@ -121362,7 +126167,7 @@ var ts; var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; textRange = { pos: startPosition, end: endPosition }; } - return { position: position, textRange: textRange }; // TODO: GH#18217 + return ts.Debug.assertDefined(position === undefined ? textRange : position); function getPosition(loc) { return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); } @@ -121370,14 +126175,12 @@ var ts; Session.prototype.getApplicableRefactors = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; - return project.getLanguageService().getApplicableRefactors(file, position || textRange, this.getPreferences(file)); + return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); }; Session.prototype.getEditsForRefactor = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; - var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), position || textRange, args.refactor, args.action, this.getPreferences(file)); + var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, this.getPreferences(file)); if (result === undefined) { return { edits: [] @@ -121441,8 +126244,8 @@ var ts; var commands = args.command; // They should be sending back the command we sent them. for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; - var project = this.getFileAndProject(command).project; - project.getLanguageService().applyCodeActionCommand(command).then(function (_result) { }, function (_error) { }); + var _b = this.getFileAndProject(command), file = _b.file, project = _b.project; + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { }); } return {}; }; @@ -121477,8 +126280,17 @@ var ts; var _this = this; return textChanges.map(function (change) { return _this.mapTextChangeToCodeEdit(change); }); }; - Session.prototype.mapTextChangeToCodeEdit = function (change) { - return mapTextChangesToCodeEdits(change, this.projectService.getScriptInfoOrConfig(change.fileName)); + Session.prototype.mapTextChangeToCodeEdit = function (textChanges) { + var scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges.fileName); + if (!!textChanges.isNewFile === !!scriptInfo) { + if (!scriptInfo) { // and !isNewFile + this.projectService.logErrorForScriptInfoNotFound(textChanges.fileName); + } + ts.Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo })); + } + return scriptInfo + ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, scriptInfo); }) } + : convertNewFileTextChangeToCodeEdit(textChanges); }; Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { return { @@ -121545,6 +126357,9 @@ var ts; // doesn't require the file to be opened this.updateErrorCheck(next, checkList, delay, /*requireOpen*/ false); }; + Session.prototype.configurePlugin = function (args) { + this.projectService.configurePlugin(args); + }; Session.prototype.getCanonicalFileName = function (fileName) { var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); return ts.normalizePath(name); @@ -121602,8 +126417,10 @@ var ts; } } var request; + var relevantFile; try { request = JSON.parse(message); + relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; if (this.logger.hasLevel(server.LogLevel.requestTime)) { var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); @@ -121627,7 +126444,7 @@ var ts; this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); return; } - this.logError(err, message); + this.logErrorWorker(err, message, relevantFile); this.doOutput( /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); @@ -121651,12 +126468,6 @@ var ts; function toFileSpan(fileName, textSpan, scriptInfo) { return { file: fileName, start: scriptInfo.positionToLineOffset(textSpan.start), end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) }; } - function mapTextChangesToCodeEdits(textChanges, scriptInfo) { - ts.Debug.assert(!!textChanges.isNewFile === !scriptInfo, "Expected isNewFile for (only) new files", function () { return JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo }); }); - return scriptInfo - ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, scriptInfo); }) } - : convertNewFileTextChangeToCodeEdit(textChanges); - } function convertTextChangeToCodeEdit(change, scriptInfo) { return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, ts.textSpanEnd(change.span)), newText: change.newText }; } @@ -121686,8 +126497,8 @@ var ts; continue; } for (var i = textChanges_4.length - 1; i >= 0; i--) { - var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_7 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_7); + var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_6 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_6); } } return text; @@ -122037,7 +126848,6 @@ var ts; }; return LineIndexSnapshot; }()); - /* @internal */ var LineIndex = /** @class */ (function () { function LineIndex() { // set this to true to check each edit for accuracy diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 096362cc6a7..0e693f698f2 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ const version: string; } @@ -27,6 +27,9 @@ declare namespace ts { interface MapLike { [index: string]: T; } + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } interface SortedArray extends Array { " __sortedArrayBrand": any; } @@ -69,7 +72,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -81,337 +85,339 @@ declare namespace ts { ShebangTrivia = 6, ConflictMarkerTrivia = 7, NumericLiteral = 8, - StringLiteral = 9, - JsxText = 10, - JsxTextAllWhiteSpaces = 11, - RegularExpressionLiteral = 12, - NoSubstitutionTemplateLiteral = 13, - TemplateHead = 14, - TemplateMiddle = 15, - TemplateTail = 16, - OpenBraceToken = 17, - CloseBraceToken = 18, - OpenParenToken = 19, - CloseParenToken = 20, - OpenBracketToken = 21, - CloseBracketToken = 22, - DotToken = 23, - DotDotDotToken = 24, - SemicolonToken = 25, - CommaToken = 26, - LessThanToken = 27, - LessThanSlashToken = 28, - GreaterThanToken = 29, - LessThanEqualsToken = 30, - GreaterThanEqualsToken = 31, - EqualsEqualsToken = 32, - ExclamationEqualsToken = 33, - EqualsEqualsEqualsToken = 34, - ExclamationEqualsEqualsToken = 35, - EqualsGreaterThanToken = 36, - PlusToken = 37, - MinusToken = 38, - AsteriskToken = 39, - AsteriskAsteriskToken = 40, - SlashToken = 41, - PercentToken = 42, - PlusPlusToken = 43, - MinusMinusToken = 44, - LessThanLessThanToken = 45, - GreaterThanGreaterThanToken = 46, - GreaterThanGreaterThanGreaterThanToken = 47, - AmpersandToken = 48, - BarToken = 49, - CaretToken = 50, - ExclamationToken = 51, - TildeToken = 52, - AmpersandAmpersandToken = 53, - BarBarToken = 54, - QuestionToken = 55, - ColonToken = 56, - AtToken = 57, - EqualsToken = 58, - PlusEqualsToken = 59, - MinusEqualsToken = 60, - AsteriskEqualsToken = 61, - AsteriskAsteriskEqualsToken = 62, - SlashEqualsToken = 63, - PercentEqualsToken = 64, - LessThanLessThanEqualsToken = 65, - GreaterThanGreaterThanEqualsToken = 66, - GreaterThanGreaterThanGreaterThanEqualsToken = 67, - AmpersandEqualsToken = 68, - BarEqualsToken = 69, - CaretEqualsToken = 70, - Identifier = 71, - BreakKeyword = 72, - CaseKeyword = 73, - CatchKeyword = 74, - ClassKeyword = 75, - ConstKeyword = 76, - ContinueKeyword = 77, - DebuggerKeyword = 78, - DefaultKeyword = 79, - DeleteKeyword = 80, - DoKeyword = 81, - ElseKeyword = 82, - EnumKeyword = 83, - ExportKeyword = 84, - ExtendsKeyword = 85, - FalseKeyword = 86, - FinallyKeyword = 87, - ForKeyword = 88, - FunctionKeyword = 89, - IfKeyword = 90, - ImportKeyword = 91, - InKeyword = 92, - InstanceOfKeyword = 93, - NewKeyword = 94, - NullKeyword = 95, - ReturnKeyword = 96, - SuperKeyword = 97, - SwitchKeyword = 98, - ThisKeyword = 99, - ThrowKeyword = 100, - TrueKeyword = 101, - TryKeyword = 102, - TypeOfKeyword = 103, - VarKeyword = 104, - VoidKeyword = 105, - WhileKeyword = 106, - WithKeyword = 107, - ImplementsKeyword = 108, - InterfaceKeyword = 109, - LetKeyword = 110, - PackageKeyword = 111, - PrivateKeyword = 112, - ProtectedKeyword = 113, - PublicKeyword = 114, - StaticKeyword = 115, - YieldKeyword = 116, - AbstractKeyword = 117, - AsKeyword = 118, - AnyKeyword = 119, - AsyncKeyword = 120, - AwaitKeyword = 121, - BooleanKeyword = 122, - ConstructorKeyword = 123, - DeclareKeyword = 124, - GetKeyword = 125, - InferKeyword = 126, - IsKeyword = 127, - KeyOfKeyword = 128, - ModuleKeyword = 129, - NamespaceKeyword = 130, - NeverKeyword = 131, - ReadonlyKeyword = 132, - RequireKeyword = 133, - NumberKeyword = 134, - ObjectKeyword = 135, - SetKeyword = 136, - StringKeyword = 137, - SymbolKeyword = 138, - TypeKeyword = 139, - UndefinedKeyword = 140, - UniqueKeyword = 141, - UnknownKeyword = 142, - FromKeyword = 143, - GlobalKeyword = 144, - OfKeyword = 145, - QualifiedName = 146, - ComputedPropertyName = 147, - TypeParameter = 148, - Parameter = 149, - Decorator = 150, - PropertySignature = 151, - PropertyDeclaration = 152, - MethodSignature = 153, - MethodDeclaration = 154, - Constructor = 155, - GetAccessor = 156, - SetAccessor = 157, - CallSignature = 158, - ConstructSignature = 159, - IndexSignature = 160, - TypePredicate = 161, - TypeReference = 162, - FunctionType = 163, - ConstructorType = 164, - TypeQuery = 165, - TypeLiteral = 166, - ArrayType = 167, - TupleType = 168, - OptionalType = 169, - RestType = 170, - UnionType = 171, - IntersectionType = 172, - ConditionalType = 173, - InferType = 174, - ParenthesizedType = 175, - ThisType = 176, - TypeOperator = 177, - IndexedAccessType = 178, - MappedType = 179, - LiteralType = 180, - ImportType = 181, - ObjectBindingPattern = 182, - ArrayBindingPattern = 183, - BindingElement = 184, - ArrayLiteralExpression = 185, - ObjectLiteralExpression = 186, - PropertyAccessExpression = 187, - ElementAccessExpression = 188, - CallExpression = 189, - NewExpression = 190, - TaggedTemplateExpression = 191, - TypeAssertionExpression = 192, - ParenthesizedExpression = 193, - FunctionExpression = 194, - ArrowFunction = 195, - DeleteExpression = 196, - TypeOfExpression = 197, - VoidExpression = 198, - AwaitExpression = 199, - PrefixUnaryExpression = 200, - PostfixUnaryExpression = 201, - BinaryExpression = 202, - ConditionalExpression = 203, - TemplateExpression = 204, - YieldExpression = 205, - SpreadElement = 206, - ClassExpression = 207, - OmittedExpression = 208, - ExpressionWithTypeArguments = 209, - AsExpression = 210, - NonNullExpression = 211, - MetaProperty = 212, - SyntheticExpression = 213, - TemplateSpan = 214, - SemicolonClassElement = 215, - Block = 216, - VariableStatement = 217, - EmptyStatement = 218, - ExpressionStatement = 219, - IfStatement = 220, - DoStatement = 221, - WhileStatement = 222, - ForStatement = 223, - ForInStatement = 224, - ForOfStatement = 225, - ContinueStatement = 226, - BreakStatement = 227, - ReturnStatement = 228, - WithStatement = 229, - SwitchStatement = 230, - LabeledStatement = 231, - ThrowStatement = 232, - TryStatement = 233, - DebuggerStatement = 234, - VariableDeclaration = 235, - VariableDeclarationList = 236, - FunctionDeclaration = 237, - ClassDeclaration = 238, - InterfaceDeclaration = 239, - TypeAliasDeclaration = 240, - EnumDeclaration = 241, - ModuleDeclaration = 242, - ModuleBlock = 243, - CaseBlock = 244, - NamespaceExportDeclaration = 245, - ImportEqualsDeclaration = 246, - ImportDeclaration = 247, - ImportClause = 248, - NamespaceImport = 249, - NamedImports = 250, - ImportSpecifier = 251, - ExportAssignment = 252, - ExportDeclaration = 253, - NamedExports = 254, - ExportSpecifier = 255, - MissingDeclaration = 256, - ExternalModuleReference = 257, - JsxElement = 258, - JsxSelfClosingElement = 259, - JsxOpeningElement = 260, - JsxClosingElement = 261, - JsxFragment = 262, - JsxOpeningFragment = 263, - JsxClosingFragment = 264, - JsxAttribute = 265, - JsxAttributes = 266, - JsxSpreadAttribute = 267, - JsxExpression = 268, - CaseClause = 269, - DefaultClause = 270, - HeritageClause = 271, - CatchClause = 272, - PropertyAssignment = 273, - ShorthandPropertyAssignment = 274, - SpreadAssignment = 275, - EnumMember = 276, - SourceFile = 277, - Bundle = 278, - UnparsedSource = 279, - InputFiles = 280, - JSDocTypeExpression = 281, - JSDocAllType = 282, - JSDocUnknownType = 283, - JSDocNullableType = 284, - JSDocNonNullableType = 285, - JSDocOptionalType = 286, - JSDocFunctionType = 287, - JSDocVariadicType = 288, - JSDocComment = 289, - JSDocTypeLiteral = 290, - JSDocSignature = 291, - JSDocTag = 292, - JSDocAugmentsTag = 293, - JSDocClassTag = 294, - JSDocCallbackTag = 295, - JSDocEnumTag = 296, - JSDocParameterTag = 297, - JSDocReturnTag = 298, - JSDocThisTag = 299, - JSDocTypeTag = 300, - JSDocTemplateTag = 301, - JSDocTypedefTag = 302, - JSDocPropertyTag = 303, - SyntaxList = 304, - NotEmittedStatement = 305, - PartiallyEmittedExpression = 306, - CommaListExpression = 307, - MergeDeclarationMarker = 308, - EndOfDeclarationMarker = 309, - Count = 310, - FirstAssignment = 58, - LastAssignment = 70, - FirstCompoundAssignment = 59, - LastCompoundAssignment = 70, - FirstReservedWord = 72, - LastReservedWord = 107, - FirstKeyword = 72, - LastKeyword = 145, - FirstFutureReservedWord = 108, - LastFutureReservedWord = 116, - FirstTypeNode = 161, - LastTypeNode = 181, - FirstPunctuation = 17, - LastPunctuation = 70, + BigIntLiteral = 9, + StringLiteral = 10, + JsxText = 11, + JsxTextAllWhiteSpaces = 12, + RegularExpressionLiteral = 13, + NoSubstitutionTemplateLiteral = 14, + TemplateHead = 15, + TemplateMiddle = 16, + TemplateTail = 17, + OpenBraceToken = 18, + CloseBraceToken = 19, + OpenParenToken = 20, + CloseParenToken = 21, + OpenBracketToken = 22, + CloseBracketToken = 23, + DotToken = 24, + DotDotDotToken = 25, + SemicolonToken = 26, + CommaToken = 27, + LessThanToken = 28, + LessThanSlashToken = 29, + GreaterThanToken = 30, + LessThanEqualsToken = 31, + GreaterThanEqualsToken = 32, + EqualsEqualsToken = 33, + ExclamationEqualsToken = 34, + EqualsEqualsEqualsToken = 35, + ExclamationEqualsEqualsToken = 36, + EqualsGreaterThanToken = 37, + PlusToken = 38, + MinusToken = 39, + AsteriskToken = 40, + AsteriskAsteriskToken = 41, + SlashToken = 42, + PercentToken = 43, + PlusPlusToken = 44, + MinusMinusToken = 45, + LessThanLessThanToken = 46, + GreaterThanGreaterThanToken = 47, + GreaterThanGreaterThanGreaterThanToken = 48, + AmpersandToken = 49, + BarToken = 50, + CaretToken = 51, + ExclamationToken = 52, + TildeToken = 53, + AmpersandAmpersandToken = 54, + BarBarToken = 55, + QuestionToken = 56, + ColonToken = 57, + AtToken = 58, + EqualsToken = 59, + PlusEqualsToken = 60, + MinusEqualsToken = 61, + AsteriskEqualsToken = 62, + AsteriskAsteriskEqualsToken = 63, + SlashEqualsToken = 64, + PercentEqualsToken = 65, + LessThanLessThanEqualsToken = 66, + GreaterThanGreaterThanEqualsToken = 67, + GreaterThanGreaterThanGreaterThanEqualsToken = 68, + AmpersandEqualsToken = 69, + BarEqualsToken = 70, + CaretEqualsToken = 71, + Identifier = 72, + BreakKeyword = 73, + CaseKeyword = 74, + CatchKeyword = 75, + ClassKeyword = 76, + ConstKeyword = 77, + ContinueKeyword = 78, + DebuggerKeyword = 79, + DefaultKeyword = 80, + DeleteKeyword = 81, + DoKeyword = 82, + ElseKeyword = 83, + EnumKeyword = 84, + ExportKeyword = 85, + ExtendsKeyword = 86, + FalseKeyword = 87, + FinallyKeyword = 88, + ForKeyword = 89, + FunctionKeyword = 90, + IfKeyword = 91, + ImportKeyword = 92, + InKeyword = 93, + InstanceOfKeyword = 94, + NewKeyword = 95, + NullKeyword = 96, + ReturnKeyword = 97, + SuperKeyword = 98, + SwitchKeyword = 99, + ThisKeyword = 100, + ThrowKeyword = 101, + TrueKeyword = 102, + TryKeyword = 103, + TypeOfKeyword = 104, + VarKeyword = 105, + VoidKeyword = 106, + WhileKeyword = 107, + WithKeyword = 108, + ImplementsKeyword = 109, + InterfaceKeyword = 110, + LetKeyword = 111, + PackageKeyword = 112, + PrivateKeyword = 113, + ProtectedKeyword = 114, + PublicKeyword = 115, + StaticKeyword = 116, + YieldKeyword = 117, + AbstractKeyword = 118, + AsKeyword = 119, + AnyKeyword = 120, + AsyncKeyword = 121, + AwaitKeyword = 122, + BooleanKeyword = 123, + ConstructorKeyword = 124, + DeclareKeyword = 125, + GetKeyword = 126, + InferKeyword = 127, + IsKeyword = 128, + KeyOfKeyword = 129, + ModuleKeyword = 130, + NamespaceKeyword = 131, + NeverKeyword = 132, + ReadonlyKeyword = 133, + RequireKeyword = 134, + NumberKeyword = 135, + ObjectKeyword = 136, + SetKeyword = 137, + StringKeyword = 138, + SymbolKeyword = 139, + TypeKeyword = 140, + UndefinedKeyword = 141, + UniqueKeyword = 142, + UnknownKeyword = 143, + FromKeyword = 144, + GlobalKeyword = 145, + BigIntKeyword = 146, + OfKeyword = 147, + QualifiedName = 148, + ComputedPropertyName = 149, + TypeParameter = 150, + Parameter = 151, + Decorator = 152, + PropertySignature = 153, + PropertyDeclaration = 154, + MethodSignature = 155, + MethodDeclaration = 156, + Constructor = 157, + GetAccessor = 158, + SetAccessor = 159, + CallSignature = 160, + ConstructSignature = 161, + IndexSignature = 162, + TypePredicate = 163, + TypeReference = 164, + FunctionType = 165, + ConstructorType = 166, + TypeQuery = 167, + TypeLiteral = 168, + ArrayType = 169, + TupleType = 170, + OptionalType = 171, + RestType = 172, + UnionType = 173, + IntersectionType = 174, + ConditionalType = 175, + InferType = 176, + ParenthesizedType = 177, + ThisType = 178, + TypeOperator = 179, + IndexedAccessType = 180, + MappedType = 181, + LiteralType = 182, + ImportType = 183, + ObjectBindingPattern = 184, + ArrayBindingPattern = 185, + BindingElement = 186, + ArrayLiteralExpression = 187, + ObjectLiteralExpression = 188, + PropertyAccessExpression = 189, + ElementAccessExpression = 190, + CallExpression = 191, + NewExpression = 192, + TaggedTemplateExpression = 193, + TypeAssertionExpression = 194, + ParenthesizedExpression = 195, + FunctionExpression = 196, + ArrowFunction = 197, + DeleteExpression = 198, + TypeOfExpression = 199, + VoidExpression = 200, + AwaitExpression = 201, + PrefixUnaryExpression = 202, + PostfixUnaryExpression = 203, + BinaryExpression = 204, + ConditionalExpression = 205, + TemplateExpression = 206, + YieldExpression = 207, + SpreadElement = 208, + ClassExpression = 209, + OmittedExpression = 210, + ExpressionWithTypeArguments = 211, + AsExpression = 212, + NonNullExpression = 213, + MetaProperty = 214, + SyntheticExpression = 215, + TemplateSpan = 216, + SemicolonClassElement = 217, + Block = 218, + VariableStatement = 219, + EmptyStatement = 220, + ExpressionStatement = 221, + IfStatement = 222, + DoStatement = 223, + WhileStatement = 224, + ForStatement = 225, + ForInStatement = 226, + ForOfStatement = 227, + ContinueStatement = 228, + BreakStatement = 229, + ReturnStatement = 230, + WithStatement = 231, + SwitchStatement = 232, + LabeledStatement = 233, + ThrowStatement = 234, + TryStatement = 235, + DebuggerStatement = 236, + VariableDeclaration = 237, + VariableDeclarationList = 238, + FunctionDeclaration = 239, + ClassDeclaration = 240, + InterfaceDeclaration = 241, + TypeAliasDeclaration = 242, + EnumDeclaration = 243, + ModuleDeclaration = 244, + ModuleBlock = 245, + CaseBlock = 246, + NamespaceExportDeclaration = 247, + ImportEqualsDeclaration = 248, + ImportDeclaration = 249, + ImportClause = 250, + NamespaceImport = 251, + NamedImports = 252, + ImportSpecifier = 253, + ExportAssignment = 254, + ExportDeclaration = 255, + NamedExports = 256, + ExportSpecifier = 257, + MissingDeclaration = 258, + ExternalModuleReference = 259, + JsxElement = 260, + JsxSelfClosingElement = 261, + JsxOpeningElement = 262, + JsxClosingElement = 263, + JsxFragment = 264, + JsxOpeningFragment = 265, + JsxClosingFragment = 266, + JsxAttribute = 267, + JsxAttributes = 268, + JsxSpreadAttribute = 269, + JsxExpression = 270, + CaseClause = 271, + DefaultClause = 272, + HeritageClause = 273, + CatchClause = 274, + PropertyAssignment = 275, + ShorthandPropertyAssignment = 276, + SpreadAssignment = 277, + EnumMember = 278, + SourceFile = 279, + Bundle = 280, + UnparsedSource = 281, + InputFiles = 282, + JSDocTypeExpression = 283, + JSDocAllType = 284, + JSDocUnknownType = 285, + JSDocNullableType = 286, + JSDocNonNullableType = 287, + JSDocOptionalType = 288, + JSDocFunctionType = 289, + JSDocVariadicType = 290, + JSDocComment = 291, + JSDocTypeLiteral = 292, + JSDocSignature = 293, + JSDocTag = 294, + JSDocAugmentsTag = 295, + JSDocClassTag = 296, + JSDocCallbackTag = 297, + JSDocEnumTag = 298, + JSDocParameterTag = 299, + JSDocReturnTag = 300, + JSDocThisTag = 301, + JSDocTypeTag = 302, + JSDocTemplateTag = 303, + JSDocTypedefTag = 304, + JSDocPropertyTag = 305, + SyntaxList = 306, + NotEmittedStatement = 307, + PartiallyEmittedExpression = 308, + CommaListExpression = 309, + MergeDeclarationMarker = 310, + EndOfDeclarationMarker = 311, + Count = 312, + FirstAssignment = 59, + LastAssignment = 71, + FirstCompoundAssignment = 60, + LastCompoundAssignment = 71, + FirstReservedWord = 73, + LastReservedWord = 108, + FirstKeyword = 73, + LastKeyword = 147, + FirstFutureReservedWord = 109, + LastFutureReservedWord = 117, + FirstTypeNode = 163, + LastTypeNode = 183, + FirstPunctuation = 18, + LastPunctuation = 71, FirstToken = 0, - LastToken = 145, + LastToken = 147, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, - LastLiteralToken = 13, - FirstTemplateToken = 13, - LastTemplateToken = 16, - FirstBinaryOperator = 27, - LastBinaryOperator = 70, - FirstNode = 146, - FirstJSDocNode = 281, - LastJSDocNode = 303, - FirstJSDocTagNode = 292, - LastJSDocTagNode = 303 + LastLiteralToken = 14, + FirstTemplateToken = 14, + LastTemplateToken = 17, + FirstBinaryOperator = 28, + LastBinaryOperator = 71, + FirstNode = 148, + FirstJSDocNode = 283, + LastJSDocNode = 305, + FirstJSDocTagNode = 294, + LastJSDocTagNode = 305 } enum NodeFlags { None = 0, @@ -498,7 +504,6 @@ declare namespace ts { type AsteriskToken = Token; type EqualsGreaterThanToken = Token; type EndOfFileToken = Token & JSDocContainer; - type AtToken = Token; type ReadonlyToken = Token; type AwaitKeywordToken = Token; type PlusToken = Token; @@ -525,7 +530,7 @@ declare namespace ts { } type EntityName = Identifier | QualifiedName; type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; - type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; + type DeclarationName = Identifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; } @@ -536,6 +541,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +638,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +675,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -720,7 +728,7 @@ declare namespace ts { _typeNodeBrand: any; } interface KeywordTypeNode extends TypeNode { - kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; + kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; } interface ImportTypeNode extends NodeWithTypeArguments { kind: SyntaxKind.ImportType; @@ -992,6 +1000,9 @@ declare namespace ts { interface NumericLiteral extends LiteralExpression { kind: SyntaxKind.NumericLiteral; } + interface BigIntLiteral extends LiteralExpression { + kind: SyntaxKind.BigIntLiteral; + } interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; parent: TemplateExpression; @@ -1079,7 +1090,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1539,7 +1550,6 @@ declare namespace ts { } interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; - atToken: AtToken; tagName: Identifier; comment?: string; } @@ -1569,7 +1579,7 @@ declare namespace ts { } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; - constraint: TypeNode | undefined; + constraint: JSDocTypeExpression | undefined; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { @@ -1751,13 +1761,14 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. */ fileExists(path: string): boolean; readFile(path: string): string | undefined; + trace?(s: string): void; } /** * Branded string for keeping track of when we've turned an ambiguous path @@ -1808,11 +1819,13 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): ReadonlyArray | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; sourceFile: SourceFile; + references?: ReadonlyArray; } interface CustomTransformers { /** Custom transformers to evaluate before built-in .js transformations. */ @@ -1836,17 +1849,6 @@ declare namespace ts { /** .ts file (index into sources array) associated with this span */ sourceIndex: number; } - interface SourceMapData { - sourceMapFilePath: string; - jsSourceMappingURL: string; - sourceMapFile: string; - sourceMapSourceRoot: string; - sourceMapSources: string[]; - sourceMapSourcesContent?: (string | null)[]; - inputSourceFileNames: string[]; - sourceMapNames?: string[]; - sourceMapMappings: string; - } /** Return code used by getEmitOutput function to indicate status of the function */ enum ExitStatus { Success = 0, @@ -1918,7 +1920,7 @@ declare namespace ts { typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; + getRootSymbols(symbol: Symbol): ReadonlyArray; getContextualType(node: Expression): Type | undefined; /** * returns unknownSignature in the case of an error. @@ -1936,7 +1938,6 @@ declare namespace ts { /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; @@ -1975,7 +1976,8 @@ declare namespace ts { AllowEmptyTuple = 524288, AllowUniqueESSymbolType = 1048576, AllowEmptyIndexInfoType = 2097152, - IgnoreErrors = 3112960, + AllowNodeModulesRelativePaths = 67108864, + IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, @@ -2056,32 +2058,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2155,44 +2157,47 @@ declare namespace ts { Number = 8, Boolean = 16, Enum = 32, - StringLiteral = 64, - NumberLiteral = 128, - BooleanLiteral = 256, - EnumLiteral = 512, - ESSymbol = 1024, - UniqueESSymbol = 2048, - Void = 4096, - Undefined = 8192, - Null = 16384, - Never = 32768, - TypeParameter = 65536, - Object = 131072, - Union = 262144, - Intersection = 524288, - Index = 1048576, - IndexedAccess = 2097152, - Conditional = 4194304, - Substitution = 8388608, - NonPrimitive = 16777216, - Literal = 448, - Unit = 27072, - StringOrNumberLiteral = 192, - PossiblyFalsy = 29148, - StringLike = 68, - NumberLike = 168, - BooleanLike = 272, - EnumLike = 544, - ESSymbolLike = 3072, - VoidLike = 12288, - UnionOrIntersection = 786432, - StructuredType = 917504, - TypeVariable = 2162688, - InstantiableNonPrimitive = 14745600, - InstantiablePrimitive = 1048576, - Instantiable = 15794176, - StructuredOrInstantiable = 16711680, - Narrowable = 33492479, - NotUnionOrUnit = 16909315 + BigInt = 64, + StringLiteral = 128, + NumberLiteral = 256, + BooleanLiteral = 512, + EnumLiteral = 1024, + BigIntLiteral = 2048, + ESSymbol = 4096, + UniqueESSymbol = 8192, + Void = 16384, + Undefined = 32768, + Null = 65536, + Never = 131072, + TypeParameter = 262144, + Object = 524288, + Union = 1048576, + Intersection = 2097152, + Index = 4194304, + IndexedAccess = 8388608, + Conditional = 16777216, + Substitution = 33554432, + NonPrimitive = 67108864, + Literal = 2944, + Unit = 109440, + StringOrNumberLiteral = 384, + PossiblyFalsy = 117724, + StringLike = 132, + NumberLike = 296, + BigIntLike = 2112, + BooleanLike = 528, + EnumLike = 1056, + ESSymbolLike = 12288, + VoidLike = 49152, + UnionOrIntersection = 3145728, + StructuredType = 3670016, + TypeVariable = 8650752, + InstantiableNonPrimitive = 58982400, + InstantiablePrimitive = 4194304, + Instantiable = 63176704, + StructuredOrInstantiable = 66846720, + Narrowable = 133970943, + NotUnionOrUnit = 67637251 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2203,7 +2208,7 @@ declare namespace ts { aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { - value: string | number; + value: string | number | PseudoBigInt; freshType: LiteralType; regularType: LiteralType; } @@ -2216,6 +2221,9 @@ declare namespace ts { interface NumberLiteralType extends LiteralType { value: number; } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } interface EnumType extends Type { } enum ObjectFlags { @@ -2234,6 +2242,7 @@ declare namespace ts { JsxAttributes = 4096, MarkerType = 8192, JSLiteral = 16384, + FreshLiteral = 32768, ClassOrInterface = 3 } interface ObjectType extends Type { @@ -2490,6 +2499,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2591,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2601,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2673,6 +2674,8 @@ declare namespace ts { primary: boolean; resolvedFileName: string | undefined; packageId?: PackageId; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; @@ -2691,16 +2694,13 @@ declare namespace ts { useCaseSensitiveFileNames(): boolean; getNewLine(): string; readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -2753,7 +2753,8 @@ declare namespace ts { Expression = 1, IdentifierName = 2, MappedTypeParameter = 3, - Unspecified = 4 + Unspecified = 4, + EmbeddedStatement = 5 } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2946,60 +2947,77 @@ declare namespace ts { BarDelimited = 4, AmpersandDelimited = 8, CommaDelimited = 16, - DelimitersMask = 28, - AllowTrailingComma = 32, - Indented = 64, - SpaceBetweenBraces = 128, - SpaceBetweenSiblings = 256, - Braces = 512, - Parenthesis = 1024, - AngleBrackets = 2048, - SquareBrackets = 4096, - BracketsMask = 7680, - OptionalIfUndefined = 8192, - OptionalIfEmpty = 16384, - Optional = 24576, - PreferNewLine = 32768, - NoTrailingNewLine = 65536, - NoInterveningComments = 131072, - NoSpaceIfEmpty = 262144, - SingleElement = 524288, - Modifiers = 131328, - HeritageClauses = 256, - SingleLineTypeLiteralMembers = 384, - MultiLineTypeLiteralMembers = 16449, - TupleTypeElements = 272, - UnionTypeConstituents = 260, - IntersectionTypeConstituents = 264, - ObjectBindingPatternElements = 262576, - ArrayBindingPatternElements = 262448, - ObjectLiteralExpressionProperties = 263122, - ArrayLiteralExpressionElements = 4466, - CommaListElements = 272, - CallExpressionArguments = 1296, - NewExpressionArguments = 9488, - TemplateExpressionSpans = 131072, - SingleLineBlockStatements = 384, - MultiLineBlockStatements = 65, - VariableDeclarationList = 272, - SingleLineFunctionBodyStatements = 384, + AsteriskDelimited = 32, + DelimitersMask = 60, + AllowTrailingComma = 64, + Indented = 128, + SpaceBetweenBraces = 256, + SpaceBetweenSiblings = 512, + Braces = 1024, + Parenthesis = 2048, + AngleBrackets = 4096, + SquareBrackets = 8192, + BracketsMask = 15360, + OptionalIfUndefined = 16384, + OptionalIfEmpty = 32768, + Optional = 49152, + PreferNewLine = 65536, + NoTrailingNewLine = 131072, + NoInterveningComments = 262144, + NoSpaceIfEmpty = 524288, + SingleElement = 1048576, + Modifiers = 262656, + HeritageClauses = 512, + SingleLineTypeLiteralMembers = 768, + MultiLineTypeLiteralMembers = 32897, + TupleTypeElements = 528, + UnionTypeConstituents = 516, + IntersectionTypeConstituents = 520, + ObjectBindingPatternElements = 525136, + ArrayBindingPatternElements = 524880, + ObjectLiteralExpressionProperties = 526226, + ArrayLiteralExpressionElements = 8914, + CommaListElements = 528, + CallExpressionArguments = 2576, + NewExpressionArguments = 18960, + TemplateExpressionSpans = 262144, + SingleLineBlockStatements = 768, + MultiLineBlockStatements = 129, + VariableDeclarationList = 528, + SingleLineFunctionBodyStatements = 768, MultiLineFunctionBodyStatements = 1, ClassHeritageClauses = 0, - ClassMembers = 65, - InterfaceMembers = 65, - EnumMembers = 81, - CaseBlockClauses = 65, - NamedImportsOrExportsElements = 262576, - JsxElementOrFragmentChildren = 131072, - JsxElementAttributes = 131328, - CaseOrDefaultClauseStatements = 81985, - HeritageClauseTypes = 272, - SourceFileStatements = 65537, - Decorators = 24577, - TypeArguments = 26896, - TypeParameters = 26896, - Parameters = 1296, - IndexSignatureParameters = 4432 + ClassMembers = 129, + InterfaceMembers = 129, + EnumMembers = 145, + CaseBlockClauses = 129, + NamedImportsOrExportsElements = 525136, + JsxElementOrFragmentChildren = 262144, + JsxElementAttributes = 262656, + CaseOrDefaultClauseStatements = 163969, + HeritageClauseTypes = 528, + SourceFileStatements = 131073, + Decorators = 49153, + TypeArguments = 53776, + TypeParameters = 53776, + Parameters = 2576, + IndexSignatureParameters = 8848, + JSDocComment = 33 + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } + /** Represents a bigint literal value without requiring bigint support */ + interface PseudoBigInt { + negative: boolean; + base10Value: string; } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; @@ -3114,10 +3132,9 @@ declare namespace ts { function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } -/** Non-internal stuff goes here */ declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray; } declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; @@ -3209,17 +3226,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -3273,6 +3300,7 @@ declare namespace ts { } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; + function isBigIntLiteral(node: Node): node is BigIntLiteral; function isStringLiteral(node: Node): node is StringLiteral; function isJsxText(node: Node): node is JsxText; function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; @@ -3450,6 +3478,7 @@ declare namespace ts { type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail; function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; + function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier; function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; function isModifier(node: Node): node is Modifier; function isEntityName(node: Node): node is EntityName; @@ -3592,7 +3621,7 @@ declare namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -3607,14 +3636,14 @@ declare namespace ts { * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string): Map; + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ interface NonRelativeModuleNameResolutionCache { - getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; + getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; @@ -3622,18 +3651,19 @@ declare namespace ts { } function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; } declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; - function createLiteral(value: number): NumericLiteral; + function createLiteral(value: number | PseudoBigInt): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; - function createLiteral(value: string | number | boolean): PrimaryExpression; + function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; + function createBigIntLiteral(value: string): BigIntLiteral; function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; function createIdentifier(text: string): Identifier; @@ -4134,7 +4164,7 @@ declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; interface FormatDiagnosticsHost { getCurrentDirectory(): string; getCanonicalFileName(fileName: string): string; @@ -4171,14 +4201,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4334,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4358,17 +4400,9 @@ declare namespace ts { /** If provided is used to get the environment variable */ getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } /** * Host to create watch with root files and options @@ -4378,6 +4412,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4448,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,193 +4459,17 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; type EventInitializationFailed = "event::initializationFailed"; - interface SortedReadonlyArray extends ReadonlyArray { - " __sortedArrayBrand": any; - } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4807,9 +4667,9 @@ declare namespace ts { realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. @@ -4817,15 +4677,11 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; + writeFile?(fileName: string, content: string): void; } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; - } + type WithMetadata = T & { + metadata?: unknown; + }; interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; @@ -4843,7 +4699,7 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; @@ -4851,16 +4707,16 @@ declare namespace ts { getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getNavigationTree(fileName: string): NavigationTree; @@ -4882,9 +4738,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5012,7 +4868,7 @@ declare namespace ts { message: string; position: number; } - class TextChange { + interface TextChange { span: TextSpan; newText: string; } @@ -5046,9 +4902,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5114,6 +4977,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5191,24 +5056,25 @@ declare namespace ts { insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter?: boolean; - insertSpaceAfterSemicolonInForStatements?: boolean; - insertSpaceBeforeAndAfterBinaryOperators?: boolean; - insertSpaceAfterConstructor?: boolean; - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - insertSpaceAfterTypeAssertion?: boolean; - insertSpaceBeforeFunctionParenthesis?: boolean; - placeOpenBraceOnNewLineForFunctions?: boolean; - placeOpenBraceOnNewLineForControlBlocks?: boolean; - insertSpaceBeforeTypeAnnotation?: boolean; - indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + readonly insertSpaceAfterCommaDelimiter?: boolean; + readonly insertSpaceAfterSemicolonInForStatements?: boolean; + readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; + readonly insertSpaceAfterConstructor?: boolean; + readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + readonly insertSpaceAfterTypeAssertion?: boolean; + readonly insertSpaceBeforeFunctionParenthesis?: boolean; + readonly placeOpenBraceOnNewLineForFunctions?: boolean; + readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; + readonly insertSpaceBeforeTypeAnnotation?: boolean; + readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } + function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; @@ -5266,15 +5132,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; @@ -5392,8 +5267,9 @@ declare namespace ts { Whitespace = 4, Identifier = 5, NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8 + BigIntLiteral = 7, + StringLiteral = 8, + RegExpLiteral = 9 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -5505,13 +5381,20 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional" + optionalModifier = "optional", + dtsModifier = ".d.ts", + tsModifier = ".ts", + tsxModifier = ".tsx", + jsModifier = ".js", + jsxModifier = ".jsx", + jsonModifier = ".json" } enum ClassificationTypeNames { comment = "comment", identifier = "identifier", keyword = "keyword", numericLiteral = "number", + bigintLiteral = "bigint", operator = "operator", stringLiteral = "string", whiteSpace = "whitespace", @@ -5556,7 +5439,8 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24 + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 } } declare namespace ts { @@ -5648,6 +5532,10 @@ declare namespace ts { function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; } +declare namespace ts { + function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string; + function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string; +} declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; diff --git a/lib/typescript.js b/lib/typescript.js index 78365f95075..25e193cff42 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -62,7 +62,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -73,7 +73,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -88,6 +88,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -477,10 +478,33 @@ var ts; return result; } ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ function flatMap(array, mapfn) { var result; if (array) { - result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { for (var i = 0; i < array.length; i++) { var v = mapfn(array[i], i); if (v) { @@ -495,7 +519,7 @@ var ts; } return result; } - ts.flatMap = flatMap; + ts.flatMapToMutable = flatMapToMutable; function flatMapIterator(iter, mapfn) { var first = iter.next(); if (first.done) { @@ -716,19 +740,25 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) - return []; + return ts.emptyArray; var last = array[0]; var deduplicated = [last]; for (var i = 1; i < array.length; i++) { @@ -759,7 +789,7 @@ var ts; } ts.insertSorted = insertSorted; function sortAndDeduplicate(array, comparer, equalityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); } ts.sortAndDeduplicate = sortAndDeduplicate; function arrayIsEqualTo(array1, array2, equalityComparer) { @@ -771,7 +801,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -912,7 +942,7 @@ var ts; * Returns a new sorted array. */ function sort(array, comparer) { - return array.slice().sort(comparer); + return (array.length === 0 ? array : array.slice().sort(comparer)); } ts.sort = sort; function arrayIterator(array) { @@ -1018,12 +1048,25 @@ var ts; * @param offset An offset into `array` at which to start the search. */ function binarySearch(array, value, keySelector, keyComparer, offset) { - if (!array || array.length === 0) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { return -1; } var low = offset || 0; var high = array.length - 1; - var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); var midKey = keySelector(array[middle]); @@ -1040,7 +1083,7 @@ var ts; } return ~low; } - ts.binarySearch = binarySearch; + ts.binarySearchKey = binarySearchKey; function reduceLeft(array, f, initial, start, count) { if (array && array.length > 0) { var size = array.length; @@ -1148,7 +1191,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1311,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1432,7 +1479,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1935,6 +1984,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -1954,6 +2007,33 @@ var ts; var counts; var marks; var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; /** * Marks a performance event. * @@ -2029,6 +2109,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2048,368 +2488,370 @@ var ts; SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; // Literals SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; - SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; - SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; // Pseudo-literals - SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; + SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail"; // Punctuation - SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken"; // Assignments - SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken"; // Identifiers - SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; + SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier"; // Reserved words - SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword"; // Strict mode reserved words - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword"; // Contextual keywords - SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; - SyntaxKind[SyntaxKind["InferKeyword"] = 126] = "InferKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 127] = "IsKeyword"; - SyntaxKind[SyntaxKind["KeyOfKeyword"] = 128] = "KeyOfKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 129] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 130] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 131] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 132] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 133] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 134] = "NumberKeyword"; - SyntaxKind[SyntaxKind["ObjectKeyword"] = 135] = "ObjectKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 136] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 137] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 138] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword"; - SyntaxKind[SyntaxKind["UnknownKeyword"] = 142] = "UnknownKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 143] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 144] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 145] = "OfKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 146] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 147] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 148] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 149] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 150] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 151] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 152] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 153] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 154] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 155] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 156] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 157] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 158] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 159] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 160] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 161] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 162] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 163] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 164] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 165] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 166] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 167] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 168] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 169] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 170] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 171] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 172] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 173] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 174] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 175] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 176] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 177] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 178] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 179] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 180] = "LiteralType"; - SyntaxKind[SyntaxKind["ImportType"] = 181] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 182] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 183] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 184] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 185] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 186] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 187] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 188] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 189] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 190] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 191] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 192] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 193] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 194] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 195] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 196] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 197] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 198] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 199] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 200] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 201] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 202] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 203] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 204] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 205] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 206] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 207] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 208] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 209] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 210] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 211] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 212] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 213] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 214] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 215] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 216] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 217] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 218] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 219] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 220] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 221] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 222] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 223] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 224] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 225] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 226] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 227] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 228] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 229] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 230] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 231] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 232] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 233] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 234] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 235] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 236] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 237] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 238] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 239] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 240] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 241] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 242] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 243] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 244] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 245] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 246] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 247] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 248] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 249] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 250] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 251] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 252] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 253] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 254] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 255] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 256] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 218] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 257] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 258] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 259] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 260] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 261] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 262] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 263] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 264] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 265] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 266] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 267] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 268] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 269] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 270] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 271] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 272] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 273] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 274] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 275] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 276] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 277] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 278] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 279] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 280] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 281] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 282] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 283] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 284] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 285] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 286] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 287] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 288] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 289] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 290] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 291] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 292] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 310] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; // Markers - SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 145] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 161] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 181] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 145] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode"; - /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -2609,7 +3051,10 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; + // Errors (cont.) + NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors"; // State NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; @@ -2665,6 +3110,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2696,14 +3143,15 @@ var ts; // of a type, such as the global `Promise` type in lib.d.ts). TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; // with call signatures. - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var SymbolFlags; (function (SymbolFlags) { @@ -2734,38 +3182,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2840,14 +3288,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2857,29 +3306,27 @@ var ts; TypeFlags[TypeFlags["Number"] = 8] = "Number"; TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 64] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 128] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 256] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 512] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 1024] = "ESSymbol"; - TypeFlags[TypeFlags["UniqueESSymbol"] = 2048] = "UniqueESSymbol"; - TypeFlags[TypeFlags["Void"] = 4096] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 8192] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 16384] = "Null"; - TypeFlags[TypeFlags["Never"] = 32768] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 65536] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 131072] = "Object"; - TypeFlags[TypeFlags["Union"] = 262144] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 524288] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 1048576] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 2097152] = "IndexedAccess"; - TypeFlags[TypeFlags["Conditional"] = 4194304] = "Conditional"; - TypeFlags[TypeFlags["Substitution"] = 8388608] = "Substitution"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; - /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; - /* @internal */ - TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes"; + TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt"; + TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 16384] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 65536] = "Null"; + TypeFlags[TypeFlags["Never"] = 131072] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 524288] = "Object"; + TypeFlags[TypeFlags["Union"] = 1048576] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 4194304] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; /* @internal */ TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ @@ -2889,40 +3336,41 @@ var ts; /* @internal */ TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 24576] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 448] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 27072] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 192] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 2944] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 2240] = "StringOrNumberLiteralOrUnique"; + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 29120] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 29148] = "PossiblyFalsy"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 16839967] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 32764] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 68] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 168] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 272] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 544] = "EnumLike"; - TypeFlags[TypeFlags["ESSymbolLike"] = 3072] = "ESSymbolLike"; - TypeFlags[TypeFlags["VoidLike"] = 12288] = "VoidLike"; + TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike"; + TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; /* @internal */ - TypeFlags[TypeFlags["DisjointDomains"] = 16809468] = "DisjointDomains"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 786432] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 917504] = "StructuredType"; - TypeFlags[TypeFlags["TypeVariable"] = 2162688] = "TypeVariable"; - TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 14745600] = "InstantiableNonPrimitive"; - TypeFlags[TypeFlags["InstantiablePrimitive"] = 1048576] = "InstantiablePrimitive"; - TypeFlags[TypeFlags["Instantiable"] = 15794176] = "Instantiable"; - TypeFlags[TypeFlags["StructuredOrInstantiable"] = 16711680] = "StructuredOrInstantiable"; + TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion"; + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ @@ -2957,6 +3405,7 @@ var ts; ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -2968,6 +3417,13 @@ var ts; Variance[Variance["Bivariant"] = 3] = "Bivariant"; Variance[Variance["Independent"] = 4] = "Independent"; })(Variance = ts.Variance || (ts.Variance = {})); + /* @internal */ + var JsxReferenceKind; + (function (JsxReferenceKind) { + JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component"; + JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function"; + JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed"; + })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {})); var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; @@ -2993,9 +3449,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3469,31 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue"; + // Object.defineProperty(exports || module.exports, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports"; + // Object.defineProperty(Foo.prototype, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3266,25 +3730,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3303,25 +3763,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3401,6 +3860,7 @@ var ts; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; + EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); var ListFormat; (function (ListFormat) { @@ -3415,64 +3875,66 @@ var ts; ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma"; // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + ListFormat[ListFormat["Indented"] = 128] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings"; // Brackets/Braces - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + ListFormat[ListFormat["Braces"] = 1024] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 49152] = "Optional"; // Other - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; + ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters"; + ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment"; })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); /* @internal */ var PragmaKindFlags; @@ -3565,20 +4027,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3796,17 +4244,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4127,11 +4579,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4742,7 +5195,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5234,11 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4793,7 +5251,7 @@ var ts; An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), - An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), @@ -4837,14 +5295,14 @@ var ts; Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), @@ -4900,7 +5358,7 @@ var ts; Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), - A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), @@ -4983,7 +5441,7 @@ var ts; _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), - Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), @@ -5014,7 +5472,7 @@ var ts; Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), @@ -5024,7 +5482,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5509,15 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5609,15 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5731,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5827,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5925,18 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5967,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5488,6 +5977,7 @@ var ts; _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), @@ -5515,6 +6005,15 @@ var ts; If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5545,6 +6044,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5609,6 +6109,7 @@ var ts; Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -5673,150 +6174,108 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { - return token >= 71 /* Identifier */; + return token >= 72 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; /* @internal */ function tokenIsIdentifierOrKeywordOrGreaterThan(token) { - return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 118 /* AbstractKeyword */, + any: 120 /* AnyKeyword */, + as: 119 /* AsKeyword */, + bigint: 146 /* BigIntKeyword */, + boolean: 123 /* BooleanKeyword */, + break: 73 /* BreakKeyword */, + case: 74 /* CaseKeyword */, + catch: 75 /* CatchKeyword */, + class: 76 /* ClassKeyword */, + continue: 78 /* ContinueKeyword */, + const: 77 /* ConstKeyword */ + }, + _a["" + "constructor"] = 124 /* ConstructorKeyword */, + _a.debugger = 79 /* DebuggerKeyword */, + _a.declare = 125 /* DeclareKeyword */, + _a.default = 80 /* DefaultKeyword */, + _a.delete = 81 /* DeleteKeyword */, + _a.do = 82 /* DoKeyword */, + _a.else = 83 /* ElseKeyword */, + _a.enum = 84 /* EnumKeyword */, + _a.export = 85 /* ExportKeyword */, + _a.extends = 86 /* ExtendsKeyword */, + _a.false = 87 /* FalseKeyword */, + _a.finally = 88 /* FinallyKeyword */, + _a.for = 89 /* ForKeyword */, + _a.from = 144 /* FromKeyword */, + _a.function = 90 /* FunctionKeyword */, + _a.get = 126 /* GetKeyword */, + _a.if = 91 /* IfKeyword */, + _a.implements = 109 /* ImplementsKeyword */, + _a.import = 92 /* ImportKeyword */, + _a.in = 93 /* InKeyword */, + _a.infer = 127 /* InferKeyword */, + _a.instanceof = 94 /* InstanceOfKeyword */, + _a.interface = 110 /* InterfaceKeyword */, + _a.is = 128 /* IsKeyword */, + _a.keyof = 129 /* KeyOfKeyword */, + _a.let = 111 /* LetKeyword */, + _a.module = 130 /* ModuleKeyword */, + _a.namespace = 131 /* NamespaceKeyword */, + _a.never = 132 /* NeverKeyword */, + _a.new = 95 /* NewKeyword */, + _a.null = 96 /* NullKeyword */, + _a.number = 135 /* NumberKeyword */, + _a.object = 136 /* ObjectKeyword */, + _a.package = 112 /* PackageKeyword */, + _a.private = 113 /* PrivateKeyword */, + _a.protected = 114 /* ProtectedKeyword */, + _a.public = 115 /* PublicKeyword */, + _a.readonly = 133 /* ReadonlyKeyword */, + _a.require = 134 /* RequireKeyword */, + _a.global = 145 /* GlobalKeyword */, + _a.return = 97 /* ReturnKeyword */, + _a.set = 137 /* SetKeyword */, + _a.static = 116 /* StaticKeyword */, + _a.string = 138 /* StringKeyword */, + _a.super = 98 /* SuperKeyword */, + _a.switch = 99 /* SwitchKeyword */, + _a.symbol = 139 /* SymbolKeyword */, + _a.this = 100 /* ThisKeyword */, + _a.throw = 101 /* ThrowKeyword */, + _a.true = 102 /* TrueKeyword */, + _a.try = 103 /* TryKeyword */, + _a.type = 140 /* TypeKeyword */, + _a.typeof = 104 /* TypeOfKeyword */, + _a.undefined = 141 /* UndefinedKeyword */, + _a.unique = 142 /* UniqueKeyword */, + _a.unknown = 143 /* UnknownKeyword */, + _a.var = 105 /* VarKeyword */, + _a.void = 106 /* VoidKeyword */, + _a.while = 107 /* WhileKeyword */, + _a.with = 108 /* WithKeyword */, + _a.yield = 117 /* YieldKeyword */, + _a.async = 121 /* AsyncKeyword */, + _a.await = 122 /* AwaitKeyword */, + _a.of = 147 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, ">": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -5951,11 +6410,28 @@ var ts; } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { - ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } } var res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } if (line < lineStarts.length - 1) { ts.Debug.assert(res < lineStarts[line + 1]); } @@ -6394,6 +6870,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6404,8 +6881,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, - isIdentifier: function () { return token === 71 /* Identifier */ || token > 107 /* LastReservedWord */; }, - isReservedWord: function () { return token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */; }, + isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; }, isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, @@ -6423,6 +6900,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6498,18 +6976,29 @@ var ts; end = pos; } } + var result; if (tokenFlags & 512 /* ContainsSeparator */) { - var result = mainFragment; + result = mainFragment; if (decimalFragment) { result += "." + decimalFragment; } if (scientificFragment) { result += scientificFragment; } - return "" + +result; } else { - return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + return { + type: 8 /* NumericLiteral */, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type: type, value: tokenValue }; } } function scanOctalDigits() { @@ -6524,21 +7013,21 @@ var ts; * returning -1 if the given number is unavailable. */ function scanExactNumberOfHexDigits(count, canHaveSeparators) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; } /** * Scans as many hexadecimal digits as are available in the text, - * returning -1 if the given number of digits was unavailable. + * returning "" if the given number of digits was unavailable. */ function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { - var digits = 0; - var value = 0; + var valueChars = []; var allowSeparator = false; var isPreviousTokenSeparator = false; - while (digits < minCount || scanAsManyAsPossible) { + while (valueChars.length < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); if (canHaveSeparators && ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; @@ -6556,29 +7045,24 @@ var ts; continue; } allowSeparator = canHaveSeparators; - if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { - value = value * 16 + ch - 48 /* _0 */; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase } - else if (ch >= 65 /* A */ && ch <= 70 /* F */) { - value = value * 16 + ch - 65 /* A */ + 10; - } - else if (ch >= 97 /* a */ && ch <= 102 /* f */) { - value = value * 16 + ch - 97 /* a */ + 10; - } - else { + else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) || + (ch >= 97 /* a */ && ch <= 102 /* f */))) { break; } + valueChars.push(ch); pos++; - digits++; isPreviousTokenSeparator = false; } - if (digits < minCount) { - value = -1; + if (valueChars.length < minCount) { + valueChars = []; } if (text.charCodeAt(pos - 1) === 95 /* _ */) { error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } - return value; + return String.fromCharCode.apply(String, valueChars); } function scanString(jsxAttributeString) { if (jsxAttributeString === void 0) { jsxAttributeString = false; } @@ -6630,7 +7114,7 @@ var ts; contents += text.substring(start, pos); tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; break; } var currChar = text.charCodeAt(pos); @@ -6638,14 +7122,14 @@ var ts; if (currChar === 96 /* backtick */) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; break; } // '${' if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 14 /* TemplateHead */ : 15 /* TemplateMiddle */; + resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */; break; } // Escape character @@ -6738,7 +7222,8 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; var isInvalidExtendedEscape = false; // Validate the value of the digit if (escapedValue < 0) { @@ -6820,20 +7305,18 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } - return token = 71 /* Identifier */; + return token = 72 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); - var value = 0; + var value = ""; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. - var numberOfDigits = 0; var separatorAllowed = false; var isPreviousTokenSeparator = false; while (true) { @@ -6855,29 +7338,45 @@ var ts; continue; } separatorAllowed = true; - var valueOfCh = ch - 48 /* _0 */; - if (!isDigit(ch) || valueOfCh >= base) { + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { break; } - value = value * base + valueOfCh; + value += text[pos]; pos++; - numberOfDigits++; isPreviousTokenSeparator = false; } - // Invalid binaryIntegerLiteral or octalIntegerLiteral - if (numberOfDigits === 0) { - return -1; - } if (text.charCodeAt(pos - 1) === 95 /* _ */) { // Literal ends with underscore - not allowed error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); - return value; } return value; } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110 /* n */) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9 /* BigIntLiteral */; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + var numericValue = tokenFlags & 128 /* BinarySpecifier */ + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & 256 /* OctalSpecifier */ + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return 8 /* NumericLiteral */; + } + } function scan() { + var _a; startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7415,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6929,82 +7446,87 @@ var ts; case 33 /* exclamation */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 35 /* ExclamationEqualsEqualsToken */; + return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */; } - return pos += 2, token = 33 /* ExclamationEqualsToken */; + return pos += 2, token = 34 /* ExclamationEqualsToken */; } pos++; - return token = 51 /* ExclamationToken */; + return token = 52 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); - return token = 9 /* StringLiteral */; + return token = 10 /* StringLiteral */; case 96 /* backtick */: return token = scanTemplateAndSetTokenValue(); case 37 /* percent */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 64 /* PercentEqualsToken */; + return pos += 2, token = 65 /* PercentEqualsToken */; } pos++; - return token = 42 /* PercentToken */; + return token = 43 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { - return pos += 2, token = 53 /* AmpersandAmpersandToken */; + return pos += 2, token = 54 /* AmpersandAmpersandToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 68 /* AmpersandEqualsToken */; + return pos += 2, token = 69 /* AmpersandEqualsToken */; } pos++; - return token = 48 /* AmpersandToken */; + return token = 49 /* AmpersandToken */; case 40 /* openParen */: pos++; - return token = 19 /* OpenParenToken */; + return token = 20 /* OpenParenToken */; case 41 /* closeParen */: pos++; - return token = 20 /* CloseParenToken */; + return token = 21 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 61 /* AsteriskEqualsToken */; + return pos += 2, token = 62 /* AsteriskEqualsToken */; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 62 /* AsteriskAsteriskEqualsToken */; + return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */; } - return pos += 2, token = 40 /* AsteriskAsteriskToken */; + return pos += 2, token = 41 /* AsteriskAsteriskToken */; } pos++; - return token = 39 /* AsteriskToken */; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } + return token = 40 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { - return pos += 2, token = 43 /* PlusPlusToken */; + return pos += 2, token = 44 /* PlusPlusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 59 /* PlusEqualsToken */; + return pos += 2, token = 60 /* PlusEqualsToken */; } pos++; - return token = 37 /* PlusToken */; + return token = 38 /* PlusToken */; case 44 /* comma */: pos++; - return token = 26 /* CommaToken */; + return token = 27 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { - return pos += 2, token = 44 /* MinusMinusToken */; + return pos += 2, token = 45 /* MinusMinusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 60 /* MinusEqualsToken */; + return pos += 2, token = 61 /* MinusEqualsToken */; } pos++; - return token = 38 /* MinusToken */; + return token = 39 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber(); + tokenValue = scanNumber().value; return token = 8 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { - return pos += 3, token = 24 /* DotDotDotToken */; + return pos += 3, token = 25 /* DotDotDotToken */; } pos++; - return token = 23 /* DotToken */; + return token = 24 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -7055,43 +7577,43 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 63 /* SlashEqualsToken */; + return pos += 2, token = 64 /* SlashEqualsToken */; } pos++; - return token = 41 /* SlashToken */; + return token = 42 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); - if (value < 0) { + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { error(ts.Diagnostics.Hexadecimal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0x" + tokenValue; tokenFlags |= 64 /* HexSpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 2); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { error(ts.Diagnostics.Binary_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0b" + tokenValue; tokenFlags |= 128 /* BinarySpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 8); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { error(ts.Diagnostics.Octal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0o" + tokenValue; tokenFlags |= 256 /* OctalSpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } // Try to parse as an octal if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { @@ -7112,14 +7634,14 @@ var ts; case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - tokenValue = scanNumber(); - return token = 8 /* NumericLiteral */; + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; case 58 /* colon */: pos++; - return token = 56 /* ColonToken */; + return token = 57 /* ColonToken */; case 59 /* semicolon */: pos++; - return token = 25 /* SemicolonToken */; + return token = 26 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7132,20 +7654,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 65 /* LessThanLessThanEqualsToken */; + return pos += 3, token = 66 /* LessThanLessThanEqualsToken */; } - return pos += 2, token = 45 /* LessThanLessThanToken */; + return pos += 2, token = 46 /* LessThanLessThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 30 /* LessThanEqualsToken */; + return pos += 2, token = 31 /* LessThanEqualsToken */; } if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */) { - return pos += 2, token = 28 /* LessThanSlashToken */; + return pos += 2, token = 29 /* LessThanSlashToken */; } pos++; - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7158,15 +7680,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 34 /* EqualsEqualsEqualsToken */; + return pos += 3, token = 35 /* EqualsEqualsEqualsToken */; } - return pos += 2, token = 32 /* EqualsEqualsToken */; + return pos += 2, token = 33 /* EqualsEqualsToken */; } if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { - return pos += 2, token = 36 /* EqualsGreaterThanToken */; + return pos += 2, token = 37 /* EqualsGreaterThanToken */; } pos++; - return token = 58 /* EqualsToken */; + return token = 59 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7178,25 +7700,25 @@ var ts; } } pos++; - return token = 29 /* GreaterThanToken */; + return token = 30 /* GreaterThanToken */; case 63 /* question */: pos++; - return token = 55 /* QuestionToken */; + return token = 56 /* QuestionToken */; case 91 /* openBracket */: pos++; - return token = 21 /* OpenBracketToken */; + return token = 22 /* OpenBracketToken */; case 93 /* closeBracket */: pos++; - return token = 22 /* CloseBracketToken */; + return token = 23 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 70 /* CaretEqualsToken */; + return pos += 2, token = 71 /* CaretEqualsToken */; } pos++; - return token = 50 /* CaretToken */; + return token = 51 /* CaretToken */; case 123 /* openBrace */: pos++; - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; case 124 /* bar */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7208,22 +7730,22 @@ var ts; } } if (text.charCodeAt(pos + 1) === 124 /* bar */) { - return pos += 2, token = 54 /* BarBarToken */; + return pos += 2, token = 55 /* BarBarToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 69 /* BarEqualsToken */; + return pos += 2, token = 70 /* BarEqualsToken */; } pos++; - return token = 49 /* BarToken */; + return token = 50 /* BarToken */; case 125 /* closeBrace */: pos++; - return token = 18 /* CloseBraceToken */; + return token = 19 /* CloseBraceToken */; case 126 /* tilde */: pos++; - return token = 52 /* TildeToken */; + return token = 53 /* TildeToken */; case 64 /* at */: pos++; - return token = 57 /* AtToken */; + return token = 58 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -7261,29 +7783,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 29 /* GreaterThanToken */) { + if (token === 30 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } - return pos += 2, token = 47 /* GreaterThanGreaterThanGreaterThanToken */; + return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 66 /* GreaterThanGreaterThanEqualsToken */; + return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */; } pos++; - return token = 46 /* GreaterThanGreaterThanToken */; + return token = 47 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { pos++; - return token = 31 /* GreaterThanEqualsToken */; + return token = 32 /* GreaterThanEqualsToken */; } } return token; } function reScanSlashToken() { - if (token === 41 /* SlashToken */ || token === 63 /* SlashEqualsToken */) { + if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -7328,7 +7850,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12 /* RegularExpressionLiteral */; + token = 13 /* RegularExpressionLiteral */; } return token; } @@ -7336,7 +7858,7 @@ var ts; * Unconditionally back up and scan a template expression portion. */ function reScanTemplateToken() { - ts.Debug.assert(token === 18 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -7353,14 +7875,14 @@ var ts; if (char === 60 /* lessThan */) { if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; - return token = 28 /* LessThanSlashToken */; + return token = 29 /* LessThanSlashToken */; } pos++; - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; } if (char === 123 /* openBrace */) { pos++; - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; } // First non-whitespace character on this line. var firstNonWhitespace = 0; @@ -7392,7 +7914,7 @@ var ts; } pos++; } - return firstNonWhitespace === -1 ? 11 /* JsxTextAllWhiteSpaces */ : 10 /* JsxText */; + return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -7418,7 +7940,7 @@ var ts; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(/*jsxAttributeString*/ true); - return token = 9 /* StringLiteral */; + return token = 10 /* StringLiteral */; default: // If this scans anything other than `{`, it's a parse error. return scan(); @@ -7442,43 +7964,43 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - return token = 57 /* AtToken */; + return token = 58 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - return token = 39 /* AsteriskToken */; + return token = 40 /* AsteriskToken */; case 123 /* openBrace */: - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; case 125 /* closeBrace */: - return token = 18 /* CloseBraceToken */; + return token = 19 /* CloseBraceToken */; case 91 /* openBracket */: - return token = 21 /* OpenBracketToken */; + return token = 22 /* OpenBracketToken */; case 93 /* closeBracket */: - return token = 22 /* CloseBracketToken */; + return token = 23 /* CloseBracketToken */; case 60 /* lessThan */: - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; case 61 /* equals */: - return token = 58 /* EqualsToken */; + return token = 59 /* EqualsToken */; case 44 /* comma */: - return token = 26 /* CommaToken */; + return token = 27 /* CommaToken */; case 46 /* dot */: - return token = 23 /* DotToken */; + return token = 24 /* DotToken */; case 96 /* backtick */: while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { pos++; } tokenValue = text.substring(tokenPos + 1, pos); pos++; - return token = 13 /* NoSubstitutionTemplateLiteral */; + return token = 14 /* NoSubstitutionTemplateLiteral */; } if (isIdentifierStart(ch, 6 /* Latest */)) { while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7555,10 +8077,12 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); -/** Non-internal stuff goes here */ var ts; (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -7575,7 +8099,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7622,7 +8145,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -7631,7 +8153,9 @@ var ts; writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, - writeSymbol: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, getTextPos: function () { return str.length; }, getLine: function () { return 0; }, getColumn: function () { return 0; }, @@ -7657,22 +8181,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8288,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -7837,7 +8354,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 277 /* SourceFile */) { + while (node && node.kind !== 279 /* SourceFile */) { node = node.parent; } return node; @@ -7845,11 +8362,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 216 /* Block */: - case 244 /* CaseBlock */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return true; } return false; @@ -7983,7 +8500,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8001,12 +8518,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,35 +8558,37 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) || + ts.isBigIntLiteral(node))) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (node.singleQuote) { return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; } else { return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; } - case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return "`" + escapeText(node.text, 96 /* backtick */) + "`"; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: // tslint:disable-next-line no-invalid-template-strings return "`" + escapeText(node.text, 96 /* backtick */) + "${"; - case 15 /* TemplateMiddle */: + case 16 /* TemplateMiddle */: // tslint:disable-next-line no-invalid-template-strings return "}" + escapeText(node.text, 96 /* backtick */) + "${"; - case 16 /* TemplateTail */: + case 17 /* TemplateTail */: return "}" + escapeText(node.text, 96 /* backtick */) + "`"; case 8 /* NumericLiteral */: - case 12 /* RegularExpressionLiteral */: + case 9 /* BigIntLiteral */: + case 13 /* RegularExpressionLiteral */: return node.text; } return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -8084,15 +8611,15 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 235 /* VariableDeclaration */ && node.parent.kind === 272 /* CatchClause */; + return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { - return ts.isModuleDeclaration(node) && node.name.kind === 9 /* StringLiteral */; + return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */; } ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { @@ -8116,11 +8643,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 242 /* ModuleDeclaration */ && (!node.body); + return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 277 /* SourceFile */ || - node.kind === 242 /* ModuleDeclaration */ || + return node.kind === 279 /* SourceFile */ || + node.kind === 244 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -8137,9 +8664,9 @@ var ts; // - 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 switch (node.parent.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.isExternalModule(node.parent); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; @@ -8155,22 +8682,22 @@ var ts; ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 277 /* SourceFile */: - case 244 /* CaseBlock */: - case 272 /* CatchClause */: - case 242 /* ModuleDeclaration */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 274 /* CatchClause */: + case 244 /* ModuleDeclaration */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; - case 216 /* Block */: + case 218 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -8180,9 +8707,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: - case 291 /* JSDocSignature */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 293 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -8192,25 +8719,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 287 /* JSDocFunctionType */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; default: ts.assertType(node); @@ -8220,8 +8747,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: return true; default: return false; @@ -8230,15 +8757,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 217 /* VariableStatement */: - case 238 /* ClassDeclaration */: - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 219 /* VariableStatement */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: return true; default: return false; @@ -8268,12 +8795,13 @@ var ts; ts.getNameFromIndexInfo = getNameFromIndexInfo; function getTextOfPropertyName(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return name.escapedText; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: return ts.Debug.assertNever(name); @@ -8282,11 +8810,11 @@ var ts; ts.getTextOfPropertyName = getTextOfPropertyName; function entityNameToString(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); default: throw ts.Debug.assertNever(name); @@ -8331,7 +8859,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 216 /* Block */) { + if (node.body && node.body.kind === 218 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -8345,7 +8873,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* 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 @@ -8354,25 +8882,25 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 240 /* TypeAliasDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: errorNode = node.name; break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -8408,6 +8936,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8417,11 +8949,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 189 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; + return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 189 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { @@ -8429,20 +8961,20 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 219 /* ExpressionStatement */ - && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 221 /* ExpressionStatement */ + && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return node.kind !== 10 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 149 /* Parameter */ || - node.kind === 148 /* TypeParameter */ || - node.kind === 194 /* FunctionExpression */ || - node.kind === 195 /* ArrowFunction */ || - node.kind === 193 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 151 /* Parameter */ || + node.kind === 150 /* TypeParameter */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 197 /* ArrowFunction */ || + node.kind === 195 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -8458,46 +8990,48 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 181 /* LastTypeNode */) { + if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) { return true; } switch (node.kind) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 134 /* NumberKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 140 /* UndefinedKeyword */: - case 131 /* NeverKeyword */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: return true; - case 105 /* VoidKeyword */: - return node.parent.kind !== 198 /* VoidExpression */; - case 209 /* ExpressionWithTypeArguments */: + case 106 /* VoidKeyword */: + return node.parent.kind !== 200 /* VoidExpression */; + case 211 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 148 /* TypeParameter */: - return node.parent.kind === 179 /* MappedType */ || node.parent.kind === 174 /* InferType */; + case 150 /* TypeParameter */: + return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container - case 71 /* Identifier */: + case 72 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 189 /* 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 === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 187 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 146 /* QualifiedName */: - case 187 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: { + case 148 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + case 100 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 165 /* TypeQuery */) { + if (parent.kind === 167 /* TypeQuery */) { return false; } - if (parent.kind === 181 /* ImportType */) { + if (parent.kind === 183 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -8506,40 +9040,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 181 /* LastTypeNode */) { + if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return node === parent.constraint; - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return node === parent.constraint; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 149 /* Parameter */: - case 235 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: return node === parent.type; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return node === parent.type; - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return node === parent.type; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return node === parent.type; - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -8564,23 +9098,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitor(node); - case 244 /* CaseBlock */: - case 216 /* Block */: - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 229 /* WithStatement */: - case 230 /* SwitchStatement */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 231 /* LabeledStatement */: - case 233 /* TryStatement */: - case 272 /* CatchClause */: + case 246 /* CaseBlock */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -8590,26 +9124,26 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 241 /* EnumDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* 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. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 147 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 149 /* 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(node.name.expression); @@ -8632,10 +9166,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 167 /* ArrayType */) { + if (node && node.kind === 169 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 162 /* TypeReference */) { + else if (node && node.kind === 164 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -8645,12 +9179,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 166 /* TypeLiteral */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 168 /* TypeLiteral */: return node.members; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return node.properties; } } @@ -8658,14 +9192,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 184 /* BindingElement */: - case 276 /* EnumMember */: - case 149 /* Parameter */: - case 273 /* PropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 274 /* ShorthandPropertyAssignment */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 278 /* EnumMember */: + case 151 /* Parameter */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 276 /* ShorthandPropertyAssignment */: + case 237 /* VariableDeclaration */: return true; } } @@ -8677,8 +9211,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 236 /* VariableDeclarationList */ - && node.parent.parent.kind === 217 /* VariableStatement */; + return node.parent.kind === 238 /* VariableDeclarationList */ + && node.parent.parent.kind === 219 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -8689,13 +9223,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return true; } return false; @@ -8706,7 +9240,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 231 /* LabeledStatement */) { + if (node.statement.kind !== 233 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -8714,17 +9248,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 216 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 186 /* ObjectLiteralExpression */; + return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 154 /* MethodDeclaration */ && - (node.parent.kind === 186 /* ObjectLiteralExpression */ || - node.parent.kind === 207 /* ClassExpression */); + return node.kind === 156 /* MethodDeclaration */ && + (node.parent.kind === 188 /* ObjectLiteralExpression */ || + node.parent.kind === 209 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -8737,7 +9271,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 273 /* PropertyAssignment */) { + if (property.kind === 275 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -8774,14 +9308,14 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 277 /* SourceFile */); + ts.Debug.assert(node.kind !== 279 /* SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* 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 @@ -8796,9 +9330,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8809,26 +9343,26 @@ var ts; node = node.parent; } break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 242 /* ModuleDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 241 /* EnumDeclaration */: - case 277 /* SourceFile */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 244 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 243 /* EnumDeclaration */: + case 279 /* SourceFile */: return node; } } @@ -8838,9 +9372,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return container; } } @@ -8862,27 +9396,27 @@ var ts; return node; } switch (node.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: node = node.parent; break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return node; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8898,14 +9432,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 194 /* FunctionExpression */ || func.kind === 195 /* ArrowFunction */) { + if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 193 /* ParenthesizedExpression */) { + while (parent.kind === 195 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 189 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -8916,8 +9450,8 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) - && node.expression.kind === 97 /* SuperKeyword */; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 98 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; /** @@ -8925,20 +9459,20 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) - && node.expression.kind === 99 /* ThisKeyword */; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 100 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; - case 71 /* Identifier */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 148 /* QualifiedName */: return node; } return undefined; @@ -8946,10 +9480,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return node.tag; - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -8958,25 +9492,25 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: // classes are valid targets return true; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 238 /* ClassDeclaration */; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: + return parent.kind === 240 /* ClassDeclaration */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 238 /* ClassDeclaration */; - case 149 /* Parameter */: + && parent.kind === 240 /* ClassDeclaration */; + case 151 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 155 /* Constructor */ - || parent.kind === 154 /* MethodDeclaration */ - || parent.kind === 157 /* SetAccessor */) - && grandparent.kind === 238 /* ClassDeclaration */; + && (parent.kind === 157 /* Constructor */ + || parent.kind === 156 /* MethodDeclaration */ + || parent.kind === 159 /* SetAccessor */) + && grandparent.kind === 240 /* ClassDeclaration */; } return false; } @@ -8992,10 +9526,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 154 /* MethodDeclaration */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 159 /* SetAccessor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -9004,9 +9538,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 260 /* JsxOpeningElement */ || - parent.kind === 259 /* JsxSelfClosingElement */ || - parent.kind === 261 /* JsxClosingElement */) { + if (parent.kind === 262 /* JsxOpeningElement */ || + parent.kind === 261 /* JsxSelfClosingElement */ || + parent.kind === 263 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -9014,56 +9548,57 @@ var ts; ts.isJSXTagName = isJSXTagName; function isExpressionNode(node) { switch (node.kind) { - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 12 /* RegularExpressionLiteral */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 191 /* TaggedTemplateExpression */: - case 210 /* AsExpression */: - case 192 /* TypeAssertionExpression */: - case 211 /* NonNullExpression */: - case 193 /* ParenthesizedExpression */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: - case 195 /* ArrowFunction */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: - case 202 /* BinaryExpression */: - case 203 /* ConditionalExpression */: - case 206 /* SpreadElement */: - case 204 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 208 /* OmittedExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 205 /* YieldExpression */: - case 199 /* AwaitExpression */: - case 212 /* MetaProperty */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 13 /* RegularExpressionLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 212 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 208 /* SpreadElement */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 210 /* OmittedExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 207 /* YieldExpression */: + case 201 /* AwaitExpression */: + case 214 /* MetaProperty */: return true; - case 146 /* QualifiedName */: - while (node.parent.kind === 146 /* QualifiedName */) { + case 148 /* QualifiedName */: + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node); - case 71 /* Identifier */: - if (node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node)) { + return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node); + case 72 /* Identifier */: + if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 99 /* ThisKeyword */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: return isInExpressionContext(node); default: return false; @@ -9073,49 +9608,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 276 /* EnumMember */: - case 273 /* PropertyAssignment */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 186 /* BindingElement */: return parent.initializer === node; - case 219 /* ExpressionStatement */: - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 228 /* ReturnStatement */: - case 229 /* WithStatement */: - case 230 /* SwitchStatement */: - case 269 /* CaseClause */: - case 232 /* ThrowStatement */: + case 221 /* ExpressionStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 230 /* ReturnStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 234 /* ThrowStatement */: return parent.expression === node; - case 223 /* ForStatement */: + case 225 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 236 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 236 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) || forInStatement.expression === node; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return node === parent.expression; - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return node === parent.expression; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return node === parent.expression; - case 150 /* Decorator */: - case 268 /* JsxExpression */: - case 267 /* JsxSpreadAttribute */: - case 275 /* SpreadAssignment */: + case 152 /* Decorator */: + case 270 /* JsxExpression */: + case 269 /* JsxSpreadAttribute */: + case 277 /* SpreadAssignment */: return true; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -9123,7 +9658,7 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */; + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -9132,21 +9667,21 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9160,15 +9695,15 @@ var ts; ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && - (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */); + (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { - if (callExpression.kind !== 189 /* CallExpression */) { + if (callExpression.kind !== 191 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 /* Identifier */ || expression.escapedText !== "require") { + if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") { return false; } if (args.length !== 1) { @@ -9186,29 +9721,29 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; decl = node.parent; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.right === node) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) { name = node.parent.left; decl = name; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54 /* BarBarToken */) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) { if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { name = node.parent.parent.name; decl = node.parent.parent; } - else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.parent.right === node.parent) { + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) { name = node.parent.parent.left; decl = name; } @@ -9216,42 +9751,55 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && - ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; } return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { - if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,47 +9808,47 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 194 /* FunctionExpression */ || - initializer.kind === 207 /* ClassExpression */ || - initializer.kind === 195 /* ArrowFunction */) { + if (initializer.kind === 196 /* FunctionExpression */ || + initializer.kind === 209 /* ClassExpression */ || + initializer.kind === 197 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : - ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { - var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; - if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) { return parent.left; } } @@ -9308,7 +9856,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9323,7 +9871,7 @@ var ts; return name.escapedText === initializer.escapedText; } if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { - return (initializer.expression.kind === 99 /* ThisKeyword */ || + return (initializer.expression.kind === 100 /* ThisKeyword */ || ts.isIdentifier(initializer.expression) && (initializer.expression.escapedText === "window" || initializer.expression.escapedText === "self" || @@ -9352,13 +9900,36 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { - if (expr.operatorToken.kind !== 58 /* EqualsToken */ || + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 59 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } @@ -9367,13 +9938,13 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { - if (lhs.expression.kind === 99 /* ThisKeyword */) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + else if (isModuleExportsPropertyAccessExpression(lhs)) { // module.exports = expr return 2 /* ModuleExports */; } @@ -9398,7 +9969,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,12 +9978,12 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && - expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; @@ -9421,7 +9992,7 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { @@ -9430,14 +10001,14 @@ var ts; ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return node.parent; - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return node.parent.parent; - case 189 /* CallExpression */: - return node.parent; - case 180 /* LiteralType */: + case 191 /* CallExpression */: + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; + case 182 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -9447,12 +10018,12 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return node.moduleSpecifier; - case 246 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 257 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 181 /* ImportType */: + case 248 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 183 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; default: return ts.Debug.assertNever(node); @@ -9461,11 +10032,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return undefined; default: return ts.Debug.assertNever(node); @@ -9473,19 +10044,19 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 247 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 149 /* Parameter */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 274 /* ShorthandPropertyAssignment */: - case 273 /* PropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 151 /* Parameter */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 276 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -9493,14 +10064,13 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 287 /* JSDocFunctionType */ && - node.parameters.length > 0 && - node.parameters[0].name && - node.parameters[0].name.escapedText === "new"; + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -9510,27 +10080,27 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 /* EqualsToken */ + node.expression.operatorToken.kind === 59 /* EqualsToken */ ? node.expression.right : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 /* BarBarToken */ + node.expression.right.operatorToken.kind === 55 /* BarBarToken */ ? node.expression.right.right : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return node.initializer; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return node.initializer; } } @@ -9540,7 +10110,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 242 /* ModuleDeclaration */ + node.body.kind === 244 /* ModuleDeclaration */ ? node.body : undefined; } @@ -9555,10 +10125,14 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.addRange(result, node.jsDoc); } - if (node.kind === 149 /* Parameter */) { + if (node.kind === 151 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 150 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9566,11 +10140,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 273 /* PropertyAssignment */ || - parent.kind === 152 /* PropertyDeclaration */ || - parent.kind === 219 /* ExpressionStatement */ && node.kind === 187 /* PropertyAccessExpression */ || + if (parent.kind === 275 /* PropertyAssignment */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ || getNestedModuleDeclaration(parent) || - ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */) { + ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) { return parent; } // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. @@ -9581,7 +10155,7 @@ var ts; // var x = function(name) { return name.length; } else if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node || - ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */)) { + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) { return parent.parent; } else if (parent.parent && parent.parent.parent && @@ -9604,7 +10178,7 @@ var ts; if (!decl) { return undefined; } - var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; @@ -9639,7 +10213,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 288 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9652,31 +10226,31 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? - binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; - return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 193 /* ParenthesizedExpression */: - case 185 /* ArrayLiteralExpression */: - case 206 /* SpreadElement */: - case 211 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 187 /* ArrayLiteralExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: node = parent; break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -9703,22 +10277,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 216 /* Block */: - case 217 /* VariableStatement */: - case 229 /* WithStatement */: - case 220 /* IfStatement */: - case 230 /* SwitchStatement */: - case 244 /* CaseBlock */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 231 /* LabeledStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 233 /* TryStatement */: - case 272 /* CatchClause */: + case 218 /* Block */: + case 219 /* VariableStatement */: + case 231 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: return true; } return false; @@ -9735,27 +10309,33 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 175 /* ParenthesizedType */); + return walkUp(node, 177 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 193 /* ParenthesizedExpression */); + return walkUp(node, 195 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function skipParentheses(node) { - while (node.kind === 193 /* ParenthesizedExpression */) { + while (node.kind === 195 /* ParenthesizedExpression */) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { + if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 196 /* DeleteExpression */; + return node && node.kind === 198 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -9773,35 +10353,39 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 72 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { - return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 147 /* ComputedPropertyName */ && + return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 149 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -9809,32 +10393,32 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 276 /* EnumMember */: - case 273 /* PropertyAssignment */: - case 187 /* PropertyAccessExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 189 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: // Name on right hand side of dot in a type query or type reference if (parent.right === node) { - while (parent.kind === 146 /* QualifiedName */) { + while (parent.kind === 148 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 165 /* TypeQuery */ || parent.kind === 162 /* TypeReference */; + return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */; } return false; - case 184 /* BindingElement */: - case 251 /* ImportSpecifier */: + case 186 /* BindingElement */: + case 253 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 255 /* ExportSpecifier */: - case 265 /* JsxAttribute */: + case 257 /* ExportSpecifier */: + case 267 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -9849,15 +10433,16 @@ var ts; // export { x as } from ... // export = // export default + // module.exports = function isAliasSymbolDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ || - node.kind === 245 /* NamespaceExportDeclaration */ || - node.kind === 248 /* ImportClause */ && !!node.name || - node.kind === 249 /* NamespaceImport */ || - node.kind === 251 /* ImportSpecifier */ || - node.kind === 255 /* ExportSpecifier */ || - node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + return node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + node.kind === 250 /* ImportClause */ && !!node.name || + node.kind === 251 /* NamespaceImport */ || + node.kind === 253 /* ImportSpecifier */ || + node.kind === 257 /* ExportSpecifier */ || + node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10451,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -9877,12 +10462,12 @@ var ts; } ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; function getClassExtendsHeritageElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; @@ -9894,7 +10479,7 @@ var ts; } ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -9928,11 +10513,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 72 /* FirstKeyword */ <= token && token <= 145 /* LastKeyword */; + return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 117 /* FirstContextualKeyword */ <= token && token <= 145 /* LastContextualKeyword */; + return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -9944,6 +10529,11 @@ var ts; return token !== undefined && isNonContextualKeyword(token); } ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; function isTrivia(token) { return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; } @@ -9962,14 +10552,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (hasModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -9983,10 +10573,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256 /* Async */); @@ -10011,7 +10601,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 147 /* ComputedPropertyName */ && + return name.kind === 149 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -10027,12 +10617,12 @@ var ts; ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return name.escapedText; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); @@ -10048,9 +10638,9 @@ var ts; ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: return true; default: @@ -10059,11 +10649,11 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? ts.idText(node) : node.text; + return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -10078,7 +10668,7 @@ var ts; * Includes the word "Symbol" with unicode escapes */ function isESSymbolIdentifier(node) { - return node.kind === 71 /* Identifier */ && node.escapedText === "Symbol"; + return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { @@ -10087,11 +10677,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 149 /* Parameter */; + return root.kind === 151 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 184 /* BindingElement */) { + while (node.kind === 186 /* BindingElement */) { node = node.parent.parent; } return node; @@ -10099,15 +10689,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 155 /* Constructor */ - || kind === 194 /* FunctionExpression */ - || kind === 237 /* FunctionDeclaration */ - || kind === 195 /* ArrowFunction */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 242 /* ModuleDeclaration */ - || kind === 277 /* SourceFile */; + return kind === 157 /* Constructor */ + || kind === 196 /* FunctionExpression */ + || kind === 239 /* FunctionDeclaration */ + || kind === 197 /* ArrowFunction */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 244 /* ModuleDeclaration */ + || kind === 279 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -10126,38 +10716,38 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 190 /* NewExpression */: + case 192 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 200 /* PrefixUnaryExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 199 /* AwaitExpression */: - case 203 /* ConditionalExpression */: - case 205 /* YieldExpression */: + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: return 1 /* Right */; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (operator) { - case 40 /* AsteriskAsteriskToken */: - case 58 /* EqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 69 /* BarEqualsToken */: + case 41 /* AsteriskAsteriskToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: return 1 /* Right */; } } @@ -10166,15 +10756,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 202 /* BinaryExpression */) { + if (expression.kind === 204 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 200 /* PrefixUnaryExpression */ || expression.kind === 201 /* PostfixUnaryExpression */) { + else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -10184,116 +10774,116 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return 0; - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return 1; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return 2; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return 4; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (operatorKind) { - case 26 /* CommaToken */: + case 27 /* CommaToken */: return 0; - case 58 /* EqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 69 /* BarEqualsToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: return 3; default: return getBinaryOperatorPrecedence(operatorKind); } - case 200 /* PrefixUnaryExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 199 /* AwaitExpression */: + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: return 16; - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return 17; - case 189 /* CallExpression */: + case 191 /* CallExpression */: return 18; - case 190 /* NewExpression */: + case 192 /* NewExpression */: return hasArguments ? 19 : 18; - case 191 /* TaggedTemplateExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 193 /* TaggedTemplateExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return 19; - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 71 /* Identifier */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 72 /* Identifier */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 207 /* ClassExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 193 /* ParenthesizedExpression */: - case 208 /* OmittedExpression */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 195 /* ParenthesizedExpression */: + case 210 /* OmittedExpression */: return 20; default: return -1; } } ts.getOperatorPrecedence = getOperatorPrecedence; - /* @internal */ function getBinaryOperatorPrecedence(kind) { switch (kind) { - case 54 /* BarBarToken */: + case 55 /* BarBarToken */: return 5; - case 53 /* AmpersandAmpersandToken */: + case 54 /* AmpersandAmpersandToken */: return 6; - case 49 /* BarToken */: + case 50 /* BarToken */: return 7; - case 50 /* CaretToken */: + case 51 /* CaretToken */: return 8; - case 48 /* AmpersandToken */: + case 49 /* AmpersandToken */: return 9; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: return 10; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: return 11; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return 12; - case 37 /* PlusToken */: - case 38 /* MinusToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: return 13; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: return 14; - case 40 /* AsteriskAsteriskToken */: + case 41 /* AsteriskAsteriskToken */: return 15; } // -1 is lower than all other precedences. Returning it will cause binary expression @@ -10361,7 +10951,7 @@ var ts; if (fileName) { return fileDiagnostics.get(fileName) || []; } - var fileDiags = ts.flatMap(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); if (!nonFileDiagnostics.length) { return fileDiags; } @@ -10419,7 +11009,7 @@ var ts; } function isIntrinsicJsxName(name) { var ch = name.charCodeAt(0); - return (ch >= 97 /* a */ && ch <= 122 /* z */) || name.indexOf("-") > -1; + return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-"); } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -10502,16 +11092,10 @@ var ts; lineStart = true; } } - function writeTextOfNode(text, node) { - var s = getTextOfNodeFromSourceText(text, node); - write(s); - updateLineCountAndPosFor(s); - } reset(); return { write: write, rawWrite: rawWrite, - writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, increaseIndent: function () { indent++; }, @@ -10534,10 +11118,77 @@ var ts; writePunctuation: write, writeSpace: write, writeStringLiteral: write, - writeSymbol: write + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write }; } ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; function getResolvedExternalModuleName(host, file, referenceFile) { return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } @@ -10600,7 +11251,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10614,7 +11265,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10673,11 +11324,11 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { - return id.originalKeywordKind === 99 /* ThisKeyword */; + return id.originalKeywordKind === 100 /* ThisKeyword */; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { @@ -10688,10 +11339,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 156 /* GetAccessor */) { + if (accessor.kind === 158 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 157 /* SetAccessor */) { + else if (accessor.kind === 159 /* SetAccessor */) { setAccessor = accessor; } else { @@ -10711,10 +11362,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 156 /* GetAccessor */ && !getAccessor) { + if (member.kind === 158 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 157 /* SetAccessor */ && !setAccessor) { + if (member.kind === 159 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -10735,7 +11386,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11402,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -10760,7 +11411,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 289 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -10794,13 +11445,13 @@ var ts; function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { if (comments && comments.length > 0) { if (leadingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } var emitInterveningSeparator = false; for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { var comment = comments_1[_i]; if (emitInterveningSeparator) { - writer.write(" "); + writer.writeSpace(" "); emitInterveningSeparator = false; } writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); @@ -10812,7 +11463,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -10930,7 +11581,7 @@ var ts; } else { // Single line comment of style //.... - writer.write(text.substring(commentPos, commentEnd)); + writer.writeComment(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; @@ -10939,14 +11590,14 @@ var ts; var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { // trimmed forward and ending spaces text - writer.write(currentLineText); + writer.writeComment(currentLineText); if (end !== commentEnd) { writer.writeLine(); } } else { // Empty string - make sure we write empty line - writer.writeLiteral(newLine); + writer.rawWrite(newLine); } } function calculateIndent(text, pos, end) { @@ -11000,7 +11651,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4 /* NestedNamespace */ || (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace)) { + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* Export */; } return flags; @@ -11008,44 +11659,49 @@ var ts; ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { - case 115 /* StaticKeyword */: return 32 /* Static */; - case 114 /* PublicKeyword */: return 4 /* Public */; - case 113 /* ProtectedKeyword */: return 16 /* Protected */; - case 112 /* PrivateKeyword */: return 8 /* Private */; - case 117 /* AbstractKeyword */: return 128 /* Abstract */; - case 84 /* ExportKeyword */: return 1 /* Export */; - case 124 /* DeclareKeyword */: return 2 /* Ambient */; - case 76 /* ConstKeyword */: return 2048 /* Const */; - case 79 /* DefaultKeyword */: return 512 /* Default */; - case 120 /* AsyncKeyword */: return 256 /* Async */; - case 132 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 116 /* StaticKeyword */: return 32 /* Static */; + case 115 /* PublicKeyword */: return 4 /* Public */; + case 114 /* ProtectedKeyword */: return 16 /* Protected */; + case 113 /* PrivateKeyword */: return 8 /* Private */; + case 118 /* AbstractKeyword */: return 128 /* Abstract */; + case 85 /* ExportKeyword */: return 1 /* Export */; + case 125 /* DeclareKeyword */: return 2 /* Ambient */; + case 77 /* ConstKeyword */: return 2048 /* Const */; + case 80 /* DefaultKeyword */: return 512 /* Default */; + case 121 /* AsyncKeyword */: return 256 /* Async */; + case 133 /* ReadonlyKeyword */: return 64 /* Readonly */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 54 /* BarBarToken */ - || token === 53 /* AmpersandAmpersandToken */ - || token === 51 /* ExclamationToken */; + return token === 55 /* BarBarToken */ + || token === 54 /* AmpersandAmpersandToken */ + || token === 52 /* ExclamationToken */; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 58 /* FirstAssignment */ && token <= 70 /* LastAssignment */; + return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment - ? node.operatorToken.kind === 58 /* EqualsToken */ + ? node.operatorToken.kind === 59 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) && ts.isLeftHandSideExpression(node.left); } @@ -11053,8 +11709,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 186 /* ObjectLiteralExpression */ - || kind === 185 /* ArrayLiteralExpression */; + return kind === 188 /* ObjectLiteralExpression */ + || kind === 187 /* ArrayLiteralExpression */; } return false; } @@ -11063,17 +11719,8 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; function isPropertyAccessEntityNameExpression(node) { @@ -11085,17 +11732,17 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 186 /* ObjectLiteralExpression */ && + return expression.kind === 188 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 185 /* ArrayLiteralExpression */ && + return expression.kind === 187 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -11107,10 +11754,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * 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. @@ -11249,6 +11896,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +12008,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11436,8 +12107,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -11514,23 +12185,47 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 201 /* PostfixUnaryExpression */: - case 200 /* PrefixUnaryExpression */: + case 195 /* ParenthesizedExpression */: + return accessKind(parent); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: var operator = parent.operator; - return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 202 /* BinaryExpression */: + return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 204 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? - operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 275 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 187 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11621,7 +12316,7 @@ var ts; } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { - return type.flags & 131072 /* Object */ ? type.objectFlags : 0; + return type.flags & 524288 /* Object */ ? type.objectFlags : 0; } ts.getObjectFlags = getObjectFlags; function typeHasCallOrConstructSignatures(type, checker) { @@ -11672,6 +12367,31 @@ var ts; return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) + || kind === 120 /* AnyKeyword */ + || kind === 143 /* UnknownKeyword */ + || kind === 135 /* NumberKeyword */ + || kind === 146 /* BigIntKeyword */ + || kind === 136 /* ObjectKeyword */ + || kind === 123 /* BooleanKeyword */ + || kind === 138 /* StringKeyword */ + || kind === 139 /* SymbolKeyword */ + || kind === 100 /* ThisKeyword */ + || kind === 106 /* VoidKeyword */ + || kind === 141 /* UndefinedKeyword */ + || kind === 96 /* NullKeyword */ + || kind === 132 /* NeverKeyword */ + || kind === 211 /* ExpressionWithTypeArguments */ + || kind === 284 /* JSDocAllType */ + || kind === 285 /* JSDocUnknownType */ + || kind === 286 /* JSDocNullableType */ + || kind === 287 /* JSDocNonNullableType */ + || kind === 288 /* JSDocOptionalType */ + || kind === 289 /* JSDocFunctionType */ + || kind === 290 /* JSDocVariadicType */; + } + ts.isTypeNodeKind = isTypeNodeKind; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11756,13 +12476,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -11899,9 +12612,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 148 /* TypeParameter */) { + if (d && d.kind === 150 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 239 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) { return current; } } @@ -11909,7 +12622,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 155 /* Constructor */; + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11939,14 +12652,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 235 /* VariableDeclaration */) { + if (node.kind === 237 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 236 /* VariableDeclarationList */) { + if (node && node.kind === 238 /* VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 217 /* VariableStatement */) { + if (node && node.kind === 219 /* VariableStatement */) { flags |= getFlags(node); } return flags; @@ -12090,38 +12803,34 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; - case 219 /* ExpressionStatement */: + break; + case 221 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return expr.name; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; - case 193 /* ParenthesizedExpression */: { + break; + case 195 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 231 /* LabeledStatement */: { + case 233 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12140,31 +12849,36 @@ var ts; /** @internal */ function getNonAssignedNameOfDeclaration(declaration) { switch (declaration.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return declaration; - case 303 /* JSDocPropertyTag */: - case 297 /* JSDocParameterTag */: { + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 146 /* QualifiedName */) { + if (name.kind === 148 /* QualifiedName */) { return name.right; } break; } - case 202 /* BinaryExpression */: { + case 191 /* CallExpression */: + case 204 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: case 3 /* PrototypeProperty */: return expr.left.name; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr.arguments[1]; default: return undefined; } } - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 252 /* ExportAssignment */: { + case 254 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } @@ -12198,15 +12912,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12940,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12350,10 +13080,23 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -12371,684 +13114,688 @@ var ts; return node.kind === 8 /* NumericLiteral */; } ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9 /* BigIntLiteral */; + } + ts.isBigIntLiteral = isBigIntLiteral; function isStringLiteral(node) { - return node.kind === 9 /* StringLiteral */; + return node.kind === 10 /* StringLiteral */; } ts.isStringLiteral = isStringLiteral; function isJsxText(node) { - return node.kind === 10 /* JsxText */; + return node.kind === 11 /* JsxText */; } ts.isJsxText = isJsxText; function isRegularExpressionLiteral(node) { - return node.kind === 12 /* RegularExpressionLiteral */; + return node.kind === 13 /* RegularExpressionLiteral */; } ts.isRegularExpressionLiteral = isRegularExpressionLiteral; function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13 /* NoSubstitutionTemplateLiteral */; + return node.kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; // Pseudo-literals function isTemplateHead(node) { - return node.kind === 14 /* TemplateHead */; + return node.kind === 15 /* TemplateHead */; } ts.isTemplateHead = isTemplateHead; function isTemplateMiddle(node) { - return node.kind === 15 /* TemplateMiddle */; + return node.kind === 16 /* TemplateMiddle */; } ts.isTemplateMiddle = isTemplateMiddle; function isTemplateTail(node) { - return node.kind === 16 /* TemplateTail */; + return node.kind === 17 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; function isIdentifier(node) { - return node.kind === 71 /* Identifier */; + return node.kind === 72 /* Identifier */; } ts.isIdentifier = isIdentifier; // Names function isQualifiedName(node) { - return node.kind === 146 /* QualifiedName */; + return node.kind === 148 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 147 /* ComputedPropertyName */; + return node.kind === 149 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 148 /* TypeParameter */; + return node.kind === 150 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 149 /* Parameter */; + return node.kind === 151 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 150 /* Decorator */; + return node.kind === 152 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 151 /* PropertySignature */; + return node.kind === 153 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 152 /* PropertyDeclaration */; + return node.kind === 154 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 153 /* MethodSignature */; + return node.kind === 155 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 154 /* MethodDeclaration */; + return node.kind === 156 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 155 /* Constructor */; + return node.kind === 157 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 156 /* GetAccessor */; + return node.kind === 158 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 157 /* SetAccessor */; + return node.kind === 159 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 158 /* CallSignature */; + return node.kind === 160 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 159 /* ConstructSignature */; + return node.kind === 161 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 160 /* IndexSignature */; + return node.kind === 162 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 157 /* SetAccessor */ || node.kind === 156 /* GetAccessor */; + return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 161 /* TypePredicate */; + return node.kind === 163 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 162 /* TypeReference */; + return node.kind === 164 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 163 /* FunctionType */; + return node.kind === 165 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 164 /* ConstructorType */; + return node.kind === 166 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 165 /* TypeQuery */; + return node.kind === 167 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 166 /* TypeLiteral */; + return node.kind === 168 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 167 /* ArrayType */; + return node.kind === 169 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 168 /* TupleType */; + return node.kind === 170 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 171 /* UnionType */; + return node.kind === 173 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 172 /* IntersectionType */; + return node.kind === 174 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 173 /* ConditionalType */; + return node.kind === 175 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 174 /* InferType */; + return node.kind === 176 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 175 /* ParenthesizedType */; + return node.kind === 177 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 176 /* ThisType */; + return node.kind === 178 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 177 /* TypeOperator */; + return node.kind === 179 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 178 /* IndexedAccessType */; + return node.kind === 180 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 179 /* MappedType */; + return node.kind === 181 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 180 /* LiteralType */; + return node.kind === 182 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 181 /* ImportType */; + return node.kind === 183 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 182 /* ObjectBindingPattern */; + return node.kind === 184 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 183 /* ArrayBindingPattern */; + return node.kind === 185 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 184 /* BindingElement */; + return node.kind === 186 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 185 /* ArrayLiteralExpression */; + return node.kind === 187 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 186 /* ObjectLiteralExpression */; + return node.kind === 188 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 187 /* PropertyAccessExpression */; + return node.kind === 189 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 188 /* ElementAccessExpression */; + return node.kind === 190 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 189 /* CallExpression */; + return node.kind === 191 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 190 /* NewExpression */; + return node.kind === 192 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 191 /* TaggedTemplateExpression */; + return node.kind === 193 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 192 /* TypeAssertionExpression */; + return node.kind === 194 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 193 /* ParenthesizedExpression */; + return node.kind === 195 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 306 /* PartiallyEmittedExpression */) { + while (node.kind === 308 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 194 /* FunctionExpression */; + return node.kind === 196 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 195 /* ArrowFunction */; + return node.kind === 197 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 196 /* DeleteExpression */; + return node.kind === 198 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 197 /* TypeOfExpression */; + return node.kind === 199 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 198 /* VoidExpression */; + return node.kind === 200 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 199 /* AwaitExpression */; + return node.kind === 201 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 200 /* PrefixUnaryExpression */; + return node.kind === 202 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 201 /* PostfixUnaryExpression */; + return node.kind === 203 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 202 /* BinaryExpression */; + return node.kind === 204 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 203 /* ConditionalExpression */; + return node.kind === 205 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 204 /* TemplateExpression */; + return node.kind === 206 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 205 /* YieldExpression */; + return node.kind === 207 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 206 /* SpreadElement */; + return node.kind === 208 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 207 /* ClassExpression */; + return node.kind === 209 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 208 /* OmittedExpression */; + return node.kind === 210 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */; + return node.kind === 211 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 210 /* AsExpression */; + return node.kind === 212 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 211 /* NonNullExpression */; + return node.kind === 213 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 212 /* MetaProperty */; + return node.kind === 214 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; // Misc function isTemplateSpan(node) { - return node.kind === 214 /* TemplateSpan */; + return node.kind === 216 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 215 /* SemicolonClassElement */; + return node.kind === 217 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Block function isBlock(node) { - return node.kind === 216 /* Block */; + return node.kind === 218 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 217 /* VariableStatement */; + return node.kind === 219 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 218 /* EmptyStatement */; + return node.kind === 220 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 219 /* ExpressionStatement */; + return node.kind === 221 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 220 /* IfStatement */; + return node.kind === 222 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 221 /* DoStatement */; + return node.kind === 223 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 222 /* WhileStatement */; + return node.kind === 224 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 223 /* ForStatement */; + return node.kind === 225 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 224 /* ForInStatement */; + return node.kind === 226 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 225 /* ForOfStatement */; + return node.kind === 227 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 226 /* ContinueStatement */; + return node.kind === 228 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 227 /* BreakStatement */; + return node.kind === 229 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isBreakOrContinueStatement(node) { - return node.kind === 227 /* BreakStatement */ || node.kind === 226 /* ContinueStatement */; + return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 228 /* ReturnStatement */; + return node.kind === 230 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 229 /* WithStatement */; + return node.kind === 231 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 230 /* SwitchStatement */; + return node.kind === 232 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 231 /* LabeledStatement */; + return node.kind === 233 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 232 /* ThrowStatement */; + return node.kind === 234 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 233 /* TryStatement */; + return node.kind === 235 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 234 /* DebuggerStatement */; + return node.kind === 236 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 235 /* VariableDeclaration */; + return node.kind === 237 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 236 /* VariableDeclarationList */; + return node.kind === 238 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 237 /* FunctionDeclaration */; + return node.kind === 239 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 238 /* ClassDeclaration */; + return node.kind === 240 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 239 /* InterfaceDeclaration */; + return node.kind === 241 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 240 /* TypeAliasDeclaration */; + return node.kind === 242 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 241 /* EnumDeclaration */; + return node.kind === 243 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */; + return node.kind === 244 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 243 /* ModuleBlock */; + return node.kind === 245 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 244 /* CaseBlock */; + return node.kind === 246 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 245 /* NamespaceExportDeclaration */; + return node.kind === 247 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */; + return node.kind === 248 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 247 /* ImportDeclaration */; + return node.kind === 249 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 248 /* ImportClause */; + return node.kind === 250 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 249 /* NamespaceImport */; + return node.kind === 251 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 250 /* NamedImports */; + return node.kind === 252 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 251 /* ImportSpecifier */; + return node.kind === 253 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 252 /* ExportAssignment */; + return node.kind === 254 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 253 /* ExportDeclaration */; + return node.kind === 255 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 254 /* NamedExports */; + return node.kind === 256 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 255 /* ExportSpecifier */; + return node.kind === 257 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 256 /* MissingDeclaration */; + return node.kind === 258 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; // Module References function isExternalModuleReference(node) { - return node.kind === 257 /* ExternalModuleReference */; + return node.kind === 259 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 258 /* JsxElement */; + return node.kind === 260 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 259 /* JsxSelfClosingElement */; + return node.kind === 261 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 260 /* JsxOpeningElement */; + return node.kind === 262 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 261 /* JsxClosingElement */; + return node.kind === 263 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 262 /* JsxFragment */; + return node.kind === 264 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 263 /* JsxOpeningFragment */; + return node.kind === 265 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 264 /* JsxClosingFragment */; + return node.kind === 266 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 265 /* JsxAttribute */; + return node.kind === 267 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 266 /* JsxAttributes */; + return node.kind === 268 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 267 /* JsxSpreadAttribute */; + return node.kind === 269 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 268 /* JsxExpression */; + return node.kind === 270 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 269 /* CaseClause */; + return node.kind === 271 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 270 /* DefaultClause */; + return node.kind === 272 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 271 /* HeritageClause */; + return node.kind === 273 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 272 /* CatchClause */; + return node.kind === 274 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 273 /* PropertyAssignment */; + return node.kind === 275 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 274 /* ShorthandPropertyAssignment */; + return node.kind === 276 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 275 /* SpreadAssignment */; + return node.kind === 277 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 276 /* EnumMember */; + return node.kind === 278 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 277 /* SourceFile */; + return node.kind === 279 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 278 /* Bundle */; + return node.kind === 280 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 279 /* UnparsedSource */; + return node.kind === 281 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 281 /* JSDocTypeExpression */; + return node.kind === 283 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 282 /* JSDocAllType */; + return node.kind === 284 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 283 /* JSDocUnknownType */; + return node.kind === 285 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 284 /* JSDocNullableType */; + return node.kind === 286 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 285 /* JSDocNonNullableType */; + return node.kind === 287 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 286 /* JSDocOptionalType */; + return node.kind === 288 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 287 /* JSDocFunctionType */; + return node.kind === 289 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 288 /* JSDocVariadicType */; + return node.kind === 290 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 289 /* JSDocComment */; + return node.kind === 291 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 293 /* JSDocAugmentsTag */; + return node.kind === 295 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 294 /* JSDocClassTag */; + return node.kind === 296 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocEnumTag(node) { - return node.kind === 296 /* JSDocEnumTag */; + return node.kind === 298 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 299 /* JSDocThisTag */; + return node.kind === 301 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 297 /* JSDocParameterTag */; + return node.kind === 299 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 298 /* JSDocReturnTag */; + return node.kind === 300 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 300 /* JSDocTypeTag */; + return node.kind === 302 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 301 /* JSDocTemplateTag */; + return node.kind === 303 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 302 /* JSDocTypedefTag */; + return node.kind === 304 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 303 /* JSDocPropertyTag */; + return node.kind === 305 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */; + return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 290 /* JSDocTypeLiteral */; + return node.kind === 292 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocCallbackTag(node) { - return node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 297 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocSignature(node) { - return node.kind === 291 /* JSDocSignature */; + return node.kind === 293 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); @@ -13059,7 +13806,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 304 /* SyntaxList */; + return n.kind === 306 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13069,7 +13816,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 146 /* FirstNode */; + return kind >= 148 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13078,7 +13825,7 @@ var ts; * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 145 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */; } ts.isToken = isToken; // Node Arrays @@ -13090,7 +13837,7 @@ var ts; // Literals /* @internal */ function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */; + return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */; } ts.isLiteralKind = isLiteralKind; function isLiteralExpression(node) { @@ -13100,7 +13847,7 @@ var ts; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { - return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; + return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isTemplateLiteralToken(node) { @@ -13109,12 +13856,16 @@ var ts; ts.isTemplateLiteralToken = isTemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node) { var kind = node.kind; - return kind === 15 /* TemplateMiddle */ - || kind === 16 /* TemplateTail */; + return kind === 16 /* TemplateMiddle */ + || kind === 17 /* TemplateTail */; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isStringTextContainingNode(node) { - return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -13127,17 +13878,17 @@ var ts; /* @internal */ function isModifierKind(token) { switch (token) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 79 /* DefaultKeyword */: - case 84 /* ExportKeyword */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 115 /* StaticKeyword */: + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 80 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 116 /* StaticKeyword */: return true; } return false; @@ -13150,7 +13901,7 @@ var ts; ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */; + return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -13159,23 +13910,23 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 146 /* QualifiedName */ - || kind === 71 /* Identifier */; + return kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 9 /* StringLiteral */ + return kind === 72 /* Identifier */ + || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 147 /* ComputedPropertyName */; + || kind === 149 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 182 /* ObjectBindingPattern */ - || kind === 183 /* ArrayBindingPattern */; + return kind === 72 /* Identifier */ + || kind === 184 /* ObjectBindingPattern */ + || kind === 185 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -13190,13 +13941,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; default: return false; @@ -13205,14 +13956,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 163 /* FunctionType */: - case 287 /* JSDocFunctionType */: - case 164 /* ConstructorType */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 166 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -13227,29 +13978,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 155 /* Constructor */ - || kind === 152 /* PropertyDeclaration */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 160 /* IndexSignature */ - || kind === 215 /* SemicolonClassElement */; + return kind === 157 /* Constructor */ + || kind === 154 /* PropertyDeclaration */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 162 /* IndexSignature */ + || kind === 217 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */); + return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */); + return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return true; default: return false; @@ -13259,11 +14010,11 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 159 /* ConstructSignature */ - || kind === 158 /* CallSignature */ - || kind === 151 /* PropertySignature */ - || kind === 153 /* MethodSignature */ - || kind === 160 /* IndexSignature */; + return kind === 161 /* ConstructSignature */ + || kind === 160 /* CallSignature */ + || kind === 153 /* PropertySignature */ + || kind === 155 /* MethodSignature */ + || kind === 162 /* IndexSignature */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -13272,51 +14023,28 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 273 /* PropertyAssignment */ - || kind === 274 /* ShorthandPropertyAssignment */ - || kind === 275 /* SpreadAssignment */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 275 /* PropertyAssignment */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 277 /* SpreadAssignment */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type - function isTypeNodeKind(kind) { - return (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) - || kind === 119 /* AnyKeyword */ - || kind === 142 /* UnknownKeyword */ - || kind === 134 /* NumberKeyword */ - || kind === 135 /* ObjectKeyword */ - || kind === 122 /* BooleanKeyword */ - || kind === 137 /* StringKeyword */ - || kind === 138 /* SymbolKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 105 /* VoidKeyword */ - || kind === 140 /* UndefinedKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 131 /* NeverKeyword */ - || kind === 209 /* ExpressionWithTypeArguments */ - || kind === 282 /* JSDocAllType */ - || kind === 283 /* JSDocUnknownType */ - || kind === 284 /* JSDocNullableType */ - || kind === 285 /* JSDocNonNullableType */ - || kind === 286 /* JSDocOptionalType */ - || kind === 287 /* JSDocFunctionType */ - || kind === 288 /* JSDocVariadicType */; - } /** * Node test that determines whether a node is a valid type node. * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* * of a TypeNode. */ function isTypeNode(node) { - return isTypeNodeKind(node.kind); + return ts.isTypeNodeKind(node.kind); } ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return true; } return false; @@ -13327,8 +14055,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 183 /* ArrayBindingPattern */ - || kind === 182 /* ObjectBindingPattern */; + return kind === 185 /* ArrayBindingPattern */ + || kind === 184 /* ObjectBindingPattern */; } return false; } @@ -13336,15 +14064,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 185 /* ArrayLiteralExpression */ - || kind === 186 /* ObjectLiteralExpression */; + return kind === 187 /* ArrayLiteralExpression */ + || kind === 188 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 184 /* BindingElement */ - || kind === 208 /* OmittedExpression */; + return kind === 186 /* BindingElement */ + || kind === 210 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -13353,9 +14081,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: return true; } return false; @@ -13376,8 +14104,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 182 /* ObjectBindingPattern */: - case 186 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: return true; } return false; @@ -13389,8 +14117,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: return true; } return false; @@ -13399,26 +14127,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 187 /* PropertyAccessExpression */ - || kind === 146 /* QualifiedName */ - || kind === 181 /* ImportType */; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */ + || kind === 183 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 187 /* PropertyAccessExpression */ - || kind === 146 /* QualifiedName */; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 191 /* TaggedTemplateExpression */: - case 150 /* Decorator */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 152 /* Decorator */: return true; default: return false; @@ -13426,13 +14154,13 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 189 /* CallExpression */ || node.kind === 190 /* NewExpression */; + return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 204 /* TemplateExpression */ - || kind === 13 /* NoSubstitutionTemplateLiteral */; + return kind === 206 /* TemplateExpression */ + || kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; /* @internal */ @@ -13442,33 +14170,34 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - case 190 /* NewExpression */: - case 189 /* CallExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 191 /* TaggedTemplateExpression */: - case 185 /* ArrayLiteralExpression */: - case 193 /* ParenthesizedExpression */: - case 186 /* ObjectLiteralExpression */: - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: - case 71 /* Identifier */: - case 12 /* RegularExpressionLiteral */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 192 /* NewExpression */: + case 191 /* CallExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 193 /* TaggedTemplateExpression */: + case 187 /* ArrayLiteralExpression */: + case 195 /* ParenthesizedExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 72 /* Identifier */: + case 13 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 101 /* TrueKeyword */: - case 97 /* SuperKeyword */: - case 211 /* NonNullExpression */: - case 212 /* MetaProperty */: - case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 102 /* TrueKeyword */: + case 98 /* SuperKeyword */: + case 213 /* NonNullExpression */: + case 214 /* MetaProperty */: + case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: return false; @@ -13481,13 +14210,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 199 /* AwaitExpression */: - case 192 /* TypeAssertionExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 194 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13496,11 +14225,11 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return true; - case 200 /* PrefixUnaryExpression */: - return expr.operator === 43 /* PlusPlusToken */ || - expr.operator === 44 /* MinusMinusToken */; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 44 /* PlusPlusToken */ || + expr.operator === 45 /* MinusMinusToken */; default: return false; } @@ -13517,15 +14246,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 203 /* ConditionalExpression */: - case 205 /* YieldExpression */: - case 195 /* ArrowFunction */: - case 202 /* BinaryExpression */: - case 206 /* SpreadElement */: - case 210 /* AsExpression */: - case 208 /* OmittedExpression */: - case 307 /* CommaListExpression */: - case 306 /* PartiallyEmittedExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + case 197 /* ArrowFunction */: + case 204 /* BinaryExpression */: + case 208 /* SpreadElement */: + case 212 /* AsExpression */: + case 210 /* OmittedExpression */: + case 309 /* CommaListExpression */: + case 308 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13533,18 +14262,18 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 192 /* TypeAssertionExpression */ - || kind === 210 /* AsExpression */; + return kind === 194 /* TypeAssertionExpression */ + || kind === 212 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 306 /* PartiallyEmittedExpression */; + return node.kind === 308 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 305 /* NotEmittedStatement */; + return node.kind === 307 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13555,13 +14284,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return true; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13569,7 +14298,7 @@ var ts; ts.isIterationStatement = isIterationStatement; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 224 /* ForInStatement */ || node.kind === 225 /* ForOfStatement */; + return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13593,113 +14322,113 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 243 /* ModuleBlock */ - || kind === 242 /* ModuleDeclaration */ - || kind === 71 /* Identifier */; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */ + || kind === 72 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 243 /* ModuleBlock */ - || kind === 242 /* ModuleDeclaration */; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 242 /* ModuleDeclaration */; + return kind === 72 /* Identifier */ + || kind === 244 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 250 /* NamedImports */ - || kind === 249 /* NamespaceImport */; + return kind === 252 /* NamedImports */ + || kind === 251 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */ || node.kind === 241 /* EnumDeclaration */; + return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 195 /* ArrowFunction */ - || kind === 184 /* BindingElement */ - || kind === 238 /* ClassDeclaration */ - || kind === 207 /* ClassExpression */ - || kind === 155 /* Constructor */ - || kind === 241 /* EnumDeclaration */ - || kind === 276 /* EnumMember */ - || kind === 255 /* ExportSpecifier */ - || kind === 237 /* FunctionDeclaration */ - || kind === 194 /* FunctionExpression */ - || kind === 156 /* GetAccessor */ - || kind === 248 /* ImportClause */ - || kind === 246 /* ImportEqualsDeclaration */ - || kind === 251 /* ImportSpecifier */ - || kind === 239 /* InterfaceDeclaration */ - || kind === 265 /* JsxAttribute */ - || kind === 154 /* MethodDeclaration */ - || kind === 153 /* MethodSignature */ - || kind === 242 /* ModuleDeclaration */ - || kind === 245 /* NamespaceExportDeclaration */ - || kind === 249 /* NamespaceImport */ - || kind === 149 /* Parameter */ - || kind === 273 /* PropertyAssignment */ - || kind === 152 /* PropertyDeclaration */ - || kind === 151 /* PropertySignature */ - || kind === 157 /* SetAccessor */ - || kind === 274 /* ShorthandPropertyAssignment */ - || kind === 240 /* TypeAliasDeclaration */ - || kind === 148 /* TypeParameter */ - || kind === 235 /* VariableDeclaration */ - || kind === 302 /* JSDocTypedefTag */ - || kind === 295 /* JSDocCallbackTag */ - || kind === 303 /* JSDocPropertyTag */; + return kind === 197 /* ArrowFunction */ + || kind === 186 /* BindingElement */ + || kind === 240 /* ClassDeclaration */ + || kind === 209 /* ClassExpression */ + || kind === 157 /* Constructor */ + || kind === 243 /* EnumDeclaration */ + || kind === 278 /* EnumMember */ + || kind === 257 /* ExportSpecifier */ + || kind === 239 /* FunctionDeclaration */ + || kind === 196 /* FunctionExpression */ + || kind === 158 /* GetAccessor */ + || kind === 250 /* ImportClause */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 253 /* ImportSpecifier */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 267 /* JsxAttribute */ + || kind === 156 /* MethodDeclaration */ + || kind === 155 /* MethodSignature */ + || kind === 244 /* ModuleDeclaration */ + || kind === 247 /* NamespaceExportDeclaration */ + || kind === 251 /* NamespaceImport */ + || kind === 151 /* Parameter */ + || kind === 275 /* PropertyAssignment */ + || kind === 154 /* PropertyDeclaration */ + || kind === 153 /* PropertySignature */ + || kind === 159 /* SetAccessor */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 150 /* TypeParameter */ + || kind === 237 /* VariableDeclaration */ + || kind === 304 /* JSDocTypedefTag */ + || kind === 297 /* JSDocCallbackTag */ + || kind === 305 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 237 /* FunctionDeclaration */ - || kind === 256 /* MissingDeclaration */ - || kind === 238 /* ClassDeclaration */ - || kind === 239 /* InterfaceDeclaration */ - || kind === 240 /* TypeAliasDeclaration */ - || kind === 241 /* EnumDeclaration */ - || kind === 242 /* ModuleDeclaration */ - || kind === 247 /* ImportDeclaration */ - || kind === 246 /* ImportEqualsDeclaration */ - || kind === 253 /* ExportDeclaration */ - || kind === 252 /* ExportAssignment */ - || kind === 245 /* NamespaceExportDeclaration */; + return kind === 239 /* FunctionDeclaration */ + || kind === 258 /* MissingDeclaration */ + || kind === 240 /* ClassDeclaration */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 243 /* EnumDeclaration */ + || kind === 244 /* ModuleDeclaration */ + || kind === 249 /* ImportDeclaration */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 255 /* ExportDeclaration */ + || kind === 254 /* ExportAssignment */ + || kind === 247 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 227 /* BreakStatement */ - || kind === 226 /* ContinueStatement */ - || kind === 234 /* DebuggerStatement */ - || kind === 221 /* DoStatement */ - || kind === 219 /* ExpressionStatement */ - || kind === 218 /* EmptyStatement */ - || kind === 224 /* ForInStatement */ - || kind === 225 /* ForOfStatement */ - || kind === 223 /* ForStatement */ - || kind === 220 /* IfStatement */ - || kind === 231 /* LabeledStatement */ - || kind === 228 /* ReturnStatement */ - || kind === 230 /* SwitchStatement */ - || kind === 232 /* ThrowStatement */ - || kind === 233 /* TryStatement */ - || kind === 217 /* VariableStatement */ - || kind === 222 /* WhileStatement */ - || kind === 229 /* WithStatement */ - || kind === 305 /* NotEmittedStatement */ - || kind === 309 /* EndOfDeclarationMarker */ - || kind === 308 /* MergeDeclarationMarker */; + return kind === 229 /* BreakStatement */ + || kind === 228 /* ContinueStatement */ + || kind === 236 /* DebuggerStatement */ + || kind === 223 /* DoStatement */ + || kind === 221 /* ExpressionStatement */ + || kind === 220 /* EmptyStatement */ + || kind === 226 /* ForInStatement */ + || kind === 227 /* ForOfStatement */ + || kind === 225 /* ForStatement */ + || kind === 222 /* IfStatement */ + || kind === 233 /* LabeledStatement */ + || kind === 230 /* ReturnStatement */ + || kind === 232 /* SwitchStatement */ + || kind === 234 /* ThrowStatement */ + || kind === 235 /* TryStatement */ + || kind === 219 /* VariableStatement */ + || kind === 224 /* WhileStatement */ + || kind === 231 /* WithStatement */ + || kind === 307 /* NotEmittedStatement */ + || kind === 311 /* EndOfDeclarationMarker */ + || kind === 310 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + if (node.kind === 150 /* TypeParameter */) { + return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -13726,10 +14455,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 216 /* Block */) + if (node.kind !== 218 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 233 /* TryStatement */ || node.parent.kind === 272 /* CatchClause */) { + if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) { return false; } } @@ -13739,81 +14468,81 @@ var ts; /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 257 /* ExternalModuleReference */ - || kind === 146 /* QualifiedName */ - || kind === 71 /* Identifier */; + return kind === 259 /* ExternalModuleReference */ + || kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; } ts.isModuleReference = isModuleReference; // JSX /* @internal */ function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 99 /* ThisKeyword */ - || kind === 71 /* Identifier */ - || kind === 187 /* PropertyAccessExpression */; + return kind === 100 /* ThisKeyword */ + || kind === 72 /* Identifier */ + || kind === 189 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 258 /* JsxElement */ - || kind === 268 /* JsxExpression */ - || kind === 259 /* JsxSelfClosingElement */ - || kind === 10 /* JsxText */ - || kind === 262 /* JsxFragment */; + return kind === 260 /* JsxElement */ + || kind === 270 /* JsxExpression */ + || kind === 261 /* JsxSelfClosingElement */ + || kind === 11 /* JsxText */ + || kind === 264 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 265 /* JsxAttribute */ - || kind === 267 /* JsxSpreadAttribute */; + return kind === 267 /* JsxAttribute */ + || kind === 269 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 268 /* JsxExpression */; + return kind === 10 /* StringLiteral */ + || kind === 270 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 260 /* JsxOpeningElement */ - || kind === 259 /* JsxSelfClosingElement */; + return kind === 262 /* JsxOpeningElement */ + || kind === 261 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 269 /* CaseClause */ - || kind === 270 /* DefaultClause */; + return kind === 271 /* CaseClause */ + || kind === 272 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */; + return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 289 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */; + return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 157 /* SetAccessor */; + return node.kind === 159 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 156 /* GetAccessor */; + return node.kind === 158 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -13843,12 +14572,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 162 /* TypeReference */ || node.kind === 209 /* ExpressionWithTypeArguments */; + return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13877,15 +14606,14 @@ var ts; } ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { - return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; + return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isStringLiteralLike = isStringLiteralLike; })(ts || (ts = {})); /* @internal */ (function (ts) { - /** @internal */ function isNamedImportsOrExports(node) { - return node.kind === 250 /* NamedImports */ || node.kind === 254 /* NamedExports */; + return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function Symbol(flags, name) { @@ -13930,10 +14658,9 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - /* @internal */ function formatStringFromArgs(text, args, baseIndex) { if (baseIndex === void 0) { baseIndex = 0; } - return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); }); + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; function getLocaleSpecificMessage(message) { @@ -13962,7 +14689,6 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; - /* @internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -13987,7 +14713,6 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; - /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -14024,14 +14749,12 @@ var ts; function getDiagnosticFilePath(diagnostic) { return diagnostic.file ? diagnostic.file.path : undefined; } - /* @internal */ function compareDiagnostics(d1, d2) { return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || 0 /* EqualTo */; } ts.compareDiagnostics = compareDiagnostics; - /* @internal */ function compareDiagnosticsSkipRelatedInformation(d1, d2) { return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || ts.compareValues(d1.start, d2.start) || @@ -14092,6 +14815,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14843,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14856,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14323,7 +15058,6 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; - /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -14401,8 +15135,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15356,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14684,6 +15423,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14910,36 +15650,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15067,14 +15828,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +16006,98 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: // 0b or 0B + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: // 0o or 0O + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + var nIndex = stringValue.length - 1; + // Skip leading 0s + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + // Omit leading "0b", "0o", or "0x", and trailing "n" + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + var digit = digitChar <= 57 /* _9 */ + ? digitChar - 48 /* _0 */ + : 10 + digitChar - + (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; })(ts || (ts = {})); var ts; (function (ts) { @@ -15264,10 +16117,10 @@ var ts; var SourceFileConstructor; // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 277 /* SourceFile */) { + if (kind === 279 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 71 /* Identifier */) { + else if (kind === 72 /* Identifier */) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } else if (!ts.isNodeKind(kind)) { @@ -15316,28 +16169,29 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 145 /* LastToken */) { + if (!node || node.kind <= 147 /* LastToken */) { return; } switch (node.kind) { - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -15345,7 +16199,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -15353,405 +16207,399 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 168 /* TupleType */: + case 170 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 174 /* InferType */: + case 176 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 181 /* ImportType */: + case 183 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 175 /* ParenthesizedType */: - case 177 /* TypeOperator */: + case 177 /* ParenthesizedType */: + case 179 /* TypeOperator */: return visitNode(cbNode, node.type); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 179 /* MappedType */: + case 181 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return visitNode(cbNode, node.literal); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 210 /* AsExpression */: + case 212 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return visitNode(cbNode, node.name); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 277 /* SourceFile */: + case 279 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: return visitNode(cbNode, node.label); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 269 /* CaseClause */: + case 271 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 150 /* Decorator */: + case 152 /* Decorator */: return visitNode(cbNode, node.expression); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 276 /* EnumMember */: + case 278 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 250 /* NamedImports */: - case 254 /* NamedExports */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 169 /* OptionalType */: - case 170 /* RestType */: - case 281 /* JSDocTypeExpression */: - case 285 /* JSDocNonNullableType */: - case 284 /* JSDocNullableType */: - case 286 /* JSDocOptionalType */: - case 288 /* JSDocVariadicType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 283 /* JSDocTypeExpression */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 288 /* JSDocOptionalType */: + case 290 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 289 /* JSDocComment */: + case 291 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: - if (node.isNameFirst) { - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression); - } - else { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - } - case 298 /* JSDocReturnTag */: - return visitNode(cbNode, node.typeExpression); - case 300 /* JSDocTypeTag */: - return visitNode(cbNode, node.typeExpression); - case 293 /* JSDocAugmentsTag */: - return visitNode(cbNode, node.class); - case 301 /* JSDocTemplateTag */: - return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302 /* JSDocTypedefTag */: - if (node.typeExpression && - node.typeExpression.kind === 281 /* JSDocTypeExpression */) { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName); - } - else { - return visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - } - case 295 /* JSDocCallbackTag */: - return visitNode(cbNode, node.fullName) || + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303 /* JSDocTemplateTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304 /* JSDocTypedefTag */: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 /* JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297 /* JSDocCallbackTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299 /* JSDocThisTag */: - return visitNode(cbNode, node.typeExpression); - case 296 /* JSDocEnumTag */: - return visitNode(cbNode, node.typeExpression); - case 291 /* JSDocSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - ts.forEach(node.typeParameters, cbNode) || + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293 /* JSDocSignature */: + return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290 /* JSDocTypeLiteral */: - if (node.jsDocPropertyTags) { - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); - } - } - return; - case 306 /* PartiallyEmittedExpression */: + case 292 /* JSDocTypeLiteral */: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294 /* JSDocTag */: + case 296 /* JSDocClassTag */: + return visitNode(cbNode, node.tagName); + case 308 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15761,7 +16609,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16778,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -15965,18 +16817,18 @@ var ts; sourceFile.endOfFileToken = parseTokenNode(); } else { - var statement = createNode(219 /* ExpressionStatement */); + var statement = createNode(221 /* ExpressionStatement */); switch (token()) { - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: statement.expression = parseArrayLiteralExpression(); break; - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: statement.expression = parseTokenNode(); break; - case 38 /* MinusToken */: - if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) { + case 39 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) { statement.expression = parsePrefixUnaryExpression(); } else { @@ -15984,8 +16836,8 @@ var ts; } break; case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) { + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) { statement.expression = parseLiteralNode(); break; } @@ -16121,7 +16973,7 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // 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(277 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -16326,20 +17178,20 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token() === 71 /* Identifier */) { + if (token() === 72 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token() === 116 /* YieldKeyword */ && inYieldContext()) { + if (token() === 117 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) { + if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token() > 107 /* LastReservedWord */; + return token() > 108 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -16382,29 +17234,29 @@ var ts; } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token() === 25 /* SemicolonToken */) { + if (token() === 26 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 25 /* SemicolonToken */) { + if (token() === 26 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } return true; } else { - return parseExpected(25 /* SemicolonToken */); + return parseExpected(26 /* SemicolonToken */); } } function createNode(kind, pos) { nodeCount++; var p = pos >= 0 ? pos : scanner.getStartPos(); return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : - kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } function createNodeWithJSDoc(kind, pos) { @@ -16446,7 +17298,7 @@ var ts; parseErrorAtCurrentToken(diagnosticMessage, arg0); } var result = createNode(kind); - if (kind === 71 /* Identifier */) { + if (kind === 72 /* Identifier */) { result.escapedText = ""; } else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { @@ -16467,9 +17319,9 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(71 /* Identifier */); + var node = createNode(72 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 71 /* Identifier */) { + if (token() !== 72 /* Identifier */) { node.originalKeywordKind = token(); } node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); @@ -16478,7 +17330,7 @@ var ts; } // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; - return createMissingNode(71 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -16488,16 +17340,16 @@ var ts; } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || + token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { var node = parseLiteralNode(); node.text = internIdentifier(node.text); return node; } - if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -16509,13 +17361,13 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(147 /* ComputedPropertyName */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(149 /* ComputedPropertyName */); + parseExpected(22 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker // will error if it sees a comma expression. node.expression = allowInAnd(parseExpression); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function parseContextualModifier(t) { @@ -16530,20 +17382,20 @@ var ts; } function nextTokenCanFollowModifier() { switch (token()) { - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; - case 84 /* ExportKeyword */: + return nextToken() === 84 /* EnumKeyword */; + case 85 /* ExportKeyword */: nextToken(); - if (token() === 79 /* DefaultKeyword */) { + if (token() === 80 /* DefaultKeyword */) { return lookAhead(nextTokenCanFollowDefaultKeyword); } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - case 79 /* DefaultKeyword */: + return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + case 80 /* DefaultKeyword */: return nextTokenCanFollowDefaultKeyword(); - case 115 /* StaticKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: + case 116 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: nextToken(); return canFollowModifier(); default: @@ -16554,18 +17406,18 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 21 /* OpenBracketToken */ - || token() === 17 /* OpenBraceToken */ - || token() === 39 /* AsteriskToken */ - || token() === 24 /* DotDotDotToken */ + return token() === 22 /* OpenBracketToken */ + || token() === 18 /* OpenBraceToken */ + || token() === 40 /* AsteriskToken */ + || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenCanFollowDefaultKeyword() { nextToken(); - return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ || - token() === 109 /* InterfaceKeyword */ || - (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ || + token() === 110 /* InterfaceKeyword */ || + (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -16583,9 +17435,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -16593,21 +17445,29 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 22 /* OpenBracketToken */: + case 40 /* AsteriskToken */: + case 25 /* DotDotDotToken */: + case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` // That way we won't consume the body of a class in its heritage clause. - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -16622,37 +17482,39 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); + return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern(); case 19 /* TypeParameters */: return isIdentifier(); case 15 /* ArrayLiteralMembers */: - if (token() === 26 /* CommaToken */) { - return true; + switch (token()) { + case 27 /* CommaToken */: + case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; } // falls through case 11 /* ArgumentExpressions */: - return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(/*isJSDocParameter*/ false); case 17 /* JSDocParameters */: return isStartOfParameter(/*isJSDocParameter*/ true); case 20 /* TypeArguments */: case 21 /* TupleElementTypes */: - return token() === 26 /* CommaToken */ || isStartOfType(); + return token() === 27 /* CommaToken */ || isStartOfType(); case 22 /* HeritageClauses */: return isHeritageClause(); case 23 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; } return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17 /* OpenBraceToken */); - if (nextToken() === 18 /* CloseBraceToken */) { + ts.Debug.assert(token() === 18 /* OpenBraceToken */); + if (nextToken() === 19 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // @@ -16661,7 +17523,7 @@ var ts; // extends {} extends // extends {} implements var next = nextToken(); - return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */; + return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */; } return true; } @@ -16678,8 +17540,8 @@ var ts; return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 /* ImplementsKeyword */ || - token() === 85 /* ExtendsKeyword */) { + if (token() === 109 /* ImplementsKeyword */ || + token() === 86 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -16707,37 +17569,37 @@ var ts; case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: case 23 /* ImportOrExportSpecifiers */: - return token() === 18 /* CloseBraceToken */; + return token() === 19 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); case 19 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; + return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: case 21 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token() === 22 /* CloseBracketToken */; + return token() === 23 /* CloseBracketToken */; case 17 /* JSDocParameters */: case 16 /* Parameters */: case 18 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 20 /* TypeArguments */: // All other tokens should cause the type-argument to terminate except comma token - return token() !== 26 /* CommaToken */; + return token() !== 27 /* CommaToken */; case 22 /* HeritageClauses */: - return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; + return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; + return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */; case 14 /* JsxChildren */: - return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash); default: return false; } @@ -16757,7 +17619,7 @@ var ts; // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -16927,20 +17789,20 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 155 /* Constructor */: - case 160 /* IndexSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 152 /* PropertyDeclaration */: - case 215 /* SemicolonClassElement */: + case 157 /* Constructor */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 217 /* SemicolonClassElement */: return true; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ && - methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */; + var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */; return !nameIsConstructor; } } @@ -16949,8 +17811,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: return true; } } @@ -16959,58 +17821,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 217 /* VariableStatement */: - case 216 /* Block */: - case 220 /* IfStatement */: - case 219 /* ExpressionStatement */: - case 232 /* ThrowStatement */: - case 228 /* ReturnStatement */: - case 230 /* SwitchStatement */: - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 218 /* EmptyStatement */: - case 233 /* TryStatement */: - case 231 /* LabeledStatement */: - case 221 /* DoStatement */: - case 234 /* DebuggerStatement */: - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: - case 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 219 /* VariableStatement */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 221 /* ExpressionStatement */: + case 234 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 232 /* SwitchStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 220 /* EmptyStatement */: + case 235 /* TryStatement */: + case 233 /* LabeledStatement */: + case 223 /* DoStatement */: + case 236 /* DebuggerStatement */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 276 /* EnumMember */; + return node.kind === 278 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 151 /* PropertySignature */: - case 158 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 153 /* PropertySignature */: + case 160 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 235 /* VariableDeclaration */) { + if (node.kind !== 237 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -17031,7 +17893,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 149 /* Parameter */) { + if (node.kind !== 151 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -17088,7 +17950,7 @@ var ts; var startPos = scanner.getStartPos(); list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(26 /* CommaToken */)) { + if (parseOptional(27 /* CommaToken */)) { // No need to check for a zero length node since we know we parsed a comma continue; } @@ -17098,13 +17960,13 @@ var ts; } // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. - parseExpected(26 /* CommaToken */); + parseExpected(27 /* CommaToken */); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // 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 (considerSemicolonAsDelimiter && token() === 25 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } if (startPos === scanner.getStartPos()) { @@ -17155,8 +18017,8 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); - while (parseOptional(23 /* DotToken */)) { - if (token() === 27 /* LessThanToken */) { + while (parseOptional(24 /* DotToken */)) { + if (token() === 28 /* LessThanToken */) { // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting entity.jsdocDotPos = dotPos; break; @@ -17167,7 +18029,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(146 /* QualifiedName */, entity.pos); + var node = createNode(148 /* QualifiedName */, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -17198,33 +18060,33 @@ 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(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(204 /* TemplateExpression */); + var template = createNode(206 /* TemplateExpression */); template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); var list = []; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */); + } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { - var span = createNode(214 /* TemplateSpan */); + var span = createNode(216 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 18 /* CloseBraceToken */) { + if (token() === 19 /* CloseBraceToken */) { reScanTemplateToken(); literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(16 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */)); + literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */)); } span.literal = literal; return finishNode(span); @@ -17234,18 +18096,17 @@ var ts; } function parseTemplateHead() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); return fragment; } function parseTemplateMiddleOrTemplateTail() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind"); + ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind"); return fragment; } function parseLiteralLikeNode(kind) { var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = text; + node.text = scanner.getTokenValue(); if (scanner.hasExtendedUnicodeEscape()) { node.hasExtendedUnicodeEscape = true; } @@ -17267,24 +18128,24 @@ var ts; } // TYPES function parseTypeReference() { - var node = createNode(162 /* TypeReference */); + var node = createNode(164 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + if (!scanner.hasPrecedingLineBreak() && token() === 28 /* LessThanToken */) { + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */); } return finishNode(node); } // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return ts.nodeIsMissing(node.typeName); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: { + case 165 /* FunctionType */: + case 166 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -17292,20 +18153,20 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(161 /* TypePredicate */, lhs.pos); + var node = createNode(163 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(176 /* ThisType */); + var node = createNode(178 /* ThisType */); nextToken(); return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(282 /* JSDocAllType */); + var result = createNode(284 /* JSDocAllType */); if (postFixEquals) { - return createPostfixType(286 /* JSDocOptionalType */, result); + return createPostfixType(288 /* JSDocOptionalType */, result); } else { nextToken(); @@ -17313,7 +18174,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(285 /* JSDocNonNullableType */); + var result = createNode(287 /* JSDocNonNullableType */); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -17331,64 +18192,66 @@ var ts; // Foo // Foo(?= // (?| - if (token() === 26 /* CommaToken */ || - token() === 18 /* CloseBraceToken */ || - token() === 20 /* CloseParenToken */ || - token() === 29 /* GreaterThanToken */ || - token() === 58 /* EqualsToken */ || - token() === 49 /* BarToken */) { - var result = createNode(283 /* JSDocUnknownType */, pos); + if (token() === 27 /* CommaToken */ || + token() === 19 /* CloseBraceToken */ || + token() === 21 /* CloseParenToken */ || + token() === 30 /* GreaterThanToken */ || + token() === 59 /* EqualsToken */ || + token() === 50 /* BarToken */) { + var result = createNode(285 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(284 /* JSDocNullableType */, pos); + var result = createNode(286 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(287 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); nextToken(); - fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); } - var node = createNode(162 /* TypeReference */); + var node = createNode(164 /* TypeReference */); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(149 /* Parameter */); - if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { + var parameter = createNode(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) { parameter.name = parseIdentifierName(); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); } parameter.type = parseJSDocType(); return finishNode(parameter); } function parseJSDocType() { - var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { - var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); + var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } - if (token() === 58 /* EqualsToken */) { - return createPostfixType(286 /* JSDocOptionalType */, type); + if (token() === 59 /* EqualsToken */) { + return createPostfixType(288 /* JSDocOptionalType */, type); } return type; } function parseTypeQuery() { - var node = createNode(165 /* TypeQuery */); - parseExpected(103 /* TypeOfKeyword */); + var node = createNode(167 /* TypeQuery */); + parseExpected(104 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(148 /* TypeParameter */); + var node = createNode(150 /* TypeParameter */); node.name = parseIdentifier(); - if (parseOptional(85 /* ExtendsKeyword */)) { + if (parseOptional(86 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the // user writes a constraint that is an expression and not an actual type, then parse // it out as an expression (so we can recover well), but report that a type is needed @@ -17407,39 +18270,39 @@ var ts; node.expression = parseUnaryExpressionOrHigher(); } } - if (parseOptional(58 /* EqualsToken */)) { + if (parseOptional(59 /* EqualsToken */)) { node.default = parseType(); } return finishNode(node); } function parseTypeParameters() { - if (token() === 27 /* LessThanToken */) { - return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + if (token() === 28 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */); } } function parseParameterType() { - if (parseOptional(56 /* ColonToken */)) { + if (parseOptional(57 /* ColonToken */)) { return parseType(); } return undefined; } function isStartOfParameter(isJSDocParameter) { - return token() === 24 /* DotDotDotToken */ || + return token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 /* AtToken */ || + token() === 58 /* AtToken */ || isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseParameter() { - var node = createNodeWithJSDoc(149 /* Parameter */); - if (token() === 99 /* ThisKeyword */) { + var node = createNodeWithJSDoc(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); @@ -17454,7 +18317,7 @@ var ts; // to avoid this we'll advance cursor to the next token. nextToken(); } - node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.questionToken = parseOptionalToken(56 /* QuestionToken */); node.type = parseParameterType(); node.initializer = parseInitializer(); return finishNode(node); @@ -17476,16 +18339,16 @@ var ts; return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { - if (returnToken === 36 /* EqualsGreaterThanToken */) { + if (returnToken === 37 /* EqualsGreaterThanToken */) { parseExpected(returnToken); return true; } - else if (parseOptional(56 /* ColonToken */)) { + else if (parseOptional(57 /* ColonToken */)) { return true; } - else if (isType && token() === 36 /* EqualsGreaterThanToken */) { + else if (isType && token() === 37 /* EqualsGreaterThanToken */) { // This is easy to get backward, especially in type contexts, so parse the type anyway - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); nextToken(); return true; } @@ -17506,7 +18369,7 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (!parseExpected(19 /* OpenParenToken */)) { + if (!parseExpected(20 /* OpenParenToken */)) { signature.parameters = createMissingList(); return false; } @@ -17519,12 +18382,12 @@ var ts; parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - return parseExpected(20 /* CloseParenToken */); + return parseExpected(21 /* CloseParenToken */); } function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. // First check if it was a comma. If so, we're done with the member. - if (parseOptional(26 /* CommaToken */)) { + if (parseOptional(27 /* CommaToken */)) { return; } // Didn't have a comma. We must have a (possible ASI) semicolon. @@ -17532,15 +18395,15 @@ var ts; } function parseSignatureMember(kind) { var node = createNodeWithJSDoc(kind); - if (kind === 159 /* ConstructSignature */) { - parseExpected(94 /* NewKeyword */); + if (kind === 161 /* ConstructSignature */) { + parseExpected(95 /* NewKeyword */); } - fillSignature(56 /* ColonToken */, 4 /* Type */, node); + fillSignature(57 /* ColonToken */, 4 /* Type */, node); parseTypeMemberSemicolon(); return finishNode(node); } function isIndexSignature() { - return token() === 21 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { // The only allowed sequence is: @@ -17560,7 +18423,7 @@ var ts; // [] // nextToken(); - if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) { + if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) { return true; } if (ts.isModifierKind(token())) { @@ -17579,39 +18442,39 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token() !== 55 /* QuestionToken */) { + if (token() !== 56 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; + return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(node) { - node.kind = 160 /* IndexSignature */; - node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.kind = 162 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(node) { node.name = parsePropertyName(); - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - node.kind = 153 /* MethodSignature */; + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + node.kind = 155 /* MethodSignature */; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] - fillSignature(56 /* ColonToken */, 4 /* Type */, node); + fillSignature(57 /* ColonToken */, 4 /* Type */, node); } else { - node.kind = 151 /* PropertySignature */; + node.kind = 153 /* PropertySignature */; node.type = parseTypeAnnotation(); - if (token() === 58 /* EqualsToken */) { + if (token() === 59 /* 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. @@ -17623,7 +18486,7 @@ var ts; } function isTypeMemberStart() { // Return true if we have the start of a signature member - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return true; } var idToken = false; @@ -17633,7 +18496,7 @@ var ts; nextToken(); } // Index signatures and computed property names are type members - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers @@ -17644,21 +18507,21 @@ var ts; // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token() === 19 /* OpenParenToken */ || - token() === 27 /* LessThanToken */ || - token() === 55 /* QuestionToken */ || - token() === 56 /* ColonToken */ || - token() === 26 /* CommaToken */ || + return token() === 20 /* OpenParenToken */ || + token() === 28 /* LessThanToken */ || + token() === 56 /* QuestionToken */ || + token() === 57 /* ColonToken */ || + token() === 27 /* CommaToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(158 /* CallSignature */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseSignatureMember(160 /* CallSignature */); } - if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(159 /* ConstructSignature */); + if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161 /* ConstructSignature */); } var node = createNodeWithJSDoc(0 /* Unknown */); node.modifiers = parseModifiers(); @@ -17669,30 +18532,30 @@ var ts; } function nextTokenIsOpenParenOrLessThan() { nextToken(); - return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; + return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */; } function nextTokenIsDot() { - return nextToken() === 23 /* DotToken */; + return nextToken() === 24 /* DotToken */; } function nextTokenIsOpenParenOrLessThanOrDot() { switch (nextToken()) { - case 19 /* OpenParenToken */: - case 27 /* LessThanToken */: - case 23 /* DotToken */: + case 20 /* OpenParenToken */: + case 28 /* LessThanToken */: + case 24 /* DotToken */: return true; } return false; } function parseTypeLiteral() { - var node = createNode(166 /* TypeLiteral */); + var node = createNode(168 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { members = parseList(4 /* TypeMembers */, parseTypeMember); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { members = createMissingList(); @@ -17701,89 +18564,89 @@ var ts; } function isStartOfMappedType() { nextToken(); - if (token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { - return nextToken() === 132 /* ReadonlyKeyword */; + if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + return nextToken() === 133 /* ReadonlyKeyword */; } - if (token() === 132 /* ReadonlyKeyword */) { + if (token() === 133 /* ReadonlyKeyword */) { nextToken(); } - return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; + return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */; } function parseMappedTypeParameter() { - var node = createNode(148 /* TypeParameter */); + var node = createNode(150 /* TypeParameter */); node.name = parseIdentifier(); - parseExpected(92 /* InKeyword */); + parseExpected(93 /* InKeyword */); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(179 /* MappedType */); - parseExpected(17 /* OpenBraceToken */); - if (token() === 132 /* ReadonlyKeyword */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { + var node = createNode(181 /* MappedType */); + parseExpected(18 /* OpenBraceToken */); + if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { node.readonlyToken = parseTokenNode(); - if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) { - parseExpectedToken(132 /* ReadonlyKeyword */); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + parseExpectedToken(133 /* ReadonlyKeyword */); } } - parseExpected(21 /* OpenBracketToken */); + parseExpected(22 /* OpenBracketToken */); node.typeParameter = parseMappedTypeParameter(); - parseExpected(22 /* CloseBracketToken */); - if (token() === 55 /* QuestionToken */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { + parseExpected(23 /* CloseBracketToken */); + if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { node.questionToken = parseTokenNode(); - if (node.questionToken.kind !== 55 /* QuestionToken */) { - parseExpectedToken(55 /* QuestionToken */); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + parseExpectedToken(56 /* QuestionToken */); } } node.type = parseTypeAnnotation(); parseSemicolon(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseTupleElementType() { var pos = getNodePos(); - if (parseOptional(24 /* DotDotDotToken */)) { - var node = createNode(170 /* RestType */, pos); + if (parseOptional(25 /* DotDotDotToken */)) { + var node = createNode(172 /* RestType */, pos); node.type = parseType(); return finishNode(node); } var type = parseType(); - if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 284 /* JSDocNullableType */ && type.pos === type.type.pos) { - type.kind = 169 /* OptionalType */; + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 171 /* OptionalType */; } return type; } function parseTupleType() { - var node = createNode(168 /* TupleType */); - node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + var node = createNode(170 /* TupleType */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(175 /* ParenthesizedType */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(177 /* ParenthesizedType */); + parseExpected(20 /* OpenParenToken */); node.type = parseType(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseFunctionOrConstructorType() { var pos = getNodePos(); - var kind = parseOptional(94 /* NewKeyword */) ? 164 /* ConstructorType */ : 163 /* FunctionType */; + var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */; var node = createNodeWithJSDoc(kind, pos); - fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 23 /* DotToken */ ? undefined : node; + return token() === 24 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(180 /* LiteralType */); + var node = createNode(182 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(200 /* PrefixUnaryExpression */); - unaryMinusExpression.operator = 38 /* MinusToken */; + unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 39 /* MinusToken */; nextToken(); } - var expression = token() === 101 /* TrueKeyword */ || token() === 86 /* FalseKeyword */ + var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */ ? parseTokenNode() : parseLiteralLikeNode(token()); if (negative) { @@ -17796,79 +18659,82 @@ var ts; } function isStartOfTypeOfImportType() { nextToken(); - return token() === 91 /* ImportKeyword */; + return token() === 92 /* ImportKeyword */; } function parseImportType() { sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; - var node = createNode(181 /* ImportType */); - if (parseOptional(103 /* TypeOfKeyword */)) { + var node = createNode(183 /* ImportType */); + if (parseOptional(104 /* TypeOfKeyword */)) { node.isTypeOf = true; } - parseExpected(91 /* ImportKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(92 /* ImportKeyword */); + parseExpected(20 /* OpenParenToken */); node.argument = parseType(); - parseExpected(20 /* CloseParenToken */); - if (parseOptional(23 /* DotToken */)) { + parseExpected(21 /* CloseParenToken */); + if (parseOptional(24 /* DotToken */)) { node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); } node.typeArguments = tryParseTypeArguments(); return finishNode(node); } - function nextTokenIsNumericLiteral() { - return nextToken() === 8 /* NumericLiteral */; + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */; } function parseNonArrayType() { switch (token()) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 138 /* SymbolKeyword */: - case 122 /* BooleanKeyword */: - case 140 /* UndefinedKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 139 /* SymbolKeyword */: + case 123 /* BooleanKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: return parseJSDocAllType(/*postfixEquals*/ false); - case 61 /* AsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: return parseJSDocAllType(/*postfixEquals*/ true); - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseJSDocFunctionType(); - case 51 /* ExclamationToken */: + case 52 /* ExclamationToken */: return parseJSDocNonNullableType(); - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return parseLiteralTypeNode(); - case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); - case 105 /* VoidKeyword */: - case 95 /* NullKeyword */: + case 39 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 106 /* VoidKeyword */: + case 96 /* NullKeyword */: return parseTokenNode(); - case 99 /* ThisKeyword */: { + case 100 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 103 /* TypeOfKeyword */: + case 104 /* TypeOfKeyword */: return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: return parseTupleType(); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return parseParenthesizedType(); - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return parseImportType(); default: return parseTypeReference(); @@ -17876,42 +18742,44 @@ var ts; } function isStartOfType(inStartOfParameter) { switch (token()) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 141 /* UniqueKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 103 /* TypeOfKeyword */: - case 131 /* NeverKeyword */: - case 17 /* OpenBraceToken */: - case 21 /* OpenBracketToken */: - case 27 /* LessThanToken */: - case 49 /* BarToken */: - case 48 /* AmpersandToken */: - case 94 /* NewKeyword */: - case 9 /* StringLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 142 /* UniqueKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 104 /* TypeOfKeyword */: + case 132 /* NeverKeyword */: + case 18 /* OpenBraceToken */: + case 22 /* OpenBracketToken */: + case 28 /* LessThanToken */: + case 50 /* BarToken */: + case 49 /* AmpersandToken */: + case 95 /* NewKeyword */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 135 /* ObjectKeyword */: - case 39 /* AsteriskToken */: - case 55 /* QuestionToken */: - case 51 /* ExclamationToken */: - case 24 /* DotDotDotToken */: - case 126 /* InferKeyword */: - case 91 /* ImportKeyword */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 136 /* ObjectKeyword */: + case 40 /* AsteriskToken */: + case 56 /* QuestionToken */: + case 52 /* ExclamationToken */: + case 25 /* DotDotDotToken */: + case 127 /* InferKeyword */: + case 92 /* ImportKeyword */: return true; - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return !inStartOfParameter; - case 38 /* MinusToken */: - return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); - case 19 /* OpenParenToken */: + case 39 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); @@ -17921,35 +18789,35 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 51 /* ExclamationToken */: - type = createPostfixType(285 /* JSDocNonNullableType */, type); + case 52 /* ExclamationToken */: + type = createPostfixType(287 /* JSDocNonNullableType */, type); break; - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createPostfixType(284 /* JSDocNullableType */, type); + type = createPostfixType(286 /* JSDocNullableType */, type); break; - case 21 /* OpenBracketToken */: - parseExpected(21 /* OpenBracketToken */); + case 22 /* OpenBracketToken */: + parseExpected(22 /* OpenBracketToken */); if (isStartOfType()) { - var node = createNode(178 /* IndexedAccessType */, type.pos); + var node = createNode(180 /* IndexedAccessType */, type.pos); node.objectType = type; node.indexType = parseType(); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); type = finishNode(node); } else { - var node = createNode(167 /* ArrayType */, type.pos); + var node = createNode(169 /* ArrayType */, type.pos); node.elementType = type; - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); type = finishNode(node); } break; @@ -17966,16 +18834,16 @@ var ts; return finishNode(postfix); } function parseTypeOperator(operator) { - var node = createNode(177 /* TypeOperator */); + var node = createNode(179 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseInferType() { - var node = createNode(174 /* InferType */); - parseExpected(126 /* InferKeyword */); - var typeParameter = createNode(148 /* TypeParameter */); + var node = createNode(176 /* InferType */); + parseExpected(127 /* InferKeyword */); + var typeParameter = createNode(150 /* TypeParameter */); typeParameter.name = parseIdentifier(); node.typeParameter = finishNode(typeParameter); return finishNode(node); @@ -17983,10 +18851,10 @@ var ts; function parseTypeOperatorOrHigher() { var operator = token(); switch (operator) { - case 128 /* KeyOfKeyword */: - case 141 /* UniqueKeyword */: + case 129 /* KeyOfKeyword */: + case 142 /* UniqueKeyword */: return parseTypeOperator(operator); - case 126 /* InferKeyword */: + case 127 /* InferKeyword */: return parseInferType(); } return parsePostfixTypeOrHigher(); @@ -18006,27 +18874,27 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(172 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(171 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */); } function isStartOfFunctionType() { - if (token() === 27 /* LessThanToken */) { + if (token() === 28 /* LessThanToken */) { return true; } - return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token() === 99 /* ThisKeyword */) { + if (isIdentifier() || token() === 100 /* ThisKeyword */) { nextToken(); return true; } - if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) { + if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -18036,7 +18904,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -18044,17 +18912,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || - token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || + token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token() === 20 /* CloseParenToken */) { + if (token() === 21 /* CloseParenToken */) { nextToken(); - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -18066,7 +18934,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(161 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -18077,7 +18945,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -18088,49 +18956,50 @@ var ts; return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) { + if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) { return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); - if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { - var node = createNode(173 /* ConditionalType */, type.pos); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) { + var node = createNode(175 /* ConditionalType */, type.pos); node.checkType = type; // The type following 'extends' is not permitted to be another conditional type node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); - parseExpected(55 /* QuestionToken */); + parseExpected(56 /* QuestionToken */); node.trueType = parseTypeWorker(); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.falseType = parseTypeWorker(); return finishNode(node); } return type; } function parseTypeAnnotation() { - return parseOptional(56 /* ColonToken */) ? parseType() : undefined; + return parseOptional(57 /* ColonToken */) ? parseType() : undefined; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { switch (token()) { - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 19 /* OpenParenToken */: - case 21 /* OpenBracketToken */: - case 17 /* OpenBraceToken */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 94 /* NewKeyword */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 71 /* Identifier */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 20 /* OpenParenToken */: + case 22 /* OpenBracketToken */: + case 18 /* OpenBraceToken */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 95 /* NewKeyword */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 72 /* Identifier */: return true; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); default: return isIdentifier(); @@ -18141,18 +19010,18 @@ var ts; return true; } switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 27 /* LessThanToken */: - case 121 /* AwaitKeyword */: - case 116 /* YieldKeyword */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 28 /* LessThanToken */: + case 122 /* AwaitKeyword */: + case 117 /* YieldKeyword */: // Yield/await always starts an expression. Either it is an identifier (in which case // it is definitely an expression). Or it's a keyword (either because we're in // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. @@ -18170,10 +19039,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 17 /* OpenBraceToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && - token() !== 57 /* AtToken */ && + return token() !== 18 /* OpenBraceToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + token() !== 58 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -18187,7 +19056,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) { + while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -18196,7 +19065,7 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(58 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { // AssignmentExpression[in,yield]: @@ -18241,7 +19110,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -18257,7 +19126,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 116 /* YieldKeyword */) { + if (token() === 117 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -18286,15 +19155,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(205 /* YieldExpression */); + var node = createNode(207 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 39 /* AsteriskToken */ || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + (token() === 40 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -18305,20 +19174,20 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(195 /* ArrowFunction */, asyncModifier.pos); + node = createNode(197 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(195 /* ArrowFunction */, identifier.pos); + node = createNode(197 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(149 /* Parameter */, identifier.pos); + var parameter = createNode(151 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); - node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -18343,8 +19212,8 @@ var ts; // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */); - arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return finishNode(arrowFunction); @@ -18354,10 +19223,10 @@ var ts; // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -18367,28 +19236,28 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) { + if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) { return 0 /* False */; } } var first = token(); var second = nextToken(); - if (first === 19 /* OpenParenToken */) { - if (second === 20 /* CloseParenToken */) { + if (first === 20 /* OpenParenToken */) { + if (second === 21 /* CloseParenToken */) { // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. var third = nextToken(); switch (third) { - case 36 /* EqualsGreaterThanToken */: - case 56 /* ColonToken */: - case 17 /* OpenBraceToken */: + case 37 /* EqualsGreaterThanToken */: + case 57 /* ColonToken */: + case 18 /* OpenBraceToken */: return 1 /* True */; default: return 0 /* False */; @@ -18400,42 +19269,42 @@ var ts; // ({ x }) => { } // ([ x ]) // ({ x }) - if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) { + if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) { return 2 /* Unknown */; } // Simple case: "(..." // This is an arrow function with a rest parameter. - if (second === 24 /* DotDotDotToken */) { + if (second === 25 /* DotDotDotToken */) { return 1 /* True */; } // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. - if (ts.isModifierKind(second) && second !== 120 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { return 1 /* True */; } // If we had "(" followed by something that's not an identifier, // then this definitely doesn't look like a lambda. "this" is not // valid, but we want to parse it and then give a semantic error. - if (!isIdentifier() && second !== 99 /* ThisKeyword */) { + if (!isIdentifier() && second !== 100 /* ThisKeyword */) { return 0 /* False */; } switch (nextToken()) { - case 56 /* ColonToken */: + case 57 /* ColonToken */: // If we have something like "(a:", then we must have a // type-annotated parameter in an arrow function expression. return 1 /* True */; - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: nextToken(); // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 58 /* EqualsToken */ || token() === 20 /* CloseParenToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) { return 1 /* True */; } // Otherwise it is definitely not a lambda. return 0 /* False */; - case 26 /* CommaToken */: - case 58 /* EqualsToken */: - case 20 /* CloseParenToken */: + case 27 /* CommaToken */: + case 59 /* EqualsToken */: + case 21 /* CloseParenToken */: // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function return 2 /* Unknown */; } @@ -18443,7 +19312,7 @@ var ts; return 0 /* False */; } else { - ts.Debug.assert(first === 27 /* LessThanToken */); + ts.Debug.assert(first === 28 /* LessThanToken */); // If we have "<" not followed by an identifier, // then this definitely is not an arrow function. if (!isIdentifier()) { @@ -18453,17 +19322,17 @@ var ts; if (sourceFile.languageVariant === 1 /* JSX */) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 85 /* ExtendsKeyword */) { + if (third === 86 /* ExtendsKeyword */) { var fourth = nextToken(); switch (fourth) { - case 58 /* EqualsToken */: - case 29 /* GreaterThanToken */: + case 59 /* EqualsToken */: + case 30 /* GreaterThanToken */: return false; default: return true; } } - else if (third === 26 /* CommaToken */) { + else if (third === 27 /* CommaToken */) { return true; } return false; @@ -18482,7 +19351,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); @@ -18495,23 +19364,23 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { return 1 /* True */; } } return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNodeWithJSDoc(195 /* ArrowFunction */); + var node = createNodeWithJSDoc(197 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. @@ -18521,7 +19390,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) { + if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) { return undefined; } // Parsing a signature isn't enough. @@ -18532,19 +19401,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { + if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); } - if (token() !== 25 /* SemicolonToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && + if (token() !== 26 /* SemicolonToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -18569,20 +19438,20 @@ var ts; } function parseConditionalExpressionRest(leftOperand) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - var questionToken = parseOptionalToken(55 /* QuestionToken */); + var questionToken = parseOptionalToken(56 /* QuestionToken */); if (!questionToken) { return leftOperand; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(203 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(205 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56 /* ColonToken */); + node.colonToken = parseExpectedToken(57 /* ColonToken */); node.whenFalse = ts.nodeIsPresent(node.colonToken) ? parseAssignmentExpressionOrHigher() - : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -18590,7 +19459,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 145 /* OfKeyword */; + return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -18619,16 +19488,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 92 /* InKeyword */ && inDisallowInContext()) { + if (token() === 93 /* InKeyword */ && inDisallowInContext()) { break; } - if (token() === 118 /* AsKeyword */) { + if (token() === 119 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -18649,51 +19518,51 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 92 /* InKeyword */) { + if (inDisallowInContext() && token() === 93 /* InKeyword */) { return false; } return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(202 /* BinaryExpression */, left.pos); + var node = createNode(204 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(210 /* AsExpression */, left.pos); + var node = createNode(212 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(200 /* PrefixUnaryExpression */); + var node = createNode(202 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(196 /* DeleteExpression */); + var node = createNode(198 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(197 /* TypeOfExpression */); + var node = createNode(199 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(198 /* VoidExpression */); + var node = createNode(200 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 121 /* AwaitKeyword */) { + if (token() === 122 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -18703,7 +19572,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(199 /* AwaitExpression */); + var node = createNode(201 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -18727,7 +19596,7 @@ var ts; */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? + return token() === 41 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } @@ -18744,10 +19613,10 @@ var ts; */ var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40 /* AsteriskAsteriskToken */) { + if (token() === 41 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 192 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) { parseErrorAt(pos, end, 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 { @@ -18772,23 +19641,23 @@ var ts; */ function parseSimpleUnaryExpression() { switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: return parsePrefixUnaryExpression(); - case 80 /* DeleteKeyword */: + case 81 /* DeleteKeyword */: return parseDeleteExpression(); - case 103 /* TypeOfKeyword */: + case 104 /* TypeOfKeyword */: return parseTypeOfExpression(); - case 105 /* VoidKeyword */: + case 106 /* VoidKeyword */: return parseVoidExpression(); - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // This is modified UnaryExpression grammar in TypeScript // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); - case 121 /* AwaitKeyword */: + case 122 /* AwaitKeyword */: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -18811,16 +19680,16 @@ var ts; // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 121 /* AwaitKeyword */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 122 /* AwaitKeyword */: return false; - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression if (sourceFile.languageVariant !== 1 /* JSX */) { return false; @@ -18843,21 +19712,21 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseUpdateExpression() { - if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(200 /* PrefixUnaryExpression */); + if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) { + var node = createNode(202 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(201 /* PostfixUnaryExpression */, expression.pos); + if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -18898,7 +19767,7 @@ var ts; // 3)we have a MemberExpression which either completes the LeftHandSideExpression, // or starts the beginning of the first four CallExpression productions. var expression; - if (token() === 91 /* ImportKeyword */) { + if (token() === 92 /* ImportKeyword */) { if (lookAhead(nextTokenIsOpenParenOrLessThan)) { // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" // For example: @@ -18913,8 +19782,8 @@ var ts; var fullStart = scanner.getStartPos(); nextToken(); // advance past the 'import' nextToken(); // advance past the dot - var node = createNode(212 /* MetaProperty */, fullStart); - node.keywordToken = 91 /* ImportKeyword */; + var node = createNode(214 /* MetaProperty */, fullStart); + node.keywordToken = 92 /* ImportKeyword */; node.name = parseIdentifierName(); expression = finishNode(node); sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; @@ -18924,7 +19793,7 @@ var ts; } } else { - expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); } // Now, we *may* be complete. However, we might have consumed the start of a // CallExpression. As such, we need to consume the rest of it here to be complete. @@ -18983,22 +19852,22 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) { + if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(187 /* PropertyAccessExpression */, expression.pos); + var node = createNode(189 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - parseExpectedToken(23 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 260 /* JsxOpeningElement */) { - var node = createNode(258 /* JsxElement */, opening.pos); + if (opening.kind === 262 /* JsxOpeningElement */) { + var node = createNode(260 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -19007,15 +19876,15 @@ var ts; } result = finishNode(node); } - else if (opening.kind === 263 /* JsxOpeningFragment */) { - var node = createNode(262 /* JsxFragment */, opening.pos); + else if (opening.kind === 265 /* JsxOpeningFragment */) { + var node = createNode(264 /* JsxFragment */, opening.pos); node.openingFragment = opening; node.children = parseJsxChildren(node.openingFragment); node.closingFragment = parseJsxClosingFragment(inExpressionContext); result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 259 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -19026,15 +19895,15 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token() === 27 /* LessThanToken */) { + if (inExpressionContext && token() === 28 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(202 /* BinaryExpression */, result.pos); + var badNode = createNode(204 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -19042,8 +19911,8 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10 /* JsxText */); - node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; + var node = createNode(11 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; currentToken = scanner.scanJsxToken(); return finishNode(node); } @@ -19059,15 +19928,15 @@ var ts; parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); } return undefined; - case 28 /* LessThanSlashToken */: + case 29 /* LessThanSlashToken */: case 7 /* ConflictMarkerTrivia */: return undefined; - case 10 /* JsxText */: - case 11 /* JsxTextAllWhiteSpaces */: + case 11 /* JsxText */: + case 12 /* JsxTextAllWhiteSpaces */: return parseJsxText(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); default: return ts.Debug.assertNever(token); @@ -19088,16 +19957,16 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(266 /* JsxAttributes */); + var jsxAttributes = createNode(268 /* JsxAttributes */); jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(27 /* LessThanToken */); - if (token() === 29 /* GreaterThanToken */) { + parseExpected(28 /* LessThanToken */); + if (token() === 30 /* GreaterThanToken */) { // See below for explanation of scanJsxText - var node_1 = createNode(263 /* JsxOpeningFragment */, fullStart); + var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart); scanJsxText(); return finishNode(node_1); } @@ -19105,23 +19974,23 @@ var ts; var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; - if (token() === 29 /* GreaterThanToken */) { + if (token() === 30 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(260 /* JsxOpeningElement */, fullStart); + node = createNode(262 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { - parseExpected(41 /* SlashToken */); + parseExpected(42 /* SlashToken */); if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(259 /* JsxSelfClosingElement */, fullStart); + node = createNode(261 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.typeArguments = typeArguments; @@ -19135,10 +20004,10 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token() === 99 /* ThisKeyword */ ? + var expression = token() === 100 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); + while (parseOptional(24 /* DotToken */)) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -19146,33 +20015,33 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(268 /* JsxExpression */); - if (!parseExpected(17 /* OpenBraceToken */)) { + var node = createNode(270 /* JsxExpression */); + if (!parseExpected(18 /* OpenBraceToken */)) { return undefined; } - if (token() !== 18 /* CloseBraceToken */) { - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + if (token() !== 19 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { - parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(265 /* JsxAttribute */); + var node = createNode(267 /* JsxAttribute */); node.name = parseIdentifierName(); - if (token() === 58 /* EqualsToken */) { + if (token() === 59 /* EqualsToken */) { switch (scanJsxAttributeValue()) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: node.initializer = parseLiteralNode(); break; default: @@ -19183,72 +20052,72 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(267 /* JsxSpreadAttribute */); - parseExpected(17 /* OpenBraceToken */); - parseExpected(24 /* DotDotDotToken */); + var node = createNode(269 /* JsxSpreadAttribute */); + parseExpected(18 /* OpenBraceToken */); + parseExpected(25 /* DotDotDotToken */); node.expression = parseExpression(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(261 /* JsxClosingElement */); - parseExpected(28 /* LessThanSlashToken */); + var node = createNode(263 /* JsxClosingElement */); + parseExpected(29 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxClosingFragment(inExpressionContext) { - var node = createNode(264 /* JsxClosingFragment */); - parseExpected(28 /* LessThanSlashToken */); + var node = createNode(266 /* JsxClosingFragment */); + parseExpected(29 /* LessThanSlashToken */); if (ts.tokenIsIdentifierOrKeyword(token())) { parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(192 /* TypeAssertionExpression */); - parseExpected(27 /* LessThanToken */); + var node = createNode(194 /* TypeAssertionExpression */); + parseExpected(28 /* LessThanToken */); node.type = parseType(); - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(23 /* DotToken */); + var dotToken = parseOptionalToken(24 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; } - if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(211 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName - if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(188 /* ElementAccessExpression */, expression.pos); + if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) { + var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; - if (token() === 22 /* CloseBracketToken */) { - indexedAccess.argumentExpression = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + if (token() === 23 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); } else { var argument = allowInAnd(parseExpression); @@ -19257,7 +20126,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } @@ -19269,13 +20138,13 @@ var ts; } } function isTemplateStartOfTaggedTemplate() { - return token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */; + return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */; } function parseTaggedTemplateRest(tag, typeArguments) { - var tagExpression = createNode(191 /* TaggedTemplateExpression */, tag.pos); + var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos); tagExpression.tag = tag; tagExpression.typeArguments = typeArguments; - tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); return finishNode(tagExpression); @@ -19283,7 +20152,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 27 /* LessThanToken */) { + if (token() === 28 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -19296,15 +20165,15 @@ var ts; expression = parseTaggedTemplateRest(expression, typeArguments); continue; } - var callExpr = createNode(189 /* CallExpression */, expression.pos); + var callExpr = createNode(191 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(189 /* CallExpression */, expression.pos); + else if (token() === 20 /* OpenParenToken */) { + var callExpr = createNode(191 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -19314,17 +20183,17 @@ var ts; } } function parseArgumentList() { - parseExpected(19 /* OpenParenToken */); + parseExpected(20 /* OpenParenToken */); var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(27 /* LessThanToken */)) { + if (!parseOptional(28 /* LessThanToken */)) { return undefined; } var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); - if (!parseExpected(29 /* GreaterThanToken */)) { + if (!parseExpected(30 /* GreaterThanToken */)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } @@ -19336,34 +20205,34 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 19 /* OpenParenToken */: // foo( - case 13 /* NoSubstitutionTemplateLiteral */: // foo `...` - case 14 /* TemplateHead */: // foo `...${100}...` + case 20 /* OpenParenToken */: // foo( + case 14 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 15 /* TemplateHead */: // foo `...${100}...` // these are the only tokens can legally follow a type argument // list. So we definitely want to treat them as type arg lists. - case 23 /* DotToken */: // foo. - case 20 /* CloseParenToken */: // foo) - case 22 /* CloseBracketToken */: // foo] - case 56 /* ColonToken */: // foo: - case 25 /* SemicolonToken */: // foo; - case 55 /* QuestionToken */: // foo? - case 32 /* EqualsEqualsToken */: // foo == - case 34 /* EqualsEqualsEqualsToken */: // foo === - case 33 /* ExclamationEqualsToken */: // foo != - case 35 /* ExclamationEqualsEqualsToken */: // foo !== - case 53 /* AmpersandAmpersandToken */: // foo && - case 54 /* BarBarToken */: // foo || - case 50 /* CaretToken */: // foo ^ - case 48 /* AmpersandToken */: // foo & - case 49 /* BarToken */: // foo | - case 18 /* CloseBraceToken */: // foo } + case 24 /* DotToken */: // foo. + case 21 /* CloseParenToken */: // foo) + case 23 /* CloseBracketToken */: // foo] + case 57 /* ColonToken */: // foo: + case 26 /* SemicolonToken */: // foo; + case 56 /* QuestionToken */: // foo? + case 33 /* EqualsEqualsToken */: // foo == + case 35 /* EqualsEqualsEqualsToken */: // foo === + case 34 /* ExclamationEqualsToken */: // foo != + case 36 /* ExclamationEqualsEqualsToken */: // foo !== + case 54 /* AmpersandAmpersandToken */: // foo && + case 55 /* BarBarToken */: // foo || + case 51 /* CaretToken */: // foo ^ + case 49 /* AmpersandToken */: // foo & + case 50 /* BarToken */: // foo | + case 19 /* CloseBraceToken */: // foo } case 1 /* EndOfFileToken */: // foo // these cases can't legally follow a type arg list. However, they're not legal // expressions either. The user is probably in the middle of a generic type. So // treat it as such. return true; - case 26 /* CommaToken */: // foo, - case 17 /* OpenBraceToken */: // foo { + case 27 /* CommaToken */: // foo, + case 18 /* OpenBraceToken */: // foo { // We don't want to treat these as type arguments. Otherwise we'll parse this // as an invocation expression. Instead, we want to parse out the expression // in isolation from the type arguments. @@ -19375,22 +20244,23 @@ var ts; function parsePrimaryExpression() { switch (token()) { case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return parseLiteralNode(); - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return parseTokenNode(); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return parseParenthesizedExpression(); - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: return parseArrayLiteralExpression(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseObjectLiteralExpression(); - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. // If we encounter `async [no LineTerminator here] function` then this is an async // function; otherwise, its an identifier. @@ -19398,75 +20268,76 @@ var ts; break; } return parseFunctionExpression(); - case 75 /* ClassKeyword */: + case 76 /* ClassKeyword */: return parseClassExpression(); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseFunctionExpression(); - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: return parseNewExpressionOrNewDotTarget(); - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) { return parseLiteralNode(); } break; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNodeWithJSDoc(193 /* ParenthesizedExpression */); - parseExpected(19 /* OpenParenToken */); + var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(206 /* SpreadElement */); - parseExpected(24 /* DotDotDotToken */); + var node = createNode(208 /* SpreadElement */); + parseExpected(25 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(208 /* OmittedExpression */) : + return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(185 /* ArrayLiteralExpression */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(187 /* ArrayLiteralExpression */); + parseExpected(22 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function parseObjectLiteralElement() { var node = createNodeWithJSDoc(0 /* Unknown */); - if (parseOptionalToken(24 /* DotDotDotToken */)) { - node.kind = 275 /* SpreadAssignment */; + if (parseOptionalToken(25 /* DotDotDotToken */)) { + node.kind = 277 /* SpreadAssignment */; node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* GetAccessor */); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); } - if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 157 /* SetAccessor */); + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); } - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } // check if it is short-hand property assignment or normal property assignment @@ -19474,30 +20345,30 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */); if (isShorthandPropertyAssignment) { - node.kind = 274 /* ShorthandPropertyAssignment */; - var equalsToken = parseOptionalToken(58 /* EqualsToken */); + node.kind = 276 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(59 /* EqualsToken */); if (equalsToken) { node.equalsToken = equalsToken; node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } } else { - node.kind = 273 /* PropertyAssignment */; - parseExpected(56 /* ColonToken */); + node.kind = 275 /* PropertyAssignment */; + parseExpected(57 /* ColonToken */); node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(186 /* ObjectLiteralExpression */); - parseExpected(17 /* OpenBraceToken */); + var node = createNode(188 /* ObjectLiteralExpression */); + parseExpected(18 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseFunctionExpression() { @@ -19510,10 +20381,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNodeWithJSDoc(194 /* FunctionExpression */); + var node = createNodeWithJSDoc(196 /* FunctionExpression */); node.modifiers = parseModifiers(); - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; node.name = @@ -19521,7 +20392,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlock(isGenerator | isAsync); if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -19533,10 +20404,10 @@ var ts; } function parseNewExpressionOrNewDotTarget() { var fullStart = scanner.getStartPos(); - parseExpected(94 /* NewKeyword */); - if (parseOptional(23 /* DotToken */)) { - var node_2 = createNode(212 /* MetaProperty */, fullStart); - node_2.keywordToken = 94 /* NewKeyword */; + parseExpected(95 /* NewKeyword */); + if (parseOptional(24 /* DotToken */)) { + var node_2 = createNode(214 /* MetaProperty */, fullStart); + node_2.keywordToken = 95 /* NewKeyword */; node_2.name = parseIdentifierName(); return finishNode(node_2); } @@ -19552,23 +20423,23 @@ var ts; } break; } - var node = createNode(190 /* NewExpression */, fullStart); + var node = createNode(192 /* NewExpression */, fullStart); node.expression = expression; node.typeArguments = typeArguments; - if (node.typeArguments || token() === 19 /* OpenParenToken */) { + if (node.typeArguments || token() === 20 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(216 /* Block */); - if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(218 /* Block */); + if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -19595,52 +20466,52 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(218 /* EmptyStatement */); - parseExpected(25 /* SemicolonToken */); + var node = createNode(220 /* EmptyStatement */); + parseExpected(26 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(220 /* IfStatement */); - parseExpected(90 /* IfKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(222 /* IfStatement */); + parseExpected(91 /* IfKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined; + node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(221 /* DoStatement */); - parseExpected(81 /* DoKeyword */); + var node = createNode(223 /* DoStatement */); + parseExpected(82 /* DoKeyword */); node.statement = parseStatement(); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. - parseOptional(25 /* SemicolonToken */); + parseOptional(26 /* SemicolonToken */); return finishNode(node); } function parseWhileStatement() { - var node = createNode(222 /* WhileStatement */); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(224 /* WhileStatement */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(88 /* ForKeyword */); - var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(89 /* ForKeyword */); + var awaitToken = parseOptionalToken(122 /* AwaitKeyword */); + parseExpected(20 /* OpenParenToken */); var initializer; - if (token() !== 25 /* SemicolonToken */) { - if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { + if (token() !== 26 /* SemicolonToken */) { + if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -19648,33 +20519,33 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(145 /* OfKeyword */) : parseOptional(145 /* OfKeyword */)) { - var forOfStatement = createNode(225 /* ForOfStatement */, pos); + if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) { + var forOfStatement = createNode(227 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } - else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(224 /* ForInStatement */, pos); + else if (parseOptional(93 /* InKeyword */)) { + var forInStatement = createNode(226 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(223 /* ForStatement */, pos); + var forStatement = createNode(225 /* ForStatement */, pos); forStatement.initializer = initializer; - parseExpected(25 /* SemicolonToken */); - if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { + parseExpected(26 /* SemicolonToken */); + if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(25 /* SemicolonToken */); - if (token() !== 20 /* CloseParenToken */) { + parseExpected(26 /* SemicolonToken */); + if (token() !== 21 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -19682,7 +20553,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 227 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -19690,8 +20561,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(228 /* ReturnStatement */); - parseExpected(96 /* ReturnKeyword */); + var node = createNode(230 /* ReturnStatement */); + parseExpected(97 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -19699,42 +20570,42 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(229 /* WithStatement */); - parseExpected(107 /* WithKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(231 /* WithStatement */); + parseExpected(108 /* WithKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(269 /* CaseClause */); - parseExpected(73 /* CaseKeyword */); + var node = createNode(271 /* CaseClause */); + parseExpected(74 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(270 /* DefaultClause */); - parseExpected(79 /* DefaultKeyword */); - parseExpected(56 /* ColonToken */); + var node = createNode(272 /* DefaultClause */); + parseExpected(80 /* DefaultKeyword */); + parseExpected(57 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(230 /* SwitchStatement */); - parseExpected(98 /* SwitchKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(232 /* SwitchStatement */); + parseExpected(99 /* SwitchKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(244 /* CaseBlock */); - parseExpected(17 /* OpenBraceToken */); + parseExpected(21 /* CloseParenToken */); + var caseBlock = createNode(246 /* CaseBlock */); + parseExpected(18 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); node.caseBlock = finishNode(caseBlock); return finishNode(node); } @@ -19746,32 +20617,32 @@ 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(232 /* ThrowStatement */); - parseExpected(100 /* ThrowKeyword */); + var node = createNode(234 /* ThrowStatement */); + parseExpected(101 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(233 /* TryStatement */); - parseExpected(102 /* TryKeyword */); + var node = createNode(235 /* TryStatement */); + parseExpected(103 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token() === 87 /* FinallyKeyword */) { - parseExpected(87 /* FinallyKeyword */); + if (!node.catchClause || token() === 88 /* FinallyKeyword */) { + parseExpected(88 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(272 /* CatchClause */); - parseExpected(74 /* CatchKeyword */); - if (parseOptional(19 /* OpenParenToken */)) { + var result = createNode(274 /* CatchClause */); + parseExpected(75 /* CatchKeyword */); + if (parseOptional(20 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); } else { // Keep shape of node to avoid degrading performance. @@ -19781,8 +20652,8 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(234 /* DebuggerStatement */); - parseExpected(78 /* DebuggerKeyword */); + var node = createNode(236 /* DebuggerStatement */); + parseExpected(79 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); } @@ -19792,13 +20663,13 @@ var ts; // a colon. var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); - if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - node.kind = 231 /* LabeledStatement */; + if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) { + node.kind = 233 /* LabeledStatement */; node.label = expression; node.statement = parseStatement(); } else { - node.kind = 219 /* ExpressionStatement */; + node.kind = 221 /* ExpressionStatement */; node.expression = expression; parseSemicolon(); } @@ -19810,25 +20681,25 @@ var ts; } function nextTokenIsClassKeywordOnSameLine() { nextToken(); - return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: return true; // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; // however, an identifier cannot be followed by another identifier on the same line. This is what we @@ -19851,41 +20722,41 @@ var ts; // I {} // // could be legal, it would add complexity for very little gain. - case 109 /* InterfaceKeyword */: - case 139 /* TypeKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 132 /* ReadonlyKeyword */: + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: nextToken(); // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 144 /* GlobalKeyword */: + case 145 /* GlobalKeyword */: nextToken(); - return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; - case 91 /* ImportKeyword */: + return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */; + case 92 /* ImportKeyword */: nextToken(); - return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); - case 84 /* ExportKeyword */: + return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 85 /* ExportKeyword */: nextToken(); - if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ || - token() === 118 /* AsKeyword */) { + if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ || + token() === 119 /* AsKeyword */) { return true; } continue; - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: nextToken(); continue; default: @@ -19898,50 +20769,50 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 57 /* AtToken */: - case 25 /* SemicolonToken */: - case 17 /* OpenBraceToken */: - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 90 /* IfKeyword */: - case 81 /* DoKeyword */: - case 106 /* WhileKeyword */: - case 88 /* ForKeyword */: - case 77 /* ContinueKeyword */: - case 72 /* BreakKeyword */: - case 96 /* ReturnKeyword */: - case 107 /* WithKeyword */: - case 98 /* SwitchKeyword */: - case 100 /* ThrowKeyword */: - case 102 /* TryKeyword */: - case 78 /* DebuggerKeyword */: + case 58 /* AtToken */: + case 26 /* SemicolonToken */: + case 18 /* OpenBraceToken */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 91 /* IfKeyword */: + case 82 /* DoKeyword */: + case 107 /* WhileKeyword */: + case 89 /* ForKeyword */: + case 78 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 97 /* ReturnKeyword */: + case 108 /* WithKeyword */: + case 99 /* SwitchKeyword */: + case 101 /* ThrowKeyword */: + case 103 /* TryKeyword */: + case 79 /* DebuggerKeyword */: // 'catch' and 'finally' do not actually indicate that the code is part of a statement, // however, we say they are here so that we may gracefully parse them and error later. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return true; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); - case 76 /* ConstKeyword */: - case 84 /* ExportKeyword */: + case 77 /* ConstKeyword */: + case 85 /* ExportKeyword */: return isStartOfDeclaration(); - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 109 /* InterfaceKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: - case 139 /* TypeKeyword */: - case 144 /* GlobalKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 110 /* InterfaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 140 /* TypeKeyword */: + case 145 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 116 /* StaticKeyword */: + case 133 /* 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); @@ -19951,7 +20822,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */; + return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -19960,67 +20831,67 @@ var ts; } function parseStatement() { switch (token()) { - case 25 /* SemicolonToken */: + case 26 /* SemicolonToken */: return parseEmptyStatement(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); - case 104 /* VarKeyword */: - return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); - case 110 /* LetKeyword */: + case 105 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + case 111 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); } break; - case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(createNodeWithJSDoc(237 /* FunctionDeclaration */)); - case 75 /* ClassKeyword */: - return parseClassDeclaration(createNodeWithJSDoc(238 /* ClassDeclaration */)); - case 90 /* IfKeyword */: + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */)); + case 76 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */)); + case 91 /* IfKeyword */: return parseIfStatement(); - case 81 /* DoKeyword */: + case 82 /* DoKeyword */: return parseDoStatement(); - case 106 /* WhileKeyword */: + case 107 /* WhileKeyword */: return parseWhileStatement(); - case 88 /* ForKeyword */: + case 89 /* ForKeyword */: return parseForOrForInOrForOfStatement(); - case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(226 /* ContinueStatement */); - case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(227 /* BreakStatement */); - case 96 /* ReturnKeyword */: + case 78 /* ContinueKeyword */: + return parseBreakOrContinueStatement(228 /* ContinueStatement */); + case 73 /* BreakKeyword */: + return parseBreakOrContinueStatement(229 /* BreakStatement */); + case 97 /* ReturnKeyword */: return parseReturnStatement(); - case 107 /* WithKeyword */: + case 108 /* WithKeyword */: return parseWithStatement(); - case 98 /* SwitchKeyword */: + case 99 /* SwitchKeyword */: return parseSwitchStatement(); - case 100 /* ThrowKeyword */: + case 101 /* ThrowKeyword */: return parseThrowStatement(); - case 102 /* TryKeyword */: + case 103 /* TryKeyword */: // Include 'catch' and 'finally' for error recovery. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return parseTryStatement(); - case 78 /* DebuggerKeyword */: + case 79 /* DebuggerKeyword */: return parseDebuggerStatement(); - case 57 /* AtToken */: + case 58 /* AtToken */: return parseDeclaration(); - case 120 /* AsyncKeyword */: - case 109 /* InterfaceKeyword */: - case 139 /* TypeKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 83 /* EnumKeyword */: - case 84 /* ExportKeyword */: - case 91 /* ImportKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: - case 144 /* GlobalKeyword */: + case 121 /* AsyncKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 84 /* EnumKeyword */: + case 85 /* ExportKeyword */: + case 92 /* ImportKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 118 /* AbstractKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + case 145 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -20029,7 +20900,7 @@ var ts; return parseExpressionOrLabeledStatement(); } function isDeclareModifier(modifier) { - return modifier.kind === 124 /* DeclareKeyword */; + return modifier.kind === 125 /* DeclareKeyword */; } function parseDeclaration() { var node = createNodeWithJSDoc(0 /* Unknown */); @@ -20048,33 +20919,33 @@ var ts; } function parseDeclarationWorker(node) { switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: return parseVariableStatement(node); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseFunctionDeclaration(node); - case 75 /* ClassKeyword */: + case 76 /* ClassKeyword */: return parseClassDeclaration(node); - case 109 /* InterfaceKeyword */: + case 110 /* InterfaceKeyword */: return parseInterfaceDeclaration(node); - case 139 /* TypeKeyword */: + case 140 /* TypeKeyword */: return parseTypeAliasDeclaration(node); - case 83 /* EnumKeyword */: + case 84 /* EnumKeyword */: return parseEnumDeclaration(node); - case 144 /* GlobalKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: + case 145 /* GlobalKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: return parseModuleDeclaration(node); - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return parseImportDeclarationOrImportEqualsDeclaration(node); - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: nextToken(); switch (token()) { - case 79 /* DefaultKeyword */: - case 58 /* EqualsToken */: + case 80 /* DefaultKeyword */: + case 59 /* EqualsToken */: return parseExportAssignment(node); - case 118 /* AsKeyword */: + case 119 /* AsKeyword */: return parseNamespaceExportDeclaration(node); default: return parseExportDeclaration(node); @@ -20083,7 +20954,7 @@ var ts; if (node.decorators || node.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 missing = createMissingNode(256 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; @@ -20094,10 +20965,10 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) { + if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -20105,25 +20976,25 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token() === 26 /* CommaToken */) { - return createNode(208 /* OmittedExpression */); + if (token() === 27 /* CommaToken */) { + return createNode(210 /* OmittedExpression */); } - var node = createNode(184 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(184 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56 /* ColonToken */) { + if (tokenIsIdentifier && token() !== 57 /* ColonToken */) { node.name = propertyName; } else { - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -20131,27 +21002,27 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(182 /* ObjectBindingPattern */); - parseExpected(17 /* OpenBraceToken */); + var node = createNode(184 /* ObjectBindingPattern */); + parseExpected(18 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(183 /* ArrayBindingPattern */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(185 /* ArrayBindingPattern */); + parseExpected(22 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier(); + return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -20160,10 +21031,10 @@ var ts; return parseVariableDeclaration(/*allowExclamation*/ true); } function parseVariableDeclaration(allowExclamation) { - var node = createNode(235 /* VariableDeclaration */); + var node = createNode(237 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); - if (allowExclamation && node.name.kind === 71 /* Identifier */ && - token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (allowExclamation && node.name.kind === 72 /* Identifier */ && + token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -20173,14 +21044,14 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(236 /* VariableDeclarationList */); + var node = createNode(238 /* VariableDeclarationList */); switch (token()) { - case 104 /* VarKeyword */: + case 105 /* VarKeyword */: break; - case 110 /* LetKeyword */: + case 111 /* LetKeyword */: node.flags |= 1 /* Let */; break; - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: node.flags |= 2 /* Const */; break; default: @@ -20196,7 +21067,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() === 145 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -20208,44 +21079,44 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; + return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */; } function parseVariableStatement(node) { - node.kind = 217 /* VariableStatement */; + node.kind = 219 /* VariableStatement */; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return finishNode(node); } function parseFunctionDeclaration(node) { - node.kind = 237 /* FunctionDeclaration */; - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.kind = 239 /* FunctionDeclaration */; + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); return finishNode(node); } function parseConstructorDeclaration(node) { - node.kind = 155 /* Constructor */; - parseExpected(123 /* ConstructorKeyword */); - fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.kind = 157 /* Constructor */; + parseExpected(124 /* ConstructorKeyword */); + fillSignature(57 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); return finishNode(node); } function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { - node.kind = 154 /* MethodDeclaration */; + node.kind = 156 /* MethodDeclaration */; node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); return finishNode(node); } function parsePropertyDeclaration(node) { - node.kind = 152 /* PropertyDeclaration */; - if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.kind = 154 /* PropertyDeclaration */; + if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -20265,12 +21136,12 @@ var ts; return finishNode(node); } function parsePropertyOrMethodDeclaration(node) { - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } return parsePropertyDeclaration(node); @@ -20278,13 +21149,13 @@ var ts; function parseAccessorDeclaration(node, kind) { node.kind = kind; node.name = parsePropertyName(); - fillSignature(56 /* ColonToken */, 0 /* None */, node); + fillSignature(57 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */); return finishNode(node); } function isClassMemberStart() { var idToken; - if (token() === 57 /* AtToken */) { + if (token() === 58 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. @@ -20301,7 +21172,7 @@ var ts; } nextToken(); } - if (token() === 39 /* AsteriskToken */) { + if (token() === 40 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. @@ -20311,24 +21182,24 @@ var ts; nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... if (idToken !== undefined) { // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!ts.isKeyword(idToken) || idToken === 136 /* SetKeyword */ || idToken === 125 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. switch (token()) { - case 19 /* OpenParenToken */: // Method declaration - case 27 /* LessThanToken */: // Generic Method declaration - case 51 /* ExclamationToken */: // Non-null assertion on property name - case 56 /* ColonToken */: // Type Annotation for declaration - case 58 /* EqualsToken */: // Initializer for declaration - case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. + case 20 /* OpenParenToken */: // Method declaration + case 28 /* LessThanToken */: // Generic Method declaration + case 52 /* ExclamationToken */: // Non-null assertion on property name + case 57 /* ColonToken */: // Type Annotation for declaration + case 59 /* EqualsToken */: // Initializer for declaration + case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. return true; default: // Covers @@ -20346,10 +21217,10 @@ var ts; var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(57 /* AtToken */)) { + if (!parseOptional(58 /* AtToken */)) { break; } - var decorator = createNode(150 /* Decorator */, decoratorStart); + var decorator = createNode(152 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -20369,7 +21240,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) { + if (token() === 77 /* 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)) { @@ -20388,7 +21259,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -20398,21 +21269,21 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 25 /* SemicolonToken */) { - var result = createNode(215 /* SemicolonClassElement */); + if (token() === 26 /* SemicolonToken */) { + var result = createNode(217 /* SemicolonClassElement */); nextToken(); return finishNode(result); } var node = createNodeWithJSDoc(0 /* Unknown */); node.decorators = parseDecorators(); node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* GetAccessor */); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); } - if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 157 /* SetAccessor */); + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); } - if (token() === 123 /* ConstructorKeyword */) { + if (token() === 124 /* ConstructorKeyword */) { return parseConstructorDeclaration(node); } if (isIndexSignature()) { @@ -20421,37 +21292,37 @@ var ts; // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || + token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || - token() === 39 /* AsteriskToken */ || - token() === 21 /* OpenBracketToken */) { + token() === 40 /* AsteriskToken */ || + token() === 22 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(node); } if (node.decorators || node.modifiers) { // treat this as a property declaration with a missing name. - node.name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 207 /* ClassExpression */); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */); } function parseClassDeclaration(node) { - return parseClassDeclarationOrExpression(node, 238 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(node, kind) { node.kind = kind; - parseExpected(75 /* ClassKeyword */); + parseExpected(76 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } node.members = parseClassMembers(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -20469,7 +21340,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses() { // ClassTail[Yield,Await] : (Modified) See 14.5 @@ -20481,33 +21352,33 @@ var ts; } function parseHeritageClause() { var tok = token(); - ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. - var node = createNode(271 /* HeritageClause */); + ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(273 /* HeritageClause */); node.token = tok; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); } function parseExpressionWithTypeArguments() { - var node = createNode(209 /* ExpressionWithTypeArguments */); + var node = createNode(211 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); node.typeArguments = tryParseTypeArguments(); return finishNode(node); } function tryParseTypeArguments() { - return token() === 27 /* LessThanToken */ - ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + return token() === 28 /* LessThanToken */ + ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */) : undefined; } function isHeritageClause() { - return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(node) { - node.kind = 239 /* InterfaceDeclaration */; - parseExpected(109 /* InterfaceKeyword */); + node.kind = 241 /* InterfaceDeclaration */; + parseExpected(110 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); @@ -20515,11 +21386,11 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(node) { - node.kind = 240 /* TypeAliasDeclaration */; - parseExpected(139 /* TypeKeyword */); + node.kind = 242 /* TypeAliasDeclaration */; + parseExpected(140 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(58 /* EqualsToken */); + parseExpected(59 /* EqualsToken */); node.type = parseType(); parseSemicolon(); return finishNode(node); @@ -20529,18 +21400,18 @@ 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 = createNodeWithJSDoc(276 /* EnumMember */); + var node = createNodeWithJSDoc(278 /* EnumMember */); node.name = parsePropertyName(); node.initializer = allowInAnd(parseInitializer); return finishNode(node); } function parseEnumDeclaration(node) { - node.kind = 241 /* EnumDeclaration */; - parseExpected(83 /* EnumKeyword */); + node.kind = 243 /* EnumDeclaration */; + parseExpected(84 /* EnumKeyword */); node.name = parseIdentifier(); - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -20548,10 +21419,10 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(243 /* ModuleBlock */); - if (parseExpected(17 /* OpenBraceToken */)) { + var node = createNode(245 /* ModuleBlock */); + if (parseExpected(18 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -20559,20 +21430,20 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(node, flags) { - node.kind = 242 /* ModuleDeclaration */; + node.kind = 244 /* ModuleDeclaration */; // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(23 /* DotToken */) + node.body = parseOptional(24 /* DotToken */) ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(node) { - node.kind = 242 /* ModuleDeclaration */; - if (token() === 144 /* GlobalKeyword */) { + node.kind = 244 /* ModuleDeclaration */; + if (token() === 145 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -20581,7 +21452,7 @@ var ts; node.name = parseLiteralNode(); node.name.text = internIdentifier(node.name.text); } - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -20591,68 +21462,68 @@ var ts; } function parseModuleDeclaration(node) { var flags = 0; - if (token() === 144 /* GlobalKeyword */) { + if (token() === 145 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(node); } - else if (parseOptional(130 /* NamespaceKeyword */)) { + else if (parseOptional(131 /* NamespaceKeyword */)) { flags |= 16 /* Namespace */; } else { - parseExpected(129 /* ModuleKeyword */); - if (token() === 9 /* StringLiteral */) { + parseExpected(130 /* ModuleKeyword */); + if (token() === 10 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(node); } } return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { - return token() === 133 /* RequireKeyword */ && + return token() === 134 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 19 /* OpenParenToken */; + return nextToken() === 20 /* OpenParenToken */; } function nextTokenIsSlash() { - return nextToken() === 41 /* SlashToken */; + return nextToken() === 42 /* SlashToken */; } function parseNamespaceExportDeclaration(node) { - node.kind = 245 /* NamespaceExportDeclaration */; - parseExpected(118 /* AsKeyword */); - parseExpected(130 /* NamespaceKeyword */); + node.kind = 247 /* NamespaceExportDeclaration */; + parseExpected(119 /* AsKeyword */); + parseExpected(131 /* NamespaceKeyword */); node.name = parseIdentifier(); parseSemicolon(); return finishNode(node); } function parseImportDeclarationOrImportEqualsDeclaration(node) { - parseExpected(91 /* ImportKeyword */); + parseExpected(92 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 143 /* FromKeyword */) { + if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) { return parseImportEqualsDeclaration(node, identifier); } } // Import statement - node.kind = 247 /* ImportDeclaration */; + node.kind = 249 /* ImportDeclaration */; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || // import id - token() === 39 /* AsteriskToken */ || // import * - token() === 17 /* OpenBraceToken */) { // import { + token() === 40 /* AsteriskToken */ || // import * + token() === 18 /* OpenBraceToken */) { // import { node.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(143 /* FromKeyword */); + parseExpected(144 /* FromKeyword */); } node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(node); } function parseImportEqualsDeclaration(node, identifier) { - node.kind = 246 /* ImportEqualsDeclaration */; + node.kind = 248 /* ImportEqualsDeclaration */; node.name = identifier; - parseExpected(58 /* EqualsToken */); + parseExpected(59 /* EqualsToken */); node.moduleReference = parseModuleReference(); parseSemicolon(); return finishNode(node); @@ -20664,7 +21535,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(248 /* ImportClause */, fullStart); + var importClause = createNode(250 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -20673,8 +21544,8 @@ var ts; // If there was no default import or if there is comma token after default import // parse namespace or named imports if (!importClause.name || - parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(250 /* NamedImports */); + parseOptional(27 /* CommaToken */)) { + importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */); } return finishNode(importClause); } @@ -20684,15 +21555,15 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(257 /* ExternalModuleReference */); - parseExpected(133 /* RequireKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(259 /* ExternalModuleReference */); + parseExpected(134 /* RequireKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = parseModuleSpecifier(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9 /* StringLiteral */) { + if (token() === 10 /* StringLiteral */) { var result = parseLiteralNode(); result.text = internIdentifier(result.text); return result; @@ -20707,9 +21578,9 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(249 /* NamespaceImport */); - parseExpected(39 /* AsteriskToken */); - parseExpected(118 /* AsKeyword */); + var namespaceImport = createNode(251 /* NamespaceImport */); + parseExpected(40 /* AsteriskToken */); + parseExpected(119 /* AsKeyword */); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } @@ -20722,14 +21593,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(255 /* ExportSpecifier */); + return parseImportOrExportSpecifier(257 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(251 /* ImportSpecifier */); + return parseImportOrExportSpecifier(253 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -20743,9 +21614,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 118 /* AsKeyword */) { + if (token() === 119 /* AsKeyword */) { node.propertyName = identifierName; - parseExpected(118 /* AsKeyword */); + parseExpected(119 /* AsKeyword */); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -20754,24 +21625,24 @@ var ts; else { node.name = identifierName; } - if (kind === 251 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(node) { - node.kind = 253 /* ExportDeclaration */; - if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(143 /* FromKeyword */); + node.kind = 255 /* ExportDeclaration */; + if (parseOptional(40 /* AsteriskToken */)) { + parseExpected(144 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(254 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(256 /* 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() === 143 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(143 /* FromKeyword */); + if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(144 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -20779,12 +21650,12 @@ var ts; return finishNode(node); } function parseExportAssignment(node) { - node.kind = 252 /* ExportAssignment */; - if (parseOptional(58 /* EqualsToken */)) { + node.kind = 254 /* ExportAssignment */; + if (parseOptional(59 /* EqualsToken */)) { node.isExportEquals = true; } else { - parseExpected(79 /* DefaultKeyword */); + parseExpected(80 /* DefaultKeyword */); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -20799,10 +21670,10 @@ var ts; } function isAnExternalModuleIndicatorNode(node) { return ts.hasModifier(node, 1 /* Export */) - || node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */ - || node.kind === 247 /* ImportDeclaration */ - || node.kind === 252 /* ExportAssignment */ - || node.kind === 253 /* ExportDeclaration */ + || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */ + || node.kind === 249 /* ImportDeclaration */ + || node.kind === 254 /* ExportAssignment */ + || node.kind === 255 /* ExportDeclaration */ ? node : undefined; } @@ -20815,7 +21686,7 @@ var ts; return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); } function isImportMeta(node) { - return ts.isMetaProperty(node) && node.keywordToken === 91 /* ImportKeyword */ && node.name.escapedText === "meta"; + return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta"; } var ParsingContext; (function (ParsingContext) { @@ -20866,11 +21737,11 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); - var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); + var result = createNode(283 /* JSDocTypeExpression */); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } fixupParentReferences(result); return finishNode(result); @@ -20958,7 +21829,7 @@ var ts; } loop: while (true) { switch (token()) { - case 57 /* AtToken */: + case 58 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingWhitespace(comments); addTag(parseTag(indent)); @@ -20978,7 +21849,7 @@ var ts; state = 0 /* BeginningOfLine */; indent = 0; break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: var asterisk = scanner.getTokenText(); if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { // If we've already seen an asterisk, then we can no longer parse a tag on this line @@ -20991,13 +21862,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21012,7 +21876,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21034,7 +21900,7 @@ var ts; } } function createJSDocComment() { - var result = createNode(289 /* JSDocComment */, start); + var result = createNode(291 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -21068,61 +21934,60 @@ var ts; } } var precedingLineBreak = scanner.hasPrecedingLineBreak(); - while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { if (token() === 4 /* NewLineTrivia */) { precedingLineBreak = true; } - else if (token() === 39 /* AsteriskToken */) { + else if (token() === 40 /* AsteriskToken */) { precedingLineBreak = false; } nextJSDocToken(); } } function parseTag(indent) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getTokenPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": case "extends": - tag = parseAugmentsTag(atToken, tagName); + tag = parseAugmentsTag(start, tagName); break; case "class": case "constructor": - tag = parseClassTag(atToken, tagName); + tag = parseClassTag(start, tagName); break; case "this": - tag = parseThisTag(atToken, tagName); + tag = parseThisTag(start, tagName); break; case "enum": - tag = parseEnumTag(atToken, tagName); + tag = parseEnumTag(start, tagName); break; case "arg": case "argument": case "param": - return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent); + return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent); case "return": case "returns": - tag = parseReturnTag(atToken, tagName); + tag = parseReturnTag(start, tagName); break; case "template": - tag = parseTemplateTag(atToken, tagName); + tag = parseTemplateTag(start, tagName); break; case "type": - tag = parseTypeTag(atToken, tagName); + tag = parseTypeTag(start, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName, indent); + tag = parseTypedefTag(start, tagName, indent); break; case "callback": - tag = parseCallbackTag(atToken, tagName, indent); + tag = parseCallbackTag(start, tagName, indent); break; default: - tag = parseUnknownTag(atToken, tagName); + tag = parseUnknownTag(start, tagName); break; } if (!tag.comment) { @@ -21152,7 +22017,7 @@ var ts; } indent = 0; break; - case 57 /* AtToken */: + case 58 /* AtToken */: scanner.setTextPos(scanner.getTextPos() - 1); // falls through case 1 /* EndOfFileToken */: @@ -21171,9 +22036,9 @@ var ts; indent += whitespace.length; } break; - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: state = 2 /* SavingComments */; - if (lookAhead(function () { return nextJSDocToken() === 57 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { pushComment(scanner.getTokenText()); nextJSDocToken(); pushComment(scanner.getTokenText()); @@ -21181,7 +22046,7 @@ var ts; } pushComment(scanner.getTokenText()); break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; @@ -21201,9 +22066,8 @@ var ts; removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } - function parseUnknownTag(atToken, tagName) { - var result = createNode(292 /* JSDocTag */, atToken.pos); - result.atToken = atToken; + function parseUnknownTag(start, tagName) { + var result = createNode(294 /* JSDocTag */, start); result.tagName = tagName; return finishNode(result); } @@ -21222,37 +22086,37 @@ var ts; } function tryParseTypeExpression() { skipWhitespaceOrAsterisk(); - return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; + return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { - if (token() === 13 /* NoSubstitutionTemplateLiteral */) { + if (token() === 14 /* NoSubstitutionTemplateLiteral */) { // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; } // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' - var isBracketed = parseOptional(21 /* OpenBracketToken */); + var isBracketed = parseOptional(22 /* OpenBracketToken */); var name = parseJSDocEntityName(); if (isBracketed) { skipWhitespace(); // May have an optional default, e.g. '[foo = 42]' - if (parseOptionalToken(58 /* EqualsToken */)) { + if (parseOptionalToken(59 /* EqualsToken */)) { parseExpression(); } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); } return { name: name, isBracketed: isBracketed }; } function isObjectOrObjectArrayTypeReference(node) { switch (node.kind) { - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return true; - case 167 /* ArrayType */: + case 169 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; } } - function parseParameterOrPropertyTag(atToken, tagName, target, indent) { + function parseParameterOrPropertyTag(start, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -21262,17 +22126,14 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(303 /* JSDocPropertyTag */, atToken.pos) : - createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + createNode(305 /* JSDocPropertyTag */, start) : + createNode(299 /* JSDocParameterTag */, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; } - result.atToken = atToken; result.tagName = tagName; result.typeExpression = typeExpression; result.name = name; @@ -21281,22 +22142,22 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 167 /* ArrayType */) { + if (typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -21304,81 +22165,74 @@ var ts; } } } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) { + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(298 /* JSDocReturnTag */, atToken.pos); - result.atToken = atToken; + var result = createNode(300 /* JSDocReturnTag */, start); result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) { + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(300 /* JSDocTypeTag */, atToken.pos); - result.atToken = atToken; + var result = createNode(302 /* JSDocTypeTag */, start); result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } - function parseAugmentsTag(atToken, tagName) { - var result = createNode(293 /* JSDocAugmentsTag */, atToken.pos); - result.atToken = atToken; + function parseAugmentsTag(start, tagName) { + var result = createNode(295 /* JSDocAugmentsTag */, start); result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } function parseExpressionWithTypeArgumentsForAugments() { - var usedBrace = parseOptional(17 /* OpenBraceToken */); - var node = createNode(209 /* ExpressionWithTypeArguments */); + var usedBrace = parseOptional(18 /* OpenBraceToken */); + var node = createNode(211 /* ExpressionWithTypeArguments */); node.expression = parsePropertyAccessEntityNameExpression(); node.typeArguments = tryParseTypeArguments(); var res = finishNode(node); if (usedBrace) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } return res; } function parsePropertyAccessEntityNameExpression() { var node = parseJSDocIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var prop = createNode(187 /* PropertyAccessExpression */, node.pos); + while (parseOptional(24 /* DotToken */)) { + var prop = createNode(189 /* PropertyAccessExpression */, node.pos); prop.expression = node; prop.name = parseJSDocIdentifierName(); node = finishNode(prop); } return node; } - function parseClassTag(atToken, tagName) { - var tag = createNode(294 /* JSDocClassTag */, atToken.pos); - tag.atToken = atToken; + function parseClassTag(start, tagName) { + var tag = createNode(296 /* JSDocClassTag */, start); tag.tagName = tagName; return finishNode(tag); } - function parseThisTag(atToken, tagName) { - var tag = createNode(299 /* JSDocThisTag */, atToken.pos); - tag.atToken = atToken; + function parseThisTag(start, tagName) { + var tag = createNode(301 /* JSDocThisTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseEnumTag(atToken, tagName) { - var tag = createNode(296 /* JSDocEnumTag */, atToken.pos); - tag.atToken = atToken; + function parseEnumTag(start, tagName) { + var tag = createNode(298 /* JSDocEnumTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseTypedefTag(atToken, tagName, indent) { + function parseTypedefTag(start, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); - typedefTag.atToken = atToken; + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304 /* JSDocTypedefTag */, start); typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); @@ -21390,12 +22244,11 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); } - if (child.kind === 300 /* JSDocTypeTag */) { + if (child.kind === 302 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -21408,7 +22261,7 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 167 /* ArrayType */) { + if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? @@ -21426,8 +22279,8 @@ var ts; return undefined; } var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(242 /* ModuleDeclaration */, pos); + if (parseOptional(24 /* DotToken */)) { + var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos); if (nested) { jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } @@ -21440,25 +22293,23 @@ var ts; } return typeNameOrNamespaceName; } - function parseCallbackTag(atToken, tagName, indent) { - var callbackTag = createNode(295 /* JSDocCallbackTag */, atToken.pos); - callbackTag.atToken = atToken; + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297 /* JSDocCallbackTag */, start); callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); skipWhitespace(); callbackTag.comment = parseTagComments(indent); var child; - var start = scanner.getStartPos(); - var jsdocSignature = createNode(291 /* JSDocSignature */, start); + var jsdocSignature = createNode(293 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { - if (parseOptionalJsdoc(57 /* AtToken */)) { + if (parseOptionalJsdoc(58 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 298 /* JSDocReturnTag */) { + if (tag && tag.kind === 300 /* JSDocReturnTag */) { return tag; } } @@ -21492,18 +22343,18 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { - case 57 /* AtToken */: + case 58 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); - if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -21516,13 +22367,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 71 /* Identifier */: + case 72 /* Identifier */: canParseTag = false; break; case 1 /* EndOfFileToken */: @@ -21530,17 +22381,16 @@ var ts; } } } - function tryParseChildTag(target) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */); - atToken.end = scanner.getTextPos(); + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getStartPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); skipWhitespace(); var t; switch (tagName.escapedText) { case "type": - return target === 1 /* Property */ && parseTypeTag(atToken, tagName); + return target === 1 /* Property */ && parseTypeTag(start, tagName); case "prop": case "property": t = 1 /* Property */; @@ -21556,28 +22406,25 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(start, tagName, target, indent); } - function parseTemplateTag(atToken, tagName) { + function parseTemplateTag(start, tagName) { // the template tag looks like '@template {Constraint} T,U,V' var constraint; - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { constraint = parseJSDocTypeExpression(); } var typeParameters = []; var typeParametersPos = getNodePos(); do { skipWhitespace(); - var typeParameter = createNode(148 /* TypeParameter */); + var typeParameter = createNode(150 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); finishNode(typeParameter); skipWhitespace(); typeParameters.push(typeParameter); - } while (parseOptionalJsdoc(26 /* CommaToken */)); - var result = createNode(301 /* JSDocTemplateTag */, atToken.pos); - result.atToken = atToken; + } while (parseOptionalJsdoc(27 /* CommaToken */)); + var result = createNode(303 /* JSDocTemplateTag */, start); result.tagName = tagName; result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -21596,16 +22443,16 @@ var ts; } function parseJSDocEntityName() { var entity = parseJSDocIdentifierName(); - if (parseOptional(21 /* OpenBracketToken */)) { - parseExpected(22 /* CloseBracketToken */); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> // but it's not worth it to enforce that restriction. } - while (parseOptional(23 /* DotToken */)) { + while (parseOptional(24 /* DotToken */)) { var name = parseJSDocIdentifierName(); - if (parseOptional(21 /* OpenBracketToken */)) { - parseExpected(22 /* CloseBracketToken */); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); } entity = createQualifiedName(entity, name); } @@ -21613,11 +22460,11 @@ var ts; } function parseJSDocIdentifierName(message) { if (!ts.tokenIsIdentifierOrKeyword(token())) { - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(71 /* Identifier */, pos); + var result = createNode(72 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); @@ -21743,9 +22590,9 @@ var ts; } function shouldCheckNode(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 71 /* Identifier */: + case 72 /* Identifier */: return true; } return false; @@ -22323,10 +23170,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 71 /* Identifier */) { + if (lhs.kind === 72 /* Identifier */) { return lhs.escapedText === rhs.escapedText; } - if (lhs.kind === 99 /* ThisKeyword */) { + if (lhs.kind === 100 /* ThisKeyword */) { return true; } // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only @@ -22383,7 +23230,8 @@ var ts; ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.symbol", "lib.esnext.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], - ["esnext.intl", "lib.esnext.intl.d.ts"] + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -22399,8 +23247,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +23261,61 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22455,26 +23357,11 @@ var ts; description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date }, { - name: "pretty", + name: "showConfig", type: "boolean", - showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental - }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, // Basic { @@ -22490,6 +23377,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23397,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23410,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23418,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23436,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23546,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23555,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23564,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23590,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23599,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23633,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23646,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23654,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23664,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23680,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23692,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23703,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22862,42 +23776,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h }, - { - name: "diagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_diagnostic_information - }, - { - name: "extendedDiagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_verbose_diagnostic_information - }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23840,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23860,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23906,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23914,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23942,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23970,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +24061,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +24111,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +24131,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +24139,7 @@ var ts; 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)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +24175,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +24218,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +24243,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23432,6 +24398,9 @@ var ts; } var result = ts.parseJsonText(configFileName, configFileText); var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; @@ -23571,7 +24540,7 @@ var ts; var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 273 /* PropertyAssignment */) { + if (element.kind !== 275 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -23619,20 +24588,24 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { - case 101 /* TrueKeyword */: + case 102 /* TrueKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return true; - case 86 /* FalseKeyword */: + case 87 /* FalseKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return false; - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for return null; // tslint:disable-line:no-null-keyword - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } @@ -23649,13 +24622,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 200 /* PrefixUnaryExpression */: - if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + case 202 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return -Number(valueExpression.operand.text); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -23672,7 +24645,7 @@ var ts; return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); } - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -23712,6 +24685,115 @@ var ts; } return false; } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return false; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + } + return function (path) { return includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return !excludeRe.test(path); }; + } + return function (_) { return false; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } /** * Generate tsconfig configuration when running command line "--init" * @param options commandlineOptions to be generated into tsconfig.json @@ -23722,62 +24804,6 @@ var ts; var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - // There is a typeMap associated with this command-line option so use it to map value back to its name - return ts.forEachEntry(customTypeMap, function (mapValue, key) { - if (mapValue === value) { - return key; - } - }); - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_3 = function (name) { - if (ts.hasProperty(options, name)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - return "continue"; - } - var value = options[name]; - var optionDefinition = optionsNameMap.get(name.toLowerCase()); - if (optionDefinition) { - var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap_1) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result.set(name, value); - } - else { - if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); - } - } - } - } - }; - for (var name in options) { - _loop_3(name); - } - return result; - } function getDefaultValueForOption(option) { switch (option.type) { case "number": @@ -23926,7 +24952,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24970,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23980,19 +25021,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +25040,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +25053,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24110,11 +25165,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24142,26 +25192,30 @@ var ts; } function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { - errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return undefined; - } - var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return undefined; + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } } + return extendedConfigPath; } - return extendedConfigPath; + // If the path isn't a rooted or relative path, resolve like a module + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +25223,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25437,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24408,10 +25462,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24421,9 +25480,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24431,7 +25506,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24442,16 +25517,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24584,7 +25659,7 @@ var ts; } } /** - * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. * Also converts enum values back to strings. */ /* @internal */ @@ -24640,6 +25715,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24649,14 +25730,15 @@ var ts; Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; Extensions[Extensions["Json"] = 2] = "Json"; - Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */ + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25747,97 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24748,9 +25879,13 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24769,8 +25904,10 @@ var ts; trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24779,13 +25916,12 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - if (!options.preserveSymlinks) { - resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); - } + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -24794,14 +25930,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } - return ts.forEach(typeRoots, function (typeRoot) { + return ts.firstDefined(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,8 +25953,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - var resolvedFile = resolvedTypeScriptOnly(result && result.value); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + var resolvedFile = resolvedTypeScriptOnly(result); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -24856,14 +26000,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -24874,29 +26022,56 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); } ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + /*@internal*/ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName) { + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); - var perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = ts.createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); } - function getOrCreateCacheForModuleName(nonRelativeModuleName) { + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); - var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); } - return perModuleNameCache; + return result; } function createPerModuleNameCache() { var directoryPathMap = ts.createMap(); @@ -24971,13 +26146,19 @@ var ts; return perFolderCache && perFolderCache.get(moduleName); } ts.resolveModuleNameFromCache = resolveModuleNameFromCache; - function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } var containingDirectory = ts.getDirectoryPath(containingFile); - var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { @@ -24999,10 +26180,10 @@ var ts; } switch (moduleResolution) { case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; default: return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); @@ -25011,7 +26192,7 @@ var ts; perFolderCache.set(moduleName, result); if (!ts.isExternalModuleNameRelative(moduleName)) { // put result in per-module name cache - cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); } } } @@ -25086,15 +26267,28 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +26326,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +26345,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,95 +26356,72 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!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); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; - function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? - tryResolve(Extensions.JavaScript) : - (tryResolve(Extensions.TypeScript) || - tryResolve(Extensions.JavaScript) || - (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); if (result && result.value) { var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +26435,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +26452,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,10 +26483,15 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; /** * This will be called on the successfully resolved path from `loadModuleFromFile`. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) @@ -25352,52 +26529,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @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; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - if (extensions === Extensions.Json) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25407,16 +26578,17 @@ var ts; return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.TSConfig: case Extensions.Json: return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26602,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26640,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,51 +26652,72 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { - // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25542,6 +26729,7 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TSConfig: case Extensions.Json: return extension === ".json" /* Json */; case Extensions.TypeScript: @@ -25550,87 +26738,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26868,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,68 +26881,69 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } - function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } if (!ts.isExternalModuleNameRelative(moduleName)) { - var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26958,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25758,24 +26989,24 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: if (!(ts.hasModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. other uninstantiated module declarations. - case 243 /* ModuleBlock */: { + case 245 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateWorker(n); @@ -25797,9 +27028,9 @@ var ts; }); return state_1; } - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return getModuleInstanceState(node); - case 71 /* Identifier */: + case 72 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should // be considered the same as type alias if (node.isInJSDocNamespace) { @@ -25944,19 +27175,23 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + 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.kind === 252 /* ExportAssignment */) { + if (node.kind === 254 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -25965,7 +27200,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -25977,36 +27212,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: return "__constructor" /* Constructor */; - case 163 /* FunctionType */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: + case 165 /* FunctionType */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: return "__call" /* Call */; - case 164 /* ConstructorType */: - case 159 /* ConstructSignature */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: return "__new" /* New */; - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return "__index" /* Index */; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 149 /* Parameter */: + case 151 /* 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 === 287 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -26075,7 +27310,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26103,7 +27339,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; } @@ -26130,7 +27366,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 255 /* ExportSpecifier */ || (node.kind === 246 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -26153,12 +27389,12 @@ var ts; // 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.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26197,7 +27433,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 195 /* ArrowFunction */) { + if (node.kind !== 197 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -26229,7 +27465,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property intialization checks. - currentReturnTarget = isIIFE || node.kind === 155 /* Constructor */ ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; @@ -26242,13 +27478,13 @@ var ts; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { node.flags |= emitFlags; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 155 /* Constructor */) { + if (node.kind === 157 /* Constructor */) { node.returnFlowNode = currentFlow; } } @@ -26291,8 +27527,8 @@ var ts; } } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -26321,81 +27557,82 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: bindWhileStatement(node); break; - case 221 /* DoStatement */: + case 223 /* DoStatement */: bindDoStatement(node); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: bindForStatement(node); break; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: bindIfStatement(node); break; - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: bindTryStatement(node); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: bindSwitchStatement(node); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: bindCaseBlock(node); break; - case 269 /* CaseClause */: + case 271 /* CaseClause */: bindCaseClause(node); break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: bindLabeledStatement(node); break; - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: bindCallExpressionFlow(node); break; - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 277 /* SourceFile */: { + case 279 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; default: @@ -26406,24 +27643,26 @@ var ts; } function isNarrowingExpression(expr) { switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return isNarrowableReference(expr); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return hasNarrowableArgument(expr); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 200 /* PrefixUnaryExpression */: - return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 202 /* PrefixUnaryExpression */: + return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 199 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || + return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && @@ -26438,7 +27677,7 @@ var ts; } } } - if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26452,32 +27691,32 @@ var ts; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return isNarrowableReference(expr.left); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); - case 92 /* InKeyword */: + case 93 /* InKeyword */: return isNarrowableInOperands(expr.left, expr.right); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return isNarrowableOperand(expr.right); } } @@ -26512,8 +27751,8 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -26551,34 +27790,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 220 /* IfStatement */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: return parent.expression === node; - case 223 /* ForStatement */: - case 203 /* ConditionalExpression */: + case 225 /* ForStatement */: + case 205 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 193 /* ParenthesizedExpression */) { + if (node.kind === 195 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 200 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 202 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 54 /* BarBarToken */); + return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 55 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 193 /* ParenthesizedExpression */ || - node.parent.kind === 200 /* PrefixUnaryExpression */ && - node.parent.operator === 51 /* ExclamationToken */) { + while (node.parent.kind === 195 /* ParenthesizedExpression */ || + node.parent.kind === 202 /* PrefixUnaryExpression */ && + node.parent.operator === 52 /* ExclamationToken */) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -26619,7 +27858,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 231 /* LabeledStatement */ + var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */ ? ts.lastOrUndefined(activeLabels) : undefined; // if do statement is wrapped in labeled statement then target labels for break/continue with or without @@ -26653,13 +27892,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 225 /* ForOfStatement */) { + if (node.kind === 227 /* ForOfStatement */) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 236 /* VariableDeclarationList */) { + if (node.initializer.kind !== 238 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -26681,7 +27920,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 228 /* ReturnStatement */) { + if (node.kind === 230 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -26701,7 +27940,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 227 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -26797,7 +28036,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 270 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; @@ -26821,7 +28060,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -26865,14 +28103,14 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } - if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { + if (!node.statement || node.statement.kind !== 223 /* DoStatement */) { // do statement sets current flow inside bindDoStatement addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -26883,10 +28121,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 185 /* ArrayLiteralExpression */) { + else if (node.kind === 187 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 206 /* SpreadElement */) { + if (e.kind === 208 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -26894,16 +28132,16 @@ var ts; } } } - else if (node.kind === 186 /* ObjectLiteralExpression */) { + else if (node.kind === 188 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 273 /* PropertyAssignment */) { + if (p.kind === 275 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 274 /* ShorthandPropertyAssignment */) { + else if (p.kind === 276 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 275 /* SpreadAssignment */) { + else if (p.kind === 277 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -26911,7 +28149,7 @@ var ts; } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -26922,7 +28160,7 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51 /* ExclamationToken */) { + if (node.operator === 52 /* ExclamationToken */) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; @@ -26932,20 +28170,20 @@ var ts; } else { bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -26959,7 +28197,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 188 /* ElementAccessExpression */) { + if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -26970,7 +28208,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -27008,6 +28246,7 @@ var ts; } } function bindJSDocTypeAlias(node) { + node.tagName.parent = node; if (node.fullName) { setParentPointers(node, node.fullName); } @@ -27017,10 +28256,10 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 193 /* ParenthesizedExpression */) { + while (expr.kind === 195 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 194 /* FunctionExpression */ || expr.kind === 195 /* ArrowFunction */) { + if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -27028,7 +28267,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -27037,54 +28276,54 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 186 /* ObjectLiteralExpression */: - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 266 /* JsxAttributes */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 268 /* JsxAttributes */: return 1 /* IsContainer */; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 179 /* MappedType */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: - case 287 /* JSDocFunctionType */: - case 163 /* FunctionType */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 164 /* ConstructorType */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 289 /* JSDocFunctionType */: + case 165 /* FunctionType */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 166 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 272 /* CatchClause */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 244 /* CaseBlock */: + case 274 /* CatchClause */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 246 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 216 /* Block */: + case 218 /* 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 @@ -27117,45 +28356,45 @@ var ts; // 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 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 277 /* SourceFile */: + case 279 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 186 /* ObjectLiteralExpression */: - case 239 /* InterfaceDeclaration */: - case 266 /* JsxAttributes */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 188 /* ObjectLiteralExpression */: + case 241 /* InterfaceDeclaration */: + case 268 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 291 /* JSDocSignature */: - case 160 /* IndexSignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 287 /* JSDocFunctionType */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 240 /* TypeAliasDeclaration */: - case 179 /* MappedType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 293 /* JSDocSignature */: + case 162 /* IndexSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 289 /* JSDocFunctionType */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -27176,11 +28415,11 @@ var ts; : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 277 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 277 /* SourceFile */ || body.kind === 243 /* ModuleBlock */)) { + var body = node.kind === 279 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 253 /* ExportDeclaration */ || stat.kind === 252 /* ExportAssignment */) { + if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { return true; } } @@ -27208,7 +28447,7 @@ var ts; } else { var pattern = void 0; - if (node.name.kind === 9 /* StringLiteral */) { + if (node.name.kind === 10 /* StringLiteral */) { var text = node.name.text; if (ts.hasZeroOrOneAsteriskCharacter(text)) { pattern = ts.tryParsePattern(text); @@ -27217,7 +28456,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +28476,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27264,7 +28503,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) { continue; } var identifier = prop.name; @@ -27276,7 +28515,7 @@ var ts; // 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 === 273 /* PropertyAssignment */ || prop.kind === 274 /* ShorthandPropertyAssignment */ || prop.kind === 154 /* MethodDeclaration */ + var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -27308,10 +28547,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -27325,9 +28564,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27345,9 +28581,9 @@ var ts; currentFlow = { flags: 2 /* Start */ }; parent = typeAlias; bind(typeAlias.typeExpression); - if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { + if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27363,8 +28599,8 @@ var ts; // check for reserved words used as identifiers in strict mode code. function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && + node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 117 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && !(node.flags & 4194304 /* Ambient */)) { // Report error only if there are no parse errors in file @@ -27400,7 +28636,7 @@ var ts; } function checkStrictModeDeleteExpression(node) { // Grammar checking - if (inStrictMode && node.expression.kind === 71 /* Identifier */) { + if (inStrictMode && node.expression.kind === 72 /* 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); @@ -27411,7 +28647,7 @@ var ts; return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71 /* Identifier */) { + if (name && name.kind === 72 /* 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 @@ -27452,8 +28688,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 277 /* SourceFile */ && - blockScopeContainer.kind !== 242 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 279 /* SourceFile */ && + blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -27479,7 +28715,7 @@ var ts; function checkStrictModePrefixUnaryExpression(node) { // Grammar checking if (inStrictMode) { - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -27548,7 +28784,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 145 /* LastToken */) { + if (node.kind > 147 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -27572,7 +28808,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27610,7 +28846,7 @@ var ts; function bindWorker(node) { switch (node.kind) { /* Strict mode checks */ - case 71 /* Identifier */: + case 72 /* Identifier */: // for typedef type names with namespaces, bind the new jsdoc type symbol here // because it requires all containing namespaces to be in effect, namely the // current "blockScopeContainer" needs to be set to its immediate namespace parent. @@ -27619,32 +28855,32 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through - case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 274 /* ShorthandPropertyAssignment */)) { + case 100 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; - case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27668,142 +28904,155 @@ var ts; // Nothing to do break; default: - ts.Debug.fail("Unknown special property assignment kind"); + ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return checkStrictModeCatchClause(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return checkStrictModeWithStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 176 /* ThisType */: + case 178 /* ThisType */: seenThisKeyword = true; return; - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: break; // Binding the children will handle everything - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return bindTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return bindParameter(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return bindPropertyWorker(node); - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 276 /* EnumMember */: + case 278 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); - case 237 /* FunctionDeclaration */: + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); + case 239 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); - case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); - case 163 /* FunctionType */: - case 287 /* JSDocFunctionType */: - case 291 /* JSDocSignature */: - case 164 /* ConstructorType */: + case 158 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); + case 159 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + case 166 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 179 /* MappedType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 181 /* MappedType */: return bindAnonymousTypeWorker(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return bindFunctionExpression(node); - case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + case 191 /* CallExpression */: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; // Nothing to do + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); - case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - case 241 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); + case 242 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + case 243 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return bindJsxAttributes(node); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return bindImportClause(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return bindExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return bindExportAssignment(node); - case 277 /* SourceFile */: + case 279 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 216 /* Block */: + case 218 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 297 /* JSDocParameterTag */: - if (node.parent.kind === 291 /* JSDocSignature */) { + case 299 /* JSDocParameterTag */: + if (node.parent.kind === 293 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 290 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { break; } // falls through - case 303 /* JSDocPropertyTag */: + case 305 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -27835,37 +29084,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27892,6 +29139,21 @@ var ts; } return true; } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } function bindExportsPropertyAssignment(node) { // When we create a property via 'exports.foo = bar', the 'exports.foo' property access // expression is the declaration @@ -27901,7 +29163,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27928,17 +29190,17 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. - if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) { var l = thisContainer.parent.left; if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); @@ -27951,18 +29213,18 @@ var ts; declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } break; - case 155 /* Constructor */: - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: // this.foo assignment in a source file // Do not bind. It would be nice to support this someday though. break; @@ -27971,10 +29233,10 @@ var ts; } } function bindSpecialPropertyDeclaration(node) { - if (node.expression.kind === 99 /* ThisKeyword */) { + if (node.expression.kind === 100 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 277 /* SourceFile */) { + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -27988,7 +29250,11 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28005,11 +29271,17 @@ var ts; classPrototype.parent = lhs; bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } function bindSpecialPropertyAssignment(node) { var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28033,42 +29305,48 @@ var ts; node.expression.parent = node; bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); } - function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) - : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; - namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ + : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,11 +29355,14 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -28090,7 +29371,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28132,7 +29413,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 238 /* ClassDeclaration */) { + if (node.kind === 240 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); } else { @@ -28174,8 +29455,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,15 +29471,15 @@ var ts; // 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 */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } function bindParameter(node) { - if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -28207,7 +29491,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +29509,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,26 +29550,26 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 174 /* InferType */) { + else if (node.parent.kind === 176 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28300,13 +29584,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 218 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) || // report error on class declarations - node.kind === 238 /* ClassDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,24 +29626,23 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return true; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.hasModifier(s, 2048 /* Const */); default: return false; } } - /* @internal */ function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || @@ -28382,6 +29663,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28393,58 +29677,58 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return computeNewExpression(node, subtreeFlags); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); - case 149 /* Parameter */: + case 151 /* Parameter */: return computeParameter(node, subtreeFlags); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return computeCatchClause(node, subtreeFlags); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 155 /* Constructor */: + case 157 /* Constructor */: return computeConstructor(node, subtreeFlags); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return computePropertyDeclaration(node, subtreeFlags); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return computeMethod(node, subtreeFlags); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -28457,61 +29741,61 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } - if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + if (expression.kind === 92 /* ImportKeyword */) { + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 186 /* ObjectLiteralExpression */) { + if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ESNext if they contain rest transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 185 /* ArrayLiteralExpression */) { + else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ - || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { + else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ + || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28522,25 +29806,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28550,8 +29834,8 @@ 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 (expressionKind === 210 /* AsExpression */ - || expressionKind === 192 /* TypeAssertionExpression */) { + if (expressionKind === 212 /* AsExpression */ + || expressionKind === 194 /* TypeAssertionExpression */) { transformFlags |= 3 /* AssertTypeScript */; } // If the expression of a ParenthesizedExpression is a destructuring assignment, @@ -28575,44 +29859,44 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 85 /* ExtendsKeyword */: + case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; - case 108 /* ImplementsKeyword */: + case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; @@ -28621,7 +29905,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28632,7 +29916,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28644,7 +29928,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28654,11 +29938,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28674,7 +29958,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28685,7 +29969,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28699,11 +29983,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28711,10 +29995,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28726,7 +30010,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28739,13 +30023,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28758,7 +30042,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28774,13 +30058,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28790,7 +30074,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28807,26 +30091,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28834,18 +30120,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28853,7 +30141,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28864,22 +30152,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28888,7 +30176,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28899,7 +30187,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28908,78 +30196,78 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { - case 120 /* AsyncKeyword */: - case 199 /* AwaitExpression */: + case 121 /* AsyncKeyword */: + case 201 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 306 /* PartiallyEmittedExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; break; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 211 /* NonNullExpression */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 213 /* NonNullExpression */: + case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: - case 10 /* JsxText */: - case 261 /* JsxClosingElement */: - case 262 /* JsxFragment */: - case 263 /* JsxOpeningFragment */: - case 264 /* JsxClosingFragment */: - case 265 /* JsxAttribute */: - case 266 /* JsxAttributes */: - case 267 /* JsxSpreadAttribute */: - case 268 /* JsxExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 11 /* JsxText */: + case 263 /* JsxClosingElement */: + case 264 /* JsxFragment */: + case 265 /* JsxOpeningFragment */: + case 266 /* JsxClosingFragment */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 270 /* JsxExpression */: // These nodes are Jsx syntax. transformFlags |= 4 /* AssertJsx */; break; - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 204 /* TemplateExpression */: - case 191 /* TaggedTemplateExpression */: - case 274 /* ShorthandPropertyAssignment */: - case 115 /* StaticKeyword */: - case 212 /* MetaProperty */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + case 276 /* ShorthandPropertyAssignment */: + case 116 /* StaticKeyword */: + case 214 /* MetaProperty */: // These nodes are ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { transformFlags |= 192 /* AssertES2015 */; } @@ -28989,65 +30277,69 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } break; - case 225 /* ForOfStatement */: + case 9 /* BigIntLiteral */: + transformFlags |= 8 /* AssertESNext */; + break; + case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { transformFlags |= 8 /* AssertESNext */; } transformFlags |= 192 /* AssertES2015 */; break; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 148 /* TypeParameter */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 161 /* TypePredicate */: - case 162 /* TypeReference */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 165 /* TypeQuery */: - case 166 /* TypeLiteral */: - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 169 /* OptionalType */: - case 170 /* RestType */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 173 /* ConditionalType */: - case 174 /* InferType */: - case 175 /* ParenthesizedType */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 176 /* ThisType */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 180 /* LiteralType */: - case 245 /* NamespaceExportDeclaration */: + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 163 /* TypePredicate */: + case 164 /* TypeReference */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 167 /* TypeQuery */: + case 168 /* TypeLiteral */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 176 /* InferType */: + case 177 /* ParenthesizedType */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = 3 /* AssertTypeScript */; excludeFlags = -3 /* TypeExcludes */; break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29056,93 +30348,93 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + case 208 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; - case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + case 277 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; - case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + case 184 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; - case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + case 185 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; - case 150 /* Decorator */: + case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; - case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + case 188 /* ObjectLiteralExpression */: + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; } break; - case 185 /* ArrayLiteralExpression */: - case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + case 187 /* ArrayLiteralExpression */: + case 192 /* NewExpression */: + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } break; - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + case 279 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29155,71 +30447,71 @@ var ts; * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather * than calling this function. */ - /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) { + if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { return -3 /* TypeExcludes */; } switch (kind) { - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; - case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; - case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; - case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; - case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 137 /* StringKeyword */: - case 135 /* ObjectKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 148 /* TypeParameter */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 187 /* ArrayLiteralExpression */: + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + case 244 /* ModuleDeclaration */: + return 647001409 /* ModuleExcludes */; + case 151 /* Parameter */: + return 637535553 /* ParameterExcludes */; + case 197 /* ArrowFunction */: + return 653604161 /* ArrowFunctionExcludes */; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return 653620545 /* FunctionExcludes */; + case 238 /* VariableDeclarationList */: + return 639894849 /* VariableDeclarationListExcludes */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 638121281 /* ClassExcludes */; + case 157 /* Constructor */: + return 653616449 /* ConstructorExcludes */; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return 653616449 /* MethodOrAccessorExcludes */; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 138 /* StringKeyword */: + case 136 /* ObjectKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; - case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; - case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 306 /* PartiallyEmittedExpression */: - case 193 /* ParenthesizedExpression */: - case 97 /* SuperKeyword */: + case 188 /* ObjectLiteralExpression */: + return 638358849 /* ObjectLiteralExcludes */; + case 274 /* CatchClause */: + return 637797697 /* CatchClauseExcludes */; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return 637666625 /* BindingPatternExcludes */; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + case 195 /* ParenthesizedExpression */: + case 98 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29277,7 +30569,7 @@ var ts; if (shouldBail) return; // Visit the type's related types, if any - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var objectType = type; var objectFlags = objectType.objectFlags; if (objectFlags & 4 /* Reference */) { @@ -29293,16 +30585,16 @@ var ts; visitObjectType(objectType); } } - if (type.flags & 65536 /* TypeParameter */) { + if (type.flags & 262144 /* TypeParameter */) { visitTypeParameter(type); } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { visitUnionOrIntersectionType(type); } - if (type.flags & 1048576 /* Index */) { + if (type.flags & 4194304 /* Index */) { visitIndexType(type); } - if (type.flags & 2097152 /* IndexedAccess */) { + if (type.flags & 8388608 /* IndexedAccess */) { visitIndexedAccessType(type); } } @@ -29391,7 +30683,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 165 /* TypeQuery */) { + if (d.type && d.type.kind === 167 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -29434,6 +30726,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30758,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29463,10 +30768,12 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); @@ -29625,27 +30932,13 @@ var ts; var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); return parsed ? isImplementationOfOverload(parsed) : undefined; }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return ts.Debug.fail(); - links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); - } - return links.immediateTarget; - }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { - var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isParameter); @@ -29669,15 +30962,17 @@ var ts; getNumberType: function () { return numberType; }, createPromiseType: createPromiseType, createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, getESSymbolType: function () { return esSymbolType; }, getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -29685,7 +30980,7 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, - getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, @@ -29739,7 +31034,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29762,24 +31058,43 @@ var ts; var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); - var undefinedType = createIntrinsicType(8192 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(8192 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(16384 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(16384 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); - var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); - var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); - var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(4096 /* Void */, "void"); - var neverType = createIntrinsicType(32768 /* Never */, "never"); - var silentNeverType = createIntrinsicType(32768 /* Never */, "never"); - var implicitNeverType = createIntrinsicType(32768 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -29792,18 +31107,18 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(65536 /* TypeParameter */); - var markerSubType = createType(65536 /* TypeParameter */); + var markerSuperType = createType(262144 /* TypeParameter */); + var markerSubType = createType(262144 /* TypeParameter */); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(65536 /* TypeParameter */); + var markerOtherType = createType(262144 /* TypeParameter */); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29815,6 +31130,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +31150,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +31162,9 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29852,6 +31172,7 @@ var ts; var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -29877,84 +31198,99 @@ var ts; TypeFacts[TypeFacts["None"] = 0] = "None"; TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; - TypeFacts[TypeFacts["TypeofEQBoolean"] = 4] = "TypeofEQBoolean"; - TypeFacts[TypeFacts["TypeofEQSymbol"] = 8] = "TypeofEQSymbol"; - TypeFacts[TypeFacts["TypeofEQObject"] = 16] = "TypeofEQObject"; - TypeFacts[TypeFacts["TypeofEQFunction"] = 32] = "TypeofEQFunction"; - TypeFacts[TypeFacts["TypeofEQHostObject"] = 64] = "TypeofEQHostObject"; - TypeFacts[TypeFacts["TypeofNEString"] = 128] = "TypeofNEString"; - TypeFacts[TypeFacts["TypeofNENumber"] = 256] = "TypeofNENumber"; - TypeFacts[TypeFacts["TypeofNEBoolean"] = 512] = "TypeofNEBoolean"; - TypeFacts[TypeFacts["TypeofNESymbol"] = 1024] = "TypeofNESymbol"; - TypeFacts[TypeFacts["TypeofNEObject"] = 2048] = "TypeofNEObject"; - TypeFacts[TypeFacts["TypeofNEFunction"] = 4096] = "TypeofNEFunction"; - TypeFacts[TypeFacts["TypeofNEHostObject"] = 8192] = "TypeofNEHostObject"; - TypeFacts[TypeFacts["EQUndefined"] = 16384] = "EQUndefined"; - TypeFacts[TypeFacts["EQNull"] = 32768] = "EQNull"; - TypeFacts[TypeFacts["EQUndefinedOrNull"] = 65536] = "EQUndefinedOrNull"; - TypeFacts[TypeFacts["NEUndefined"] = 131072] = "NEUndefined"; - TypeFacts[TypeFacts["NENull"] = 262144] = "NENull"; - TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; - TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; - TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["All"] = 4194303] = "All"; + TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; + TypeFacts[TypeFacts["All"] = 16777215] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. - TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; - TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; - TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; - TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; - TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; - TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; - TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; - TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; - TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; - TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; - TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; - TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; - TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; - TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; - TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; - TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; - TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; - TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; - TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; - TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; - TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; - TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; - TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; - TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; - TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; - TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts"; + TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts"; + TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, number: 2 /* TypeofEQNumber */, - boolean: 4 /* TypeofEQBoolean */, - symbol: 8 /* TypeofEQSymbol */, - undefined: 16384 /* EQUndefined */, - object: 16 /* TypeofEQObject */, - function: 32 /* TypeofEQFunction */ + bigint: 4 /* TypeofEQBigInt */, + boolean: 8 /* TypeofEQBoolean */, + symbol: 16 /* TypeofEQSymbol */, + undefined: 65536 /* EQUndefined */, + object: 32 /* TypeofEQObject */, + function: 64 /* TypeofEQFunction */ }); var typeofNEFacts = ts.createMapFromTemplate({ - string: 128 /* TypeofNEString */, - number: 256 /* TypeofNENumber */, - boolean: 512 /* TypeofNEBoolean */, - symbol: 1024 /* TypeofNESymbol */, - undefined: 131072 /* NEUndefined */, - object: 2048 /* TypeofNEObject */, - function: 4096 /* TypeofNEFunction */ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ }); var typeofTypesByName = ts.createMapFromTemplate({ string: stringType, number: numberType, + bigint: bigintType, boolean: booleanType, symbol: esSymbolType, undefined: undefinedType @@ -29975,6 +31311,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +31448,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,10 +31509,14 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { - target = cloneSymbol(target); + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); } // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { @@ -30184,8 +31526,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30204,55 +31547,56 @@ var ts; else if (target.flags & 1024 /* NamespaceModule */) { error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } - else { + else { // error var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30268,7 +31612,8 @@ var ts; } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { - target.set(id, target.has(id) ? mergeSymbol(target.get(id), sourceSymbol) : sourceSymbol); + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); }); } function mergeModuleAugmentation(moduleName) { @@ -30330,7 +31675,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { - return node.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -30360,8 +31705,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30388,17 +31733,17 @@ var ts; } if (declaration.pos <= usage.pos) { // declaration is before usage - if (declaration.kind === 184 /* BindingElement */) { + if (declaration.kind === 186 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 184 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 235 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage); } - else if (declaration.kind === 235 /* VariableDeclaration */) { + else if (declaration.kind === 237 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -30417,12 +31762,12 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 252 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -30430,9 +31775,9 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 217 /* VariableStatement */: - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 219 /* VariableStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -30453,16 +31798,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 152 /* PropertyDeclaration */ && + current.parent.kind === 154 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 154 /* MethodDeclaration */) { + if (declaration.kind === 156 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -30504,27 +31849,35 @@ var ts; // - 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 & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 149 /* Parameter */ || - lastLocation.kind === 148 /* TypeParameter */ + lastLocation.kind === 151 /* Parameter */ || + lastLocation.kind === 150 /* TypeParameter */ // local types not visible outside the function body : false; } - if (meaning & 67216319 /* 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 === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (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 === 151 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } - else if (location.kind === 173 /* ConditionalType */) { + else if (location.kind === 175 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -30538,14 +31891,14 @@ var ts; } } switch (location.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -30569,7 +31922,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 255 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) { break; } } @@ -30583,13 +31936,13 @@ var ts; } } break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* 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 @@ -30599,17 +31952,20 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } } } break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30624,7 +31980,7 @@ var ts; } break loop; } - if (location.kind === 207 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -30632,11 +31988,11 @@ var ts; } } break; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. - if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { + if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30652,29 +32008,29 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -30687,7 +32043,7 @@ var ts; } } break; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -30696,7 +32052,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 === 149 /* Parameter */) { + if (location.parent && location.parent.kind === 151 /* Parameter */) { location = location.parent; } // @@ -30709,8 +32065,8 @@ var ts; location = location.parent; } break; - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); break; @@ -30724,13 +32080,13 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { result.isReferenced |= meaning; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30739,7 +32095,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,16 +32150,15 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -30812,12 +32167,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: // For `namespace N { N; }` + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -30829,7 +32184,7 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 148 /* TypeParameter */) { + if (decl.kind === 150 /* TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 @@ -30884,10 +32239,10 @@ var ts; */ function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -30897,9 +32252,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +32273,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30951,7 +32309,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30968,6 +32326,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -30983,13 +32344,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node; - case 248 /* ImportClause */: + case 250 /* ImportClause */: return node.parent; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return node.parent.parent; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -30999,7 +32360,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -31037,7 +32398,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +32452,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31147,7 +32508,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31181,7 +32542,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31191,20 +32552,20 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 252 /* ExportAssignment */: - case 202 /* BinaryExpression */: + case 257 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 254 /* ExportAssignment */: + case 204 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -31215,10 +32576,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32610,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31265,11 +32626,11 @@ var ts; var node = getDeclarationOfAliasSymbol(symbol); if (!node) return ts.Debug.fail(); - if (node.kind === 252 /* ExportAssignment */) { + if (node.kind === 254 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 255 /* ExportSpecifier */) { + else if (node.kind === 257 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -31287,22 +32648,22 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 146 /* QualifiedName */) { + if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31311,19 +32672,19 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; - if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + if (name.kind === 72 /* Identifier */) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; } } - else if (name.kind === 146 /* QualifiedName */ || name.kind === 187 /* PropertyAccessExpression */) { - var left = name.kind === 146 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 146 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) { + var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -31331,7 +32692,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32727,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32743,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,8 +32765,18 @@ var ts; return symbol && symbol.valueDeclaration; } } - function resolveExternalModuleName(location, moduleReferenceExpression) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); } function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { if (isForAugmentation === void 0) { isForAugmentation = false; } @@ -31421,7 +32804,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32823,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32855,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32863,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,24 +32875,28 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { return exported; } var merged = cloneSymbol(exported); @@ -31530,7 +32917,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 277 /* SourceFile */)) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); return symbol; } @@ -31598,7 +32985,7 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 32764 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -31688,6 +33075,50 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } /** * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` @@ -31696,10 +33127,12 @@ var ts; var container = getParentOfSymbol(symbol); if (container) { var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { - return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope } - return ts.append(additionalContainers, container); + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); } var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); if (!ts.length(candidates)) { @@ -31737,13 +33170,13 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 155 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -31766,7 +33199,7 @@ var ts; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(131072 /* Object */); + var type = createType(524288 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; type.members = undefined; @@ -31821,12 +33254,12 @@ var ts; } } switch (location.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -31837,7 +33270,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +33320,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31923,7 +33359,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -31938,10 +33374,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: continue; default: return false; @@ -31952,11 +33388,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +33430,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32048,10 +33494,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -32098,21 +33544,21 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 165 /* TypeQuery */ || + if (entityName.parent.kind === 167 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 147 /* ComputedPropertyName */) { + entityName.parent.kind === 149 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || - entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ || + entityName.parent.kind === 248 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32125,7 +33571,7 @@ var ts; } function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } - var nodeFlags = 3112960 /* IgnoreErrors */; + var nodeFlags = 70221824 /* IgnoreErrors */; if (flags & 2 /* UseOnlyExternalAliasing */) { nodeFlags |= 128 /* UseOnlyExternalAliasing */; } @@ -32135,6 +33581,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32151,15 +33600,15 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 164 /* ConstructorType */ : 163 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 159 /* ConstructSignature */ : 158 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */; } - var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 return writer; } } @@ -32167,7 +33616,7 @@ var ts; if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -32217,9 +33666,15 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, - visitedSymbols: undefined, + visitedTypes: undefined, + symbolDepth: undefined, inferTypeParameters: undefined, approximateLength: 0 }; @@ -32243,85 +33698,92 @@ var ts; } if (type.flags & 1 /* Any */) { context.approximateLength += 3; - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } if (type.flags & 2 /* Unknown */) { - return ts.createKeywordTypeNode(142 /* UnknownKeyword */); + return ts.createKeywordTypeNode(143 /* UnknownKeyword */); } if (type.flags & 4 /* String */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(137 /* StringKeyword */); + return ts.createKeywordTypeNode(138 /* StringKeyword */); } if (type.flags & 8 /* Number */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(134 /* NumberKeyword */); + return ts.createKeywordTypeNode(135 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146 /* BigIntKeyword */); } if (type.flags & 16 /* Boolean */) { context.approximateLength += 7; - return ts.createKeywordTypeNode(122 /* BooleanKeyword */); + return ts.createKeywordTypeNode(123 /* BooleanKeyword */); } - if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { + if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined)); + return enumLiteralName; } - if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + if (type.flags & 1056 /* EnumLike */) { + return symbolToTypeNode(type.symbol, context, 67897832 /* Type */); } - if (type.flags & 64 /* StringLiteral */) { + if (type.flags & 128 /* StringLiteral */) { context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & 128 /* NumberLiteral */) { + if (type.flags & 256 /* NumberLiteral */) { context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } - if (type.flags & 256 /* BooleanLiteral */) { + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512 /* BooleanLiteral */) { context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 2048 /* UniqueESSymbol */) { + if (type.flags & 8192 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } context.approximateLength += 13; - return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); + return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */)); } - if (type.flags & 4096 /* Void */) { + if (type.flags & 16384 /* Void */) { context.approximateLength += 4; - return ts.createKeywordTypeNode(105 /* VoidKeyword */); + return ts.createKeywordTypeNode(106 /* VoidKeyword */); } - if (type.flags & 8192 /* Undefined */) { + if (type.flags & 32768 /* Undefined */) { context.approximateLength += 9; - return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + return ts.createKeywordTypeNode(141 /* UndefinedKeyword */); } - if (type.flags & 16384 /* Null */) { + if (type.flags & 65536 /* Null */) { context.approximateLength += 4; - return ts.createKeywordTypeNode(95 /* NullKeyword */); + return ts.createKeywordTypeNode(96 /* NullKeyword */); } - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { context.approximateLength += 5; - return ts.createKeywordTypeNode(131 /* NeverKeyword */); + return ts.createKeywordTypeNode(132 /* NeverKeyword */); } - if (type.flags & 1024 /* ESSymbol */) { + if (type.flags & 4096 /* ESSymbol */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(138 /* SymbolKeyword */); + return ts.createKeywordTypeNode(139 /* SymbolKeyword */); } - if (type.flags & 16777216 /* NonPrimitive */) { + if (type.flags & 67108864 /* NonPrimitive */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(135 /* ObjectKeyword */); + return ts.createKeywordTypeNode(136 /* ObjectKeyword */); } - if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { + if (type.flags & 262144 /* TypeParameter */ && type.isThisType) { if (context.flags & 4194304 /* InObjectTypeLiteral */) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; @@ -32335,16 +33797,16 @@ var ts; } var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); return typeReferenceToTypeNode(type); } - if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && - type.flags & 65536 /* TypeParameter */ && + type.flags & 262144 /* TypeParameter */ && ts.length(type.symbol.declarations) && ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && @@ -32355,20 +33817,23 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } - if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { - var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -32379,23 +33844,23 @@ var ts; } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & 1048576 /* Index */) { + if (type.flags & 4194304 /* Index */) { var indexedType = type.type; context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 2097152 /* IndexedAccess */) { + if (type.flags & 8388608 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } - if (type.flags & 4194304 /* Conditional */) { + if (type.flags & 16777216 /* Conditional */) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); var saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; @@ -32406,12 +33871,12 @@ var ts; context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } - if (type.flags & 8388608 /* Substitution */) { + if (type.flags & 33554432 /* Substitution */) { return typeToTypeNodeHelper(type.typeVariable, context); } return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; var appropriateConstraintTypeNode; @@ -32430,43 +33895,52 @@ var ts; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { + var typeId = "" + type.id; var symbol = type.symbol; var id; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects - else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } - else if (context.visitedSymbols && context.visitedSymbols.has(id)) { + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { - context.approximateLength += 3; - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return createElidedInformationPlaceholder(context); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.visitedSymbols) { - context.visitedSymbols = ts.createMap(); + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); } - context.visitedSymbols.set(id, true); + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); var result = createTypeNodeFromObjectType(type); - context.visitedSymbols.delete(id); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); return result; } } @@ -32480,11 +33954,11 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 277 /* SourceFile */ || declaration.parent.kind === 243 /* ModuleBlock */; + return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } @@ -32501,12 +33975,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 163 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 164 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context); return signatureNode; } } @@ -32533,8 +34007,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +34047,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +34060,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32638,17 +34112,22 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 158 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 159 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ? - createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : - resolvedType.stringIndexInfo; - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context)); + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context); + } + typeElements.push(indexSignature); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); @@ -32679,31 +34158,34 @@ var ts; return typeElements.length ? typeElements : undefined; } } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; if (propertySymbol.valueDeclaration) { @@ -32715,10 +34197,16 @@ var ts; } else { var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; } @@ -32769,7 +34257,7 @@ var ts; } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 137 /* StringKeyword */ : 134 /* NumberKeyword */); + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -32782,7 +34270,7 @@ var ts; } context.approximateLength += (name.length + 4); return ts.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { var typeParameters; @@ -32793,7 +34281,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -32812,18 +34300,18 @@ var ts; returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } if (context.flags & 256 /* SuppressAnyReturnType */) { - if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) { returnTypeNode = undefined; } } else if (!returnTypeNode) { - returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */); } context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +34322,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32846,9 +34334,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -32857,16 +34345,16 @@ var ts; var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; - var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - parameterDeclaration.name.kind === 146 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; - var questionToken = isOptional ? ts.createToken(55 /* QuestionToken */) : undefined; + var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); @@ -32875,21 +34363,34 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 184 /* BindingElement */) { + if (clone.kind === 186 /* BindingElement */) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32900,13 +34401,22 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + var parentSpecifiers; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); - if (ts.length(parents)) { - for (var _i = 0, _a = parents; _i < _a.length; _i++) { - var parent = _a[_i]; + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); @@ -32929,6 +34439,24 @@ var ts; } return [symbol]; } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } } } function typeParametersToTypeParameterDeclarations(symbol, context) { @@ -32966,7 +34494,7 @@ var ts; return top; } function getSpecifierForModuleSymbol(symbol, context) { - var file = ts.getDeclarationOfKind(symbol, 277 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -32996,7 +34524,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,12 +34539,20 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); @@ -33103,6 +34646,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33143,7 +34689,7 @@ var ts; if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { - var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); @@ -33156,12 +34702,12 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 24576 /* Nullable */)) { - if (t.flags & (256 /* BooleanLiteral */ | 512 /* EnumLiteral */)) { - var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 262144 /* Union */) { + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) { + var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33171,9 +34717,9 @@ var ts; result.push(t); } } - if (flags & 16384 /* Null */) + if (flags & 65536 /* Null */) result.push(nullType); - if (flags & 8192 /* Undefined */) + if (flags & 32768 /* Undefined */) result.push(undefinedType); return result || types; } @@ -33188,8 +34734,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 175 /* ParenthesizedType */; }); - if (node.kind === 240 /* TypeAliasDeclaration */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; }); + if (node.kind === 242 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -33197,11 +34743,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 243 /* ModuleBlock */ && + node.parent.kind === 245 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); } /** * Gets a human-readable name for a symbol. @@ -33224,27 +34770,30 @@ var ts; var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 235 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 207 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var nameType = symbol.nameType; if (nameType) { - if (nameType.flags & 64 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; } - if (nameType && nameType.flags & 2048 /* UniqueESSymbol */) { + if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; } } @@ -33261,27 +34810,27 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 237 /* FunctionDeclaration */: - case 241 /* EnumDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 243 /* EnumDeclaration */: + case 248 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -33289,53 +34838,53 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 246 /* ImportEqualsDeclaration */ && parent.kind !== 277 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 155 /* Constructor */: - case 159 /* ConstructSignature */: - case 158 /* CallSignature */: - case 160 /* IndexSignature */: - case 149 /* Parameter */: - case 243 /* ModuleBlock */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 166 /* TypeLiteral */: - case 162 /* TypeReference */: - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 175 /* ParenthesizedType */: + case 157 /* Constructor */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 151 /* Parameter */: + case 245 /* ModuleBlock */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 164 /* TypeReference */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 177 /* 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 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: return false; // Type parameters are always visible - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: // Source file and namespace export are always visible - case 277 /* SourceFile */: - case 245 /* NamespaceExportDeclaration */: + case 279 /* SourceFile */: + case 247 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return false; default: return false; @@ -33344,11 +34893,11 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + if (node.parent && node.parent.kind === 254 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + else if (node.parent.kind === 257 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34918,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34967,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33426,6 +34977,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33439,12 +34992,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 235 /* VariableDeclaration */: - case 236 /* VariableDeclarationList */: - case 251 /* ImportSpecifier */: - case 250 /* NamedImports */: - case 249 /* NamespaceImport */: - case 248 /* ImportClause */: + case 237 /* VariableDeclaration */: + case 238 /* VariableDeclarationList */: + case 253 /* ImportSpecifier */: + case 252 /* NamedImports */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: return false; default: return true; @@ -33474,28 +35027,36 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); + return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); - if (source.flags & 32768 /* Never */) { + source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); + if (source.flags & 131072 /* Never */) { return emptyObjectType; } - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } - var members = ts.createSymbolTable(); - var names = ts.createUnderscoreEscapedMap(); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var name = properties_2[_i]; - names.set(ts.getTextOfPropertyName(name), true); + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - if (!names.has(prop.escapedName) + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getNonReadonlySymbol(prop)); + members.set(prop.escapedName, getSpreadSymbol(prop)); } } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); @@ -33519,8 +35080,12 @@ var ts; if (isTypeAny(parentType)) { return parentType; } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } var type; - if (pattern.kind === 182 /* ObjectBindingPattern */) { + if (pattern.kind === 184 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -33538,51 +35103,9 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - var isLate = isLateBindableName(name); - var isWellKnown = ts.isComputedPropertyName(name) && ts.isWellKnownSymbolSyntactically(name.expression); - if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { - var exprType = checkExpression(name.expression); - if (isTypeAssignableToKind(exprType, 3072 /* ESSymbolLike */)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); - } - return anyType; - } - var indexerType = isTypeAssignableToKind(exprType, 168 /* NumberLike */) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); - if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(parentType, 1 /* Number */)) { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType)); - } - } - return indexerType || 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. - var nameType = isLate ? checkComputedPropertyName(name) : undefined; - var text = isLate ? getLateBoundNameFromType(nameType) : - isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : - ts.getTextOfPropertyName(name); - // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation - if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { - parentType = getNonNullableType(parentType); - } - if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType)); - } - return anyType; - } - var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); - type = declaredType && getFlowTypeOfReference(declaration, declaredType) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || - getIndexTypeOfType(parentType, 0 /* String */); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return errorType; - } + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); } } else { @@ -33590,27 +35113,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33618,11 +35141,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { - type = getTypeWithFacts(type, 131072 /* NEUndefined */); + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) { + type = getTypeWithFacts(type, 524288 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33634,11 +35157,11 @@ var ts; } function isNullOrUndefined(node) { var expr = ts.skipParentheses(node); - return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 185 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -33648,11 +35171,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 224 /* ForInStatement */) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (65536 /* TypeParameter */ | 1048576 /* Index */) ? getExtractStringType(indexType) : stringType; + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 225 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* 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, @@ -33670,8 +35193,8 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no @@ -33685,11 +35208,11 @@ var ts; return autoArrayType; } } - if (declaration.kind === 149 /* Parameter */) { + if (declaration.kind === 151 /* 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 === 157 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 156 /* GetAccessor */); + if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -33701,16 +35224,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +35259,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33747,14 +35276,14 @@ var ts; var types; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = ts.isBinaryExpression(declaration) ? declaration : + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +35291,11 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,26 +35303,24 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; } } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(24576 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +35339,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +35353,35 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); - if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + if (type.flags & 524288 /* Object */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33851,9 +35405,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33862,9 +35414,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 155 /* Constructor */ || - thisContainer.kind === 237 /* FunctionDeclaration */ || - (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 157 /* Constructor */ || + thisContainer.kind === 239 /* FunctionDeclaration */ || + (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -33876,8 +35428,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +35437,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33899,8 +35451,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33939,7 +35491,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var hasRestElement = !!(lastElement && lastElement.kind === 184 /* BindingElement */ && lastElement.dotDotDotToken); + var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken); if (elements.length === 0 || elements.length === 1 && hasRestElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -33962,7 +35514,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 182 /* ObjectBindingPattern */ + return pattern.kind === 184 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -33984,7 +35536,7 @@ var ts; reportErrorsFromWidening(declaration, type); } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & 2048 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } return getWidenedType(type); @@ -33992,16 +35544,16 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 149 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -34037,19 +35589,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } - if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + if (declaration.kind === 254 /* ExportAssignment */) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && - (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +35622,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34085,6 +35644,14 @@ var ts; || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } @@ -34095,7 +35662,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 156 /* GetAccessor */) { + if (accessor.kind === 158 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -34122,9 +35689,9 @@ var ts; return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); } function getTypeOfAccessorsWorker(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */); + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34152,14 +35719,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34168,7 +35733,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* 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)); } } @@ -34176,13 +35741,13 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 2162688 /* TypeVariable */ ? baseConstructorType : undefined; + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34208,9 +35773,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 202 /* BinaryExpression */ || - declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + else if (declaration.kind === 204 /* BinaryExpression */ || + declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) { + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35784,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35813,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35822,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34329,7 +35886,7 @@ var ts; var target = getTargetType(type); return target === checkBase || ts.some(getBaseTypes(target), check); } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return ts.some(type.types, check); } return false; @@ -34353,35 +35910,35 @@ var ts; return undefined; } switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 287 /* JSDocFunctionType */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 179 /* MappedType */: - case 173 /* ConditionalType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 181 /* MappedType */: + case 175 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 179 /* MappedType */) { + if (node.kind === 181 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 173 /* ConditionalType */) { + else if (node.kind === 175 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */ || node.kind === 239 /* InterfaceDeclaration */) && + (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } @@ -34389,7 +35946,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, 239 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -34398,9 +35955,9 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 239 /* InterfaceDeclaration */ || - node.kind === 238 /* ClassDeclaration */ || - node.kind === 207 /* ClassExpression */ || + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || + node.kind === 209 /* ClassExpression */ || ts.isTypeAlias(node)) { var declaration = node; result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); @@ -34427,27 +35984,24 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { return true; } - if (type.flags & 2162688 /* TypeVariable */) { + if (type.flags & 8650752 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34473,7 +36027,7 @@ var ts; ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag checkExpression(extended.expression); } - if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */)) { + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -34483,7 +36037,18 @@ var ts; return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } return type.resolvedBaseConstructorType = errorType; } type.resolvedBaseConstructorType = baseConstructorType; @@ -34512,13 +36077,15 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 1 /* Any */))) { + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? 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 @@ -34529,8 +36096,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34547,7 +36114,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { @@ -34577,14 +36144,14 @@ var ts; // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return !!(type.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 524288 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -34603,7 +36170,7 @@ var ts; } } else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -34620,7 +36187,7 @@ var ts; function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 /* InterfaceDeclaration */) { + if (declaration.kind === 241 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -34629,7 +36196,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34661,7 +36228,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536 /* TypeParameter */); + type.thisType = createType(262144 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -34678,7 +36245,7 @@ var ts; return errorType; } var declaration = ts.find(symbol.declarations, function (d) { - return ts.isJSDocTypeAlias(d) || d.kind === 240 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */; }); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. @@ -34702,10 +36269,10 @@ var ts; return links.declaredType; } function isStringConcatExpression(expr) { - if (expr.kind === 9 /* StringLiteral */) { + if (expr.kind === 10 /* StringLiteral */) { return true; } - else if (expr.kind === 202 /* BinaryExpression */) { + else if (expr.kind === 204 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -34716,15 +36283,15 @@ var ts; return !(member.flags & 4194304 /* Ambient */); } switch (expr.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return true; - case 200 /* PrefixUnaryExpression */: - return expr.operator === 38 /* MinusToken */ && + case 202 /* PrefixUnaryExpression */: + return expr.operator === 39 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -34738,10 +36305,10 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241 /* EnumDeclaration */) { + if (declaration.kind === 243 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) { return links.enumKind = 1 /* Literal */; } if (!isLiteralEnumMember(member)) { @@ -34753,7 +36320,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -34765,19 +36332,19 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241 /* EnumDeclaration */) { + if (declaration.kind === 243 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); - if (enumType_1.flags & 262144 /* Union */) { - enumType_1.flags |= 512 /* EnumLiteral */; + if (enumType_1.flags & 1048576 /* Union */) { + enumType_1.flags |= 1024 /* EnumLiteral */; enumType_1.symbol = symbol; } return links.declaredType = enumType_1; @@ -34800,7 +36367,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(65536 /* TypeParameter */); + var type = createType(262144 /* TypeParameter */); type.symbol = symbol; links.declaredType = type; } @@ -34844,22 +36411,23 @@ var ts; */ function isThislessType(node) { switch (node.kind) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 135 /* ObjectKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: - case 180 /* LiteralType */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + case 182 /* LiteralType */: return true; - case 167 /* ArrayType */: + case 169 /* ArrayType */: return isThislessType(node.elementType); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -34885,7 +36453,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 155 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -34901,12 +36469,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -34950,7 +36518,7 @@ var ts; * Indicates whether a type can be used as a late-bound name. */ function isTypeUsableAsLateBoundName(type) { - return !!(type.flags & 2240 /* StringOrNumberLiteralOrUnique */); + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); } /** * Indicates whether a declaration name is definitely late-bindable. @@ -34993,10 +36561,10 @@ var ts; * Gets the symbolic name for a late-bound member from its type. */ function getLateBoundNameFromType(type) { - if (type.flags & 2048 /* UniqueESSymbol */) { + if (type.flags & 8192 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +36584,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35161,7 +36729,7 @@ var ts; return needApparentType ? getApparentType(ref) : ref; } } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } return needApparentType ? getApparentType(type) : type; @@ -35270,7 +36838,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35290,7 +36858,7 @@ var ts; function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { return s; } } @@ -35324,8 +36892,7 @@ var ts; // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional // parameters and may differ in return types. When signatures differ in return types, the resulting return // type is the union of the constituent return types. - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + function getUnionSignatures(signatureLists) { var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { @@ -35371,8 +36938,8 @@ var ts; 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 callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -35407,7 +36974,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35430,7 +36997,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35468,7 +37035,7 @@ var ts; if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 2162688 /* TypeVariable */)) { + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -35484,6 +37051,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35501,7 +37069,7 @@ var ts; var modifiers = getMappedTypeModifiers(type.mappedType); var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; - var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; @@ -35511,6 +37079,7 @@ var ts; inferredProp.nameType = prop.nameType; inferredProp.propertyType = getTypeOfSymbol(prop); inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -35529,12 +37098,12 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateModifiers = getMappedTypeModifiers(type); - var include = keyofStringsOnly ? 64 /* StringLiteral */ : 2240 /* StringOrNumberLiteralOrUnique */; + var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); @@ -35544,11 +37113,9 @@ var ts; } } else { - // First, if the constraint type is a type parameter, obtain the base constraint. Then, - // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 14745600 /* InstantiableNonPrimitive */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 1048576 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); @@ -35560,7 +37127,7 @@ var ts; var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. - if (t.flags & 2240 /* StringOrNumberLiteralOrUnique */) { + if (t.flags & 8576 /* StringOrNumberLiteralOrUnique */) { var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || @@ -35572,7 +37139,7 @@ var ts; // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks // mode, if the underlying property is optional we remove 'undefined' from the type. prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; @@ -35595,7 +37162,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35608,8 +37175,8 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 177 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; + return constraintDeclaration.kind === 179 /* TypeOperator */ && + constraintDeclaration.operator === 129 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { @@ -35625,16 +37192,16 @@ var ts; // the modifiers type is T. Otherwise, the modifiers type is {}. var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 1048576 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } function getMappedTypeModifiers(type) { var declaration = type.declaration; - return (declaration.readonlyToken ? declaration.readonlyToken.kind === 38 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | - (declaration.questionToken ? declaration.questionToken.kind === 38 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); } function getMappedTypeOptionality(type) { var modifiers = getMappedTypeModifiers(type); @@ -35653,7 +37220,7 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { if (type.objectFlags & 4 /* Reference */) { resolveTypeReferenceMembers(type); } @@ -35670,10 +37237,10 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 262144 /* Union */) { + else if (type.flags & 1048576 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -35681,7 +37248,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; @@ -35690,7 +37257,7 @@ var ts; * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -35714,7 +37281,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { break; } } @@ -35724,12 +37291,13 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 786432 /* UnionOrIntersection */ ? + return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { - return obj.properties.some(function (property) { + var list = obj.properties; + return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); @@ -35737,7 +37305,7 @@ var ts; } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 262144 /* Union */)) { + if (!(unionType.flags & 1048576 /* Union */)) { return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); @@ -35756,24 +37324,33 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : - type.flags & 2097152 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : - type.flags & 4194304 /* Conditional */ ? getConstraintOfConditionalType(type) : + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { var rootTrueType = type.root.trueType; - var rootTrueConstraint = rootTrueType.flags & 8388608 /* Substitution */ ? rootTrueType.substitute : rootTrueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); } return type.resolvedDefaultConstraint; @@ -35785,11 +37362,12 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); - if (!(instantiated.flags & 32768 /* Never */)) { + if (!(instantiated.flags & 131072 /* Never */)) { return instantiated; } } @@ -35804,23 +37382,23 @@ var ts; var hasDisjointDomainType = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 15794176 /* Instantiable */) { + if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). var constraint = getConstraintOfType(t); - while (constraint && constraint.flags & (65536 /* TypeParameter */ | 1048576 /* Index */ | 4194304 /* Conditional */)) { + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { constraint = getConstraintOfType(constraint); } if (constraint) { // A constraint that isn't a union type implies that the final type would be a non-union // type as well. Since non-union constraints are of no interest, we can exit here. - if (!(constraint.flags & 262144 /* Union */)) { + if (!(constraint.flags & 1048576 /* Union */)) { return undefined; } constraints = ts.append(constraints, constraint); } } - else if (t.flags & 16809468 /* DisjointDomains */) { + else if (t.flags & 67238908 /* DisjointDomains */) { hasDisjointDomainType = true; } } @@ -35832,7 +37410,7 @@ var ts; // intersection operation to reduce the union constraints. for (var _b = 0, _c = type.types; _b < _c.length; _b++) { var t = _c[_b]; - if (t.flags & 16809468 /* DisjointDomains */) { + if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } } @@ -35842,11 +37420,11 @@ var ts; return undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; + return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -35864,6 +37442,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +37450,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35884,45 +37473,42 @@ var ts; return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { - if (t.flags & 65536 /* TypeParameter */) { + if (t.flags & 262144 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint); } - if (t.flags & 786432 /* UnionOrIntersection */) { + if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 262144 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 524288 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 1048576 /* Index */) { + if (t.flags & 4194304 /* Index */) { return keyofConstraintType; } - if (t.flags & 2097152 /* IndexedAccess */) { + if (t.flags & 8388608 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } - if (t.flags & 4194304 /* Conditional */) { + if (t.flags & 16777216 /* Conditional */) { var constraint = getConstraintOfConditionalType(t); return constraint && getBaseConstraint(constraint); } - if (t.flags & 8388608 /* Substitution */) { + if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,26 +37558,42 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 /* StringLike */ ? globalStringType : + t.flags & 296 /* NumberLike */ ? globalNumberType : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 528 /* BooleanLike */ ? globalBooleanType : + t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : + t.flags & 4194304 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var indexTypes; - var isUnion = containingType.flags & 262144 /* Union */; + var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; @@ -36016,10 +37618,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36104,27 +37706,31 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 917504 /* StructuredType */) { + if (type.flags & 3670016 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -36138,7 +37744,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 917504 /* StructuredType */) { + if (type.flags & 3670016 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -36192,12 +37798,12 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 286 /* JSDocOptionalType */ + node.type && node.type.kind === 288 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -36231,7 +37837,7 @@ var ts; return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -36256,30 +37862,32 @@ var ts; } function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { - if (!typeArguments) { - typeArguments = []; - } - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { - defaultType = anyType; - } - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - typeArguments.length = typeParameters.length; - } + if (!numTypeParameters) { + return []; } - return typeArguments; + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); @@ -36292,7 +37900,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37913,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36315,7 +37923,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 180 /* LiteralType */) { + if (type && type.kind === 182 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter @@ -36329,20 +37937,20 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 156 /* GetAccessor */ || declaration.kind === 157 /* SetAccessor */) && + if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) && !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 155 /* Constructor */ ? + var classType = declaration.kind === 157 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37981,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36396,13 +38004,13 @@ var ts; if (!node) return false; switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node.escapedText === "arguments" && ts.isExpressionNode(node); - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return node.name.kind === 147 /* ComputedPropertyName */ + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node.name.kind === 149 /* ComputedPropertyName */ && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -36460,7 +38068,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36477,7 +38085,7 @@ var ts; function createTypePredicateFromTypePredicateNode(node, func) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71 /* Identifier */) { + if (parameterName.kind === 72 /* Identifier */) { return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); } else { @@ -36487,7 +38095,7 @@ var ts; function getTypePredicateParameterIndex(parameterList, parameter) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { return i; } } @@ -36501,6 +38109,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36526,7 +38135,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 155 /* Constructor */) { + if (declaration.kind === 157 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -36536,12 +38145,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -36556,8 +38165,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +38211,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36615,7 +38228,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 === 155 /* Constructor */ || signature.declaration.kind === 159 /* ConstructSignature */; // TODO: GH#18217 + var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217 var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -36629,7 +38242,7 @@ var ts; return symbol.members.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 134 /* NumberKeyword */ : 137 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -36656,7 +38269,7 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */); return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { @@ -36664,13 +38277,13 @@ var ts; if (typeParameter.symbol) { for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.parent.kind === 174 /* InferType */) { + if (declaration.parent.kind === 176 /* InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. var grandParent = declaration.parent.parent; - if (grandParent.kind === 162 /* TypeReference */) { + if (grandParent.kind === 164 /* TypeReference */) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -36695,7 +38308,7 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter // declaration, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 149 /* Parameter */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } } @@ -36719,7 +38332,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -36792,10 +38405,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36825,7 +38438,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36852,9 +38465,9 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -36880,14 +38493,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +38522,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36904,16 +38531,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -36936,13 +38568,13 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { - var result = createType(8388608 /* Substitution */); + var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 168 /* TupleType */ && node.elementTypes.length === 1; + return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1; } function getImpliedConstraint(typeVariable, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : @@ -36951,9 +38583,9 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 289 /* JSDocComment */) { + while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 173 /* ConditionalType */ && node === parent.trueType) { + if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -36964,7 +38596,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */); + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -37022,23 +38654,23 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getNullableType(type, 16384 /* Null */) : type; + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37065,9 +38697,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: return declaration; } } @@ -37076,7 +38708,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 131072 /* Object */)) { + if (!(type.flags & 524288 /* Object */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } @@ -37087,10 +38719,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37118,6 +38750,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37144,12 +38779,21 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType; + } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -37198,7 +38842,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(65536 /* TypeParameter */); + var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); if (i < maxLength) { var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); property.type = typeParameter; @@ -37220,7 +38864,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536 /* TypeParameter */); + type.thisType = createType(262144 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -37255,8 +38899,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var lastElement = ts.lastOrUndefined(node.elementTypes); - var restElement_1 = lastElement && lastElement.kind === 170 /* RestType */ ? lastElement : undefined; - var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 169 /* OptionalType */ && n !== restElement_1; }) + 1; + var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1; var elementTypes = ts.map(node.elementTypes, function (n) { var type = getTypeFromTypeNode(n); return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; @@ -37265,6 +38909,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37295,16 +38947,17 @@ var ts; var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 27072 /* Unit */ && combined & 27072 /* Unit */) { + if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) { return true; } combined |= t.flags; - if (combined & 24576 /* Nullable */ && combined & (131072 /* Object */ | 16777216 /* NonPrimitive */) || - combined & 16777216 /* NonPrimitive */ && combined & (16809468 /* DisjointDomains */ & ~16777216 /* NonPrimitive */) || - combined & 68 /* StringLike */ && combined & (16809468 /* DisjointDomains */ & ~68 /* StringLike */) || - combined & 168 /* NumberLike */ && combined & (16809468 /* DisjointDomains */ & ~168 /* NumberLike */) || - combined & 3072 /* ESSymbolLike */ && combined & (16809468 /* DisjointDomains */ & ~3072 /* ESSymbolLike */) || - combined & 12288 /* VoidLike */ && combined & (16809468 /* DisjointDomains */ & ~12288 /* VoidLike */)) { + if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) || + combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || + combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || + combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || + combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) || + combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || + combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) { return true; } } @@ -37312,20 +38965,18 @@ var ts; } function addTypeToUnion(typeSet, includes, type) { var flags = type.flags; - if (flags & 262144 /* Union */) { + if (flags & 1048576 /* Union */) { return addTypesToUnion(typeSet, includes, type.types); } // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are // another form of 'never' (in that they have an empty value domain). We could in theory turn // intersections of unit types into 'never' upon construction, but deferring the reduction makes it // easier to reason about their origin. - if (!(flags & 32768 /* Never */ || flags & 524288 /* Intersection */ && isEmptyIntersectionType(type))) { + if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { includes |= flags & ~939524096 /* ConstructionFlags */; - if (flags & 3 /* AnyOrUnknown */) { - if (type === wildcardType) - includes |= 268435456 /* Wildcard */; - } - else if (!strictNullChecks && flags & 24576 /* Nullable */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(flags & 134217728 /* ContainsWideningType */)) includes |= 134217728 /* NonWideningType */; } @@ -37333,10 +38984,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38999,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - 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 isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37373,11 +39012,11 @@ var ts; } function isSetOfLiteralsFromSameEnum(types) { var first = types[0]; - if (first.flags & 512 /* EnumLiteral */) { + if (first.flags & 1024 /* EnumLiteral */) { var firstEnum = getParentOfSymbol(first.symbol); for (var i = 1; i < types.length; i++) { var other = types[i]; - if (!(other.flags & 512 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { return false; } } @@ -37402,10 +39041,11 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || - t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37428,25 +39068,27 @@ var ts; } var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); - if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1 /* Literal */: + if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + neverType; + } } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { - removeRedundantLiteralTypes(typeSet, includes); - } - break; - case 2 /* Subtype */: - removeSubtypes(typeSet); - break; - } - if (typeSet.length === 0) { - return includes & 16384 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : - includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -37483,7 +39125,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -37493,10 +39135,11 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 24576 /* Nullable */); - type = createType(262144 /* Union */ | propagatedFlags | unionOfUnitTypes); + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(1048576 /* Union */ | propagatedFlags); unionTypes.set(id, type); type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; /* Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. @@ -37518,11 +39161,14 @@ var ts; } function addTypeToIntersection(typeSet, includes, type) { var flags = type.flags; - if (flags & 524288 /* Intersection */) { + if (flags & 2097152 /* Intersection */) { return addTypesToIntersection(typeSet, includes, type.types); } - if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { - includes |= 536870912 /* EmptyObject */; + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912 /* EmptyObject */)) { + includes |= 536870912 /* EmptyObject */; + typeSet.push(type); + } } else { includes |= flags & ~939524096 /* ConstructionFlags */; @@ -37530,10 +39176,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +39185,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37553,9 +39196,10 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 4 /* String */ && includes & 64 /* StringLiteral */ || - t.flags & 8 /* Number */ && includes & 128 /* NumberLiteral */ || - t.flags & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */; + var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37568,10 +39212,11 @@ var ts; for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { var u = unionTypes_1[_i]; if (!containsType(u.types, type)) { - var primitive = type.flags & 64 /* StringLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ ? numberType : - type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : - undefined; + var primitive = type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + undefined; if (!primitive || !containsType(u.types, primitive)) { return false; } @@ -37584,13 +39229,16 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; }); + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } var i = index + 1; // Remove all but the first union of primitive types and collect them in // the unionTypes array. while (i < types.length) { var t = types[i]; - if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) { + if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -37619,7 +39267,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */); + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -37635,22 +39283,23 @@ var ts; function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); - if (includes & 32768 /* Never */) { + if (includes & 131072 /* Never */) { return neverType; } if (includes & 1 /* Any */) { return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; } - if (!strictNullChecks && includes & 24576 /* Nullable */) { - return includes & 8192 /* Undefined */ ? undefinedType : nullType; + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 32768 /* Undefined */ ? undefinedType : nullType; } - if (includes & 4 /* String */ && includes & 64 /* StringLiteral */ || - includes & 8 /* Number */ && includes & 128 /* NumberLiteral */ || - includes & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */) { + if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 536870912 /* EmptyObject */ && !(includes & 131072 /* Object */)) { - typeSet.push(emptyObjectType); + if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { return unknownType; @@ -37658,8 +39307,8 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - if (includes & 262144 /* Union */) { - if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) { + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -37667,15 +39316,15 @@ var ts; } // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. - var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 262144 /* Union */) !== 0; }); + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; }); var unionType = typeSet[unionIndex_1]; return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 24576 /* Nullable */); - type = createType(524288 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(2097152 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. @@ -37692,7 +39341,7 @@ var ts; return links.resolvedType; } function createIndexType(type, stringsOnly) { - var result = createType(1048576 /* Index */); + var result = createType(4194304 /* Index */); result.type = type; result.stringsOnly = stringsOnly; return result; @@ -37702,14 +39351,22 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } - function getLiteralTypeFromPropertyName(prop, include) { + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) : - name && name.kind === 147 /* ComputedPropertyName */ && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : - getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); } if (type && type.flags & include) { return type; @@ -37717,8 +39374,8 @@ var ts; } return neverType; } - function getLiteralTypeFromPropertyNames(type, include) { - return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromPropertyName(t, include); })); + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); } function getNonEnumNumberIndexInfo(type) { var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); @@ -37726,16 +39383,16 @@ var ts; } function getIndexType(type, stringsOnly) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } - return type.flags & 262144 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - type.flags & 524288 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : type === wildcardType ? wildcardType : type.flags & 1 /* Any */ ? keyofConstraintType : - stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */) : - getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, 2048 /* UniqueESSymbol */)]) : - getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */ | 2048 /* UniqueESSymbol */)]) : - getLiteralTypeFromPropertyNames(type, 2240 /* StringOrNumberLiteralOrUnique */); + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) : + getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */); } function getExtractStringType(type) { if (keyofStringsOnly) { @@ -37746,17 +39403,17 @@ var ts; } function getIndexTypeOrString(type) { var indexType = getExtractStringType(getIndexType(type)); - return indexType.flags & 32768 /* Never */ ? stringType : indexType; + return indexType.flags & 131072 /* Never */ ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { switch (node.operator) { - case 128 /* KeyOfKeyword */: + case 129 /* KeyOfKeyword */: links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); break; - case 141 /* UniqueKeyword */: - links.resolvedType = node.type.kind === 138 /* SymbolKeyword */ + case 142 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 139 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) : errorType; break; @@ -37765,7 +39422,7 @@ var ts; return links.resolvedType; // TODO: GH#18217 } function createIndexedAccessType(objectType, indexType) { - var type = createType(2097152 /* IndexedAccess */); + var type = createType(8388608 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; return type; @@ -37786,56 +39443,63 @@ var ts; if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { return true; } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { return ts.every(type.types, isJSLiteralType); } - if (type.flags & 524288 /* Intersection */) { + if (type.flags & 2097152 /* Intersection */) { return ts.some(type.types, isJSLiteralType); } - if (type.flags & 15794176 /* Instantiable */) { + if (type.flags & 63176704 /* Instantiable */) { return isJSLiteralType(getResolvedBaseConstraint(type)); } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - undefined; + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } - if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { - if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) { + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { return objectType; } - var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { - var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = getIndexNodeForAccessExpression(accessNode); error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { @@ -37843,7 +39507,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768 /* Never */) { + if (indexType.flags & 131072 /* Never */) { return neverType; } if (isJSLiteralType(objectType)) { @@ -37869,15 +39533,15 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { return anyType; } if (accessNode) { - var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; - if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { @@ -37887,30 +39551,38 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 /* ElementAccessExpression */ + ? accessNode.argumentExpression + : accessNode.kind === 180 /* IndexedAccessType */ + ? accessNode.indexType + : accessNode.kind === 149 /* ComputedPropertyName */ + ? accessNode.expression + : accessNode; } function isGenericObjectType(type) { - return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); } function isGenericIndexType(type) { - return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); - } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); } function getSimplifiedType(type) { - return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 1048576 /* Union */) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // the type itself if no transformation is possible. @@ -37922,37 +39594,20 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); - } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 1048576 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 63176704 /* Instantiable */)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37960,7 +39615,7 @@ var ts; if (isGenericMappedType(objectType)) { return type.simplified = substituteIndexedMappedType(objectType, type); } - if (objectType.flags & 65536 /* TypeParameter */) { + if (objectType.flags & 262144 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); @@ -37973,7 +39628,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -37982,7 +39638,7 @@ var ts; // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 188 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } @@ -37998,19 +39654,30 @@ var ts; // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38018,7 +39685,7 @@ var ts; var objectType = getTypeFromTypeNode(node.objectType); var indexType = getTypeFromTypeNode(node.indexType); var resolved = getIndexedAccessType(objectType, indexType, node); - links.resolvedType = resolved.flags & 2097152 /* IndexedAccess */ && + links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && resolved.objectType === objectType && resolved.indexType === indexType ? getConstrainedTypeVariable(resolved, node) : resolved; @@ -38040,7 +39707,7 @@ var ts; return links.resolvedType; } function getActualTypeVariable(type) { - return type.flags & 8388608 /* Substitution */ ? type.typeVariable : type; + return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); @@ -38051,7 +39718,7 @@ var ts; // If this is a distributive conditional type and the check type is generic we need to defer // resolution of the conditional type such that a later instantiation will properly distribute // over union types. - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 15794176 /* Instantiable */); + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); @@ -38090,7 +39757,7 @@ var ts; } // Return a deferred type for a check that is neither definitely true nor definitely false var erasedCheckType = getActualTypeVariable(checkType); - var result = createType(4194304 /* Conditional */); + var result = createType(16777216 /* Conditional */); result.root = root; result.checkType = erasedCheckType; result.extendsType = extendsType; @@ -38122,7 +39789,7 @@ var ts; return true; } while (node) { - if (node.kind === 173 /* ConditionalType */) { + if (node.kind === 175 /* ConditionalType */) { if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { return true; } @@ -38145,7 +39812,7 @@ var ts; extendsType: getTypeFromTypeNode(node.extendsType), trueType: getTypeFromTypeNode(node.trueType), falseType: getTypeFromTypeNode(node.falseType), - isDistributive: !!(checkType.flags & 65536 /* TypeParameter */), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, @@ -38188,7 +39855,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39885,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39899,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38265,6 +39932,9 @@ var ts; function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } /** * Since the source of spread types are object literals, which are not binary, * this function should be called in a left folding style, with left = previous result of getSpreadType @@ -38277,21 +39947,37 @@ var ts; if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { return unknownType; } - if (left.flags & 32768 /* Never */) { + if (left.flags & 131072 /* Never */) { return right; } - if (right.flags & 32768 /* Never */) { + if (right.flags & 131072 /* Never */) { return left; } - if (left.flags & 262144 /* Union */) { + if (left.flags & 1048576 /* Union */) { return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); } - if (right.flags & 262144 /* Union */) { + if (right.flags & 1048576 /* Union */) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); } - if (right.flags & (272 /* BooleanLike */ | 168 /* NumberLike */ | 68 /* StringLike */ | 544 /* EnumLike */ | 16777216 /* NonPrimitive */ | 1048576 /* Index */)) { + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { return left; } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & 2097152 /* Intersection */) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); var stringIndexInfo; @@ -38311,7 +39997,7 @@ var ts; skippedPrivateMembers.set(rightProp.escapedName, true); } else if (isSpreadableProperty(rightProp)) { - members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { @@ -38326,7 +40012,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); var result = createSymbol(flags, leftProp.escapedName); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -38335,27 +40021,28 @@ var ts; } } else { - members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= typeFlags | 268435456 /* ContainsObjectLiteral */; - spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); + spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */) - ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) - : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable + return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isReadonly && !isSetonlyAccessor) { return prop; } var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); var result = createSymbol(flags, prop.escapedName); - result.type = getTypeOfSymbol(prop); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); result.declarations = prop.declarations; result.nameType = prop.nameType; result.syntheticOrigin = prop; @@ -38374,10 +40061,11 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; + freshType.freshType = freshType; type.freshType = freshType; } return type.freshType; @@ -38385,21 +40073,27 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + return type.flags & 2944 /* Literal */ ? type.regularType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } + function isFreshLiteralType(type) { + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; + } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', // where NNN is the text representation of a numeric literal and SSS are the characters // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where // EEE is a unique id for the containing enum type. - var qualifier = typeof value === "number" ? "#" : "@"; - var key = enumId ? enumId + qualifier + value : qualifier + value; + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); var type = literalTypes.get(key); if (!type) { - var flags = (typeof value === "number" ? 128 /* NumberLiteral */ : 64 /* StringLiteral */) | (enumId ? 512 /* EnumLiteral */ : 0); + var flags = (typeof value === "number" ? 256 /* NumberLiteral */ : + typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) | + (enumId ? 1024 /* EnumLiteral */ : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; } return type; } @@ -38411,7 +40105,7 @@ var ts; return links.resolvedType; } function createUniqueESSymbolType(symbol) { - var type = createType(2048 /* UniqueESSymbol */); + var type = createType(8192 /* UniqueESSymbol */); type.symbol = symbol; return type; } @@ -38426,9 +40120,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 239 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) { if (!ts.hasModifier(container, 32 /* Static */) && - (container.kind !== 155 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -38444,87 +40138,89 @@ var ts; } function getTypeFromTypeNode(node) { switch (node.kind) { - case 119 /* AnyKeyword */: - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: + case 120 /* AnyKeyword */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: return anyType; - case 142 /* UnknownKeyword */: + case 143 /* UnknownKeyword */: return unknownType; - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: return stringType; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: return numberType; - case 122 /* BooleanKeyword */: + case 146 /* BigIntKeyword */: + return bigintType; + case 123 /* BooleanKeyword */: return booleanType; - case 138 /* SymbolKeyword */: + case 139 /* SymbolKeyword */: return esSymbolType; - case 105 /* VoidKeyword */: + case 106 /* VoidKeyword */: return voidType; - case 140 /* UndefinedKeyword */: + case 141 /* UndefinedKeyword */: return undefinedType; - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: return nullType; - case 131 /* NeverKeyword */: + case 132 /* NeverKeyword */: return neverType; - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; - case 176 /* ThisType */: - case 99 /* ThisKeyword */: + case 178 /* ThisType */: + case 100 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return getTypeFromTypeReference(node); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return booleanType; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return getTypeFromOptionalTypeNode(node); - case 171 /* UnionType */: + case 173 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 175 /* ParenthesizedType */: - case 170 /* RestType */: - case 285 /* JSDocNonNullableType */: - case 281 /* JSDocTypeExpression */: + case 177 /* ParenthesizedType */: + case 172 /* RestType */: + case 287 /* JSDocNonNullableType */: + case 283 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 287 /* JSDocFunctionType */: - case 291 /* JSDocSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 174 /* InferType */: + case 176 /* InferType */: return getTypeFromInferTypeNode(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode - case 71 /* Identifier */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 148 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -38591,7 +40287,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38605,10 +40301,10 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function wildcardMapper(type) { - return type.flags & 65536 /* TypeParameter */ ? wildcardType : type; + return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; } function cloneTypeParameter(typeParameter) { - var result = createType(65536 /* TypeParameter */); + var result = createType(262144 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -38654,7 +40350,7 @@ var ts; } function instantiateSymbol(symbol, mapper) { var links = getSymbolLinks(symbol); - if (links.type && !maybeTypeOfKind(links.type, 131072 /* Object */ | 15794176 /* Instantiable */)) { + if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { // If the type of the symbol is already resolved, and if that type could not possibly // be affected by instantiation, simply return the symbol itself. return symbol; @@ -38692,7 +40388,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +40398,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38734,8 +40430,8 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 146 /* QualifiedName */ || - node.parent.kind === 162 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + return !(node.kind === 148 /* QualifiedName */ || + node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks @@ -38743,26 +40439,36 @@ var ts; // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 216 /* Block */ ? "quit" : n === container_3; })) { + if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) { return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { - case 176 /* ThisType */: + case 178 /* ThisType */: return !!tp.isThisType; - case 71 /* Identifier */: + case 72 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return true; } return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +40478,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38812,13 +40522,19 @@ var ts; var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); var modifiers = getMappedTypeModifiers(type); return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38851,61 +40567,77 @@ var ts; if (root.isDistributive) { var checkType_1 = root.checkType; var instantiatedType = mapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & (262144 /* Union */ | 32768 /* Never */)) { + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return mapper(type); + } + if (flags & 524288 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } function getWildcardInstantiation(type) { - return type.flags & (32764 /* Primitive */ | 3 /* AnyOrUnknown */ | 32768 /* Never */) ? type : + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); } function instantiateIndexInfo(info, mapper) { @@ -38914,34 +40646,34 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 202 /* BinaryExpression */: - return node.operatorToken.kind === 54 /* BarBarToken */ && + case 204 /* BinaryExpression */: + return node.operatorToken.kind === 55 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 266 /* JsxAttributes */: - return ts.some(node.properties, isContextSensitive); - case 265 /* JsxAttribute */: { + case 268 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 268 /* JsxExpression */: { + case 270 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -38958,7 +40690,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 195 /* ArrowFunction */) { + if (node.kind !== 197 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -38971,14 +40703,14 @@ var ts; function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. var body = node.body; - return body.kind === 216 /* Block */ ? false : isContextSensitive(body); + return body.kind === 218 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); @@ -38989,7 +40721,7 @@ var ts; return result; } } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -39004,6 +40736,9 @@ var ts; function compareTypesAssignable(source, target) { return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } function isTypeSubtypeOf(source, target) { return isTypeRelatedTo(source, target, subtypeRelation); } @@ -39019,11 +40754,12 @@ var ts; // Note that this check ignores type parameters and only considers the // inheritance hierarchy. function isTypeDerivedFrom(source, target) { - return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : - target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : - source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39049,33 +40785,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { - case 268 /* JsxExpression */: - case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); - case 202 /* BinaryExpression */: + case 270 /* JsxExpression */: + case 195 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: - case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage); } break; - case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); - case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); - case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + case 188 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation); + case 187 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation); + case 268 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target, relation); + case 197 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40885,17 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */) + continue; // Don't elaborate on indexes on generic variables + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40904,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39112,16 +40915,19 @@ var ts; var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; var issuedElaboration = false; if (!targetProp) { - var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40961,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40994,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39208,17 +41019,17 @@ var ts; prop = _a[_i]; if (ts.isSpreadAssignment(prop)) return [3 /*break*/, 7]; - type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), 2240 /* StringOrNumberLiteralOrUnique */); - if (!type || (type.flags & 32768 /* Never */)) { + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 131072 /* Never */)) { return [3 /*break*/, 7]; } _b = prop.kind; switch (_b) { - case 157 /* SetAccessor */: return [3 /*break*/, 2]; - case 156 /* GetAccessor */: return [3 /*break*/, 2]; - case 154 /* MethodDeclaration */: return [3 /*break*/, 2]; - case 274 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 273 /* PropertyAssignment */: return [3 /*break*/, 4]; + case 159 /* SetAccessor */: return [3 /*break*/, 2]; + case 158 /* GetAccessor */: return [3 /*break*/, 2]; + case 156 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 275 /* PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -39239,8 +41050,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,14 +41081,15 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 154 /* MethodDeclaration */ && - kind !== 153 /* MethodSignature */ && kind !== 155 /* Constructor */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ && + kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -39295,11 +41107,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39311,7 +41123,7 @@ var ts; var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && - (getFalsyFlags(sourceType) & 24576 /* Nullable */) === (getFalsyFlags(targetType) & 24576 /* Nullable */); + (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); var related = callbacks ? // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : @@ -39325,13 +41137,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39403,12 +41215,15 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 131072 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 /* NonPrimitive */ ? true : - type.flags & 262144 /* Union */ ? ts.some(type.types, isEmptyObjectType) : - type.flags & 524288 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : + return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 /* NonPrimitive */ ? true : + type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : false; } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type); + } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { if (sourceSymbol === targetSymbol) { return true; @@ -39445,43 +41260,45 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 3 /* AnyOrUnknown */ || s & 32768 /* Never */ || source === wildcardType) + if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType) return true; - if (t & 32768 /* Never */) + if (t & 131072 /* Never */) return false; - if (s & 68 /* StringLike */ && t & 4 /* String */) + if (s & 132 /* StringLike */ && t & 4 /* String */) return true; - if (s & 64 /* StringLiteral */ && s & 512 /* EnumLiteral */ && - t & 64 /* StringLiteral */ && !(t & 512 /* EnumLiteral */) && + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && + t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 168 /* NumberLike */ && t & 8 /* Number */) + if (s & 296 /* NumberLike */ && t & 8 /* Number */) return true; - if (s & 128 /* NumberLiteral */ && s & 512 /* EnumLiteral */ && - t & 128 /* NumberLiteral */ && !(t & 512 /* EnumLiteral */) && + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && + t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 272 /* BooleanLike */ && t & 16 /* Boolean */) + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) return true; - if (s & 3072 /* ESSymbolLike */ && t & 1024 /* ESSymbol */) + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) + return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) return true; if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 512 /* EnumLiteral */ && t & 512 /* EnumLiteral */) { - if (s & 262144 /* Union */ && t & 262144 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 448 /* Literal */ && t & 448 /* Literal */ && + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 8192 /* Undefined */ && (!strictNullChecks || t & (8192 /* Undefined */ | 4096 /* Void */))) + if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */))) return true; - if (s & 16384 /* Null */ && (!strictNullChecks || t & 16384 /* Null */)) + if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */)) return true; - if (s & 131072 /* Object */ && t & 16777216 /* NonPrimitive */) + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) return true; - if (s & 2048 /* UniqueESSymbol */ || t & 2048 /* UniqueESSymbol */) + if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) @@ -39489,30 +41306,30 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (8 /* Number */ | 128 /* NumberLiteral */) && !(s & 512 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 128 /* NumberLiteral */ && t & 512 /* EnumLiteral */)) + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; } return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(target)) { target = target.regularType; } if (source === target || - relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */) { + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */) { + if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) { return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); } return false; @@ -39532,6 +41349,7 @@ var ts; */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -39539,7 +41357,7 @@ var ts; var depth = 0; var expandingFlags = 0 /* None */; var overflow = false; - var isIntersectionConstituent = false; + var suppressNextError = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (overflow) { @@ -39566,15 +41384,27 @@ var ts; } } var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } if (errorOutputContainer) { errorOutputContainer.error = diag; } diagnostics.add(diag); // TODO: GH#18217 } return result !== 0 /* False */; - function reportError(message, arg0, arg1, arg2) { + function reportError(message, arg0, arg1, arg2, arg3) { ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } } function reportRelationError(message, source, target) { var sourceType = typeToString(source); @@ -39607,7 +41437,7 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 786432 /* UnionOrIntersection */)) { + if (!(type.flags & 3145728 /* UnionOrIntersection */)) { return false; } // at this point we know that this is union or intersection type possibly with nullable constituents. @@ -39615,7 +41445,7 @@ var ts; var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 24576 /* Nullable */) { + if (t.flags & 98304 /* Nullable */) { continue; } if (seenNonNullable) { @@ -39631,24 +41461,24 @@ var ts; * * Ternary.Maybe if they are related with assumptions of other relationships, or * * Ternary.False if they are not related. */ - function isRelatedTo(source, target, reportErrors, headMessage) { + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(target)) { target = target.regularType; } - if (source.flags & 8388608 /* Substitution */) { + if (source.flags & 33554432 /* Substitution */) { source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } - if (target.flags & 8388608 /* Substitution */) { + if (target.flags & 33554432 /* Substitution */) { target = target.typeVariable; } - if (source.flags & 2097152 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { source = getSimplifiedType(source); } - if (target.flags & 2097152 /* IndexedAccess */) { + if (target.flags & 8388608 /* IndexedAccess */) { target = getSimplifiedType(target); } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. @@ -39660,10 +41490,10 @@ var ts; // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" // when dealing with generics. // * We also don't deal with primitive source types, since we already halt elaboration below. - if (target.flags & 262144 /* Union */ && source.flags & 131072 /* Object */ && - target.types.length <= 3 && maybeTypeOfKind(target, 24576 /* Nullable */)) { - var nullStrippedTarget = extractTypesOfKind(target, ~24576 /* Nullable */); - if (!(nullStrippedTarget.flags & (262144 /* Union */ | 32768 /* Never */))) { + if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); + if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { target = nullStrippedTarget; } } @@ -39673,11 +41503,12 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (isObjectLiteralType(source) && source.flags & 33554432 /* FreshLiteral */) { - var discriminantType = target.flags & 262144 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) { + var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -39692,14 +41523,11 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && - !hasCommonProperties(source, target)) { + !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); var constructs = getSignaturesOfType(source, 1 /* Construct */); @@ -39715,25 +41543,24 @@ var ts; } var result = 0 /* False */; var saveErrorInfo = errorInfo; - var saveIsIntersectionConstituent = isIntersectionConstituent; - isIntersectionConstituent = false; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); } else { - if (target.flags & 262144 /* Union */) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */) && !(target.flags & 32764 /* Primitive */)); + if (target.flags & 1048576 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); } - else if (target.flags & 524288 /* Intersection */) { - isIntersectionConstituent = true; + else if (target.flags & 2097152 /* Intersection */) { + isIntersectionConstituent = true; // set here to affect the following trio of checks result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 524288 /* Intersection */) { + else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -39749,13 +41576,13 @@ var ts; // breaking the intersection apart. result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } - if (!result && (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - if (!result && source.flags & 524288 /* Intersection */) { + if (!result && source.flags & 2097152 /* Intersection */) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -39765,22 +41592,23 @@ var ts; // we need to check this constraint against a union on the target side. Also, given a type // variable V constrained to 'string | number', 'V & number' has a combined constraint of // 'string & number | number & number' which reduces to just 'number'. - var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 262144 /* Union */)); + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */)); if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 131072 /* Object */ && target.flags & 32764 /* Primitive */) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 131072 /* Object */ && globalObjectType === source) { + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } - else if (ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && target.flags & 524288 /* Intersection */) { + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { var targetTypes = target.types; var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); @@ -39790,6 +41618,10 @@ var ts; return result; } } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } reportRelationError(headMessage, source, target); } return result; @@ -39797,49 +41629,23 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); + if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); } - if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { + if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { @@ -39849,17 +41655,18 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. if (!errorNode) return { value: ts.Debug.fail() }; - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { @@ -39888,13 +41695,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39910,7 +41720,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 262144 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -39923,16 +41733,17 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; } function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { var sourceObjectFlags = ts.getObjectFlags(source); - if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 262144 /* Union */) { + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { return ts.find(unionTarget.types, function (target) { - if (target.flags & 131072 /* Object */) { + if (target.flags & 524288 /* Object */) { var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); if (overlapObjFlags & 4 /* Reference */) { return source.target === target.target; @@ -39950,39 +41761,33 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); - if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } + if (target.flags & 1048576 /* Union */) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; var targetTypes = target.types; for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); + var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); if (!related) { return 0 /* False */; } @@ -39992,7 +41797,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 262144 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -40017,9 +41822,10 @@ var ts; } return result; } - function typeArgumentsRelatedTo(source, target, variances, reportErrors) { - var sources = source.typeArguments || ts.emptyArray; - var targets = target.typeArguments || ts.emptyArray; + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } @@ -40073,7 +41879,7 @@ var ts; // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function recursiveTypeRelatedTo(source, target, reportErrors) { + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { if (overflow) { return 0 /* False */; } @@ -40116,7 +41922,7 @@ var ts; expandingFlags |= 1 /* Source */; if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) expandingFlags |= 2 /* Target */; - var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -40139,13 +41945,57 @@ var ts; function getConstraintForRelation(type) { return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } - function structuredTypeRelatedTo(source, target, reportErrors) { + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288 /* Object */)) { + if (flags & 4194304 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 8388608 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 16777216 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 65536 /* TypeParameter */) { - // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144 /* TypeParameter */) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -40155,9 +42005,9 @@ var ts; } } } - else if (target.flags & 1048576 /* Index */) { + else if (target.flags & 4194304 /* Index */) { // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 1048576 /* Index */) { + if (source.flags & 4194304 /* Index */) { if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } @@ -40168,20 +42018,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } - else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (target.flags & 8388608 /* IndexedAccess */) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40190,23 +42045,24 @@ var ts; var template = getTemplateTypeFromMappedType(target); var modifiers = getMappedTypeModifiers(target); if (!(modifiers & 8 /* ExcludeOptional */)) { - if (template.flags & 2097152 /* IndexedAccess */ && template.objectType === source && + if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source && template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } } - if (source.flags & 2162688 /* TypeVariable */) { - if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + if (source.flags & 8650752 /* TypeVariable */) { + if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { // A type S[K] is related to a type T[J] if S is related to T and K is related to J. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { result &= isRelatedTo(source.indexType, target.indexType, reportErrors); @@ -40217,29 +42073,32 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 65536 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~16777216 /* NonPrimitive */))) { + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { errorInfo = saveErrorInfo; return result; } } - else { - var instantiated = getTypeWithThisArgument(constraint, source); - if (result = isRelatedTo(instantiated, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; } } - else if (source.flags & 1048576 /* Index */) { + else if (source.flags & 4194304 /* Index */) { if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { errorInfo = saveErrorInfo; return result; } } - else if (source.flags & 4194304 /* Conditional */) { - if (target.flags & 4194304 /* Conditional */) { + else if (source.flags & 16777216 /* Conditional */) { + if (target.flags & 16777216 /* Conditional */) { // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, // and Y1 is related to Y2. @@ -40272,13 +42131,33 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); - if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { return result; } // The type arguments did not relate appropriately, but it may be because we have no variance @@ -40305,36 +42184,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +42226,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40373,7 +42242,24 @@ var ts; var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } } return 0 /* False */; } @@ -40420,8 +42306,8 @@ var ts; } } var properties = getPropertiesOfObjectType(target); - for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { - var targetProp = properties_3[_b]; + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { @@ -40491,35 +42377,8 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { + if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -40549,8 +42408,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40647,7 +42506,7 @@ var ts; continue; } // Skip over symbol-named members - if (prop.nameType && prop.nameType.flags & 2048 /* UniqueESSymbol */) { + if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) { continue; } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { @@ -40742,6 +42601,51 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -40749,62 +42653,71 @@ var ts; result.objectFlags |= 8192 /* MarkerType */; return result; } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } // Return an array containing the variance of each type parameter. The variance is effectively // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } function getVariances(type) { if (!strictFunctionTypes) { return ts.emptyArray; } - var typeParameters = type.typeParameters || ts.emptyArray; - var variances = type.variances; - if (!variances) { - if (type === globalArrayType || type === globalReadonlyArrayType) { - // Arrays are known to be covariant, no need to spend time computing this - variances = [1 /* Covariant */]; - } - else { - // The emptyArray singleton is used to signal a recursive invocation. - type.variances = ts.emptyArray; - variances = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - // We first compare instantiations where the type parameter is replaced with - // marker types that have a known subtype relationship. From this we can infer - // invariance, covariance, contravariance or bivariance. - var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); - var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); - var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | - (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); - // If the instantiations appear to be related bivariantly it may be because the - // type parameter is independent (i.e. it isn't witnessed anywhere in the generic - // type). To determine this we compare instantiations where the type parameter is - // replaced with marker types that are known to be unrelated. - if (variance === 3 /* Bivariant */ && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { - variance = 4 /* Independent */; - } - variances.push(variance); - } - } - type.variances = variances; + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return ts.emptyArray; } - return variances; + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } // Return true if the given type reference has a 'void' type argument for a covariant type parameter. // See comment at call in recursiveTypeRelatedTo for when this case matters. function hasCovariantVoidArgument(type, variances) { for (var i = 0; i < variances.length; i++) { - if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 4096 /* Void */) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { return true; } } return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -40897,13 +42810,13 @@ var ts; // levels, but unequal at some level beyond that. function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 131072 /* Object */) { + if (depth >= 5 && type.flags & 524288 /* Object */) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 131072 /* Object */ && t.symbol === symbol) { + if (t.flags & 524288 /* Object */ && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -40958,12 +42871,8 @@ var ts; return true; } // A source signature partially matches a target signature if the target signature has no fewer required - // parameters and no more overall parameters than the source signature (where a signature with a rest - // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = sourceHasRestParameter ? 1 : 0; - var targetRestCount = targetHasRestParameter ? 1 : 0; - if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) { + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { return true; } return false; @@ -41009,7 +42918,7 @@ var ts; for (var i = 0; i < targetLen; i++) { var s = getTypeAtPosition(source, i); var t = getTypeAtPosition(target, i); - var related = compareTypes(s, t); + var related = compareTypes(t, s); if (!related) { return 0 /* False */; } @@ -41030,8 +42939,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41054,9 +42963,9 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 24576 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 24576 /* Nullable */) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) : getUnionType(types, 2 /* Subtype */); } // Return the leftmost type for which no type to the right is a subtype. @@ -41069,11 +42978,14 @@ var ts; function isReadonlyArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 24576 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isEmptyArrayLiteralType(type) { var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; @@ -41083,40 +42995,47 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { - return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); + return !(type.flags & (109440 /* Unit */ | 131072 /* Never */)); } function isUnitType(type) { - return !!(type.flags & 27072 /* Unit */); + return !!(type.flags & 109440 /* Unit */); } function isLiteralType(type) { return type.flags & 16 /* Boolean */ ? true : - type.flags & 262144 /* Union */ ? type.flags & 512 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : + type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 /* StringLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : - type; + return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 512 /* BooleanLiteral */ ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : - type; + return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : + type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : + type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; } function getWidenedUniqueESSymbolType(type) { - return type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : type; } function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { @@ -41135,13 +43054,21 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41150,15 +43077,16 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : - type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : - type.flags & 29148 /* PossiblyFalsy */; + return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 : + type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 : + type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 : + type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 : + type.flags & 117724 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 29120 /* DefinitelyFalsy */); }) : + return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) : type; } function extractDefinitelyFalsyTypes(type) { @@ -41167,10 +43095,13 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : - type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + type.flags & 64 /* BigInt */ ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) || + type.flags & 128 /* StringLiteral */ && type.value === "" || + type.flags & 256 /* NumberLiteral */ && type.value === 0 || + type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : neverType; } /** @@ -41179,15 +43110,15 @@ var ts; * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both */ function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (8192 /* Undefined */ | 16384 /* Null */); + var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */); return missing === 0 ? type : - missing === 8192 /* Undefined */ ? getUnionType([type, undefinedType]) : - missing === 16384 /* Null */ ? getUnionType([type, nullType]) : + missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 65536 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } function getOptionalType(type) { ts.Debug.assert(strictNullChecks); - return type.flags & 8192 /* Undefined */ ? type : getUnionType([type, undefinedType]); + return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { if (!deferredGlobalNonNullableTypeAlias) { @@ -41197,7 +43128,7 @@ var ts; if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); } - return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -41240,7 +43171,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && type.flags & 33554432 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -41250,7 +43181,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; + regularNew.flags = resolved.flags; regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); type.regularType = regularNew; return regularNew; @@ -41338,15 +43269,15 @@ var ts; } function getWidenedTypeWithContext(type, context) { if (type.flags & 402653184 /* RequiresWidening */) { - if (type.flags & 24576 /* Nullable */) { + if (type.flags & 98304 /* Nullable */) { return anyType; } if (isObjectLiteralType(type)) { return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); - var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 24576 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). @@ -41372,7 +43303,7 @@ var ts; function reportWideningErrorsInType(type) { var errorReported = false; if (type.flags & 134217728 /* ContainsWideningType */) { - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } @@ -41408,68 +43339,90 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { - case 202 /* BinaryExpression */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + case 204 /* BinaryExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 149 /* Parameter */: + case 151 /* Parameter */: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - if (!declaration.name) { + case 289 /* JSDocFunctionType */: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; break; - case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + case 181 /* MappedType */: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41518,11 +43471,11 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - return !!(type.flags & 15794176 /* Instantiable */ || + return !!(type.flags & 63176704 /* Instantiable */ || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || - type.flags & 786432 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -41531,13 +43484,13 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || !!(type.flags & 786432 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { - if (!(t.flags & 64 /* StringLiteral */)) { + if (!(t.flags & 128 /* StringLiteral */)) { return; } var name = ts.escapeLeadingUnderscores(t.value); @@ -41558,25 +43511,25 @@ var ts; * property is computed by inferring from the source property type to X for the type * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ - function inferTypeForHomomorphicMappedType(source, target) { - var key = source.id + "," + target.id; + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } reverseMappedCache.set(key, undefined); - var type = createReverseMappedType(source, target); + var type = createReverseMappedType(source, target, constraint); reverseMappedCache.set(key, type); return type; } - function createReverseMappedType(source, target) { + function createReverseMappedType(source, target, constraint) { var properties = getPropertiesOfType(source); if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { return undefined; } // If any property contains context sensitive functions that have been skipped, the source type // is incomplete and we can't infer a meaningful input type. - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var prop = properties_4[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { return undefined; } @@ -41584,13 +43537,13 @@ var ts; // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been // applied to the element type(s). if (isArrayType(source)) { - return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isReadonlyArrayType(source)) { - return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isTupleType(source)) { - var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); @@ -41600,30 +43553,46 @@ var ts; var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; + reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); } - function inferReverseMappedType(sourceType, target) { - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = target.flags & 524288 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; - if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (!sourceProp) { - return targetProp; - } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3 /*break*/, 3]; + return [4 /*yield*/, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; } - } - return undefined; + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -41645,7 +43614,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41671,8 +43642,8 @@ var ts; } return; } - if (source.flags & 262144 /* Union */ && target.flags & 262144 /* Union */ && !(source.flags & 512 /* EnumLiteral */ && target.flags & 512 /* EnumLiteral */) || - source.flags & 524288 /* Intersection */ && target.flags & 524288 /* Intersection */) { + if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) || + source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -41695,7 +43666,7 @@ var ts; (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } - else if (t.flags & (128 /* NumberLiteral */ | 64 /* StringLiteral */)) { + else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) { var b = getBaseTypeOfLiteralType(t); if (typeIdenticalToSomeType(b, target.types)) { (matchingTypes || (matchingTypes = [])).push(t, b); @@ -41710,7 +43681,7 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 2162688 /* TypeVariable */) { + if (target.flags & 8650752 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding @@ -41718,7 +43689,7 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType) { + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -41731,19 +43702,39 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } - if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 63176704 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments @@ -41760,12 +43751,12 @@ var ts; } } } - else if (source.flags & 1048576 /* Index */ && target.flags & 1048576 /* Index */) { + else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { contravariant = !contravariant; inferFromTypes(source.type, target.type); contravariant = !contravariant; } - else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 1048576 /* Index */) { + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; var savePriority = priority; @@ -41774,17 +43765,20 @@ var ts; priority = savePriority; contravariant = !contravariant; } - else if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (source.flags & 4194304 /* Conditional */ && target.flags & 4194304 /* Conditional */) { + else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } - else if (target.flags & 786432 /* UnionOrIntersection */) { + else if (target.flags & 16777216 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -41809,7 +43803,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 262144 /* Union */) { + else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -41818,10 +43812,25 @@ var ts; } } else { - if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } - if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -41831,7 +43840,7 @@ var ts; // an instantiation of the same generic type), we do not explore this target as it would yield // no further inferences. We exclude the static side of classes from this check since it shares // its symbol with the instance side which would lead to false positives. - var isNonConstructorObject = target.flags & 131072 /* Object */ && + var isNonConstructorObject = target.flags & 524288 /* Object */ && !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { @@ -41847,6 +43856,13 @@ var ts; } } } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { @@ -41859,7 +43875,7 @@ var ts; } } function getInferenceInfoForType(type) { - if (type.flags & 2162688 /* TypeVariable */) { + if (type.flags & 8650752 /* TypeVariable */) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -41869,6 +43885,44 @@ var ts; } return undefined; } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* HomomorphicMappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } function inferFromObjectTypes(source, target) { if (isGenericMappedType(source) && isGenericMappedType(target)) { // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer @@ -41878,31 +43932,7 @@ var ts; } if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 1048576 /* Index */) { - // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, - // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source - // type and then make a secondary inference from that type to T. We make a secondary inference - // such that direct inferences to T get priority over inferences to Partial, for example. - var inference = getInferenceInfoForType(constraintType.type); - if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - var savePriority = priority; - priority |= 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; - } - } - return; - } - if (constraintType.flags & 65536 /* TypeParameter */) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. - var savePriority = priority; - priority |= 4 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { return; } } @@ -41915,33 +43945,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +43986,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +44030,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42007,11 +44050,11 @@ var ts; reducedTypes.push(t); } } - return type.flags & 262144 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +44072,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +44085,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +44098,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +44127,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +44156,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42124,7 +44198,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 165 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 146 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the @@ -42133,20 +44207,20 @@ var ts; // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } - if (node.kind === 99 /* ThisKeyword */) { + if (node.kind === 100 /* ThisKeyword */) { return "0"; } - if (node.kind === 187 /* PropertyAccessExpression */) { + if (node.kind === 189 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); return key && key + "." + ts.idText(node.name); } - if (node.kind === 184 /* BindingElement */) { + if (node.kind === 186 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 184 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -42155,14 +44229,14 @@ var ts; } function getBindingElementNameText(element) { var parent = element.parent; - if (parent.kind === 182 /* ObjectBindingPattern */) { + if (parent.kind === 184 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.idText(name); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return name.text; default: @@ -42176,29 +44250,29 @@ var ts; } function isMatchingReference(source, target) { switch (source.kind) { - case 71 /* Identifier */: - return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 235 /* VariableDeclaration */ || target.kind === 184 /* BindingElement */) && + case 72 /* Identifier */: + return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99 /* ThisKeyword */: - return target.kind === 99 /* ThisKeyword */; - case 97 /* SuperKeyword */: - return target.kind === 97 /* SuperKeyword */; - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 100 /* ThisKeyword */: + return target.kind === 100 /* ThisKeyword */; + case 98 /* SuperKeyword */: + return target.kind === 98 /* SuperKeyword */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 184 /* BindingElement */: - if (target.kind !== 187 /* PropertyAccessExpression */) + case 186 /* BindingElement */: + if (target.kind !== 189 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 184 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 235 /* VariableDeclaration */) { + if (source.parent.parent.kind === 237 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; return !!maybeId && isMatchingReference(maybeId, t.expression); } @@ -42211,7 +44285,7 @@ var ts; undefined; } function containsMatchingReference(source, target) { - while (source.kind === 187 /* PropertyAccessExpression */) { + while (source.kind === 189 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -42224,32 +44298,52 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 187 /* PropertyAccessExpression */ && + return target.kind === 189 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71 /* Identifier */) { + if (expr.kind === 72 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 187 /* PropertyAccessExpression */) { + if (expr.kind === 189 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 262144 /* Union */) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; + function isDiscriminantType(type) { + if (type.flags & 1048576 /* Union */) { + if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { + return true; } } return false; } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576 /* Union */); + } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -42276,7 +44370,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -42289,16 +44383,35 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 32768 /* Never */) { + if (assignedType.flags & 131072 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +44419,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42322,55 +44435,66 @@ var ts; function getTypeFacts(type) { var flags = type.flags; if (flags & 4 /* String */) { - return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; } - if (flags & 64 /* StringLiteral */) { + if (flags & 128 /* StringLiteral */) { var isEmpty = type.value === ""; return strictNullChecks ? - isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : + isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; } if (flags & (8 /* Number */ | 32 /* Enum */)) { - return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; } - if (flags & 128 /* NumberLiteral */) { + if (flags & 256 /* NumberLiteral */) { var isZero = type.value === 0; return strictNullChecks ? - isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : - isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; + isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : + isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : + isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; } if (flags & 16 /* Boolean */) { - return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; } - if (flags & 272 /* BooleanLike */) { + if (flags & 528 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 524288 /* Object */) { + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ : + strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } - if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { - return 2457472 /* UndefinedFacts */; + if (flags & (16384 /* Void */ | 32768 /* Undefined */)) { + return 9830144 /* UndefinedFacts */; } - if (flags & 16384 /* Null */) { - return 2340752 /* NullFacts */; + if (flags & 65536 /* Null */) { + return 9363232 /* NullFacts */; } - if (flags & 3072 /* ESSymbolLike */) { - return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; } - if (flags & 16777216 /* NonPrimitive */) { - return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } - if (flags & 15794176 /* Instantiable */) { + if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 786432 /* UnionOrIntersection */) { + if (flags & 3145728 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } - return 4194303 /* All */; + return 16777215 /* All */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -42378,7 +44502,7 @@ var ts; function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); + return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); } return type; } @@ -42390,7 +44514,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42398,15 +44522,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 185 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 273 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 225 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -42423,21 +44547,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return stringType; - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return undefinedType; - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -42445,7 +44569,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 182 /* ObjectBindingPattern */ ? + var type = pattern.kind === 184 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -42463,39 +44587,39 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 224 /* ForInStatement */) { + if (node.parent.parent.kind === 226 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 225 /* ForOfStatement */) { + if (node.parent.parent.kind === 227 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 235 /* VariableDeclaration */ ? + return node.kind === 237 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { - return node.kind === 235 /* VariableDeclaration */ && node.initializer && + return node.kind === 237 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 184 /* BindingElement */ && node.parent.kind === 202 /* BinaryExpression */ && + node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return getReferenceCandidate(node.left); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return getReferenceCandidate(node.right); } } @@ -42503,13 +44627,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 193 /* ParenthesizedExpression */ || - parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + return parent.kind === 195 /* ParenthesizedExpression */ || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 269 /* CaseClause */) { + if (clause.kind === 271 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -42525,14 +44649,31 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271 /* CaseClause */) { + if (clause.expression.kind === 10 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { - return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 262144 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -42541,34 +44682,37 @@ var ts; } return true; } - if (source.flags & 512 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); + return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); } return f(type) ? type : neverType; } function mapType(type, mapper, noReductions) { - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { return type; } - if (!(type.flags & 262144 /* Union */)) { + if (!(type.flags & 1048576 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42591,12 +44735,14 @@ var ts; // typeWithPrimitives have been replaced with occurrences of string literals and numeric // literals in typeWithLiterals, respectively. function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* StringLiteral */) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* NumberLiteral */)) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) { return mapType(typeWithPrimitives, function (t) { - return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 64 /* StringLiteral */) : - t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 128 /* NumberLiteral */) : - t; + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : + t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : + t; }); } return typeWithPrimitives; @@ -42630,9 +44776,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 32768 /* Never */ ? + return elementType.flags & 131072 /* Never */ ? autoArrayType : - createArrayType(elementType.flags & 262144 /* Union */ ? + createArrayType(elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType); } @@ -42648,9 +44794,9 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - if (!(t.flags & 32768 /* Never */)) { + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; } @@ -42672,15 +44818,15 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 187 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || - parent.parent.kind === 189 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 188 /* ElementAccessExpression */ && + var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 202 /* BinaryExpression */ && - parent.parent.operatorToken.kind === 58 /* EqualsToken */ && + parent.parent.kind === 204 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 59 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 168 /* NumberLike */); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -42691,7 +44837,7 @@ var ts; return links.maybeTypePredicate; } function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97 /* SuperKeyword */) { + if (node.expression.kind !== 98 /* SuperKeyword */) { var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); @@ -42713,7 +44859,7 @@ var ts; if (flowAnalysisDisabled) { return errorType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 33492479 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) { return declaredType; } var sharedFlowStart = sharedFlowCount; @@ -42723,14 +44869,14 @@ var ts; // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. - var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent && reference.parent.kind === 211 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 32768 /* Never */) { + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { return declaredType; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42796,9 +44942,9 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.container; if (container && container !== flowContainer && - reference.kind !== 187 /* PropertyAccessExpression */ && - reference.kind !== 188 /* ElementAccessExpression */ && - reference.kind !== 99 /* ThisKeyword */) { + reference.kind !== 189 /* PropertyAccessExpression */ && + reference.kind !== 190 /* ElementAccessExpression */ && + reference.kind !== 100 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -42833,11 +44979,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + if (declaredType.flags & 1048576 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,15 +44992,27 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } + // for (const _ in ref) acts as a nonnull on ref + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } // Assignment doesn't affect reference return undefined; } function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 189 /* CallExpression */ ? + var expr = node.kind === 191 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -42862,15 +45020,16 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -42884,7 +45043,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { return flowType; } // If we have an antecedent type (meaning we're reachable in some way), we first @@ -42901,19 +45060,25 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 32768 /* Never */ ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43027,8 +45192,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 262144 /* Union */) || - expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + if (!(computedType.flags & 1048576 /* Union */) || + expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { return false; } var access = expr; @@ -43049,10 +45214,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); + return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } if (isMatchingReferenceDiscriminant(expr, declaredType)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } if (containsMatchingReferenceDiscriminant(reference, expr)) { return declaredType; @@ -43070,7 +45235,7 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if ((type.flags & (262144 /* Union */ | 131072 /* Object */)) || (type.flags & 65536 /* TypeParameter */ && type.isThisType)) { + if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); } @@ -43078,19 +45243,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -43109,15 +45274,15 @@ var ts; return declaredType; } break; - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 92 /* InKeyword */: + case 93 /* InKeyword */: var target = getReferenceCandidate(expr.right); if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; - case 26 /* CommaToken */: + case 27 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } return type; @@ -43126,28 +45291,28 @@ var ts; if (type.flags & 1 /* Any */) { return type; } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 24576 /* Nullable */) { + if (valueType.flags & 98304 /* Nullable */) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; + var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */; var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - valueType.flags & 16384 /* Null */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : + valueType.flags & 65536 /* Null */ ? + assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : + assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 16909315 /* NotUnionOrUnit */) { + if (type.flags & 67637251 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 32768 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -43159,40 +45324,47 @@ var ts; // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { return declaredType; } return type; } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 15794176 /* Instantiable */) { + if (type.flags & 63176704 /* Instantiable */) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43203,27 +45375,115 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 32768 /* Never */ ? neverType : + var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 /* Any */ ? type : globalFunctionType; + case "object": + return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjusted clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { return declaredType; } return type; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43240,22 +45500,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43263,9 +45513,9 @@ var ts; } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 32768 /* Never */)) { + if (!(assignableType.flags & 131072 /* Never */)) { return assignableType; } } @@ -43305,7 +45555,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 188 /* ElementAccessExpression */ || invokedExpression.kind === 187 /* PropertyAccessExpression */) { + if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -43322,20 +45572,20 @@ var ts; // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 200 /* PrefixUnaryExpression */: - if (expr.operator === 51 /* ExclamationToken */) { + case 202 /* PrefixUnaryExpression */: + if (expr.operator === 52 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -43349,7 +45599,7 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 71 /* Identifier */) { + if (location.kind === 72 /* Identifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } @@ -43370,17 +45620,17 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 243 /* ModuleBlock */ || - node.kind === 277 /* SourceFile */ || - node.kind === 152 /* PropertyDeclaration */; + node.kind === 245 /* ModuleBlock */ || + node.kind === 279 /* SourceFile */ || + node.kind === 154 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43388,13 +45638,13 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 149 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) { symbol.isAssigned = true; } } @@ -43409,21 +45659,21 @@ var ts; /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 149 /* Parameter */ && + declaration.kind === 151 /* Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 8192 /* Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 8192 /* Undefined */); - return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 187 /* PropertyAccessExpression */ || - parent.kind === 189 /* CallExpression */ && parent.expression === node || - parent.kind === 188 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 184 /* BindingElement */ && parent.name === node && !!parent.initializer; + return parent.kind === 189 /* PropertyAccessExpression */ || + parent.kind === 191 /* CallExpression */ && parent.expression === node || + parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { - return type.flags & 14745600 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 24576 /* Nullable */); + return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */); } function getConstraintForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, @@ -43436,7 +45686,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43454,7 +45704,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 195 /* ArrowFunction */) { + if (container.kind === 197 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { @@ -43475,28 +45725,28 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 238 /* ClassDeclaration */ + if (declaration.kind === 240 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); } } - else if (declaration.kind === 207 /* ClassExpression */) { + else if (declaration.kind === 209 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 277 /* SourceFile */) { + while (container.kind !== 279 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43509,12 +45759,17 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } return errorType; } } @@ -43538,7 +45793,7 @@ var ts; // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 149 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -43547,8 +45802,8 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 194 /* FunctionExpression */ || - flowContainer.kind === 195 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ || + flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -43557,9 +45812,9 @@ var ts; // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || - isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || - node.parent.kind === 211 /* NonNullExpression */ || - declaration.kind === 235 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) || + node.parent.kind === 213 /* NonNullExpression */ || + declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 4194304 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -43568,7 +45823,7 @@ var ts; // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (type === autoType || type === autoArrayType) { + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); @@ -43577,7 +45832,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -43587,10 +45842,13 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 272 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -43611,26 +45869,46 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + 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 === 223 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && + if (container.kind === 225 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 193 /* ParenthesizedExpression */) { + while (current.parent.kind === 195 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -43638,9 +45916,9 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 200 /* PrefixUnaryExpression */ || current.parent.kind === 201 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) { var expr = current.parent; - isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; + isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */; } if (!isAssigned) { return false; @@ -43651,7 +45929,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 152 /* PropertyDeclaration */ || container.kind === 155 /* Constructor */) { + if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -43719,37 +45997,37 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 155 /* Constructor */) { + if (container.kind === 157 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 195 /* ArrowFunction */) { + if (container.kind === 197 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } switch (container.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* 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 241 /* EnumDeclaration */: + case 243 /* 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 155 /* Constructor */: + case 157 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: if (ts.hasModifier(container, 32 /* Static */)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -43760,39 +46038,43 @@ var ts; var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ? + var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } } return type || anyType; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,16 +46089,68 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 196 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 156 /* MethodDeclaration */ && + container.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 196 /* FunctionExpression */ && + container.parent.kind === 275 /* PropertyAssignment */ && + container.parent.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === 196 /* FunctionExpression */ && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -43830,15 +46164,15 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 149 /* Parameter */; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 189 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 195 /* ArrowFunction */) { + while (container && container.kind === 197 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -43851,14 +46185,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 147 /* ComputedPropertyName */; }); - if (current && current.kind === 147 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; }); + if (current && current.kind === 149 /* 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 === 186 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -43866,7 +46200,7 @@ var ts; } return errorType; } - if (!isCallExpression && container.kind === 155 /* Constructor */) { + if (!isCallExpression && container.kind === 157 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { @@ -43898,16 +46232,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // 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: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43919,20 +46255,21 @@ var ts; // // 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); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = 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 === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. + if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -43946,7 +46283,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 186 /* ObjectLiteralExpression */) { + if (container.parent.kind === 188 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -43967,7 +46304,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 155 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 157 /* 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 errorType; @@ -43982,7 +46319,7 @@ 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 === 155 /* Constructor */; + return container.kind === 157 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -43990,21 +46327,21 @@ var 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\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) { if (ts.hasModifier(container, 32 /* Static */)) { - return container.kind === 154 /* MethodDeclaration */ || - container.kind === 153 /* MethodSignature */ || - container.kind === 156 /* GetAccessor */ || - container.kind === 157 /* SetAccessor */; + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */; } else { - return container.kind === 154 /* MethodDeclaration */ || - container.kind === 153 /* MethodSignature */ || - container.kind === 156 /* GetAccessor */ || - container.kind === 157 /* SetAccessor */ || - container.kind === 152 /* PropertyDeclaration */ || - container.kind === 151 /* PropertySignature */ || - container.kind === 155 /* Constructor */; + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */ || + container.kind === 154 /* PropertyDeclaration */ || + container.kind === 153 /* PropertySignature */ || + container.kind === 157 /* Constructor */; } } } @@ -44012,10 +46349,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 154 /* MethodDeclaration */ || - func.kind === 156 /* GetAccessor */ || - func.kind === 157 /* SetAccessor */) && func.parent.kind === 186 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 194 /* FunctionExpression */ && func.parent.kind === 273 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 156 /* MethodDeclaration */ || + func.kind === 158 /* GetAccessor */ || + func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -44023,11 +46360,11 @@ var ts; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 524288 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 195 /* ArrowFunction */) { + if (func.kind === 197 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -44039,7 +46376,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44054,7 +46391,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 273 /* PropertyAssignment */) { + if (literal.parent.kind !== 275 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -44068,9 +46405,9 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = func.parent; - if (parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) { var target = parent.left; - if (target.kind === 187 /* PropertyAccessExpression */ || target.kind === 188 /* ElementAccessExpression */) { + if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) { var expression = target.expression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { @@ -44096,7 +46433,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44130,7 +46467,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 149 /* Parameter */) { + if (declaration.kind === 151 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -44142,7 +46479,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 184 /* BindingElement */) { + if (parentDeclaration.kind !== 186 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -44163,9 +46500,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44212,7 +46561,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44220,10 +46569,13 @@ var ts; // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 191 /* TaggedTemplateExpression */) { + if (template.parent.kind === 193 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -44232,26 +46584,33 @@ var ts; var binaryExpression = node.parent; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { - case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; - case 54 /* BarBarToken */: + case 59 /* EqualsToken */: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; - case 53 /* AmpersandAmpersandToken */: - case 26 /* CommaToken */: + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; default: return undefined; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,26 +46628,57 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return ts.Debug.fail("Does not apply"); default: return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - if (t.flags & 917504 /* StructuredType */) { + if (t.flags & 3670016 /* StructuredType */) { var prop = getPropertyOfType(t, name); if (prop) { return getTypeOfSymbol(prop); @@ -44299,6 +46689,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +46698,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44329,8 +46717,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44346,7 +46734,6 @@ var ts; // type of T. function getContextualTypeForElementExpression(arrayContextualType, index) { return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) - || getIndexTypeOfContextualType(arrayContextualType, 1 /* Number */) || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); } // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. @@ -44388,54 +46775,44 @@ var ts; // recursive (and possibly infinite) invocations of getContextualType. function isPossiblyDiscriminantValue(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 71 /* Identifier */: + case 9 /* BigIntLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 72 /* Identifier */: + case 141 /* UndefinedKeyword */: return true; - case 187 /* PropertyAccessExpression */: - case 193 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 195 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 270 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44464,52 +46841,54 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 186 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 195 /* ArrowFunction */: - case 228 /* ReturnStatement */: + case 197 /* ArrowFunction */: + case 230 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 201 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); + case 191 /* CallExpression */: + case 192 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 185 /* ArrayLiteralExpression */: { + case 187 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 214 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 204 /* TemplateExpression */); + case 216 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 193 /* ParenthesizedExpression */: { + case 195 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent); } return undefined; @@ -44519,67 +46898,16 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; } - var valueType = checkExpression(node.tagName); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); + return getContextualTypeForArgumentAtIndex(node, 0); } - function getJsxSignaturesParameterTypes(valueType, isJs, context) { - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (valueType.flags & 4 /* String */) { - return anyType; - } - else if (valueType.flags & 64 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = valueType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - } - return anyType; - } - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(valueType, 1 /* Construct */); - var ctor = true; - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, 0 /* Call */); - ctor = false; - if (signatures.length === 0) { - // We found no signatures at all, which is an error - return errorType; - } - } - var links = getNodeLinks(context); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(valueType); - var cachedResolved = links.resolvedSignatures.get(cacheKey); - if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { - signatures = cachedResolved; - } - else if (!cachedResolved) { - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); - } - return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); @@ -44594,22 +46922,40 @@ var ts; var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } return attributesType; } - function getJsxPropsTypeFromClassType(sig, isJs, context, reportErrors) { + function getJsxPropsTypeFromClassType(sig, context) { var ns = getJsxNamespaceAt(context); var forcedLookupLocation = getJsxElementPropertiesName(ns); var attributesType = forcedLookupLocation === undefined @@ -44622,7 +46968,7 @@ var ts; : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); if (!attributesType) { // There is no property named 'props' on this instance type - if (reportErrors && !!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); } return emptyObjectType; @@ -44640,7 +46986,7 @@ var ts; var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); var hostClassType = getReturnTypeOfSignature(sig); apparentAttributesType = intersectTypes(typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) : intrinsicClassAttribs, apparentAttributesType); } var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); @@ -44676,7 +47022,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 194 /* FunctionExpression */ || node.kind === 195 /* ArrowFunction */; + return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -44695,7 +47041,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -44704,13 +47050,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 262144 /* Union */)) { + if (!(type.flags & 1048576 /* Union */)) { return getContextualCallSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44743,10 +47089,10 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 184 /* BindingElement */ && !!node.initializer) || - (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + return (node.kind === 186 /* BindingElement */ && !!node.initializer) || + (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44755,7 +47101,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elementCount; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 206 /* SpreadElement */) { + if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -44768,7 +47114,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,47 +47123,59 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } - if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { + if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) { hasNonEndingSpreadElement = true; } } if (!hasNonEndingSpreadElement) { - var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206 /* SpreadElement */; + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - 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 (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + 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 (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) { + if (e.kind !== 210 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44826,12 +47184,12 @@ var ts; } function isNumericName(name) { switch (name.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return isNumericComputedName(name); - case 71 /* Identifier */: + case 72 /* Identifier */: return isNumericLiteralName(name.escapedText); case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return isNumericLiteralName(name.text); default: return false; @@ -44840,7 +47198,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAssignableToKind(checkComputedPropertyName(name), 168 /* NumberLike */); + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -44875,8 +47233,8 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (links.resolvedType.flags & 24576 /* Nullable */ || - !isTypeAssignableToKind(links.resolvedType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */) && + if (links.resolvedType.flags & 98304 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -44896,6 +47254,17 @@ var ts; var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + } function checkObjectLiteral(node, checkMode) { var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking @@ -44903,13 +47272,13 @@ var ts; var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 33554432 /* FreshLiteral */; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44919,15 +47288,15 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 147 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 273 /* PropertyAssignment */ || - memberDecl.kind === 274 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 275 /* PropertyAssignment */ || + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : - memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -44938,7 +47307,7 @@ var ts; } } typeFlags |= type.flags; - var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? + var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : @@ -44949,8 +47318,8 @@ 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 === 273 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 274 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -44975,12 +47344,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 275 /* SpreadAssignment */) { + else if (memberDecl.kind === 277 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -44992,7 +47361,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); offset = i + 1; continue; } @@ -45002,10 +47371,10 @@ 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 === 156 /* GetAccessor */ || memberDecl.kind === 157 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (computedNameType && !(computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */)) { + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { if (isTypeAssignableTo(computedNameType, numberType)) { hasComputedNumberProperty = true; @@ -45039,7 +47408,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); } return spread; } @@ -45048,9 +47417,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; - result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); - result.objectFlags |= 128 /* ObjectLiteral */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; + result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -45060,20 +47428,17 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 24576 /* Nullable */)) { - propagatedFlags |= (result.flags & 939524096 /* PropagatingFlags */); - } + propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; return result; } } function isValidSpreadType(type) { - return !!(type.flags & (3 /* AnyOrUnknown */ | 16777216 /* NonPrimitive */) || - getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 131072 /* Object */ && !isGenericMappedType(type) || - type.flags & 786432 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); } function checkJsxSelfClosingElementDeferred(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node, 0 /* Normal */); + checkJsxOpeningLikeElementOrOpeningFragment(node); } function checkJsxSelfClosingElement(node, _checkMode) { checkNodeDeferred(node); @@ -45081,7 +47446,7 @@ var ts; } function checkJsxElementDeferred(node) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, 0 /* Normal */); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -45089,18 +47454,20 @@ var ts; else { checkExpression(node.closingElement.tagName); } + checkJsxChildren(node); } function checkJsxElement(node, _checkMode) { checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } - function checkJsxFragment(node, checkMode) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { error(node, compilerOptions.jsxFactory ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } + checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } /** @@ -45114,7 +47481,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) { - return tagName.kind === 71 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); + return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); } function checkJsxAttribute(node, checkMode) { return node.initializer @@ -45133,16 +47500,19 @@ var ts; function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); - var spread = emptyObjectType; + var spread = emptyJsxObjectType; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45157,9 +47527,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +47537,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,11 +47546,11 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 258 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -45191,32 +47561,35 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); } } if (hasSpreadAnyType) { return anyType; } - if (typeToIntersect && spread !== emptyObjectType) { + if (typeToIntersect && spread !== emptyJsxObjectType) { return getIntersectionType([typeToIntersect, spread]); } - return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable * @param attributesTable a symbol table of attributes property */ function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; - result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; return result; } } @@ -45226,7 +47599,7 @@ var ts; var child = _a[_i]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. - if (child.kind === 10 /* JsxText */) { + if (child.kind === 11 /* JsxText */) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); } @@ -45248,7 +47621,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45289,57 +47662,6 @@ var ts; } return links.resolvedSymbol; } - function instantiateJsxSignatures(node, signatures) { - var instantiatedSignatures = []; - var candidateForTypeArgumentError; - var hasTypeArgumentError = !!node.typeArguments; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); - if (typeArgumentInstantiated) { - hasTypeArgumentError = false; - instantiatedSignatures.push(typeArgumentInstantiated); - } - else { - if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - candidateForTypeArgumentError = signature; - } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - } - else { - instantiatedSignatures.push(signature); - } - } - if (node.typeArguments && hasTypeArgumentError) { - if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); - } - // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine - else if (node.typeArguments.length !== 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); - } - } - return instantiatedSignatures; - } - function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { - if (reportErrors === void 0) { reportErrors = false; } - if (!node.typeArguments) { - return; - } - if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - return; - } - var args = checkTypeArguments(signature, node.typeArguments, reportErrors); - if (!args) { - return; - } - return getSignatureInstantiation(signature, args, isJavascript); - } function getJsxNamespaceAt(location) { var links = location && getNodeLinks(location); if (links && links.jsxNamespace) { @@ -45373,7 +47695,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +47719,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45410,217 +47732,78 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - return undefined; + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; } - if (propsType.flags & 524288 /* Intersection */) { - var propsApparentType = []; - for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { - var t = _a[_i]; - propsApparentType.push(getApparentType(t)); + else if (elementType.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; } - return getIntersectionType(propsApparentType); - } - return getApparentType(propsType); - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return only attributes type of successfully resolved call signature. - * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) - * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); - if (callSignature !== unknownSignature) { - var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); - var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; } } - return undefined; - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return all attributes type of resolved call signature including candidate signatures. - * This function assumes that the caller handled other possible element type of the JSX element. - * This function is a behavior used by language service when looking up completion in JSX element. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - var candidate = candidatesOutArray_1[_i]; - var callReturnType = getReturnTypeOfSignature(candidate); - // TODO: GH#18217: callReturnType should always be defined... - var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - var shouldBeCandidate = true; - for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217 - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - // If we can't find any matching, just return everything. - if (!result) { - result = allMatchingAttributesType; - } - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { - var links = getNodeLinks(openingLikeElement); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(elementType); - if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { - return; - } - else if (links.resolvedSignatures.get(cacheKey)) { - return links.resolvedSignatures.get(cacheKey); - } - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + var apparentElemType = getApparentType(elementType); // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(elementType, 1 /* Construct */); + var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); if (signatures.length === 0) { // No construct signatures, try call signatures - signatures = getSignaturesOfType(elementType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - if (reportErrors) { - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - } + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0 /* Component */) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { // Mixed + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { return; } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - // Instantiate in context of source type - var results = instantiateJsxSignatures(openingLikeElement, signatures); - links.resolvedSignatures.set(cacheKey, results); - return results; - } - /** - * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. - * For instance: - * declare function Foo(attr: { p1: string}): JSX.Element; - * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" - * - * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. - * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component - * - * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement - * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature - * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present - * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) - * @return attributes type if able to resolve the type of node - * anyType if there is no type ElementAttributesProperty or there is an error - * emptyObjectType if there is no "prop" in the element instance type - */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType.flags & 262144 /* Union */) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), 2 /* Subtype */); - } - // Shortcircuit any - if (isTypeAny(elementType)) { - return elementType; - } - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - else if (elementType.flags & 4 /* String */) { - return anyType; - } - else if (elementType.flags & 64 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - // If we need to report an error, we already done so here. So just return any to prevent any more error downstream - return anyType; - } - // Get the element instance type (the result of newing or invoking this tag) - var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); - if (!ts.length(instantiatedSignatures)) { - return errorType; - } - var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */); - // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. - // Otherwise get only attributes type from the signature picked by choose-overload logic. - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -45644,53 +47827,6 @@ var ts; } return links.resolvedJsxElementAttributesType; } - /** - * Get attributes type of the given custom opening-like JSX element. - * This function is intended to be called from a caller that handles intrinsic JSX element already. - * @param node a custom JSX opening-like element - * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component - */ - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); - } - /** - * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. - * This function is called by language service (see: completions-tryGetGlobalSymbols). - * @param node a JSX opening-like element to get attributes type for - */ - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - // Because in language service, the given JSX opening-like element may be incomplete and therefore, - // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); - } - } - /** - * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. - * @param node a JSXOpeningLikeElement node - * @return an attributes type of the given node - */ - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); - } - } - /** - * Given a JSX attribute, returns the symbol for the corresponds property - * of the element attributes type. Will return unknownSymbol for attributes - * that have no matching element attributes type property. - */ - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.escapedText); - return prop || unknownSymbol; - } function getJsxElementClassTypeAt(location) { var type = getJsxType(JsxNames.ElementClass, location); if (type === errorType) @@ -45724,7 +47860,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -45735,7 +47871,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45746,10 +47882,8 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } /** @@ -45766,7 +47900,7 @@ var ts; * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType */ function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 131072 /* Object */) { + if (targetType.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -45776,7 +47910,7 @@ var ts; return true; } } - else if (targetType.flags & 786432 /* UnionOrIntersection */) { + else if (targetType.flags & 3145728 /* UnionOrIntersection */) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -45784,55 +47918,12 @@ var ts; } } } - else if (targetType.flags & 4194304 /* Conditional */) { + else if (targetType.flags & 16777216 /* Conditional */) { return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); } return false; } - /** - * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. - * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" - * Check assignablity between given attributes property, "source attributes", and the "target attributes" - * @param openingLikeElement an opening-like JSX element to check its JSXAttributes - */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { - // The function involves following steps: - // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. - // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) - // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. - // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); - // sourceAttributesType is a type of an attributes properties. - // i.e
- // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); - // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties - var isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); - // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { - var attribute = _a[_i]; - if (!ts.isJsxAttribute(attribute)) { - continue; - } - var attrName = attribute.name; - var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); - // We break here so that errors won't be cascading - break; - } - } - } - else if (!isSourceAttributeTypeAssignableToTarget) { - checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); - } - } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -45856,10 +47947,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45872,7 +47963,7 @@ var ts; */ function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name; + var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); @@ -45904,7 +47995,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -45944,13 +48035,13 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { return true; } - if (type.flags & 65536 /* TypeParameter */) { + if (type.flags & 262144 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } @@ -45970,19 +48061,26 @@ var ts; function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + return getNonNullableType(type); + } + return type; + } function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { if (type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 24576 /* Nullable */; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 8192 /* Undefined */ ? kind & 16384 /* Null */ ? + error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); - return t.flags & (24576 /* Nullable */ | 32768 /* Never */) ? errorType : t; + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } @@ -46015,7 +48113,7 @@ var ts; return anyType; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } return errorType; } @@ -46026,12 +48124,12 @@ var ts; } else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); + markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } } @@ -46040,9 +48138,9 @@ var ts; // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 187 /* PropertyAccessExpression */ || + if (node.kind !== 189 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 262144 /* Union */)) { + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } // If strict null checks and strict property initialization checks are enabled, if we have @@ -46050,17 +48148,23 @@ var ts; // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && left.kind === 99 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 155 /* Constructor */ && flowContainer.parent === declaration.parent) { + if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) { assumeUninitialized = true; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -46079,8 +48183,8 @@ var ts; && !isPropertyDeclaredInAncestorClass(prop)) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 238 /* ClassDeclaration */ && - node.parent.kind !== 162 /* TypeReference */ && + else if (valueDeclaration.kind === 240 /* ClassDeclaration */ && + node.parent.kind !== 164 /* TypeReference */ && !(valueDeclaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -46092,9 +48196,9 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return true; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: @@ -46132,7 +48236,7 @@ var ts; function reportNonexistentProperty(propNode, containingType) { var errorInfo; var relatedInfo; - if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { + if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -46172,7 +48276,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46224,7 +48328,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -46241,16 +48345,16 @@ var ts; } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: - return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 146 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 148 /* QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 181 /* ImportType */: + case 183 /* ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -46277,20 +48381,20 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * 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 === 236 /* VariableDeclarationList */) { + if (initializer.kind === 238 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 71 /* Identifier */) { + else if (initializer.kind === 72 /* Identifier */) { return getResolvedSymbol(initializer); } return undefined; @@ -46307,13 +48411,13 @@ var ts; */ function isForInVariableForNumericPropertyNames(expr) { var e = ts.skipParentheses(expr); - if (e.kind === 71 /* Identifier */) { + if (e.kind === 72 /* Identifier */) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3 /* Variable */) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 224 /* ForInStatement */ && + if (node.kind === 226 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -46331,7 +48435,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 190 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 192 /* 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); @@ -46343,15 +48447,15 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) { error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46362,7 +48466,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 3072 /* ESSymbolLike */) === 0) { + if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -46389,8 +48493,7 @@ var ts; return true; } function callLikeExpressionMayHaveTypeArguments(node) { - // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) - return ts.isCallOrNewExpression(node); + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); } function resolveUntypedCall(node) { if (callLikeExpressionMayHaveTypeArguments(node)) { @@ -46398,10 +48501,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 191 /* TaggedTemplateExpression */) { + if (node.kind === 193 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 150 /* Decorator */) { + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -46428,8 +48534,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -46465,25 +48571,23 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 206 /* SpreadElement */ || arg.kind === 213 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call + var argCount; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". - return true; - } - if (node.kind === 191 /* TaggedTemplateExpression */) { - // 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 + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193 /* TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 204 /* TemplateExpression */) { + if (node.template.kind === 206 /* 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 lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -46494,35 +48598,53 @@ var ts; // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. var templateLiteral = node.template; - ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */); + ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + else if (node.kind === 152 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 190 /* NewExpression */); + ts.Debug.assert(node.kind === 192 /* NewExpression */); return getMinArgumentCount(signature) === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. - if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { return false; } // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = argCount >= getMinArgumentCount(signature); - return callIsIncomplete || hasEnoughArguments; + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; } function hasCorrectTypeArgumentArity(signature, typeArguments) { // If the user supplied type arguments, but the number of type arguments does not match @@ -46534,7 +48656,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -46545,7 +48667,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,16 +48676,11 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, node, context) { - // Skip context sensitive pass - var skipContextParamType = getTypeAtPosition(signature, 0); - var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); - inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); - // Standard pass - var paramType = getTypeAtPosition(signature, 0); - var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } @@ -46579,11 +48696,14 @@ var ts; inference.inferredType = undefined; } } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (node.kind !== 150 /* Decorator */) { + if (node.kind !== 152 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -46612,71 +48732,50 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; 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 !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. - return arg.kind === 213 /* SyntheticExpression */ ? + return arg.kind === 215 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; - var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 32764 /* Primitive */ | 1048576 /* Index */); + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */); var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,27 +48784,40 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2 /* Mixed */; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. * @param node a JSX opening-like element we are trying to figure its call signature @@ -46713,37 +48825,20 @@ var ts; * @param relation a relationship to check parameter and argument type * @param excludeArgument */ - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: - // 1. callIsIncomplete - // 2. attributes property has same number of properties as the parameter object type. - // We can figure that out by resolving attributes property and check number of properties in the resolved type - // If the call has correct arity, we will then check if the argument type and parameter type is assignable - var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete - if (callIsIncomplete) { - return true; - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, // can be specified by users through attributes property. - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 190 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -46756,346 +48851,142 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; 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 !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); - if (callee.kind === 187 /* PropertyAccessExpression */ || callee.kind === 188 /* ElementAccessExpression */) { + if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) { return callee.expression; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { - if (node.kind === 191 /* TaggedTemplateExpression */) { + if (node.kind === 193 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 - if (template.kind === 204 /* TemplateExpression */) { + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 152 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* 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); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* 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. + var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 1; + case 154 /* PropertyDeclaration */: + return 2; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 151 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,15 +48995,19 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; var minCount = getMinArgumentCount(sig); var maxCount = getParameterCount(sig); if (minCount < argCount && minCount > belowArgCount) belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,22 +49018,31 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -47146,14 +49050,15 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { - var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 150 /* Decorator */; + var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 152 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; var typeArguments; if (!isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -47161,40 +49066,26 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47222,7 +49113,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -47246,32 +49137,33 @@ var ts; // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, // skip the checkApplicableSignature check. - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". - return candidateForArgumentError; + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); - } - else if (candidateForArgumentArityError) { - diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); - } - else if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); - } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +49183,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47364,7 +49276,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47375,7 +49287,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47414,17 +49326,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47443,7 +49365,7 @@ var ts; return maxParamsIndex; } function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { @@ -47477,11 +49399,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47493,16 +49415,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47515,8 +49444,8 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -47575,11 +49504,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47592,7 +49523,7 @@ var ts; return false; } var firstBase = baseTypes[0]; - if (firstBase.flags & 524288 /* Intersection */) { + if (firstBase.flags & 2097152 /* Intersection */) { var types = firstBase.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); var i = 0; @@ -47649,10 +49580,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47676,8 +49608,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47691,16 +49623,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 149 /* Parameter */: + case 151 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -47716,8 +49648,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47736,6 +49668,46 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node); + var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.type = result; + return createSignature(declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } /** * Sometimes, we have a decorator that could accept zero arguments, * but is receiving too many arguments as part of the decorator invocation. @@ -47745,52 +49717,22 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } - /** - * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. - * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName - * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) - * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. - * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function - * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); - if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); - } - return undefined; - } function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); - case 150 /* Decorator */: + case 152 /* Decorator */: return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: - // This code-path is called by language service - var exprTypes = checkExpression(node.tagName); - return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); - if (sfcResult && sfcResult !== unknownSignature) { - return sfcResult; - } - var sigs = getInstantiatedJsxSignatures(node, exprType); - if (candidatesOutArray && ts.length(sigs)) { - candidatesOutArray.push.apply(candidatesOutArray, sigs); - } - return ts.length(sigs) ? sigs[0] : unknownSignature; - }) || unknownSignature; + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -47824,34 +49766,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { - if (type.flags & 131072 /* Object */) { + function isJSConstructorType(type) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,22 +49810,19 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } var parent = node.parent; - while (parent && parent.kind === 187 /* PropertyAccessExpression */) { + while (parent && parent.kind === 189 /* PropertyAccessExpression */) { parent = parent.parent; } - if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) { var right = ts.getInitializerOfBinaryExpression(parent); return ts.isObjectLiteralExpression(right) && right; } @@ -47905,15 +49848,15 @@ var ts; if (!checkGrammarTypeArguments(node, node.typeArguments)) checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { return voidType; } - if (node.kind === 190 /* NewExpression */) { + if (node.kind === 192 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 155 /* Constructor */ && - declaration.kind !== 159 /* ConstructSignature */ && - declaration.kind !== 164 /* ConstructorType */ && + declaration.kind !== 157 /* Constructor */ && + declaration.kind !== 161 /* ConstructSignature */ && + declaration.kind !== 166 /* 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 @@ -47921,10 +49864,10 @@ var ts; // Note:JS inferred classes might come from a variable declaration instead of a function declaration. // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. var funcSymbol = checkExpression(node.expression).symbol; - if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { + if (!funcSymbol && node.expression.kind === 72 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,18 +49878,18 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property // as a fresh unique symbol literal type. - if (returnType.flags & 3072 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49915,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -47987,7 +49930,7 @@ var ts; for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 8192 /* Undefined */ || specifierType.flags & 16384 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal @@ -48031,7 +49974,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48040,9 +49983,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 237 /* FunctionDeclaration */ + ? 239 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 235 /* VariableDeclaration */ + ? 237 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -48078,10 +50021,10 @@ var ts; } function checkMetaProperty(node) { checkGrammarMetaProperty(node); - if (node.keywordToken === 94 /* NewKeyword */) { + if (node.keywordToken === 95 /* NewKeyword */) { return checkNewTargetMetaProperty(node); } - if (node.keywordToken === 91 /* ImportKeyword */) { + if (node.keywordToken === 92 /* ImportKeyword */) { return checkImportMetaProperty(node); } return ts.Debug.assertNever(node.keywordToken); @@ -48092,7 +50035,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 155 /* Constructor */) { + else if (container.kind === 157 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -48156,14 +50099,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +50112,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,15 +50136,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48222,6 +50143,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48274,7 +50206,7 @@ var ts; for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71 /* Identifier */) { + if (element.name.kind === 72 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } else { @@ -48288,7 +50220,7 @@ var ts; if (!links.type) { links.type = contextualType; var decl = parameter.valueDeclaration; - if (decl.name.kind !== 71 /* Identifier */) { + if (decl.name.kind !== 72 /* Identifier */) { // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType) { links.type = getTypeFromBindingPattern(decl.name); @@ -48307,6 +50239,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48328,7 +50270,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 216 /* Block */) { + if (func.body.kind !== 218 /* Block */) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any @@ -48424,10 +50366,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 199 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48442,7 +50435,7 @@ var ts; if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - if (ts.some(func.body.statements, function (statement) { return statement.kind === 230 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -48464,7 +50457,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -48477,7 +50470,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48485,11 +50478,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; - case 154 /* MethodDeclaration */: - return func.parent.kind === 186 /* ObjectLiteralExpression */; + case 156 /* MethodDeclaration */: + return func.parent.kind === 188 /* ObjectLiteralExpression */; default: return false; } @@ -48508,16 +50501,16 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 153 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 216 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 32768 /* Never */) { + if (returnType && returnType.flags & 131072 /* Never */) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -48546,7 +50539,8 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48556,14 +50550,16 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 194 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -48598,7 +50594,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48609,7 +50604,7 @@ var ts; getAwaitedType(type) || errorType : type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function @@ -48625,7 +50620,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 216 /* Block */) { + if (node.body.kind === 218 /* Block */) { checkSourceElement(node.body); } else { @@ -48648,34 +50643,66 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAssignableToKind(type, 168 /* NumberLike */)) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { error(operand, diagnostic); return false; } return true; } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } 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 + // Object.defineProperty assignments with writable false or no setter // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || - symbol.flags & 8 /* EnumMember */); + symbol.flags & 8 /* EnumMember */ || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); } 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 === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) && - expr.expression.kind === 99 /* ThisKeyword */) { + (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) && + expr.expression.kind === 100 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 155 /* Constructor */)) { + if (!(func && func.kind === 157 /* Constructor */)) { return true; } // If func.parent is a class and symbol is a (readonly) property of that class, or @@ -48688,13 +50715,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) { + if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return !!declaration && declaration.kind === 249 /* NamespaceImport */; + return !!declaration && declaration.kind === 251 /* NamespaceImport */; } } } @@ -48703,7 +50730,7 @@ var ts; function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); - if (node.kind !== 71 /* Identifier */ && node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { + if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -48712,7 +50739,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -48749,37 +50776,52 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operand.kind === 8 /* NumericLiteral */) { - if (node.operator === 38 /* MinusToken */) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - else if (node.operator === 37 /* PlusToken */) { - return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); - } + switch (node.operand.kind) { + case 8 /* NumericLiteral */: + switch (node.operator) { + case 39 /* MinusToken */: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38 /* PlusToken */: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9 /* BigIntLiteral */: + if (node.operator === 39 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } } switch (node.operator) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 3072 /* ESSymbolLike */)) { + if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } - return numberType; - case 51 /* ExclamationToken */: + if (node.operator === 38 /* PlusToken */) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52 /* ExclamationToken */: checkTruthinessExpression(node.operand); - var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); - return facts === 1048576 /* Truthy */ ? falseType : - facts === 2097152 /* Falsy */ ? trueType : + var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : + facts === 8388608 /* Falsy */ ? trueType : booleanType; - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } - return numberType; + return getUnaryResultType(operandType); } return errorType; } @@ -48788,11 +50830,20 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number return numberType; } // Return true if type might be of the given kind. A union or intersection type might be of a given @@ -48801,10 +50852,10 @@ var ts; if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { return true; } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48816,21 +50867,22 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (3 /* AnyOrUnknown */ | 4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */)) { + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { return false; } - return !!(kind & 168 /* NumberLike */) && isTypeAssignableTo(source, numberType) || - !!(kind & 68 /* StringLike */) && isTypeAssignableTo(source, stringType) || - !!(kind & 272 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || - !!(kind & 4096 /* Void */) && isTypeAssignableTo(source, voidType) || - !!(kind & 32768 /* Never */) && isTypeAssignableTo(source, neverType) || - !!(kind & 16384 /* Null */) && isTypeAssignableTo(source, nullType) || - !!(kind & 8192 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || - !!(kind & 1024 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || - !!(kind & 16777216 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { - return source.flags & 262144 /* Union */ ? + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : isTypeAssignableToKind(source, kind, strict); } @@ -48850,7 +50902,7 @@ var ts; // 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 (!isTypeAny(leftType) && - allTypesAssignableToKind(leftType, 32764 /* Primitive */)) { + allTypesAssignableToKind(leftType, 131068 /* 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 @@ -48869,10 +50921,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 168 /* NumberLike */ | 3072 /* ESSymbolLike */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + if (!isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -48882,8 +50934,8 @@ var ts; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; @@ -48891,9 +50943,9 @@ var ts; /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { if (rightIsThis === void 0) { rightIsThis = false; } - if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { + if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -48902,13 +50954,13 @@ var ts; var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 275 /* SpreadAssignment */) { + else if (property.kind === 277 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } @@ -48960,11 +51012,11 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 208 /* OmittedExpression */) { - if (element.kind !== 206 /* SpreadElement */) { + if (element.kind !== 210 /* OmittedExpression */) { + if (element.kind !== 208 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48985,13 +51037,13 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 202 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49002,14 +51054,14 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 8192 /* Undefined */)) { - sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); } @@ -49018,21 +51070,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 202 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 186 /* ObjectLiteralExpression */) { + if (target.kind === 188 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 185 /* ArrayLiteralExpression */) { + if (target.kind === 187 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 275 /* SpreadAssignment */ ? + var error = target.parent.kind === 277 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { @@ -49051,72 +51103,73 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 191 /* TaggedTemplateExpression */: - case 204 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 193 /* TaggedTemplateExpression */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 140 /* UndefinedKeyword */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: - case 195 /* ArrowFunction */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 197 /* TypeOfExpression */: - case 211 /* NonNullExpression */: - case 259 /* JsxSelfClosingElement */: - case 258 /* JsxElement */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 141 /* UndefinedKeyword */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 199 /* TypeOfExpression */: + case 213 /* NonNullExpression */: + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: return true; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { - case 51 /* ExclamationToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: + case 52 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: return true; } return false; // Some forms listed here for clarity - case 198 /* VoidExpression */: // Explicit opt-out - case 192 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 210 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 200 /* VoidExpression */: // Explicit opt-out + case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */); + if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */); } var leftType; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { leftType = checkTruthinessExpression(left, checkMode); } else { @@ -49124,28 +51177,28 @@ var ts; } var rightType = checkExpression(right, checkMode); switch (operator) { - case 39 /* AsteriskToken */: - case 40 /* AsteriskAsteriskToken */: - case 61 /* AsteriskEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 42 /* PercentToken */: - case 64 /* PercentEqualsToken */: - case 38 /* MinusToken */: - case 60 /* MinusEqualsToken */: - case 45 /* LessThanLessThanToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: + case 40 /* AsteriskToken */: + case 41 /* AsteriskAsteriskToken */: + case 62 /* AsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 43 /* PercentToken */: + case 65 /* PercentEqualsToken */: + case 39 /* MinusToken */: + case 61 /* MinusEqualsToken */: + case 46 /* LessThanLessThanToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -49154,36 +51207,61 @@ var ts; 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 & 272 /* BooleanLike */) && - (rightType.flags & 272 /* BooleanLike */) && + if ((leftType.flags & 528 /* BooleanLike */) && + (rightType.flags & 528 /* BooleanLike */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; } else { // otherwise just check each operand separately and report errors as normal - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType_1 = numberType; } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) { + switch (operator) { + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; } - return numberType; - case 37 /* PlusToken */: - case 59 /* PlusEqualsToken */: + case 38 /* PlusToken */: + case 60 /* PlusEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 68 /* StringLike */) && !isTypeAssignableToKind(rightType, 68 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeAssignableToKind(leftType, 168 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 168 /* NumberLike */, /*strict*/ true)) { + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) { // 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 (isTypeAssignableToKind(leftType, 68 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 68 /* StringLike */, /*strict*/ true)) { + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -49200,26 +51278,27 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 59 /* PlusEqualsToken */) { + if (operator === 60 /* PlusEqualsToken */) { checkAssignmentOperator(resultType); } return resultType; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: if (checkForDisallowedESSymbolOperand(operator)) { leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { reportOperatorError(); } } return booleanType; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -49230,29 +51309,38 @@ var ts; reportOperatorError(); } return booleanType; - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return checkInstanceOfExpression(left, right, leftType, rightType); - case 92 /* InKeyword */: + case 93 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); - case 53 /* AmpersandAmpersandToken */: - return getTypeFacts(leftType) & 1048576 /* Truthy */ ? + case 54 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 4194304 /* Truthy */ ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; - case 54 /* BarBarToken */: - return getTypeFacts(leftType) & 2097152 /* Falsy */ ? + case 55 /* BarBarToken */: + return getTypeFacts(leftType) & 8388608 /* Falsy */ ? getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; - case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + case 59 /* EqualsToken */: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || + declKind !== 2 /* ModuleExports */ && + declKind !== 6 /* Prototype */ && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1 /* Class */)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } return leftType; } else { checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); } - case 26 /* CommaToken */: + case 27 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -49260,15 +51348,14 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { - var rightType_1 = checkExpression(right, checkMode); - for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2 /* ModuleExports */) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49278,12 +51365,12 @@ var ts; } } function isEvalNode(node) { - return node.kind === 71 /* Identifier */ && node.escapedText === "eval"; + return node.kind === 72 /* Identifier */ && node.escapedText === "eval"; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 3072 /* ESSymbolLike */) ? left : - maybeTypeOfKind(rightType, 3072 /* ESSymbolLike */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -49293,15 +51380,15 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - return 54 /* BarBarToken */; - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - return 35 /* ExclamationEqualsEqualsToken */; - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: - return 53 /* AmpersandAmpersandToken */; + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + return 55 /* BarBarToken */; + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + return 36 /* ExclamationEqualsEqualsToken */; + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + return 54 /* AmpersandAmpersandToken */; default: return undefined; } @@ -49321,8 +51408,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +51418,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49348,11 +51435,11 @@ var ts; } function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { switch (operatorToken.kind) { - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); } return undefined; @@ -49430,14 +51517,14 @@ var ts; // A place where we actually *are* concerned with the expressions' types are // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { - if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) { error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49473,25 +51560,21 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 192 /* TypeAssertionExpression */ || node.kind === 210 /* AsExpression */; + return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */; } function checkDeclarationInitializer(declaration) { var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { - if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304 /* Nullable */) { + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49499,34 +51582,36 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 786432 /* UnionOrIntersection */) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { var types = contextualType.types; return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } - if (contextualType.flags & 14745600 /* InstantiableNonPrimitive */) { + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { // If the contextual type is a type variable constrained to a primitive type, consider // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || - maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || - maybeTypeOfKind(constraint, 1024 /* ESSymbol */) && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (64 /* StringLiteral */ | 1048576 /* Index */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || - contextualType.flags & 128 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || - contextualType.flags & 256 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 256 /* BooleanLiteral */) || - contextualType.flags & 2048 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */)); + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || + contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49534,7 +51619,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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -49545,7 +51630,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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -49573,15 +51658,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +51684,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +51701,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; - if (node.kind === 146 /* QualifiedName */) { + if (node.kind === 148 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49622,10 +51715,10 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 165 /* TypeQuery */ && node.parent.exprName === node)); + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === 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_or_type_query); } @@ -49633,102 +51726,105 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return checkIdentifier(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return checkThisExpression(node); - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return checkSuperExpression(node); - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: return nullWideningType; - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101 /* TrueKeyword */: + case 9 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102 /* TrueKeyword */: return trueType; - case 86 /* FalseKeyword */: + case 87 /* FalseKeyword */: return falseType; - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return checkTemplateExpression(node); - case 12 /* RegularExpressionLiteral */: + case 13 /* RegularExpressionLiteral */: return globalRegExpType; - case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); - case 186 /* ObjectLiteralExpression */: + case 187 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 189 /* CallExpression */: - if (node.expression.kind === 91 /* ImportKeyword */) { + case 191 /* CallExpression */: + if (node.expression.kind === 92 /* ImportKeyword */) { return checkImportCallExpression(node); } /* falls through */ - case 190 /* NewExpression */: + case 192 /* NewExpression */: return checkCallExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return checkClassExpression(node); - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return checkAssertion(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return checkNonNullAssertion(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return checkMetaProperty(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return checkDeleteExpression(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return checkVoidExpression(node); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return checkAwaitExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 208 /* OmittedExpression */: + case 210 /* OmittedExpression */: return undefinedWideningType; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return checkYieldExpression(node); - case 213 /* SyntheticExpression */: + case 215 /* SyntheticExpression */: return node.type; - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return checkJsxElement(node, checkMode); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 262 /* JsxFragment */: - return checkJsxFragment(node, checkMode); - case 266 /* JsxAttributes */: + case 264 /* JsxFragment */: + return checkJsxFragment(node); + case 268 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -49757,9 +51853,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49769,7 +51862,7 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 155 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -49780,16 +51873,16 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { + if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 195 /* ArrowFunction */) { + if (func.kind === 197 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -49838,13 +51931,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 195 /* ArrowFunction */: - case 158 /* CallSignature */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 163 /* FunctionType */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 197 /* ArrowFunction */: + case 160 /* CallSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 165 /* FunctionType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -49858,11 +51951,11 @@ var ts; continue; } var name = element.name; - if (name.kind === 71 /* Identifier */ && name.escapedText === predicateVariableName) { + if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 183 /* ArrayBindingPattern */ || name.kind === 182 /* ObjectBindingPattern */) { + else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -49871,13 +51964,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 160 /* IndexSignature */) { + if (node.kind === 162 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 163 /* FunctionType */ || node.kind === 237 /* FunctionDeclaration */ || node.kind === 164 /* ConstructorType */ || - node.kind === 158 /* CallSignature */ || node.kind === 155 /* Constructor */ || - node.kind === 159 /* ConstructSignature */) { + else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ || + node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ || + node.kind === 161 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -49907,10 +52000,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 158 /* CallSignature */: + case 160 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -49940,7 +52033,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -49957,7 +52050,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 155 /* Constructor */) { + if (member.kind === 157 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -49972,16 +52065,16 @@ var ts; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (name && memberName) { switch (member.kind) { - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: addName(names, name, memberName, 1 /* Getter */); break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: addName(names, name, memberName, 2 /* Setter */); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: addName(names, name, memberName, 3 /* Property */); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: addName(names, name, memberName, 4 /* Method */); break; } @@ -50044,15 +52137,15 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151 /* PropertySignature */) { + if (member.kind === 153 /* PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: memberName = name.text; break; - case 71 /* Identifier */: + case 72 /* Identifier */: memberName = ts.idText(name); break; default: @@ -50069,7 +52162,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 239 /* InterfaceDeclaration */) { + if (node.kind === 241 /* 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 @@ -50089,7 +52182,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -50097,7 +52190,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -50124,7 +52217,7 @@ var ts; checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 154 /* MethodDeclaration */ && node.body) { + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -50149,7 +52242,7 @@ var ts; return; } function isInstancePropertyWithInitializer(n) { - return n.kind === 152 /* PropertyDeclaration */ && + return n.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } @@ -50179,7 +52272,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -50204,7 +52297,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -50214,13 +52307,13 @@ 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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(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 === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); @@ -50238,7 +52331,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -50255,7 +52348,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +52379,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50334,7 +52427,7 @@ var ts; var seenOptionalElement = false; for (var i = 0; i < elementTypes.length; i++) { var e = elementTypes[i]; - if (e.kind === 170 /* RestType */) { + if (e.kind === 172 /* RestType */) { if (i !== elementTypes.length - 1) { grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); break; @@ -50343,7 +52436,7 @@ var ts; error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); } } - else if (e.kind === 169 /* OptionalType */) { + else if (e.kind === 171 /* OptionalType */) { seenOptionalElement = true; } else if (seenOptionalElement) { @@ -50358,14 +52451,14 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 2097152 /* IndexedAccess */)) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { return type; } // Check if the index type is assignable to 'keyof T' for the object type. var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 188 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -50373,7 +52466,7 @@ var ts; } // Check if we're indexing with a numeric type and if either object or index types // is a generic type with a constraint that has a numeric index signature. - if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -50387,8 +52480,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50405,7 +52498,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 173 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -50422,9 +52515,9 @@ var ts; var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 239 /* InterfaceDeclaration */ && - n.parent.kind !== 238 /* ClassDeclaration */ && - n.parent.kind !== 207 /* ClassExpression */ && + if (n.parent.kind !== 241 /* InterfaceDeclaration */ && + n.parent.kind !== 240 /* ClassDeclaration */ && + n.parent.kind !== 209 /* ClassExpression */ && n.flags & 4194304 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -50515,7 +52608,7 @@ var ts; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */) && + var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) && ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -50554,7 +52647,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = node.flags & 4194304 /* Ambient */; - var inAmbientContextOrInterface = node.parent.kind === 239 /* InterfaceDeclaration */ || node.parent.kind === 166 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -50565,7 +52658,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 === 237 /* FunctionDeclaration */ || node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */ || node.kind === 155 /* Constructor */) { + if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -50617,8 +52710,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var signature = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -50627,6 +52720,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,32 +52784,25 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return 2 /* ExportType */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values if (!ts.isEntityNameExpression(d.expression)) { return 1 /* ExportValue */; @@ -50717,17 +52810,17 @@ var ts; d = d.expression; /* falls through */ // The below options all declare an Alias, which is allowed to merge with other values within the importing module - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 248 /* ImportClause */: - var result_3 = 0 /* None */; + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 237 /* FunctionDeclaration */: - case 251 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 239 /* FunctionDeclaration */: + case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); @@ -50774,7 +52867,7 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -50805,7 +52898,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -50953,10 +53046,10 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { - if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { @@ -50976,7 +53069,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -50995,24 +53088,24 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 149 /* Parameter */: + case 151 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -51033,7 +53126,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51058,50 +53151,55 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 172 /* IntersectionType */: - case 171 /* UnionType */: - var commonEntityName = void 0; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175 /* ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 131 /* NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); - if (!individualEntityName) { - // Individual is something like string number - // So it would be serialized to either that type or object - // Safe to return here - return undefined; - } - if (commonEntityName) { - // Note this is in sync with the transformation that happens for type node. - // Keep this in sync with serializeUnionOrIntersectionType - // Verify if they refer to same entity and is identifier - // return undefined if they dont match because we would emit object - if (!ts.isIdentifier(commonEntityName) || - !ts.isIdentifier(individualEntityName) || - commonEntityName.escapedText !== individualEntityName.escapedText) { - return undefined; - } - } - else { - commonEntityName = individualEntityName; - } - } - return commonEntityName; - case 175 /* ParenthesizedType */: + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; } } } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } function getParameterTypeNodeForDecoratorCheck(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; @@ -51121,14 +53219,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 149 /* Parameter */) { + if (node.kind === 151 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -51137,23 +53235,23 @@ var ts; } } break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 149 /* Parameter */: + case 151 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -51206,16 +53304,22 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); } } } } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } function checkJSDocAugmentsTag(node) { var classLike = ts.getJSDocHost(node); if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { @@ -51238,9 +53342,9 @@ var ts; } function getIdentifierFromEntityNameExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return node.name; default: return undefined; @@ -51253,7 +53357,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 && node.name.kind === 147 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -51282,7 +53386,7 @@ var ts; } } } - var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); @@ -51291,8 +53395,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51302,7 +53406,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51311,7 +53415,7 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. - if (produceDiagnostics) { + if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) { var sourceFile = ts.getSourceFileOfNode(node); var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); if (!potentiallyUnusedIdentifiers) { @@ -51327,44 +53431,44 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 239 /* InterfaceDeclaration */: - checkUnusedTypeParameters(node, addDiagnostic); - break; - case 277 /* SourceFile */: - case 242 /* ModuleDeclaration */: - case 216 /* Block */: - case 244 /* CaseBlock */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 279 /* SourceFile */: + case 244 /* ModuleDeclaration */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - if (node.body) { + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 240 /* TypeAliasDeclaration */: - case 174 /* InferType */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; + case 176 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; default: ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); } @@ -51379,77 +53483,73 @@ var ts; return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 154 /* MethodDeclaration */: - case 152 /* PropertyDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - if (member.kind === 157 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { - // Already would have reported an error on the getter. - break; - } - var symbol = getSymbolOfNode(member); - if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. break; - case 155 /* Constructor */: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } - break; - case 160 /* IndexSignature */: - case 215 /* SemicolonClassElement */: - // Can't be private - break; - default: - ts.Debug.fail(); - } + } + break; + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) + if (ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174 /* InferType */) { - var typeParameter = node.typeParameter; - if (isTypeParameterUnused(typeParameter)) { - addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } } - } - else { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - var seenParentsWithEveryUnused = new ts.NodeSet(); - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var typeParameter = typeParameters_2[_i]; - if (!isTypeParameterUnused(typeParameter)) - continue; - var name = ts.idText(typeParameter.name); - var parent = typeParameter.parent; - if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { - if (seenParentsWithEveryUnused.tryAdd(parent)) { - var range = ts.isJSDocTemplateTag(parent) - // Whole @template tag - ? ts.rangeOfNode(parent) - // Include the `<>` in the error message - : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; - var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; - var arg0 = only ? name : undefined; - addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); - } - } - else { - addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); - } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } @@ -51520,7 +53620,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 @@ -51538,7 +53638,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 235 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 236 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -51559,7 +53659,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -51571,24 +53671,24 @@ var ts; } function bindingNameText(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.idText(name); - case 183 /* ArrayBindingPattern */: - case 182 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 248 /* ImportClause */ || node.kind === 251 /* ImportSpecifier */ || node.kind === 249 /* NamespaceImport */; + return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 248 /* ImportClause */ ? decl : decl.kind === 249 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 216 /* Block */) { + if (node.kind === 218 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -51618,12 +53718,12 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 151 /* PropertySignature */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 153 /* MethodSignature */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { + if (node.kind === 154 /* PropertyDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 156 /* MethodDeclaration */ || + node.kind === 155 /* MethodSignature */ || + node.kind === 158 /* GetAccessor */ || + node.kind === 159 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -51632,7 +53732,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 149 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -51642,7 +53742,7 @@ var ts; function checkIfThisIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { - var isDeclaration_1 = node.kind !== 71 /* Identifier */; + var isDeclaration_1 = node.kind !== 72 /* Identifier */; if (isDeclaration_1) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -51657,7 +53757,7 @@ var ts; function checkIfNewTargetIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { - var isDeclaration_2 = node.kind !== 71 /* Identifier */; + var isDeclaration_2 = node.kind !== 72 /* Identifier */; if (isDeclaration_2) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } @@ -51683,7 +53783,7 @@ var ts; } // 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 === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 279 /* 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)); } @@ -51698,7 +53798,7 @@ var ts; } // 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 === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -51733,7 +53833,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 235 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -51745,17 +53845,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 236 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 217 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 219 /* 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 === 216 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 243 /* ModuleBlock */ || - container.kind === 242 /* ModuleDeclaration */ || - container.kind === 277 /* SourceFile */); + (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 245 /* ModuleBlock */ || + container.kind === 244 /* ModuleDeclaration */ || + container.kind === 279 /* 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 @@ -51770,7 +53870,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 !== 149 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -51781,14 +53881,14 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 187 /* PropertyAccessExpression */) { + if (n.kind === 189 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } - else if (n.kind === 71 /* Identifier */) { + else if (n.kind === 72 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51800,8 +53900,8 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 149 /* Parameter */ || - symbol.valueDeclaration.kind === 184 /* BindingElement */) { + if (symbol.valueDeclaration.kind === 151 /* Parameter */ || + symbol.valueDeclaration.kind === 186 /* BindingElement */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -51815,7 +53915,7 @@ var ts; return ts.isFunctionLike(current.parent) || // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - (current.parent.kind === 152 /* PropertyDeclaration */ && + (current.parent.kind === 154 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)); })) { @@ -51848,18 +53948,18 @@ 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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 184 /* BindingElement */) { - if (node.parent.kind === 182 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + if (node.kind === 186 /* BindingElement */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 147 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -51870,29 +53970,29 @@ var ts; var nameText = ts.getTextOfPropertyName(name); if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { - checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property); } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 183 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 149 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) { var initializerType = checkExpressionCached(node.initializer); if (strictNullChecks && node.name.elements.length === 0) { checkNonNullType(initializerType, node); @@ -51911,15 +54011,20 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); checkParameterInitializer(node); } } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } } else { // Node is a secondary declaration, check that type is identical to primary declaration and check that @@ -51927,21 +54032,20 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */) { + if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -51950,14 +54054,14 @@ var ts; } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 152 /* PropertyDeclaration */ || nextDeclaration.kind === 151 /* PropertySignature */ + var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 149 /* Parameter */ && right.kind === 235 /* VariableDeclaration */) || - (left.kind === 235 /* VariableDeclaration */ && right.kind === 149 /* Parameter */)) { + if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) || + (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -51996,7 +54100,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 218 /* EmptyStatement */) { + if (node.thenStatement.kind === 220 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -52015,7 +54119,7 @@ var ts; } function checkTruthinessExpression(node, checkMode) { var type = checkExpression(node, checkMode); - if (type.flags & 4096 /* Void */) { + if (type.flags & 16384 /* Void */) { error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); } return type; @@ -52023,12 +54127,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -52062,14 +54166,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 === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side - if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* 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. @@ -52095,13 +54199,13 @@ var ts; function checkForInStatement(node) { // Grammar checking checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* 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); @@ -52115,7 +54219,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 === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -52128,7 +54232,7 @@ var ts; } // 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 (rightType === neverType || !isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -52183,16 +54287,16 @@ var ts; // This allows us to find other non-string element types from an array unioned with // a string. if (allowStringInput) { - if (arrayType.flags & 262144 /* Union */) { + if (arrayType.flags & 1048576 /* Union */) { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the result of filter is a new array. var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 68 /* StringLike */); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } } - else if (arrayType.flags & 68 /* StringLike */) { + else if (arrayType.flags & 132 /* StringLike */) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -52205,7 +54309,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType.flags & 32768 /* Never */) { + if (arrayType.flags & 131072 /* Never */) { return stringType; } } @@ -52236,7 +54340,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); if (hasStringConstituent && arrayElementType) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 68 /* StringLike */) { + if (arrayElementType.flags & 132 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], 2 /* Subtype */); @@ -52301,13 +54405,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52334,9 +54442,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52444,7 +54554,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 4096 /* Void */ | 3 /* AnyOrUnknown */); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { // Grammar checking @@ -52460,7 +54570,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); var functionFlags = ts.getFunctionFlags(func); var isGenerator = functionFlags & 1 /* Generator */; - if (strictNullChecks || node.expression || returnType.flags & 32768 /* Never */) { + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (isGenerator) { // AsyncGenerator function or Generator function // A generator does not need its return expressions checked against its return type. @@ -52469,12 +54579,12 @@ var ts; // for generators. return; } - else if (func.kind === 157 /* SetAccessor */) { + else if (func.kind === 159 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 155 /* Constructor */) { + else if (func.kind === 157 /* Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -52495,7 +54605,7 @@ var ts; } } } - else if (func.kind !== 155 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -52524,7 +54634,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 270 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -52536,7 +54646,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 269 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 271 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -52565,7 +54675,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 231 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -52672,8 +54782,8 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 202 /* BinaryExpression */ || - name.kind === 147 /* ComputedPropertyName */ || + (propDeclaration.kind === 204 /* BinaryExpression */ || + name.kind === 149 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -52702,6 +54812,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -52877,18 +54988,21 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 2162688 /* TypeVariable */)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52916,7 +55030,7 @@ var ts; } } else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -52931,7 +55045,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52950,7 +55064,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -52976,7 +55090,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 238 /* ClassDeclaration */ || d.kind === 239 /* InterfaceDeclaration */; + return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -53015,7 +55129,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 || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { - if (derivedClassDecl.kind === 207 /* ClassExpression */) { + if (derivedClassDecl.kind === 209 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -53065,8 +55179,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -53097,7 +55211,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 8192 /* Undefined */)) { + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -53107,16 +55221,18 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 152 /* PropertyDeclaration */ && + return node.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 8192 /* Undefined */); + return !(getFalsyFlags(flowType) & 32768 /* Undefined */); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -53129,7 +55245,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -53234,60 +55350,60 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { - case 37 /* PlusToken */: return value_2; - case 38 /* MinusToken */: return -value_2; - case 52 /* TildeToken */: return ~value_2; + case 38 /* PlusToken */: return value_2; + case 39 /* MinusToken */: return -value_2; + case 53 /* TildeToken */: return ~value_2; } } break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { switch (expr.operatorToken.kind) { - case 49 /* BarToken */: return left | right; - case 48 /* AmpersandToken */: return left & right; - case 46 /* GreaterThanGreaterThanToken */: return left >> right; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; - case 45 /* LessThanLessThanToken */: return left << right; - case 50 /* CaretToken */: return left ^ right; - case 39 /* AsteriskToken */: return left * right; - case 41 /* SlashToken */: return left / right; - case 37 /* PlusToken */: return left + right; - case 38 /* MinusToken */: return left - right; - case 42 /* PercentToken */: return left % right; - case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right); + case 50 /* BarToken */: return left | right; + case 49 /* AmpersandToken */: return left & right; + case 47 /* GreaterThanGreaterThanToken */: return left >> right; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 46 /* LessThanLessThanToken */: return left << right; + case 51 /* CaretToken */: return left ^ right; + case 40 /* AsteriskToken */: return left * right; + case 42 /* SlashToken */: return left / right; + case 38 /* PlusToken */: return left + right; + case 39 /* MinusToken */: return left - right; + case 43 /* PercentToken */: return left % right; + case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right); } } - else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 37 /* PlusToken */) { + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) { return left + right; } break; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return expr.text; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return evaluate(expr.expression); - case 71 /* Identifier */: + case 72 /* Identifier */: var identifier = expr; if (isInfinityOrNaNString(identifier.escapedText)) { return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 188 /* ElementAccessExpression */: - case 187 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 187 /* PropertyAccessExpression */) { + if (ex.kind === 189 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -53318,10 +55434,10 @@ var ts; } } function isConstantMemberAccess(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 187 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 188 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && - node.argumentExpression.kind === 9 /* StringLiteral */; + return node.kind === 72 /* Identifier */ || + node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10 /* StringLiteral */; } function checkEnumDeclaration(node) { if (!produceDiagnostics) { @@ -53358,7 +55474,7 @@ var ts; 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 !== 241 /* EnumDeclaration */) { + if (declaration.kind !== 243 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -53381,8 +55497,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { var declaration = declarations_8[_i]; - if ((declaration.kind === 238 /* ClassDeclaration */ || - (declaration.kind === 237 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 240 /* ClassDeclaration */ || + (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304 /* Ambient */)) { return declaration; } @@ -53419,7 +55535,7 @@ var ts; return; } if (!checkGrammarDecoratorsAndModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { + if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } @@ -53445,7 +55561,7 @@ 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, 238 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -53495,23 +55611,23 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* 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 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 184 /* BindingElement */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -53522,12 +55638,12 @@ var ts; break; } // falls through - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 237 /* FunctionDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -53540,7 +55656,7 @@ var ts; var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { // symbol should not originate in augmentation - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -53548,17 +55664,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: do { node = node.left; - } while (node.kind !== 71 /* Identifier */); + } while (node.kind !== 72 /* Identifier */); return node; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: do { node = node.expression; - } while (node.kind !== 71 /* Identifier */); + } while (node.kind !== 72 /* Identifier */); return node; } } @@ -53572,9 +55688,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 253 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -53603,19 +55719,19 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 255 /* ExportSpecifier */ ? + var message = node.kind === 257 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && node.kind === 257 /* ExportSpecifier */ + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53641,7 +55757,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -53665,17 +55781,17 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53701,10 +55817,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 243 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; - if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -53721,7 +55837,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 277 /* SourceFile */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 242 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -53729,13 +55845,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53750,8 +55866,8 @@ 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 === 277 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -53764,9 +55880,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 71 /* Identifier */) { + if (node.expression.kind === 72 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +55914,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53839,14 +55955,14 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 237 /* FunctionDeclaration */ && declaration.kind !== 154 /* MethodDeclaration */) || + return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -53857,163 +55973,163 @@ var ts; // 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 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return checkTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return checkParameter(node); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return checkPropertyDeclaration(node); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return checkSignatureDeclaration(node); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return checkMethodDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return checkConstructorDeclaration(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return checkAccessorDeclaration(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return checkTypeReferenceNode(node); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return checkTypePredicate(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return checkTypeQuery(node); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return checkTypeLiteral(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return checkArrayType(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return checkTupleType(node); - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 175 /* ParenthesizedType */: - case 169 /* OptionalType */: - case 170 /* RestType */: + case 177 /* ParenthesizedType */: + case 171 /* OptionalType */: + case 172 /* RestType */: return checkSourceElement(node.type); - case 176 /* ThisType */: + case 178 /* ThisType */: return checkThisType(node); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return checkTypeOperator(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return checkConditionalType(node); - case 174 /* InferType */: + case 176 /* InferType */: return checkInferType(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return checkImportType(node); - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 297 /* JSDocParameterTag */: + case 299 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 287 /* JSDocFunctionType */: - checkSignatureDeclaration(node); + case 289 /* JSDocFunctionType */: + checkJSDocFunctionType(node); // falls through - case 285 /* JSDocNonNullableType */: - case 284 /* JSDocNullableType */: - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: - case 290 /* JSDocTypeLiteral */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + case 292 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 281 /* JSDocTypeExpression */: + case 283 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return checkMappedType(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return checkBlock(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return checkVariableStatement(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return checkExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return checkIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return checkDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return checkWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return checkForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return checkForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return checkForOfStatement(node); - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return checkReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return checkWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return checkSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return checkLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return checkThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return checkTryStatement(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return checkBindingElement(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return checkClassDeclaration(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return checkImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return checkExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return checkExportAssignment(node); - case 218 /* EmptyStatement */: - case 234 /* DebuggerStatement */: + case 220 /* EmptyStatement */: + case 236 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return checkMissingDeclaration(node); } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54084,31 +56200,38 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: checkClassExpressionDeferred(node); break; - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 258 /* JsxElement */: + case 260 /* JsxElement */: checkJsxElementDeferred(node); break; } @@ -54144,9 +56267,9 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54157,7 +56280,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54239,13 +56361,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 242 /* ModuleDeclaration */: + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + // falls through + case 244 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -54253,17 +56379,17 @@ var ts; // falls through // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* 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 (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -54305,17 +56431,17 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 71 /* Identifier */ && + return name.kind === 72 /* Identifier */ && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 148 /* TypeParameter */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: + case 150 /* TypeParameter */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: return true; default: return false; @@ -54323,16 +56449,16 @@ var ts; } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 146 /* QualifiedName */) { + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 162 /* TypeReference */; + return node.parent.kind === 164 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 187 /* PropertyAccessExpression */) { + while (node.parent.kind === 189 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 209 /* ExpressionWithTypeArguments */; + return node.parent.kind === 211 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -54345,12 +56471,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54360,13 +56486,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 146 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 246 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 252 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -54375,7 +56501,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54392,7 +56518,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 181 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -54401,8 +56527,8 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 187 /* PropertyAccessExpression */ && + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -54410,17 +56536,17 @@ var ts; return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } } else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 246 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } @@ -54438,11 +56564,11 @@ 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 === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) { + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54454,11 +56580,11 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 297 /* JSDocParameterTag */) { + if (entityName.parent.kind === 299 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54467,19 +56593,19 @@ var ts; // Missing entity name. return undefined; } - if (entityName.kind === 71 /* Identifier */) { + if (entityName.kind === 72 /* Identifier */) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { + else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 187 /* PropertyAccessExpression */) { + if (entityName.kind === 189 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -54489,20 +56615,17 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 265 /* JsxAttribute */) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 161 /* TypePredicate */) { + if (entityName.parent.kind === 163 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -54513,17 +56636,20 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(parent); + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(parent.parent); } - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (parent.kind === 184 /* BindingElement */ && - grandParent.kind === 182 /* ObjectBindingPattern */ && + else if (parent.kind === 186 /* BindingElement */ && + grandParent.kind === 184 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -54533,11 +56659,11 @@ var ts; } } switch (node.kind) { - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -54549,29 +56675,32 @@ var ts; return checkExpression(node).symbol; } // falls through - case 176 /* ThisType */: + case 178 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return checkExpression(node).symbol; - case 123 /* ConstructorKeyword */: + case 124 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 155 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } // falls through case 8 /* NumericLiteral */: // index access @@ -54581,19 +56710,22 @@ var ts; ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); - case 79 /* DefaultKeyword */: - case 89 /* FunctionKeyword */: - case 36 /* EqualsGreaterThanToken */: + case 80 /* DefaultKeyword */: + case 90 /* FunctionKeyword */: + case 37 /* EqualsGreaterThanToken */: + case 76 /* ClassKeyword */: return getSymbolOfNode(node.parent); - case 181 /* ImportType */: + case 183 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85 /* ExportKeyword */: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + if (location && location.kind === 276 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,30 +56733,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54665,28 +56792,28 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 186 /* ObjectLiteralExpression */ || expr.kind === 185 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 225 /* ForOfStatement */) { + if (expr.parent.kind === 227 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 202 /* BinaryExpression */) { + if (expr.parent.kind === 204 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 273 /* PropertyAssignment */) { + if (expr.parent.kind === 275 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 185 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; @@ -54719,13 +56846,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return getLiteralType(name.text); + case 149 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54765,7 +56911,7 @@ var ts; if (!ts.isGeneratedIdentifier(nodeIn)) { var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -54786,13 +56932,13 @@ var ts; // 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 & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54821,7 +56967,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 277 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -54841,7 +56987,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,11 +57000,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54874,9 +57020,9 @@ var ts; // * 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 isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -54917,18 +57063,18 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return node.expression - && node.expression.kind === 71 /* Identifier */ + && node.expression.kind === 72 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -54936,7 +57082,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 277 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -54950,7 +57096,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +57109,8 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && + target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +57155,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55017,15 +57183,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 276 /* EnumMember */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 278 /* EnumMember */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 276 /* EnumMember */) { + if (node.kind === 278 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -55039,7 +57205,7 @@ var ts; return undefined; } function isFunctionType(type) { - return !!(type.flags & 131072 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeNameIn, location) { // ensure both `typeName` and `location` are parse tree nodes. @@ -55052,9 +57218,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55076,22 +57242,25 @@ var ts; else if (type.flags & 3 /* AnyOrUnknown */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 4096 /* Void */ | 24576 /* Nullable */ | 32768 /* Never */)) { + else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeAssignableToKind(type, 272 /* BooleanLike */)) { + else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeAssignableToKind(type, 168 /* NumberLike */)) { + else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 68 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 3072 /* ESSymbolLike */)) { + else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -55107,14 +57276,14 @@ var ts; function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; - if (type.flags & 2048 /* UniqueESSymbol */ && + if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } @@ -55126,7 +57295,7 @@ var ts; function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); @@ -55134,7 +57303,7 @@ var ts; function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } var type = getWidenedType(getRegularTypeOfExpression(expr)); return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); @@ -55156,7 +57325,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +57340,19 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } - function createLiteralConstValue(node) { + function createLiteralConstValue(node, tracker) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node, tracker); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +57395,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55253,12 +57425,12 @@ var ts; getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 157 /* SetAccessor */ ? 156 /* GetAccessor */ : 157 /* SetAccessor */; + var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 157 /* SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 156 /* GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -55266,10 +57438,15 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { - return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; + return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -55280,9 +57457,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55332,7 +57509,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 277 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -55347,12 +57524,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 242 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 277 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -55371,6 +57548,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55415,6 +57595,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55442,31 +57624,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55478,7 +57659,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55526,14 +57707,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 154 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 156 /* 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 === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */) { + else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* 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); @@ -55550,23 +57731,23 @@ var ts; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 132 /* ReadonlyKeyword */) { - if (node.kind === 151 /* PropertySignature */ || node.kind === 153 /* MethodSignature */) { + if (modifier.kind !== 133 /* ReadonlyKeyword */) { + if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 160 /* IndexSignature */) { + if (node.kind === 162 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 76 /* ConstKeyword */: - if (node.kind !== 241 /* EnumDeclaration */) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); + case 77 /* ConstKeyword */: + if (node.kind !== 243 /* EnumDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */)); } break; - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: + case 115 /* PublicKeyword */: + case 114 /* ProtectedKeyword */: + case 113 /* PrivateKeyword */: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); @@ -55580,11 +57761,11 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { - if (modifier.kind === 112 /* PrivateKeyword */) { + if (modifier.kind === 113 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -55593,7 +57774,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -55603,10 +57784,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -55615,18 +57796,18 @@ var ts; flags |= 32 /* Static */; lastStatic = modifier; break; - case 132 /* ReadonlyKeyword */: + case 133 /* ReadonlyKeyword */: if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */ && node.kind !== 160 /* IndexSignature */ && node.kind !== 149 /* Parameter */) { + else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; lastReadonly = modifier; break; - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: if (flags & 1 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -55639,52 +57820,52 @@ 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 === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; - case 79 /* DefaultKeyword */: - var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + case 80 /* DefaultKeyword */: + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; break; - case 124 /* DeclareKeyword */: + case 125 /* DeclareKeyword */: if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 243 /* ModuleBlock */) { + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; lastDeclare = modifier; break; - case 117 /* AbstractKeyword */: + case 118 /* AbstractKeyword */: if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 238 /* ClassDeclaration */) { - if (node.kind !== 154 /* MethodDeclaration */ && - node.kind !== 152 /* PropertyDeclaration */ && - node.kind !== 156 /* GetAccessor */ && - node.kind !== 157 /* SetAccessor */) { + if (node.kind !== 240 /* ClassDeclaration */) { + if (node.kind !== 156 /* MethodDeclaration */ && + node.kind !== 154 /* PropertyDeclaration */ && + node.kind !== 158 /* GetAccessor */ && + node.kind !== 159 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 238 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -55696,14 +57877,14 @@ var ts; } flags |= 128 /* Abstract */; break; - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -55711,7 +57892,7 @@ var ts; break; } } - if (node.kind === 155 /* Constructor */) { + if (node.kind === 157 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -55726,13 +57907,13 @@ var ts; } return false; } - else if ((node.kind === 247 /* ImportDeclaration */ || node.kind === 246 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -55753,38 +57934,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 242 /* ModuleDeclaration */: - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 149 /* Parameter */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 244 /* ModuleDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 151 /* Parameter */: return false; default: - if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return false; } switch (node.kind) { - case 237 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 238 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 239 /* InterfaceDeclaration */: - case 217 /* VariableStatement */: - case 240 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */); + case 240 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */); + case 241 /* InterfaceDeclaration */: + case 219 /* VariableStatement */: + case 242 /* TypeAliasDeclaration */: return true; - case 241 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); + case 243 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */); default: ts.Debug.fail(); return false; @@ -55796,10 +57977,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -55852,11 +58033,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -55896,12 +58098,12 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 137 /* StringKeyword */ && parameter.type.kind !== 134 /* NumberKeyword */) { + if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) { var type = getTypeFromTypeNode(parameter.type); if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); } - if (type.flags & 262144 /* Union */ && allTypesAssignableToKind(type, 64 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); @@ -55932,7 +58134,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 208 /* OmittedExpression */) { + if (arg.kind === 210 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -55962,7 +58164,7 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (heritageClause.token === 86 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -55975,7 +58177,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -55991,14 +58193,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (heritageClause.token === 86 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } // Grammar checking heritageClause inside class declaration @@ -56009,20 +58211,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 147 /* ComputedPropertyName */) { + if (node.kind !== 149 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 202 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 237 /* FunctionDeclaration */ || - node.kind === 194 /* FunctionExpression */ || - node.kind === 154 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 156 /* MethodDeclaration */); if (node.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -56034,6 +58236,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56045,15 +58250,15 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 /* SpreadAssignment */) { + if (prop.kind === 277 /* SpreadAssignment */) { continue; } var name = prop.name; - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 274 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 276 /* 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); @@ -56062,7 +58267,7 @@ var ts; if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 154 /* MethodDeclaration */) { + if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -56077,21 +58282,23 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 275 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { checkGrammarNumericLiteral(name); } // falls through - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: currentKind = 1 /* Property */; break; - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: currentKind = 2 /* GetAccessor */; break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: currentKind = 4 /* SetAccessor */; break; default: @@ -56128,7 +58335,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 267 /* JsxSpreadAttribute */) { + if (attr.kind === 269 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -56138,7 +58345,7 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 268 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -56147,12 +58354,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 225 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 236 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -56167,20 +58374,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* 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 === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* 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); @@ -56207,11 +58414,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 156 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 157 /* SetAccessor */) { + else if (kind === 159 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -56235,23 +58442,23 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } function checkGrammarTypeOperatorNode(node) { - if (node.operator === 141 /* UniqueKeyword */) { - if (node.type.kind !== 138 /* SymbolKeyword */) { - return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(138 /* SymbolKeyword */)); + if (node.operator === 142 /* UniqueKeyword */) { + if (node.type.kind !== 139 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */)); } var parent = ts.walkUpParenthesizedTypes(node.parent); switch (parent.kind) { - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: var decl = parent; - if (decl.name.kind !== 71 /* Identifier */) { + if (decl.name.kind !== 72 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); } if (!ts.isVariableDeclarationInVariableStatement(decl)) { @@ -56261,13 +58468,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: if (!ts.hasModifier(parent, 32 /* Static */) || !ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: if (!ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -56286,15 +58493,18 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 154 /* MethodDeclaration */) { - if (node.parent.kind === 186 /* ObjectLiteralExpression */) { + if (node.kind === 156 /* MethodDeclaration */) { + if (node.parent.kind === 188 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 120 /* AsyncKeyword */)) { + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56312,14 +58522,14 @@ var ts; if (node.flags & 4194304 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 154 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 156 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 239 /* InterfaceDeclaration */) { + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 166 /* TypeLiteral */) { + else if (node.parent.kind === 168 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -56330,11 +58540,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 226 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 228 /* 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); @@ -56342,8 +58552,8 @@ var ts; return false; } break; - case 230 /* SwitchStatement */: - if (node.kind === 227 /* BreakStatement */ && !node.label) { + case 232 /* SwitchStatement */: + if (node.kind === 229 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -56358,13 +58568,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 227 /* BreakStatement */ + var message = node.kind === 229 /* 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 === 227 /* BreakStatement */ + var message = node.kind === 229 /* 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); @@ -56387,30 +58597,45 @@ var ts; } } function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 /* BigIntLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 9 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { + if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56421,7 +58646,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 217 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && @@ -56438,7 +58663,7 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkESModuleMarker(name) { - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } @@ -56455,8 +58680,8 @@ var ts; return false; } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71 /* Identifier */) { - if (name.originalKeywordKind === 110 /* LetKeyword */) { + if (name.kind === 72 /* Identifier */) { + if (name.originalKeywordKind === 111 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -56483,15 +58708,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return false; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -56509,12 +58734,12 @@ var ts; function checkGrammarMetaProperty(node) { var escapedText = node.name.escapedText; switch (node.keywordToken) { - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: if (escapedText !== "target") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); } break; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: if (escapedText !== "meta") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); } @@ -56550,10 +58775,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56568,7 +58794,7 @@ var ts; return true; } } - else if (node.parent.kind === 239 /* InterfaceDeclaration */) { + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -56576,7 +58802,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 166 /* TypeLiteral */) { + else if (node.parent.kind === 168 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -56584,8 +58810,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -56605,13 +58831,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 239 /* InterfaceDeclaration */ || - node.kind === 240 /* TypeAliasDeclaration */ || - node.kind === 247 /* ImportDeclaration */ || - node.kind === 246 /* ImportEqualsDeclaration */ || - node.kind === 253 /* ExportDeclaration */ || - node.kind === 252 /* ExportAssignment */ || - node.kind === 245 /* NamespaceExportDeclaration */ || + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 242 /* TypeAliasDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 255 /* ExportDeclaration */ || + node.kind === 254 /* ExportAssignment */ || + node.kind === 247 /* NamespaceExportDeclaration */ || ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -56620,7 +58846,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 === 217 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -56647,7 +58873,7 @@ var ts; // 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 === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -56669,20 +58895,32 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 180 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 276 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */; + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */; var literal = (withMinus ? "-" : "") + "0o" + node.text; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } return false; } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6 /* ESNext */) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { @@ -56727,8 +58965,8 @@ var ts; /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); @@ -56736,14 +58974,14 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 248 /* ImportClause */: // For default import - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: // For rename import `x as y` + case 250 /* ImportClause */: // For default import + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: // For rename import `x as y` return true; - case 71 /* Identifier */: + case 72 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 251 /* ImportSpecifier */; + return decl.parent.kind === 253 /* ImportSpecifier */; default: return false; } @@ -56763,7 +59001,7 @@ var ts; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); function typeIsLiteralType(type) { - return !!(type.flags & 448 /* Literal */); + return !!(type.flags & 2944 /* Literal */); } })(ts || (ts = {})); var ts; @@ -56827,6 +59065,9 @@ var ts; if (typeof value === "number") { return createNumericLiteral(value + ""); } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } @@ -56846,14 +59087,20 @@ var ts; return node; } ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9 /* BigIntLiteral */); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; function createStringLiteral(text) { - var node = createSynthesizedNode(9 /* StringLiteral */); + var node = createSynthesizedNode(10 /* StringLiteral */); node.text = text; return node; } ts.createStringLiteral = createStringLiteral; function createRegularExpressionLiteral(text) { - var node = createSynthesizedNode(12 /* RegularExpressionLiteral */); + var node = createSynthesizedNode(13 /* RegularExpressionLiteral */); node.text = text; return node; } @@ -56864,7 +59111,7 @@ var ts; return node; } function createIdentifier(text, typeArguments) { - var node = createSynthesizedNode(71 /* Identifier */); + var node = createSynthesizedNode(72 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateFlags = 0 /* None */; @@ -56945,23 +59192,23 @@ var ts; ts.createToken = createToken; // Reserved words function createSuper() { - return createSynthesizedNode(97 /* SuperKeyword */); + return createSynthesizedNode(98 /* SuperKeyword */); } ts.createSuper = createSuper; function createThis() { - return createSynthesizedNode(99 /* ThisKeyword */); + return createSynthesizedNode(100 /* ThisKeyword */); } ts.createThis = createThis; function createNull() { - return createSynthesizedNode(95 /* NullKeyword */); + return createSynthesizedNode(96 /* NullKeyword */); } ts.createNull = createNull; function createTrue() { - return createSynthesizedNode(101 /* TrueKeyword */); + return createSynthesizedNode(102 /* TrueKeyword */); } ts.createTrue = createTrue; function createFalse() { - return createSynthesizedNode(86 /* FalseKeyword */); + return createSynthesizedNode(87 /* FalseKeyword */); } ts.createFalse = createFalse; // Modifiers @@ -56972,44 +59219,44 @@ var ts; function createModifiersFromModifierFlags(flags) { var result = []; if (flags & 1 /* Export */) { - result.push(createModifier(84 /* ExportKeyword */)); + result.push(createModifier(85 /* ExportKeyword */)); } if (flags & 2 /* Ambient */) { - result.push(createModifier(124 /* DeclareKeyword */)); + result.push(createModifier(125 /* DeclareKeyword */)); } if (flags & 512 /* Default */) { - result.push(createModifier(79 /* DefaultKeyword */)); + result.push(createModifier(80 /* DefaultKeyword */)); } if (flags & 2048 /* Const */) { - result.push(createModifier(76 /* ConstKeyword */)); + result.push(createModifier(77 /* ConstKeyword */)); } if (flags & 4 /* Public */) { - result.push(createModifier(114 /* PublicKeyword */)); + result.push(createModifier(115 /* PublicKeyword */)); } if (flags & 8 /* Private */) { - result.push(createModifier(112 /* PrivateKeyword */)); + result.push(createModifier(113 /* PrivateKeyword */)); } if (flags & 16 /* Protected */) { - result.push(createModifier(113 /* ProtectedKeyword */)); + result.push(createModifier(114 /* ProtectedKeyword */)); } if (flags & 128 /* Abstract */) { - result.push(createModifier(117 /* AbstractKeyword */)); + result.push(createModifier(118 /* AbstractKeyword */)); } if (flags & 32 /* Static */) { - result.push(createModifier(115 /* StaticKeyword */)); + result.push(createModifier(116 /* StaticKeyword */)); } if (flags & 64 /* Readonly */) { - result.push(createModifier(132 /* ReadonlyKeyword */)); + result.push(createModifier(133 /* ReadonlyKeyword */)); } if (flags & 256 /* Async */) { - result.push(createModifier(120 /* AsyncKeyword */)); + result.push(createModifier(121 /* AsyncKeyword */)); } return result; } ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; // Names function createQualifiedName(left, right) { - var node = createSynthesizedNode(146 /* QualifiedName */); + var node = createSynthesizedNode(148 /* QualifiedName */); node.left = left; node.right = asName(right); return node; @@ -57028,7 +59275,7 @@ var ts; : expression; } function createComputedPropertyName(expression) { - var node = createSynthesizedNode(147 /* ComputedPropertyName */); + var node = createSynthesizedNode(149 /* ComputedPropertyName */); node.expression = parenthesizeForComputedName(expression); return node; } @@ -57041,7 +59288,7 @@ var ts; ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(148 /* TypeParameter */); + var node = createSynthesizedNode(150 /* TypeParameter */); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -57057,7 +59304,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149 /* Parameter */); + var node = createSynthesizedNode(151 /* Parameter */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -57081,7 +59328,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(150 /* Decorator */); + var node = createSynthesizedNode(152 /* Decorator */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -57094,7 +59341,7 @@ var ts; ts.updateDecorator = updateDecorator; // Type Elements function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(151 /* PropertySignature */); + var node = createSynthesizedNode(153 /* PropertySignature */); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -57114,12 +59361,12 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createSynthesizedNode(152 /* PropertyDeclaration */); + var node = createSynthesizedNode(154 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); - node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined; - node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined; + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined; node.type = type; node.initializer = initializer; return node; @@ -57129,8 +59376,8 @@ var ts; return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name - || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined) - || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined) + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) @@ -57138,7 +59385,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(153 /* MethodSignature */, typeParameters, parameters, type); + var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -57155,7 +59402,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(154 /* MethodDeclaration */); + var node = createSynthesizedNode(156 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -57183,7 +59430,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(155 /* Constructor */); + var node = createSynthesizedNode(157 /* Constructor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -57203,7 +59450,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(156 /* GetAccessor */); + var node = createSynthesizedNode(158 /* GetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57226,7 +59473,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(157 /* SetAccessor */); + var node = createSynthesizedNode(159 /* SetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57247,7 +59494,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(158 /* CallSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -57255,7 +59502,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(159 /* ConstructSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -57263,7 +59510,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(160 /* IndexSignature */); + var node = createSynthesizedNode(162 /* IndexSignature */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -57303,7 +59550,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(161 /* TypePredicate */); + var node = createSynthesizedNode(163 /* TypePredicate */); node.parameterName = asName(parameterName); node.type = type; return node; @@ -57317,7 +59564,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(162 /* TypeReference */); + var node = createSynthesizedNode(164 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -57331,7 +59578,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(163 /* FunctionType */, typeParameters, parameters, type); + return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -57339,7 +59586,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(164 /* ConstructorType */, typeParameters, parameters, type); + return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -57347,7 +59594,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(165 /* TypeQuery */); + var node = createSynthesizedNode(167 /* TypeQuery */); node.exprName = exprName; return node; } @@ -57359,7 +59606,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(166 /* TypeLiteral */); + var node = createSynthesizedNode(168 /* TypeLiteral */); node.members = createNodeArray(members); return node; } @@ -57371,7 +59618,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(167 /* ArrayType */); + var node = createSynthesizedNode(169 /* ArrayType */); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -57383,7 +59630,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(168 /* TupleType */); + var node = createSynthesizedNode(170 /* TupleType */); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -57395,7 +59642,7 @@ var ts; } ts.updateTupleTypeNode = updateTupleTypeNode; function createOptionalTypeNode(type) { - var node = createSynthesizedNode(169 /* OptionalType */); + var node = createSynthesizedNode(171 /* OptionalType */); node.type = ts.parenthesizeArrayTypeMember(type); return node; } @@ -57407,7 +59654,7 @@ var ts; } ts.updateOptionalTypeNode = updateOptionalTypeNode; function createRestTypeNode(type) { - var node = createSynthesizedNode(170 /* RestType */); + var node = createSynthesizedNode(172 /* RestType */); node.type = type; return node; } @@ -57419,7 +59666,7 @@ var ts; } ts.updateRestTypeNode = updateRestTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(171 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(173 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -57427,7 +59674,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(172 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -57446,7 +59693,7 @@ var ts; : node; } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createSynthesizedNode(173 /* ConditionalType */); + var node = createSynthesizedNode(175 /* ConditionalType */); node.checkType = ts.parenthesizeConditionalTypeMember(checkType); node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); node.trueType = trueType; @@ -57464,7 +59711,7 @@ var ts; } ts.updateConditionalTypeNode = updateConditionalTypeNode; function createInferTypeNode(typeParameter) { - var node = createSynthesizedNode(174 /* InferType */); + var node = createSynthesizedNode(176 /* InferType */); node.typeParameter = typeParameter; return node; } @@ -57476,7 +59723,7 @@ var ts; } ts.updateInferTypeNode = updateInferTypeNode; function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { - var node = createSynthesizedNode(181 /* ImportType */); + var node = createSynthesizedNode(183 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = asNodeArray(typeArguments); @@ -57494,7 +59741,7 @@ var ts; } ts.updateImportTypeNode = updateImportTypeNode; function createParenthesizedType(type) { - var node = createSynthesizedNode(175 /* ParenthesizedType */); + var node = createSynthesizedNode(177 /* ParenthesizedType */); node.type = type; return node; } @@ -57506,12 +59753,12 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(176 /* ThisType */); + return createSynthesizedNode(178 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; function createTypeOperatorNode(operatorOrType, type) { - var node = createSynthesizedNode(177 /* TypeOperator */); - node.operator = typeof operatorOrType === "number" ? operatorOrType : 128 /* KeyOfKeyword */; + var node = createSynthesizedNode(179 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */; node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } @@ -57521,7 +59768,7 @@ var ts; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(178 /* IndexedAccessType */); + var node = createSynthesizedNode(180 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -57535,7 +59782,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(179 /* MappedType */); + var node = createSynthesizedNode(181 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -57553,7 +59800,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(180 /* LiteralType */); + var node = createSynthesizedNode(182 /* LiteralType */); node.literal = literal; return node; } @@ -57566,7 +59813,7 @@ var ts; ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(182 /* ObjectBindingPattern */); + var node = createSynthesizedNode(184 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -57578,7 +59825,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(183 /* ArrayBindingPattern */); + var node = createSynthesizedNode(185 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -57590,7 +59837,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(184 /* BindingElement */); + var node = createSynthesizedNode(186 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -57609,7 +59856,7 @@ var ts; ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(185 /* ArrayLiteralExpression */); + var node = createSynthesizedNode(187 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -57623,7 +59870,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(186 /* ObjectLiteralExpression */); + var node = createSynthesizedNode(188 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -57637,7 +59884,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(187 /* PropertyAccessExpression */); + var node = createSynthesizedNode(189 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); @@ -57654,7 +59901,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(188 /* ElementAccessExpression */); + var node = createSynthesizedNode(190 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -57668,7 +59915,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(189 /* CallExpression */); + var node = createSynthesizedNode(191 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -57684,7 +59931,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(190 /* NewExpression */); + var node = createSynthesizedNode(192 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -57700,7 +59947,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { - var node = createSynthesizedNode(191 /* TaggedTemplateExpression */); + var node = createSynthesizedNode(193 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); if (template) { node.typeArguments = asNodeArray(typeArgumentsOrTemplate); @@ -57723,7 +59970,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(192 /* TypeAssertionExpression */); + var node = createSynthesizedNode(194 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -57737,7 +59984,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(193 /* ParenthesizedExpression */); + var node = createSynthesizedNode(195 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -57749,7 +59996,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(194 /* FunctionExpression */); + var node = createSynthesizedNode(196 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -57773,12 +60020,12 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(195 /* ArrowFunction */); + var node = createSynthesizedNode(197 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(36 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */); node.body = ts.parenthesizeConciseBody(body); return node; } @@ -57795,7 +60042,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(196 /* DeleteExpression */); + var node = createSynthesizedNode(198 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57807,7 +60054,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(197 /* TypeOfExpression */); + var node = createSynthesizedNode(199 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57819,7 +60066,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(198 /* VoidExpression */); + var node = createSynthesizedNode(200 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57831,7 +60078,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(199 /* AwaitExpression */); + var node = createSynthesizedNode(201 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57843,7 +60090,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(200 /* PrefixUnaryExpression */); + var node = createSynthesizedNode(202 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -57856,7 +60103,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(201 /* PostfixUnaryExpression */); + var node = createSynthesizedNode(203 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -57869,7 +60116,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(202 /* BinaryExpression */); + var node = createSynthesizedNode(204 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -57886,11 +60133,11 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(203 /* ConditionalExpression */); + var node = createSynthesizedNode(205 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); - node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); - node.colonToken = whenFalse ? colonToken : createToken(56 /* ColonToken */); + node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */); node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); return node; } @@ -57906,7 +60153,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(204 /* TemplateExpression */); + var node = createSynthesizedNode(206 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -57920,33 +60167,33 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createTemplateHead(text) { - var node = createSynthesizedNode(14 /* TemplateHead */); + var node = createSynthesizedNode(15 /* TemplateHead */); node.text = text; return node; } ts.createTemplateHead = createTemplateHead; function createTemplateMiddle(text) { - var node = createSynthesizedNode(15 /* TemplateMiddle */); + var node = createSynthesizedNode(16 /* TemplateMiddle */); node.text = text; return node; } ts.createTemplateMiddle = createTemplateMiddle; function createTemplateTail(text) { - var node = createSynthesizedNode(16 /* TemplateTail */); + var node = createSynthesizedNode(17 /* TemplateTail */); node.text = text; return node; } ts.createTemplateTail = createTemplateTail; function createNoSubstitutionTemplateLiteral(text) { - var node = createSynthesizedNode(13 /* NoSubstitutionTemplateLiteral */); + var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */); node.text = text; return node; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(205 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + var node = createSynthesizedNode(207 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; } ts.createYield = createYield; @@ -57958,7 +60205,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(206 /* SpreadElement */); + var node = createSynthesizedNode(208 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -57970,7 +60217,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(207 /* ClassExpression */); + var node = createSynthesizedNode(209 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57991,11 +60238,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(208 /* OmittedExpression */); + return createSynthesizedNode(210 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(209 /* ExpressionWithTypeArguments */); + var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -58009,7 +60256,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(210 /* AsExpression */); + var node = createSynthesizedNode(212 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -58023,7 +60270,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(211 /* NonNullExpression */); + var node = createSynthesizedNode(213 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -58035,7 +60282,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(212 /* MetaProperty */); + var node = createSynthesizedNode(214 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -58049,7 +60296,7 @@ var ts; ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(214 /* TemplateSpan */); + var node = createSynthesizedNode(216 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -58063,12 +60310,12 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(215 /* SemicolonClassElement */); + return createSynthesizedNode(217 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(216 /* Block */); + var block = createSynthesizedNode(218 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -58082,7 +60329,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(217 /* VariableStatement */); + var node = createSynthesizedNode(219 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -58097,11 +60344,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(218 /* EmptyStatement */); + return createSynthesizedNode(220 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; function createExpressionStatement(expression) { - var node = createSynthesizedNode(219 /* ExpressionStatement */); + var node = createSynthesizedNode(221 /* ExpressionStatement */); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -58117,7 +60364,7 @@ var ts; /** @deprecated Use `updateExpressionStatement` instead. */ ts.updateStatement = updateExpressionStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(220 /* IfStatement */); + var node = createSynthesizedNode(222 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -58133,7 +60380,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(221 /* DoStatement */); + var node = createSynthesizedNode(223 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -58147,7 +60394,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(222 /* WhileStatement */); + var node = createSynthesizedNode(224 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -58161,7 +60408,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(223 /* ForStatement */); + var node = createSynthesizedNode(225 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -58179,7 +60426,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(224 /* ForInStatement */); + var node = createSynthesizedNode(226 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -58195,7 +60442,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(225 /* ForOfStatement */); + var node = createSynthesizedNode(227 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -58213,7 +60460,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(226 /* ContinueStatement */); + var node = createSynthesizedNode(228 /* ContinueStatement */); node.label = asName(label); return node; } @@ -58225,7 +60472,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(227 /* BreakStatement */); + var node = createSynthesizedNode(229 /* BreakStatement */); node.label = asName(label); return node; } @@ -58237,7 +60484,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(228 /* ReturnStatement */); + var node = createSynthesizedNode(230 /* ReturnStatement */); node.expression = expression; return node; } @@ -58249,7 +60496,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(229 /* WithStatement */); + var node = createSynthesizedNode(231 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -58263,7 +60510,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(230 /* SwitchStatement */); + var node = createSynthesizedNode(232 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -58277,7 +60524,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(231 /* LabeledStatement */); + var node = createSynthesizedNode(233 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -58291,7 +60538,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(232 /* ThrowStatement */); + var node = createSynthesizedNode(234 /* ThrowStatement */); node.expression = expression; return node; } @@ -58303,7 +60550,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(233 /* TryStatement */); + var node = createSynthesizedNode(235 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -58319,11 +60566,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(234 /* DebuggerStatement */); + return createSynthesizedNode(236 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(235 /* VariableDeclaration */); + var node = createSynthesizedNode(237 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -58340,7 +60587,7 @@ var ts; ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(236 /* VariableDeclarationList */); + var node = createSynthesizedNode(238 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; @@ -58353,7 +60600,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(237 /* FunctionDeclaration */); + var node = createSynthesizedNode(239 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -58379,7 +60626,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(238 /* ClassDeclaration */); + var node = createSynthesizedNode(240 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58401,7 +60648,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(239 /* InterfaceDeclaration */); + var node = createSynthesizedNode(241 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58423,7 +60670,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(240 /* TypeAliasDeclaration */); + var node = createSynthesizedNode(242 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58443,7 +60690,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(241 /* EnumDeclaration */); + var node = createSynthesizedNode(243 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58462,7 +60709,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(242 /* ModuleDeclaration */); + var node = createSynthesizedNode(244 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -58481,7 +60728,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(243 /* ModuleBlock */); + var node = createSynthesizedNode(245 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -58493,7 +60740,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(244 /* CaseBlock */); + var node = createSynthesizedNode(246 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -58505,7 +60752,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(245 /* NamespaceExportDeclaration */); + var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -58517,7 +60764,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(246 /* ImportEqualsDeclaration */); + var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58535,7 +60782,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(247 /* ImportDeclaration */); + var node = createSynthesizedNode(249 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -58553,7 +60800,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(248 /* ImportClause */); + var node = createSynthesizedNode(250 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -58567,7 +60814,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(249 /* NamespaceImport */); + var node = createSynthesizedNode(251 /* NamespaceImport */); node.name = name; return node; } @@ -58579,7 +60826,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(250 /* NamedImports */); + var node = createSynthesizedNode(252 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -58591,7 +60838,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(251 /* ImportSpecifier */); + var node = createSynthesizedNode(253 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -58605,11 +60852,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(252 /* ExportAssignment */); + var node = createSynthesizedNode(254 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -58622,7 +60869,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(253 /* ExportDeclaration */); + var node = createSynthesizedNode(255 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -58640,7 +60887,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(254 /* NamedExports */); + var node = createSynthesizedNode(256 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -58652,7 +60899,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(255 /* ExportSpecifier */); + var node = createSynthesizedNode(257 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -58667,7 +60914,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(257 /* ExternalModuleReference */); + var node = createSynthesizedNode(259 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -58678,9 +60925,57 @@ var ts; : node; } ts.updateExternalModuleReference = updateExternalModuleReference; + // JSDoc + /* @internal */ + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + /* @internal */ + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + /* @internal */ + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + /* @internal */ + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + /* @internal */ + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291 /* JSDocComment */); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + /* @internal */ + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(258 /* JsxElement */); + var node = createSynthesizedNode(260 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -58696,7 +60991,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); + var node = createSynthesizedNode(261 /* JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -58712,7 +61007,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(260 /* JsxOpeningElement */); + var node = createSynthesizedNode(262 /* JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -58728,7 +61023,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(261 /* JsxClosingElement */); + var node = createSynthesizedNode(263 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -58740,7 +61035,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxFragment(openingFragment, children, closingFragment) { - var node = createSynthesizedNode(262 /* JsxFragment */); + var node = createSynthesizedNode(264 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -58756,7 +61051,7 @@ var ts; } ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(265 /* JsxAttribute */); + var node = createSynthesizedNode(267 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -58770,7 +61065,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(266 /* JsxAttributes */); + var node = createSynthesizedNode(268 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -58782,7 +61077,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(267 /* JsxSpreadAttribute */); + var node = createSynthesizedNode(269 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -58794,7 +61089,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(268 /* JsxExpression */); + var node = createSynthesizedNode(270 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -58808,7 +61103,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(269 /* CaseClause */); + var node = createSynthesizedNode(271 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -58822,7 +61117,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(270 /* DefaultClause */); + var node = createSynthesizedNode(272 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -58834,7 +61129,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(271 /* HeritageClause */); + var node = createSynthesizedNode(273 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -58847,7 +61142,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(272 /* CatchClause */); + var node = createSynthesizedNode(274 /* CatchClause */); node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -58862,7 +61157,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(273 /* PropertyAssignment */); + var node = createSynthesizedNode(275 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = ts.parenthesizeExpressionForList(initializer); @@ -58877,7 +61172,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(274 /* ShorthandPropertyAssignment */); + var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -58891,7 +61186,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(275 /* SpreadAssignment */); + var node = createSynthesizedNode(277 /* SpreadAssignment */); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } @@ -58904,7 +61199,7 @@ var ts; ts.updateSpreadAssignment = updateSpreadAssignment; // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(276 /* EnumMember */); + var node = createSynthesizedNode(278 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -58925,7 +61220,7 @@ var ts; (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { - var updated = createSynthesizedNode(277 /* SourceFile */); + var updated = createSynthesizedNode(279 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -59009,7 +61304,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(305 /* NotEmittedStatement */); + var node = createSynthesizedNode(307 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -59021,7 +61316,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -59033,7 +61328,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(308 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -59048,7 +61343,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -59064,17 +61359,17 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 307 /* CommaListExpression */) { + if (node.kind === 309 /* CommaListExpression */) { return node.elements; } - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { return [node.left, node.right]; } } return node; } function createCommaList(elements) { - var node = createSynthesizedNode(307 /* CommaListExpression */); + var node = createSynthesizedNode(309 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -59087,14 +61382,14 @@ var ts; ts.updateCommaList = updateCommaList; function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = ts.createNode(278 /* Bundle */); + var node = ts.createNode(280 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; function createUnparsedSourceFile(text, mapPath, map) { - var node = ts.createNode(279 /* UnparsedSource */); + var node = ts.createNode(281 /* UnparsedSource */); node.text = text; node.sourceMapPath = mapPath; node.sourceMapText = map; @@ -59102,7 +61397,7 @@ var ts; } ts.createUnparsedSourceFile = createUnparsedSourceFile; function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { - var node = ts.createNode(280 /* InputFiles */); + var node = ts.createNode(282 /* InputFiles */); node.javascriptText = javascript; node.javascriptMapPath = javascriptMapPath; node.javascriptMapText = javascriptMapText; @@ -59144,47 +61439,47 @@ var ts; } ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { - return createBinary(left, 26 /* CommaToken */, right); + return createBinary(left, 27 /* CommaToken */, right); } ts.createComma = createComma; function createLessThan(left, right) { - return createBinary(left, 27 /* LessThanToken */, right); + return createBinary(left, 28 /* LessThanToken */, right); } ts.createLessThan = createLessThan; function createAssignment(left, right) { - return createBinary(left, 58 /* EqualsToken */, right); + return createBinary(left, 59 /* EqualsToken */, right); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 34 /* EqualsEqualsEqualsToken */, right); + return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 35 /* ExclamationEqualsEqualsToken */, right); + return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 37 /* PlusToken */, right); + return createBinary(left, 38 /* PlusToken */, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 38 /* MinusToken */, right); + return createBinary(left, 39 /* MinusToken */, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand) { - return createPostfix(operand, 43 /* PlusPlusToken */); + return createPostfix(operand, 44 /* PlusPlusToken */); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 53 /* AmpersandAmpersandToken */, right); + return createBinary(left, 54 /* AmpersandAmpersandToken */, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 54 /* BarBarToken */, right); + return createBinary(left, 55 /* BarBarToken */, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(51 /* ExclamationToken */, operand); + return createPrefix(52 /* ExclamationToken */, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { @@ -59245,7 +61540,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -59756,7 +62051,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 231 /* LabeledStatement */ + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -59768,19 +62063,20 @@ var ts; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = ts.skipParentheses(node); switch (target.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return cacheIdentifiers; - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: return false; - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -59795,7 +62091,7 @@ var ts; thisArg = ts.createThis(); target = callee; } - else if (callee.kind === 97 /* SuperKeyword */) { + else if (callee.kind === 98 /* SuperKeyword */) { thisArg = ts.createThis(); target = languageVersion < 2 /* ES2015 */ ? ts.setTextRange(ts.createIdentifier("_super"), callee) @@ -59807,7 +62103,7 @@ var ts; } else { switch (callee.kind) { - case 187 /* PropertyAccessExpression */: { + case 189 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -59820,7 +62116,7 @@ var ts; } break; } - case 188 /* ElementAccessExpression */: { + case 190 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -59877,14 +62173,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -59892,7 +62188,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_9 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -59903,7 +62199,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_9.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -59915,15 +62211,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_9.push(setter); + properties_8.push(setter); } - properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_9, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -60161,6 +62457,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +62485,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -60207,7 +62506,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 193 /* ParenthesizedExpression */) { + if (skipped.kind === 195 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -60241,10 +62540,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -60256,7 +62555,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 205 /* YieldExpression */) { + && operand.kind === 207 /* YieldExpression */) { return false; } return true; @@ -60293,7 +62592,7 @@ var ts; // the same kind (recursively). // "a"+(1+2) => "a"+(1+2) // "a"+("b"+"c") => "a"+"b"+"c" - if (binaryOperator === 37 /* PlusToken */) { + if (binaryOperator === 38 /* PlusToken */) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -60328,10 +62627,10 @@ var ts; // // While addition is associative in mathematics, JavaScript's `+` is not // guaranteed to be associative as it is overloaded with string concatenation. - return binaryOperator === 39 /* AsteriskToken */ - || binaryOperator === 49 /* BarToken */ - || binaryOperator === 48 /* AmpersandToken */ - || binaryOperator === 50 /* CaretToken */; + return binaryOperator === 40 /* AsteriskToken */ + || binaryOperator === 50 /* BarToken */ + || binaryOperator === 49 /* AmpersandToken */ + || binaryOperator === 51 /* CaretToken */; } /** * This function determines whether an expression consists of a homogeneous set of @@ -60344,7 +62643,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -60359,7 +62658,7 @@ var ts; return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(203 /* ConditionalExpression */, 55 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { @@ -60394,8 +62693,8 @@ var ts; var needsParens = isCommaSequence(check); if (!needsParens) { switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: needsParens = true; } } @@ -60411,9 +62710,9 @@ var ts; function parenthesizeForNew(expression) { var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return ts.createParen(expression); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return !leftmostExpr.arguments ? ts.createParen(expression) : expression; @@ -60436,7 +62735,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 190 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -60474,7 +62773,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, 26 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -60485,29 +62784,29 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 194 /* FunctionExpression */ || kind === 195 /* ArrowFunction */) { + if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 186 /* ObjectLiteralExpression */ || leftmostExpressionKind === 194 /* FunctionExpression */) { + if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeConditionalTypeMember(member) { - return member.kind === 173 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; } ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return ts.createParenthesizedType(member); } return parenthesizeConditionalTypeMember(member); @@ -60515,9 +62814,9 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 165 /* TypeQuery */: - case 177 /* TypeOperator */: - case 174 /* InferType */: + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 176 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -60543,28 +62842,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: node = node.operand; continue; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: node = node.left; continue; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: node = node.condition; continue; - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: node = node.tag; continue; - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 210 /* AsExpression */: - case 188 /* ElementAccessExpression */: - case 187 /* PropertyAccessExpression */: - case 211 /* NonNullExpression */: - case 306 /* PartiallyEmittedExpression */: + case 212 /* AsExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 213 /* NonNullExpression */: + case 308 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -60572,15 +62871,15 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 186 /* ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) { return ts.setTextRange(ts.createParen(body), body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { - return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || - node.kind === 307 /* CommaListExpression */; + return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 309 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; @@ -60593,13 +62892,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 211 /* NonNullExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 213 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -60624,7 +62923,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 211 /* NonNullExpression */) { + while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) { node = node.expression; } return node; @@ -60632,11 +62931,11 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 193 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); - case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -60654,7 +62953,7 @@ var ts; * the containing expression is created/updated. */ function isIgnorableParen(node) { - return node.kind === 193 /* ParenthesizedExpression */ + return node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -60719,10 +63018,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 247 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 249 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 253 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -60738,7 +63037,7 @@ var ts; */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 - if (moduleName.kind === 9 /* StringLiteral */) { + if (moduleName.kind === 10 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) || ts.getSynthesizedClone(moduleName); @@ -60841,7 +63140,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -60853,11 +63152,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -60889,12 +63188,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 149 /* Parameter */: - case 184 /* BindingElement */: + case 151 /* Parameter */: + case 186 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 206 /* SpreadElement */: - case 275 /* SpreadAssignment */: + case 208 /* SpreadElement */: + case 277 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -60906,7 +63205,7 @@ var ts; */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 184 /* BindingElement */: + case 186 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -60918,7 +63217,7 @@ var ts; : propertyName; } break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -60930,7 +63229,7 @@ var ts; : propertyName; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -60945,7 +63244,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; - return kind === 9 /* StringLiteral */ + return kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */; } /** @@ -60953,13 +63252,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -60999,11 +63298,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 182 /* ObjectBindingPattern */: - case 186 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -61164,276 +63463,276 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */) || kind === 176 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) { return node; } switch (kind) { // Names - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 149 /* Parameter */: + case 151 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 150 /* Decorator */: + case 152 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); // Type elements - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 153 /* MethodSignature */: + case 155 /* MethodSignature */: return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 155 /* Constructor */: + case 157 /* Constructor */: return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 158 /* CallSignature */: + case 160 /* CallSignature */: return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 163 /* FunctionType */: + case 165 /* FunctionType */: return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 164 /* ConstructorType */: + case 166 /* ConstructorType */: return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); - case 168 /* TupleType */: + case 170 /* TupleType */: return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 170 /* RestType */: + case 172 /* RestType */: return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 171 /* UnionType */: + case 173 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); - case 174 /* InferType */: + case 176 /* InferType */: return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 181 /* ImportType */: + case 183 /* ImportType */: return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 179 /* MappedType */: + case 181 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); // Binding patterns - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); // Expression - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 210 /* AsExpression */: + case 212 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 216 /* Block */: + case 218 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 250 /* NamedImports */: + case 252 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 254 /* NamedExports */: + case 256 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 255 /* ExportSpecifier */: + case 257 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -61475,58 +63774,58 @@ var ts; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 161 /* TypePredicate */ && kind <= 180 /* LiteralType */)) { + if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 215 /* SemicolonClassElement */: - case 218 /* EmptyStatement */: - case 208 /* OmittedExpression */: - case 234 /* DebuggerStatement */: - case 305 /* NotEmittedStatement */: + case 217 /* SemicolonClassElement */: + case 220 /* EmptyStatement */: + case 210 /* OmittedExpression */: + case 236 /* DebuggerStatement */: + case 307 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 149 /* Parameter */: + case 151 /* Parameter */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 150 /* Decorator */: + case 152 /* Decorator */: result = reduceNode(node.expression, cbNode, result); break; // Type member - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61535,12 +63834,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 155 /* Constructor */: + case 157 /* Constructor */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61548,7 +63847,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61556,49 +63855,50 @@ var ts; result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 190 /* NewExpression */: + case 192 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNode(node.template, cbNode, result); break; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -61606,123 +63906,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 193 /* ParenthesizedExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 199 /* AwaitExpression */: - case 205 /* YieldExpression */: - case 206 /* SpreadElement */: - case 211 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 210 /* AsExpression */: + case 212 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; // Element - case 216 /* Block */: + case 218 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 221 /* DoStatement */: + case 223 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 222 /* WhileStatement */: - case 229 /* WithStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61731,7 +64031,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61739,139 +64039,140 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 250 /* NamedImports */: - case 254 /* NamedExports */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: result = reduceNode(node.openingFragment, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingFragment, cbNode, result); break; - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); // falls through - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 272 /* CatchClause */: + case 274 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 277 /* SourceFile */: + case 279 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -61944,7 +64245,7 @@ var ts; function aggregateTransformFlagsForSubtree(node) { // We do not transform ambient declarations or types, so there is no need to // recursively aggregate transform flags. - if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 209 /* ExpressionWithTypeArguments */)) { + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) { return 0 /* None */; } // Aggregate the transform flags of each child. @@ -61994,7 +64295,7 @@ var ts; }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, - __debugObjectFlags: { get: function () { return this.flags & 131072 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ @@ -62031,288 +64332,623 @@ var ts; /* @internal */ var ts; (function (ts) { - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + // Current source map file and its index in the sources list + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + // Last recorded and encoded mappings + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - // And failing that, check the disk - var text = host.readFile(path); // TODO: GH#18217 - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + // Then reencode all the updated mappings into the overall map + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } } - }; - cached.set(path, file); - return file; + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } + } + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + /** + * Tries to find the sourceMappingURL comment at the end of a file. + * @param text The source text of the file. + * @param lineStarts The line starts of the file. + */ + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + // empty + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + // Next entry is on same line - no action needed + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); } }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 /* comma */ || + mappings.charCodeAt(pos) === 59 /* semicolon */); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + // 6 digit number + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } } - ts.createSourceFileLikeCache = createSourceFileLikeCache; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - var sourcemaps; - (function (sourcemaps) { - sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; - function decode(host, mapPath, map, program, fallbackCache) { - if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } - var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; - var decodedMappings; - var generatedOrderedMappings; - var sourceOrderedMappings; - return { - getOriginalPosition: getOriginalPosition, - getGeneratedPosition: getGeneratedPosition - }; - function getGeneratedPosition(loc) { - var maps = getSourceOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { - return loc; - } - return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos - } - function getOriginalPosition(loc) { - var maps = getGeneratedOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos - } - function getSourceFileLike(fileName, location) { - // Lookup file in program, if provided - var path = ts.toPath(fileName, location, host.getCanonicalFileName); - var file = program && program.getSourceFile(path); - // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file - if (!file || file.resolvedPath !== path) { - // Otherwise check the cache (which may hit disk) - return fallbackCache.get(path); - } - return file; - } - function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { - var file = getSourceFileLike(fileName, directory); - if (!file) { - return -1; - } - return ts.getPositionOfLineAndCharacter(file, line, character); - } - function getDecodedMappings() { - return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host)); - } - function getSourceOrderedMappings() { - return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); - } - function getGeneratedOrderedMappings() { - return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); - } - function compareProcessedPositionSourcePositions(a, b) { - return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || - ts.compareValues(a.sourcePosition, b.sourcePosition); - } - function compareProcessedPositionEmittedPositions(a, b) { - return ts.compareValues(a.emittedPosition, b.emittedPosition); - } - function processPosition(position) { - var sourcePath = map.sources[position.sourceIndex]; - return { - emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), - sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), - sourcePath: sourcePath, - }; - } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : + value >= 26 && value < 52 ? 97 /* a */ + value - 26 : + value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : + value === 62 ? 43 /* plus */ : + value === 63 ? 47 /* slash */ : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : + ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : + ch === 43 /* plus */ ? 62 : + ch === 47 /* slash */ ? 63 : + -1; + } + 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; } - sourcemaps.decode = decode; - /*@internal*/ - function decodeMappings(map) { - var state = { - encodedText: map.mappings, - currentNameIndex: undefined, - sourceMapNamesLength: map.names ? map.names.length : undefined, - currentEmittedColumn: 0, - currentEmittedLine: 0, - currentSourceColumn: 0, - currentSourceLine: 0, - currentSourceIndex: 0, - decodingIndex: 0 - }; - function captureSpan() { - return { - emittedColumn: state.currentEmittedColumn, - emittedLine: state.currentEmittedLine, - sourceColumn: state.currentSourceColumn, - sourceIndex: state.currentSourceIndex, - sourceLine: state.currentSourceLine, - nameIndex: state.currentNameIndex - }; + 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 + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; } return { - get decodingIndex() { return state.decodingIndex; }, - get error() { return state.error; }, - get lastSpan() { return captureSpan(); }, - next: function () { - if (hasCompletedDecoding(state) || state.error) - return { done: true, value: undefined }; - if (!decodeSinglePosition(state)) - return { done: true, value: undefined }; - return { done: false, value: captureSpan() }; - } + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex }; } - sourcemaps.decodeMappings = decodeMappings; - function calculateDecodedMappings(map, processPosition, host) { - var decoder = decodeMappings(map); - var positions = ts.arrayFrom(decoder, processPosition); - if (decoder.error) { - if (host && host.log) { - host.log("Encountered error while decoding sourcemap: " + decoder.error); - } - return []; - } - return positions; - } - function hasCompletedDecoding(state) { - return state.decodingIndex === state.encodedText.length; - } - function decodeSinglePosition(state) { - while (state.decodingIndex < state.encodedText.length) { - var char = state.encodedText.charCodeAt(state.decodingIndex); - if (char === 59 /* semicolon */) { - // New line - state.currentEmittedLine++; - state.currentEmittedColumn = 0; - state.decodingIndex++; - continue; - } - if (char === 44 /* comma */) { - // Next entry is on same line - no action needed - state.decodingIndex++; - continue; - } - // Read the current position - // 1. Column offset from prev read jsColumn - state.currentEmittedColumn += base64VLQFormatDecode(); - // Incorrect emittedColumn dont support this map - if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { - return false; - } - // 2. Relative sourceIndex - state.currentSourceIndex += base64VLQFormatDecode(); - // Incorrect sourceIndex dont support this map - if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { - return false; - } - // Dont support reading mappings that dont have information about original source position - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { - return false; - } - // 3. Relative sourceLine 0 based - state.currentSourceLine += base64VLQFormatDecode(); - // Incorrect sourceLine dont support this map - if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { - return false; - } - // 4. Relative sourceColumn 0 based - state.currentSourceColumn += base64VLQFormatDecode(); - // Incorrect sourceColumn dont support this map - if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { - return false; - } - // 5. Check if there is name: - if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { - if (state.currentNameIndex === undefined) { - state.currentNameIndex = 0; + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); } - state.currentNameIndex += base64VLQFormatDecode(); - // Incorrect nameIndex dont support this map - // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap - // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { - // return; - // } - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { - return false; - } - // Entry should be complete - return true; - } - createErrorIfCondition(/*condition*/ true, "No encoded entry found"); - return false; - function createErrorIfCondition(condition, errormsg) { - if (state.error) { - // An error was already reported - return true; - } - if (condition) { - state.error = errormsg; - } - return condition; - } - function base64VLQFormatDecode() { - var moreDigits = true; - var shiftCount = 0; - var value = 0; - for (; moreDigits; state.decodingIndex++) { - if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return undefined; // TODO: GH#18217 - } - // 6 digit number - var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); - // If msb is set, we still have more bits to continue - moreDigits = (currentByte & 32) !== 0; - // least significant 5 bits are the next msbs in the final value. - value = value | ((currentByte & 31) << shiftCount); - shiftCount += 5; - } - // Least significant bit if 1 represents negative and rest of the msb is actual absolute value - if ((value & 1) === 0) { - // + number - value = value >> 1; + decodedMappings = ts.emptyArray; } else { - // - number - value = value >> 1; - value = -value; + decodedMappings = mappings; } - return value; } + return decodedMappings; } - function base64FormatDecode(char) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; } - function isSourceMappingSegmentEnd(encodedText, pos) { - return (pos === encodedText.length || - encodedText.charCodeAt(pos) === 44 /* comma */ || - encodedText.charCodeAt(pos) === 59 /* semicolon */); + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; } - })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; })(ts || (ts = {})); /* @internal */ var ts; @@ -62335,7 +64971,7 @@ var ts; function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 277 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -62381,7 +65017,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -62389,13 +65025,13 @@ var ts; externalImports.push(node); hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; - case 246 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { + case 248 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -62425,13 +65061,13 @@ var ts; } } break; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -62439,7 +65075,7 @@ var ts; } } break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default function() { } @@ -62459,7 +65095,7 @@ var ts; } } break; - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default class { } @@ -62811,8 +65447,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62878,7 +65514,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63075,8 +65711,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -63106,14 +65742,14 @@ var ts; var pendingExpressions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 278 /* Bundle */) { + if (node.kind === 280 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280 /* InputFiles */) { + if (prepend.kind === 282 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); } return prepend; @@ -63162,16 +65798,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 277 /* SourceFile */: - case 244 /* CaseBlock */: - case 243 /* ModuleBlock */: - case 216 /* Block */: + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 245 /* ModuleBlock */: + case 218 /* Block */: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 238 /* ClassDeclaration */: - case 237 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: if (ts.hasModifier(node, 2 /* Ambient */)) { break; } @@ -63183,7 +65819,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 238 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); } if (ts.isClassDeclaration(node)) { // XXX: should probably also cover interfaces and type aliases that can have type variables? @@ -63231,10 +65867,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -63255,13 +65891,13 @@ var ts; return node; } switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -63281,11 +65917,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 253 /* ExportDeclaration */ || - node.kind === 247 /* ImportDeclaration */ || - node.kind === 248 /* ImportClause */ || - (node.kind === 246 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 257 /* ExternalModuleReference */)) { + if (node.kind === 255 /* ExportDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 250 /* ImportClause */ || + (node.kind === 248 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 259 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -63315,19 +65951,19 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 152 /* PropertyDeclaration */: - case 160 /* IndexSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); @@ -63337,7 +65973,7 @@ var ts; if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { return undefined; } - else if (currentNamespace && node.kind === 84 /* ExportKeyword */) { + else if (currentNamespace && node.kind === 85 /* ExportKeyword */) { return undefined; } return node; @@ -63354,67 +65990,67 @@ var ts; return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 133 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 169 /* OptionalType */: - case 170 /* RestType */: - case 166 /* TypeLiteral */: - case 161 /* TypePredicate */: - case 148 /* TypeParameter */: - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 105 /* VoidKeyword */: - case 138 /* SymbolKeyword */: - case 164 /* ConstructorType */: - case 163 /* FunctionType */: - case 165 /* TypeQuery */: - case 162 /* TypeReference */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 173 /* ConditionalType */: - case 175 /* ParenthesizedType */: - case 176 /* ThisType */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 180 /* LiteralType */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 168 /* TypeLiteral */: + case 163 /* TypePredicate */: + case 150 /* TypeParameter */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 123 /* BooleanKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 132 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 139 /* SymbolKeyword */: + case 166 /* ConstructorType */: + case 165 /* FunctionType */: + case 167 /* TypeQuery */: + case 164 /* TypeReference */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 177 /* ParenthesizedType */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: // TypeScript type nodes are elided. - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: // TypeScript index signatures are elided. - case 150 /* Decorator */: + case 152 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 155 /* Constructor */: + case 157 /* Constructor */: return visitConstructor(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -63425,7 +66061,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -63436,35 +66072,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 149 /* Parameter */: + case 151 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -63474,35 +66110,35 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: @@ -63539,7 +66175,7 @@ var ts; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); - if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) facts |= 2 /* HasConstructorDecorators */; @@ -63608,7 +66244,7 @@ var ts; // return C; // }(); // - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18 /* CloseBraceToken */); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */); var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -63810,7 +66446,7 @@ var ts; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85 /* ExtendsKeyword */; })); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; })); var classExpression = ts.createClassExpression( /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, heritageClauses, members); @@ -63818,7 +66454,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63866,9 +66502,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -63984,7 +66622,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -64055,7 +66693,7 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 152 /* PropertyDeclaration */ + return member.kind === 154 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } @@ -64066,8 +66704,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -64083,8 +66721,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { - var property = properties_11[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var expression = transformInitializedProperty(property, receiver); ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -64195,12 +66833,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -64353,7 +66991,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 152 /* PropertyDeclaration */ + ? member.kind === 154 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? ts.createVoidZero() @@ -64454,13 +67092,13 @@ var ts; if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); } if (properties) { decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); @@ -64476,10 +67114,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 152 /* PropertyDeclaration */; + return kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 154 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -64489,7 +67127,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 154 /* MethodDeclaration */; + return node.kind === 156 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -64500,12 +67138,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return true; } return false; @@ -64522,15 +67160,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 152 /* PropertyDeclaration */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: return serializeTypeNode(node.type); - case 157 /* SetAccessor */: - case 156 /* GetAccessor */: + case 159 /* SetAccessor */: + case 158 /* GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 154 /* MethodDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 156 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -64567,7 +67205,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 156 /* GetAccessor */) { + if (container && node.kind === 158 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -64612,77 +67250,83 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: return ts.createVoidZero(); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return ts.createIdentifier("Function"); - case 167 /* ArrayType */: - case 168 /* TupleType */: + case 169 /* ArrayType */: + case 170 /* TupleType */: return ts.createIdentifier("Array"); - case 161 /* TypePredicate */: - case 122 /* BooleanKeyword */: + case 163 /* TypePredicate */: + case 123 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: return ts.createIdentifier("String"); - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 180 /* LiteralType */: + case 182 /* LiteralType */: switch (node.literal.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return ts.createIdentifier("String"); case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 9 /* BigIntLiteral */: + return getGlobalBigIntNameWithFallback(); + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: return ts.Debug.failBadSyntaxKind(node.literal); } - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: return ts.createIdentifier("Number"); - case 138 /* SymbolKeyword */: + case 146 /* BigIntKeyword */: + return getGlobalBigIntNameWithFallback(); + case 139 /* SymbolKeyword */: return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return serializeTypeReferenceNode(node); - case 172 /* IntersectionType */: - case 171 /* UnionType */: - return serializeUnionOrIntersectionType(node); - case 165 /* TypeQuery */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 166 /* TypeLiteral */: - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 176 /* ThisType */: - case 181 /* ImportType */: + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return serializeTypeList(node.types); + case 175 /* ConditionalType */: + return serializeTypeList([node.trueType, node.falseType]); + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 168 /* TypeLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 178 /* ThisType */: + case 183 /* ImportType */: break; default: return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } - function serializeUnionOrIntersectionType(node) { + function serializeTypeList(types) { // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175 /* ParenthesizedType */) { + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } - if (typeNode.kind === 131 /* NeverKeyword */) { + if (typeNode.kind === 132 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedIndividual = serializeTypeNode(typeNode); @@ -64718,6 +67362,10 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); @@ -64725,6 +67373,8 @@ var ts; return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); case ts.TypeReferenceSerializationKind.BooleanType: return ts.createIdentifier("Boolean"); case ts.TypeReferenceSerializationKind.NumberLikeType: @@ -64756,12 +67406,12 @@ var ts; * @param node The entity name to serialize. */ function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { // A -> typeof A !== undefined && A var copied = serializeEntityNameAsExpression(node); return createCheckedValue(copied, copied); } - if (node.left.kind === 71 /* Identifier */) { + if (node.left.kind === 72 /* Identifier */) { // A.B -> typeof A !== undefined && A.B return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); } @@ -64777,7 +67427,7 @@ var ts; */ function serializeEntityNameAsExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were // a source tree node for the purposes of the checker. var name = ts.getMutableClone(node); @@ -64785,7 +67435,7 @@ var ts; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. return name; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -64806,6 +67456,15 @@ var ts; function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 /* ESNext */ + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } /** * A simple inlinable expression is an expression which can be copied into multiple locations * without risk of repeating any sideeffects and whose value could not possibly change between @@ -64886,9 +67545,9 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 85 /* ExtendsKeyword */) { + if (node.token === 86 /* ExtendsKeyword */) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(85 /* ExtendsKeyword */, types), node); + return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); } return undefined; } @@ -65284,7 +67943,7 @@ var ts; var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); var valueExpression = transformEnumMemberDeclarationValue(member); var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); - var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? innerAssignment : ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); @@ -65365,12 +68024,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 277 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 241 /* EnumDeclaration */) { + if (node.kind === 243 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -65495,7 +68154,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 243 /* ModuleBlock */) { + if (body.kind === 245 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -65541,13 +68200,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 243 /* ModuleBlock */) { + if (body.kind !== 245 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -65588,7 +68247,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 249 /* NamespaceImport */) { + if (node.kind === 251 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -65782,7 +68441,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65801,7 +68460,7 @@ var ts; function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } function enableSubstitutionForClassAliases() { @@ -65809,7 +68468,7 @@ var ts; enabledSubstitutions |= 1 /* ClassAliases */; // We need to enable substitutions for identifiers. This allows us to // substitute class names inside of a class declaration. - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); // Keep track of class aliases. classAliases = []; } @@ -65819,17 +68478,17 @@ var ts; enabledSubstitutions |= 2 /* NamespaceExports */; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. - context.enableSubstitution(71 /* Identifier */); - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); + context.enableSubstitution(72 /* Identifier */); + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(242 /* ModuleDeclaration */); + context.enableEmitNotification(244 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 242 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 241 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */; } /** * Hook for node emit. @@ -65888,11 +68547,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -65904,7 +68563,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // 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. @@ -65930,9 +68589,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 277 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 242 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 241 /* EnumDeclaration */); + if (container && container.kind !== 279 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), /*location*/ node); @@ -66044,6 +68703,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66064,19 +68731,29 @@ var ts; return node; } switch (node.kind) { - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitAwaitExpression(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66084,27 +68761,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 216 /* Block */: - case 230 /* SwitchStatement */: - case 244 /* CaseBlock */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 233 /* TryStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 220 /* IfStatement */: - case 229 /* WithStatement */: - case 231 /* LabeledStatement */: + case 218 /* Block */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 231 /* WithStatement */: + case 233 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -66305,7 +68982,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 195 /* ArrowFunction */; + var isArrowFunction = node.kind === 197 /* 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 @@ -66318,23 +68995,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66352,6 +69039,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66378,15 +69067,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(189 /* CallExpression */); - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(238 /* ClassDeclaration */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); } } /** @@ -66409,6 +69100,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66426,24 +69125,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66462,24 +69161,68 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 /* ClassDeclaration */ - || kind === 155 /* Constructor */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66489,7 +69232,7 @@ var ts; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); var generatorFunc = ts.createFunctionExpression( - /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), /*name*/ undefined, /*typeParameters*/ undefined, /*parameters*/ [], @@ -66507,12 +69250,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66535,6 +69278,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66551,7 +69300,7 @@ var ts; return visitorWorker(node, /*noDestructuringValue*/ true); } function visitorNoAsyncModifier(node) { - if (node.kind === 120 /* AsyncKeyword */) { + if (node.kind === 121 /* AsyncKeyword */) { return undefined; } return node; @@ -66561,48 +69310,58 @@ var ts; return node; } switch (node.kind) { - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitAwaitExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return visitVoidExpression(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return visitConstructorDeclaration(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: return visitGetAccessorDeclaration(node); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitParameter(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitExpressionStatement(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66635,7 +69394,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 225 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); @@ -66647,7 +69406,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 275 /* SpreadAssignment */) { + if (e.kind === 277 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -66656,7 +69415,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 273 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */ ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -66667,14 +69426,14 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); // If the first element is a spread element, then the first argument to __assign is {}: // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 186 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -66699,10 +69458,10 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } - else if (node.operatorToken.kind === 26 /* CommaToken */) { + else if (node.operatorToken.kind === 27 /* CommaToken */) { return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); @@ -66714,7 +69473,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66731,7 +69490,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66828,7 +69587,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66925,25 +69684,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( - /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66967,7 +69738,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -66987,15 +69758,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(189 /* CallExpression */); - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(238 /* ClassDeclaration */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); } } /** @@ -67018,6 +69791,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67035,24 +69816,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67071,19 +69852,19 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 /* ClassDeclaration */ - || kind === 155 /* Constructor */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67184,13 +69965,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67198,15 +69979,15 @@ var ts; } function transformJsxChildToExpression(node) { switch (node.kind) { - case 10 /* JsxText */: + case 11 /* JsxText */: return visitJsxText(node); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitJsxExpression(node); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -67274,14 +70055,14 @@ var ts; if (node === undefined) { return ts.createTrue(); } - else if (node.kind === 9 /* StringLiteral */) { + else if (node.kind === 10 /* StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); return ts.setTextRange(literal, node); } - else if (node.kind === 268 /* JsxExpression */) { + else if (node.kind === 270 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } @@ -67375,7 +70156,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 258 /* JsxElement */) { + if (node.kind === 260 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -67681,7 +70462,7 @@ var ts; return node; } switch (node.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67689,9 +70470,9 @@ var ts; } function visitBinaryExpression(node) { switch (node.operatorToken.kind) { - case 62 /* AsteriskAsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: return visitExponentiationAssignmentExpression(node); - case 40 /* AsteriskAsteriskToken */: + case 41 /* AsteriskAsteriskToken */: return visitExponentiationExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67741,6 +70522,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67914,14 +70700,14 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 228 /* ReturnStatement */ + && node.kind === 230 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -67939,104 +70725,104 @@ var ts; return node; } function callExpressionVisitor(node) { - if (node.kind === 97 /* SuperKeyword */) { + if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); } return visitor(node); } function visitJavaScript(node) { switch (node.kind) { - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: return undefined; // elide static keyword - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return visitClassExpression(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitParameter(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 71 /* Identifier */: + case 72 /* Identifier */: return visitIdentifier(node); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitCaseBlock(node); - case 216 /* Block */: + case 218 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitExpressionStatement(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node, /*needsDestructuringValue*/ true); - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: return visitTemplateLiteral(node); - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return visitTemplateExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return visitSpreadElement(node); - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return visitThisKeyword(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return visitMetaProperty(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return visitAccessorDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -68123,14 +70909,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 227 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 227 /* BreakStatement */) { + if (node.kind === 229 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -68141,7 +70927,7 @@ var ts; } } else { - if (node.kind === 227 /* BreakStatement */) { + if (node.kind === 229 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -68160,10 +70946,10 @@ var ts; expr = copyExpr; } else { - expr = ts.createBinary(expr, 26 /* CommaToken */, copyExpr); + expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr); } } - returnExpression = ts.createBinary(expr, 26 /* CommaToken */, returnExpression); + returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression); } return ts.createReturn(returnExpression); } @@ -68297,7 +71083,7 @@ var ts; addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); // Create a synthetic text range for the return statement. - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18 /* CloseBraceToken */); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */); var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -68402,7 +71188,7 @@ var ts; } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); // The last statement expression was replaced. Skip it. if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { @@ -68441,11 +71227,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 228 /* ReturnStatement */) { + if (statement.kind === 230 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 220 /* IfStatement */) { + else if (statement.kind === 222 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -68453,7 +71239,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 216 /* Block */) { + else if (statement.kind === 218 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -68511,7 +71297,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -68519,10 +71305,10 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 202 /* BinaryExpression */ - || superCallExpression.left.kind !== 189 /* CallExpression */) { + if (superCallExpression.kind !== 204 /* BinaryExpression */ + || superCallExpression.left.kind !== 191 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } // Shift comments from the original super call to the return statement. @@ -68590,7 +71376,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68667,7 +71453,7 @@ var ts; * synthesized call to `super` */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 71 /* Identifier */ && !inConstructorWithSynthesizedSuper; + return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; } /** * Adds statements to the body of a function-like node if it contains a rest parameter. @@ -68719,7 +71505,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68738,25 +71524,25 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return statements; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = ts.createVoidZero(); break; - case 155 /* Constructor */: + case 157 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. - newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); break; default: return ts.Debug.failBadSyntaxKind(node); @@ -68784,20 +71570,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 155 /* Constructor */: + case 157 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -68907,7 +71693,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -68989,7 +71775,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 237 /* FunctionDeclaration */ || node.kind === 194 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); @@ -69034,7 +71820,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 195 /* ArrowFunction */); + ts.Debug.assert(node.kind === 197 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -69072,7 +71858,7 @@ var ts; ts.setEmitFlags(block, 1 /* SingleLine */); } if (closeBraceLocation) { - ts.setTokenSourceMapRange(block, 18 /* CloseBraceToken */, closeBraceLocation); + ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -69102,9 +71888,9 @@ var ts; function visitExpressionStatement(node) { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); @@ -69123,9 +71909,9 @@ var ts; // expression. If we are in a state where we do not need the destructuring value, // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } @@ -69160,7 +71946,7 @@ var ts; assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); } else { - assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); @@ -69197,19 +71983,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69257,8 +72051,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69326,14 +72120,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -69513,11 +72307,11 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 147 /* ComputedPropertyName */) { + if (property.name.kind === 149 /* ComputedPropertyName */) { numInitialProperties = i; break; } @@ -69544,7 +72338,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69556,7 +72366,7 @@ var ts; } visit(node.name); function visit(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { state.hoistedLocalVariables.push(node); } else { @@ -69570,7 +72380,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69586,14 +72396,76 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 236 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 238 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -69603,165 +72475,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // 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 - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.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 = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.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'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 58 /* EqualsToken */, source); + return ts.createBinary(target, 59 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69769,38 +72752,38 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); } if (state.nonLocalJumps & 2 /* Break */) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69840,21 +72823,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69873,20 +72864,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -69994,10 +72985,10 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -70173,15 +73164,15 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || - node.expression.kind === 97 /* SuperKeyword */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70210,7 +73201,7 @@ var ts; resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { var actualThis = ts.createThis(); ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); var initializer = ts.createLogicalOr(resultingCall, actualThis); @@ -70228,7 +73219,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70275,7 +73266,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 185 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -70392,7 +73383,7 @@ var ts; // thus we need to remove those characters. // First template piece starts with "`", others with "}" // Last template piece ends with "`", others with "${" - var isLast = node.kind === 13 /* NoSubstitutionTemplateLiteral */ || node.kind === 16 /* TemplateTail */; + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; text = text.substring(1, text.length - (isLast ? 1 : 2)); // Newline normalization: // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's @@ -70490,7 +73481,7 @@ var ts; : ts.createFileLevelUniqueName("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") { + if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { if (hierarchyFacts & 8192 /* ComputedPropertyName */) { hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; } @@ -70527,7 +73518,7 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } /** @@ -70537,14 +73528,14 @@ var ts; function enableSubstitutionsForCapturedThis() { if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; - context.enableSubstitution(99 /* ThisKeyword */); - context.enableEmitNotification(155 /* Constructor */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(195 /* ArrowFunction */); - context.enableEmitNotification(194 /* FunctionExpression */); - context.enableEmitNotification(237 /* FunctionDeclaration */); + context.enableSubstitution(100 /* ThisKeyword */); + context.enableEmitNotification(157 /* Constructor */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(197 /* ArrowFunction */); + context.enableEmitNotification(196 /* FunctionExpression */); + context.enableEmitNotification(239 /* FunctionDeclaration */); } } /** @@ -70585,10 +73576,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 237 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -70601,9 +73592,9 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return substituteThisKeyword(node); } return node; @@ -70670,19 +73661,19 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 219 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 189 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 97 /* SuperKeyword */) { + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) { return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 206 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -70710,7 +73701,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -70735,15 +73726,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(260 /* JsxOpeningElement */); - context.enableEmitNotification(261 /* JsxClosingElement */); - context.enableEmitNotification(259 /* JsxSelfClosingElement */); + context.enableEmitNotification(262 /* JsxOpeningElement */); + context.enableEmitNotification(263 /* JsxClosingElement */); + context.enableEmitNotification(261 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(273 /* PropertyAssignment */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(275 /* PropertyAssignment */); return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -70762,9 +73753,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -70821,7 +73812,7 @@ var ts; */ function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { + if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -71096,13 +74087,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitWhileStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -71115,30 +74106,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return visitAccessorDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return visitBreakStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return visitContinueStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71153,21 +74144,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return visitConditionalExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -71180,9 +74171,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -71341,7 +74332,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71381,23 +74372,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 59 /* FirstCompoundAssignment */ - && kind <= 70 /* LastCompoundAssignment */; + return kind >= 60 /* FirstCompoundAssignment */ + && kind <= 71 /* LastCompoundAssignment */; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 59 /* PlusEqualsToken */: return 37 /* PlusToken */; - case 60 /* MinusEqualsToken */: return 38 /* MinusToken */; - case 61 /* AsteriskEqualsToken */: return 39 /* AsteriskToken */; - case 62 /* AsteriskAsteriskEqualsToken */: return 40 /* AsteriskAsteriskToken */; - case 63 /* SlashEqualsToken */: return 41 /* SlashToken */; - case 64 /* PercentEqualsToken */: return 42 /* PercentToken */; - case 65 /* LessThanLessThanEqualsToken */: return 45 /* LessThanLessThanToken */; - case 66 /* GreaterThanGreaterThanEqualsToken */: return 46 /* GreaterThanGreaterThanToken */; - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanGreaterThanToken */; - case 68 /* AmpersandEqualsToken */: return 48 /* AmpersandToken */; - case 69 /* BarEqualsToken */: return 49 /* BarToken */; - case 70 /* CaretEqualsToken */: return 50 /* CaretToken */; + case 60 /* PlusEqualsToken */: return 38 /* PlusToken */; + case 61 /* MinusEqualsToken */: return 39 /* MinusToken */; + case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */; + case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */; + case 64 /* SlashEqualsToken */: return 42 /* SlashToken */; + case 65 /* PercentEqualsToken */: return 43 /* PercentToken */; + case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */; + case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */; + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */; + case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */; + case 70 /* BarEqualsToken */: return 50 /* BarToken */; + case 71 /* CaretEqualsToken */: return 51 /* CaretToken */; } } /** @@ -71410,7 +74401,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -71422,7 +74413,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -71454,7 +74445,7 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 26 /* CommaToken */) { + else if (node.operatorToken.kind === 27 /* CommaToken */) { return visitCommaExpression(node); } // [source] @@ -71465,10 +74456,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71509,7 +74500,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { // Logical `&&` shortcuts when the left-hand operand is falsey. emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); } @@ -71540,7 +74531,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { visit(node.left); visit(node.right); } @@ -71729,10 +74720,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -71798,35 +74789,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 216 /* Block */: + case 218 /* Block */: return transformAndEmitBlock(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return transformAndEmitIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return transformAndEmitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return transformAndEmitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return transformAndEmitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -72256,7 +75247,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 270 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -72269,7 +75260,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 269 /* CaseClause */) { + if (clause.kind === 271 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -72399,7 +75390,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72431,10 +75422,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -72581,7 +75572,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = []; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } renamedCatchVariables.set(text, true); renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -73497,12 +76488,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -73516,7 +76507,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +76564,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +76595,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73824,23 +76821,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 308 /* MergeDeclarationMarker */: + case 310 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 309 /* EndOfDeclarationMarker */: + case 311 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -73849,7 +76846,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73867,24 +76864,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -73916,7 +76913,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74362,7 +77359,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -74417,10 +77414,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -74602,8 +77599,8 @@ var ts; function modifierVisitor(node) { // Elide module-specific modifiers. switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: return undefined; } return node; @@ -74619,7 +77616,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -74681,12 +77678,12 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return substituteBinaryExpression(node); - case 201 /* PostfixUnaryExpression */: - case 200 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -74707,7 +77704,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -74775,15 +77772,15 @@ var ts; // - We do not substitute identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only substitute identifiers that are exported at the top level. - if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 /* PostfixUnaryExpression */ - ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { @@ -74857,12 +77854,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -74881,7 +77878,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75083,7 +78080,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 253 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -75108,7 +78105,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 253 /* ExportDeclaration */) { + if (externalImport.kind !== 255 /* ExportDeclaration */) { continue; } if (!externalImport.exportClause) { @@ -75186,19 +78183,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -75248,15 +78245,15 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: // ExportDeclarations are elided as they are handled via // `appendExportsOfDeclaration`. return undefined; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -75432,7 +78429,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 277 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -75496,7 +78493,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -75558,10 +78555,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -75741,43 +78738,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitWhileStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return visitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitCaseBlock(node); - case 269 /* CaseClause */: + case 271 /* CaseClause */: return visitCaseClause(node); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return visitDefaultClause(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return visitTryStatement(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); - case 216 /* Block */: + case 218 /* Block */: return visitBlock(node); - case 308 /* MergeDeclarationMarker */: + case 310 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 309 /* EndOfDeclarationMarker */: + case 311 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -75960,13 +78957,13 @@ var ts; */ function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 202 /* BinaryExpression */) { + && node.kind === 204 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76025,7 +79022,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 277 /* SourceFile */; + return container !== undefined && container.kind === 279 /* SourceFile */; } else { return false; @@ -76041,8 +79038,8 @@ var ts; */ function modifierVisitor(node) { switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: return undefined; } return node; @@ -76058,7 +79055,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -76106,7 +79103,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -76140,12 +79137,12 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return substituteBinaryExpression(node); - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -76231,22 +79228,22 @@ var ts; // - We do not substitute identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only substitute identifiers that are exported at the top level. - if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 /* PostfixUnaryExpression */ + var expression = node.kind === 203 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 201 /* PostfixUnaryExpression */) { - expression = node.operator === 43 /* PlusPlusToken */ + if (node.kind === 203 /* PostfixUnaryExpression */) { + expression = node.operator === 44 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); } @@ -76267,7 +79264,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -76306,8 +79303,8 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(277 /* SourceFile */); - context.enableSubstitution(71 /* Identifier */); + context.enableEmitNotification(279 /* SourceFile */); + context.enableSubstitution(72 /* Identifier */); var currentSourceFile; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { @@ -76335,10 +79332,10 @@ var ts; } function visitor(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); } return node; @@ -76445,7 +79442,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* 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 : @@ -76474,7 +79471,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -76521,7 +79518,7 @@ var ts; return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { 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 : @@ -76530,8 +79527,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 152 /* PropertyDeclaration */ || node.kind === 151 /* PropertySignature */ || - (node.kind === 149 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -76540,7 +79537,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */ || node.kind === 149 /* Parameter */) { + else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -76565,7 +79562,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 157 /* SetAccessor */) { + if (node.kind === 159 /* SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.hasModifier(node, 32 /* Static */)) { @@ -76604,26 +79601,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named 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 158 /* CallSignature */: + case 160 /* CallSignature */: // Interfaces cannot have return types that cannot be named 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 160 /* IndexSignature */: + case 162 /* IndexSignature */: // Interfaces cannot have return types that cannot be named 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 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -76631,7 +79628,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* 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 : @@ -76645,7 +79642,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 237 /* FunctionDeclaration */: + case 239 /* 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 : @@ -76670,30 +79667,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 155 /* Constructor */: + case 157 /* 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 159 /* ConstructSignature */: - case 164 /* ConstructorType */: + case 161 /* ConstructSignature */: + case 166 /* ConstructorType */: // Interfaces cannot have parameter types that cannot be named 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 158 /* CallSignature */: + case 160 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named 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 160 /* IndexSignature */: + case 162 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -76701,7 +79698,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 240 /* 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 : @@ -76714,8 +79711,8 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 237 /* FunctionDeclaration */: - case 163 /* FunctionType */: + case 239 /* FunctionDeclaration */: + case 165 /* FunctionType */: 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 : @@ -76729,34 +79726,34 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 158 /* CallSignature */: + case 160 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node.parent, 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 === 238 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 240 /* 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 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -76771,9 +79768,9 @@ var ts; function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + if (node.parent.parent.kind === 240 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ? 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; } @@ -76808,11 +79805,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +79835,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76849,6 +79846,7 @@ var ts; reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode @@ -76856,6 +79854,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +79864,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76936,16 +79935,22 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } - if (node.kind === 278 /* Bundle */) { + if (node.kind === 280 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,23 +79962,25 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280 /* InputFiles */) { + if (prepend.kind === 282 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +79999,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +80012,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77038,7 +80049,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77046,13 +80057,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,12 +80078,21 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { return name; } else { - if (name.kind === 183 /* ArrayBindingPattern */) { + if (name.kind === 185 /* ArrayBindingPattern */) { return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -77075,7 +80100,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 208 /* OmittedExpression */) { + if (elem.kind === 210 /* OmittedExpression */) { return elem; } return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -77088,7 +80113,7 @@ var ts; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } var newParam = ts.updateParameter(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -77100,7 +80125,7 @@ var ts; } function ensureNoInitializer(node) { if (shouldPrintWithInitializer(node)) { - return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe } return undefined; } @@ -77113,19 +80138,19 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 149 /* Parameter */ && + var shouldUseResolverType = node.kind === 151 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { return ts.visitNode(type, visitDeclarationSubtree); } if (!ts.getParseTreeNode(node)) { - return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */); } - if (node.kind === 157 /* SetAccessor */) { + if (node.kind === 159 /* SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } errorNameNode = node.name; var oldDiag; @@ -77133,12 +80158,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 149 /* Parameter */ - || node.kind === 152 /* PropertyDeclaration */ - || node.kind === 151 /* PropertySignature */) { + if (node.kind === 151 /* Parameter */ + || node.kind === 154 /* PropertyDeclaration */ + || node.kind === 153 /* PropertySignature */) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -77149,26 +80174,26 @@ var ts; if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } - return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */); + return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */); } } function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: return false; } return false; @@ -77222,7 +80247,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -77242,7 +80267,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 257 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return ts.updateImportEqualsDeclaration(decl, @@ -77269,7 +80294,7 @@ var ts; return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -77374,68 +80399,68 @@ var ts; checkEntityNameVisibility(input.exprName, enclosingDeclaration); } var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 /* TypeLiteral */ || input.kind === 179 /* MappedType */) && input.parent.kind !== 240 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */); if (shouldEnterSuppressNewDiagnosticsContextContext) { // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. suppressNewDiagnosticContexts = true; } if (isProcessedComponent(input)) { switch (input.kind) { - case 209 /* ExpressionWithTypeArguments */: { + case 211 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); } - case 162 /* TypeReference */: { + case 164 /* TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); } - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 155 /* Constructor */: { + case 157 /* Constructor */: { var isPrivate = ts.hasModifier(input, 8 /* Private */); // A constructor declaration may not have a type annotation - var ctor = ts.createSignatureDeclaration(155 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), // TODO: GH#18217 isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), /*type*/ undefined); ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); return cleanup(ctor); } - case 154 /* MethodDeclaration */: { - var sig = ts.createSignatureDeclaration(153 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + case 156 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); sig.name = input.name; sig.modifiers = ts.createNodeArray(ensureModifiers(input)); sig.questionToken = input.questionToken; return cleanup(sig); } - case 156 /* GetAccessor */: { + case 158 /* GetAccessor */: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 157 /* SetAccessor */: { + case 159 /* SetAccessor */: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return cleanup(ts.updateProperty(input, /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 153 /* MethodSignature */: { + case 155 /* MethodSignature */: { return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); } - case 158 /* CallSignature */: { + case 160 /* CallSignature */: { return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 160 /* IndexSignature */: { + case 162 /* IndexSignature */: { return cleanup(ts.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */))); } - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -77443,13 +80468,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); } - case 148 /* TypeParameter */: { + case 150 /* TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 173 /* ConditionalType */: { + case 175 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -77461,13 +80486,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 163 /* FunctionType */: { + case 165 /* FunctionType */: { return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 164 /* ConstructorType */: { + case 166 /* ConstructorType */: { return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 181 /* ImportType */: { + case 183 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -77496,7 +80521,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 154 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -77506,7 +80531,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 253 /* ExportDeclaration */: { + case 255 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; @@ -77515,13 +80540,13 @@ var ts; // Rewrite external module names if necessary return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 252 /* ExportAssignment */: { + case 254 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; } - if (input.expression.kind === 71 /* Identifier */) { + if (input.expression.kind === 72 /* Identifier */) { return input; } else { @@ -77531,7 +80556,7 @@ var ts; errorNode: input }); }; var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } @@ -77545,10 +80570,10 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 246 /* ImportEqualsDeclaration */: { + case 248 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 247 /* ImportDeclaration */: { + case 249 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -77569,24 +80594,39 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 240 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(ts.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 239 /* InterfaceDeclaration */: { + case 241 /* InterfaceDeclaration */: { return cleanup(ts.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 237 /* FunctionDeclaration */: { + case 239 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } - case 242 /* ModuleDeclaration */: { + case 244 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 243 /* ModuleBlock */) { + if (inner && inner.kind === 245 /* ModuleBlock */) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; @@ -77607,7 +80647,7 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 238 /* ClassDeclaration */: { + case 240 /* ClassDeclaration */: { var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -77618,7 +80658,7 @@ var ts; if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); - if (param.name.kind === 71 /* Identifier */) { + if (param.name.kind === 72 /* Identifier */) { return preserveJsDoc(ts.createProperty( /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } @@ -77648,7 +80688,7 @@ var ts; } var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); - if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 getSymbolAccessibilityDiagnostic = function () { return ({ @@ -77657,16 +80697,16 @@ var ts; typeName: input.name }); }; var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { - if (clause.token === 85 /* ExtendsKeyword */) { + if (clause.token === 86 /* ExtendsKeyword */) { var oldDiag_2 = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); getSymbolAccessibilityDiagnostic = oldDiag_2; return newClause; } - return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree)); })); return [statement, cleanup(ts.updateClassDeclaration(input, /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 @@ -77677,10 +80717,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { return cleanup(transformVariableStatement(input, isPrivate)); } - case 241 /* EnumDeclaration */: { + case 243 /* EnumDeclaration */: { return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -77699,7 +80739,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242 /* ModuleDeclaration */) { + if (input.kind === 244 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -77720,7 +80760,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 208 /* OmittedExpression */) { + if (e.kind === 210 /* OmittedExpression */) { return; } if (e.name) { @@ -77783,7 +80823,7 @@ var ts; function ensureModifierFlags(node, privateDeclaration) { var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 277 /* SourceFile */; + var parentIsFile = node.parent.kind === 279 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; @@ -77804,7 +80844,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77818,20 +80858,20 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; } function transformHeritageClauses(nodes) { return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { - return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */); + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */); })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); } } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 239 /* InterfaceDeclaration */) { + if (node.kind === 241 /* InterfaceDeclaration */) { return true; } return false; @@ -77856,7 +80896,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 156 /* GetAccessor */ + return accessor.kind === 158 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -77865,51 +80905,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: - case 217 /* VariableStatement */: - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 219 /* VariableStatement */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 159 /* ConstructSignature */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 160 /* IndexSignature */: - case 235 /* VariableDeclaration */: - case 148 /* TypeParameter */: - case 209 /* ExpressionWithTypeArguments */: - case 162 /* TypeReference */: - case 173 /* ConditionalType */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 181 /* ImportType */: + case 161 /* ConstructSignature */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 237 /* VariableDeclaration */: + case 150 /* TypeParameter */: + case 211 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 175 /* ConditionalType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 183 /* ImportType */: return true; } return false; @@ -77974,6 +81015,14 @@ var ts; return transformers; } ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -77985,7 +81034,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(310 /* Count */); + var enabledSyntaxKindFeatures = new Array(312 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -77993,8 +81042,8 @@ var ts; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; - var onSubstituteNode = function (_, node) { return node; }; - var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; var state = 0 /* Uninitialized */; var diagnostics = []; // The transformation context is provided to each transformer as part of transformer @@ -78243,825 +81292,11 @@ var ts; } ts.transformNodes = transformNodes; })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans - var defaultLastEncodedSourceMapSpan = { - emittedLine: 0, - emittedColumn: 0, - sourceLine: 0, - sourceColumn: 0, - sourceIndex: 0 - }; - function createSourceMapWriter(host, writer, compilerOptions) { - if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } - var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSource; - var currentSourceText; - var sourceMapDir; // The directory in which sourcemap will be - // 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; - var sourceMapDataList; - var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); - return { - initialize: initialize, - reset: reset, - setSourceFile: setSourceFile, - emitPos: emitPos, - emitNodeWithSourceMap: emitNodeWithSourceMap, - emitTokenWithSourceMap: emitTokenWithSourceMap, - getText: getText, - getSourceMappingURL: getSourceMappingURL, - }; - /** - * Skips trivia such as comments and white-space that can optionally overriden by the source map source - */ - function skipSourceTrivia(pos) { - return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); - } - /** - * Initialize the SourceMapWriter for a new output file. - * - * @param filePath The path to the generated output file. - * @param sourceMapFilePath The path to the output source map file. - * @param sourceFileOrBundle The input source file or bundle for the program. - */ - function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) { - return; - } - if (sourceMapData) { - reset(); - } - sourceMapDataList = outputSourceMapDataList; - currentSource = undefined; - currentSourceText = 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, - }; - // 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 (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file - // 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(sourceFileOrBundle.fileName, 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)); - } - } - /** - * Reset the SourceMapWriter to an empty state. - */ - function reset() { - if (disabled) { - return; - } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMapData); - } - currentSource = undefined; - sourceMapDir = undefined; - sourceMapSourceIndex = undefined; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = undefined; - lastEncodedNameIndex = undefined; - sourceMapData = undefined; - sourceMapDataList = undefined; - } - function captureSection() { - return { - version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent, - }; - } - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - ts.Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative"); - 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 = 0; - } - // 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; - } - /** - * Emits a mapping. - * - * If the position is synthetic (undefined or a negative value), no mapping will be - * created. - * - * @param pos The position. - */ - function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); - 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 - }; - } - 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; - } - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } - } - function isPossiblySourceMap(x) { - return typeof x === "object" && !!x.mappings && typeof x.mappings === "string" && !!x.sources; - } - /** - * Emits a node with possible leading and trailing source maps. - * - * @param hint A hint as to the intended usage of the node. - * @param node The node to emit. - * @param emitCallback The callback used to emit the node. - */ - function emitNodeWithSourceMap(hint, node, emitCallback) { - var _a; - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(hint, node); - } - if (node) { - if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { - var text = node.sourceMapText; - var parsed = void 0; - try { - parsed = JSON.parse(text); - } - catch (_b) { - // empty - } - if (!parsed || !isPossiblySourceMap(parsed)) { - return emitCallback(hint, node); - } - var offsetLine = writer.getLine(); - var firstLineColumnOffset = writer.getColumn(); - // First, decode the old component sourcemap - var originalMap = parsed; - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var resolvedPathCache = ts.createMap(); - var absolutePathCache = ts.createMap(); - var sourcemapIterator = ts.sourcemaps.decodeMappings(originalMap); - for (var _c = sourcemapIterator.next(), raw = _c.value, done = _c.done; !done; _a = sourcemapIterator.next(), raw = _a.value, done = _a.done, _a) { - var pathCacheKey = "" + raw.sourceIndex; - // Apply offsets to each position and fixup source entries - if (!resolvedPathCache.has(pathCacheKey)) { - var rawPath = originalMap.sources[raw.sourceIndex]; - var relativePath = originalMap.sourceRoot ? ts.combinePaths(originalMap.sourceRoot, rawPath) : rawPath; - var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath); - var resolvedPath_1 = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - resolvedPathCache.set(pathCacheKey, resolvedPath_1); - absolutePathCache.set(pathCacheKey, ts.getNormalizedAbsolutePath(resolvedPath_1, sourcesDirectoryPath)); - } - var resolvedPath = resolvedPathCache.get(pathCacheKey); - var absolutePath = absolutePathCache.get(pathCacheKey); - // tslint:disable-next-line:no-null-keyword - setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); // TODO: Lookup content for inlining? - var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath); - // Then reencode all the updated spans into the overall map - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = __assign({}, raw, { emittedLine: raw.emittedLine + offsetLine, emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, sourceIndex: newIndex }); - } - // And actually emit the text these sourcemaps are for - return emitCallback(hint, node); - } - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0 /* None */; - var range = emitNode && emitNode.sourceMapRange; - var _d = range || node, pos = _d.pos, end = _d.end; - var source = range && range.source; - var oldSource = currentSource; - if (source === oldSource) - source = undefined; - if (source) - setSourceFile(source); - if (node.kind !== 305 /* NotEmittedStatement */ - && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && pos >= 0) { - emitPos(skipSourceTrivia(pos)); - } - if (source) - setSourceFile(oldSource); - if (emitFlags & 64 /* NoNestedSourceMaps */) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - if (source) - setSourceFile(source); - if (node.kind !== 305 /* NotEmittedStatement */ - && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && end >= 0) { - emitPos(end); - } - if (source) - setSourceFile(oldSource); - } - } - /** - * Emits a token of a node with possible leading and trailing source maps. - * - * @param node The node containing the token. - * @param token The token to emit. - * @param tokenStartPos The start pos of the token. - * @param emitCallback The callback used to emit the token. - */ - function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(token, writer, tokenPos); - } - var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0 /* None */; - var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); - if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - tokenPos = emitCallback(token, writer, tokenPos); - if (range) - tokenPos = range.end; - if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - return tokenPos; - } - function isJsonSourceMapSource(sourceFile) { - return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); - } - /** - * Set the current source file. - * - * @param sourceFile The source file. - */ - function setSourceFile(sourceFile) { - if (disabled) { - return; - } - currentSource = sourceFile; - currentSourceText = currentSource.text; - if (isJsonSourceMapSource(sourceFile)) { - return; - } - setupSourceEntry(sourceFile.fileName, sourceFile.text); - } - function setupSourceEntry(fileName, content, source) { - if (!source) { - // 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; - source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(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(fileName); - if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(content); - } - } - } - /** - * Gets the text for the source map. - */ - function getText() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; // TODO: GH#18217 - } - encodeLastRecordedSourceMapSpan(); - return JSON.stringify(captureSection()); - } - /** - * Gets the SourceMappingURL for the source map. - */ - function getSourceMappingURL() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; // TODO: GH#18217 - } - if (compilerOptions.inlineSourceMap) { - // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.base64encode(ts.sys, 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 createCommentWriter(printerOptions, emitPos) { - var extendedDiagnostics = printerOptions.extendedDiagnostics; - var newLine = ts.getNewLineCharacter(printerOptions); - var writer; - var containerPos = -1; - var containerEnd = -1; - var declarationListContainerEnd = -1; - var currentSourceFile; - var currentText; - var currentLineMap; - var detachedCommentsInfo; - var hasWrittenComment = false; - var disabled = !!printerOptions.removeComments; - return { - reset: reset, - setWriter: setWriter, - setSourceFile: setSourceFile, - emitNodeWithComments: emitNodeWithComments, - emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, - emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, - }; - function emitNodeWithComments(hint, node, emitCallback) { - if (disabled) { - emitCallback(hint, node); - return; - } - if (node) { - hasWrittenComment = false; - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0; - var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; - if ((pos < 0 && end < 0) || (pos === end)) { - // Both pos and end are synthesized, so just emit the node without comments. - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - } - else { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithComment"); - } - var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */; - // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. - // It is expensive to walk entire tree just to set one kind of node to have no comments. - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; - var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 10 /* JsxText */; - // Emit leading comments if the position is not synthesized and the node - // has not opted out from emitting leading comments. - if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); - } - // Save current container state on the stack. - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { - // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. - containerPos = pos; - } - if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { - // As above. - containerEnd = end; - // To avoid invalid comment emit in a down-level binding pattern, we - // keep track of the last declaration list container's end - if (node.kind === 236 /* VariableDeclarationList */) { - declarationListContainerEnd = end; - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithComment"); - } - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithComment"); - } - // Restore previous container state. - containerPos = savedContainerPos; - containerEnd = savedContainerEnd; - declarationListContainerEnd = savedDeclarationListContainerEnd; - // Emit trailing comments if the position is not synthesized and the node - // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { - emitTrailingComments(end); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithComment"); - } - } - } - } - function emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback) { - var leadingComments = emitNode && emitNode.leadingComments; - if (ts.some(leadingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithSynthesizedComments"); - } - ts.forEach(leadingComments, emitLeadingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithSynthesizedComments"); - } - } - emitNodeWithNestedComments(hint, node, emitFlags, emitCallback); - var trailingComments = emitNode && emitNode.trailingComments; - if (ts.some(trailingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithSynthesizedComments"); - } - ts.forEach(trailingComments, emitTrailingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithSynthesizedComments"); - } - } - } - function emitLeadingSynthesizedComment(comment) { - if (comment.kind === 2 /* SingleLineCommentTrivia */) { - writer.writeLine(); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function emitTrailingSynthesizedComment(comment) { - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - } - function writeSynthesizedComment(comment) { - var text = formatSynthesizedComment(comment); - var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; - ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); - } - function formatSynthesizedComment(comment) { - return comment.kind === 3 /* MultiLineCommentTrivia */ - ? "/*" + comment.text + "*/" - : "//" + comment.text; - } - function emitNodeWithNestedComments(hint, node, emitFlags, emitCallback) { - if (emitFlags & 2048 /* NoNestedComments */) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - } - function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitBodyWithDetachedComments"); - } - var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = ts.getEmitFlags(node); - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; - if (!skipLeadingComments) { - emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); - } - if (emitFlags & 2048 /* NoNestedComments */ && !disabled) { - disabled = true; - emitCallback(node); - disabled = false; - } - else { - emitCallback(node); - } - if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); - } - if (!skipTrailingComments) { - emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); - if (hasWrittenComment && !writer.isAtStartOfLine()) { - writer.writeLine(); - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); - } - } - function emitLeadingComments(pos, isEmittedNode) { - hasWrittenComment = false; - if (isEmittedNode) { - forEachLeadingCommentToEmit(pos, emitLeadingComment); - } - else if (pos === 0) { - // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, - // unless it is a triple slash comment at the top of the file. - // For Example: - // /// - // declare var x; - // /// - // interface F {} - // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted - forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); - } - } - function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (isTripleSlashComment(commentPos, commentEnd)) { - emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); - } - } - function shouldWriteComment(text, pos) { - if (printerOptions.onlyPrintJsDocStyle) { - return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); - } - return true; - } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (!hasWrittenComment) { - ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); - hasWrittenComment = true; - } - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else if (kind === 3 /* MultiLineCommentTrivia */) { - writer.write(" "); - } - } - function emitLeadingCommentsOfPosition(pos) { - if (disabled || pos === -1) { - return; - } - emitLeadingComments(pos, /*isEmittedNode*/ true); - } - function emitTrailingComments(pos) { - forEachTrailingCommentToEmit(pos, emitTrailingComment); - } - function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - } - function emitTrailingCommentsOfPosition(pos, prefixSpace) { - if (disabled) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); - } - forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); - } - } - function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { - // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function forEachLeadingCommentToEmit(pos, cb) { - // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments - if (containerPos === -1 || pos !== containerPos) { - if (hasDetachedComments(pos)) { - forEachLeadingCommentWithoutDetachedComments(cb); - } - else { - ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - } - } - function forEachTrailingCommentToEmit(end, cb) { - // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments - if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { - ts.forEachTrailingCommentRange(currentText, end, cb); - } - } - function reset() { - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - detachedCommentsInfo = undefined; - } - function setWriter(output) { - writer = output; - } - function setSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = currentSourceFile.text; - currentLineMap = ts.getLineStarts(currentSourceFile); - detachedCommentsInfo = undefined; - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; - } - function forEachLeadingCommentWithoutDetachedComments(cb) { - // get the leading comments from detachedPos - var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - function emitDetachedCommentsAndUpdateCommentsInfo(range) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - } - /** - * Determine if the given comment is a triple-slash - * - * @return true if the comment is a triple-slash comment else false - */ - function isTripleSlashComment(commentPos, commentEnd) { - return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); - } - } - ts.createCommentWriter = createCommentWriter; -})(ts || (ts = {})); var ts; (function (ts) { var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ /** * Iterates over the source files that are expected to have an emit output. @@ -79099,21 +81334,26 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + if (sourceFile.kind === 280 /* Bundle */) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79136,7 +81376,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79156,22 +81396,16 @@ var ts; var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var newLine = host.getNewLine(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); var writer = ts.createTextWriter(newLine); - var sourceMap = ts.createSourceMapWriter(host, writer); - var declarationSourceMap = ts.createSourceMapWriter(host, writer, { - sourceMap: compilerOptions.declarationMap, - sourceRoot: compilerOptions.sourceRoot, - mapRoot: compilerOptions.mapRoot, - extendedDiagnostics: compilerOptions.extendedDiagnostics, - }); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; var exportedModulesFromDeclarationEmit; // Emit each output file - ts.performance.mark("beforePrint"); + enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); - ts.performance.measure("printTime", "beforePrint"); + exit(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -79185,56 +81419,66 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; // Create a printer to print the nodes - var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { + var printer = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, // transform hooks onEmitNode: transform.emitNodeWithNotification, substituteNode: transform.substituteNode, - // sourcemap hooks - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - // emitter hooks - onSetSourceFile: setSourceFile, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79248,14 +81492,20 @@ var ts; emitterDiagnostics.add(diagnostic); } } - var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true, noEmitHelpers: true }), { + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, - // sourcemap hooks - onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: declarationSourceMap.emitPos, - onSetSourceFile: setSourceFileForDeclarationSourceMaps, // transform hooks onEmitNode: declarationTransform.emitNodeWithNotification, substituteNode: declarationTransform.substituteNode, @@ -79264,8 +81514,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); - if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -79274,7 +81529,7 @@ var ts; } function collectLinkedAliases(node) { if (ts.isExportAssignment(node)) { - if (node.expression.kind === 71 /* Identifier */) { + if (node.expression.kind === 72 /* Identifier */) { resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); } return; @@ -79285,25 +81540,41 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { - var bundle = sourceFileOrBundle.kind === 278 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 277 /* SourceFile */ ? sourceFileOrBundle : undefined; + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } if (bundle) { - printer.writeBundle(bundle, writer, bundleInfo); + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); } else { - printer.writeFile(sourceFile, writer); + printer.writeFile(sourceFile, writer, sourceMapGenerator); } - writer.writeLine(); - var sourceMappingURL = mapRecorder.getSourceMappingURL(); - if (sourceMappingURL) { - writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } } - // Write the source map - if (sourceMapFilePath) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); + else { + writer.writeLine(); } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); @@ -79313,32 +81584,84 @@ var ts; ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); } // Reset state - mapRecorder.reset(); writer.clear(); bundleInfo = createDefaultBundleInfo(); } - function setSourceFile(node) { - sourceMap.setSourceFile(node); + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } - function setSourceFileForDeclarationSourceMaps(node) { - declarationSourceMap.setSourceFile(node); + function getSourceRoot(mapOptions) { + // 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 + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; } } ts.emitFiles = emitFiles; var PipelinePhase; (function (PipelinePhase) { PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; - PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; - PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; - PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); - var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); var currentSourceFile; var nodeIdToGeneratedName; // Map of generated names for specific nodes. var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. @@ -79348,19 +81671,23 @@ var ts; var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; - var ownWriter; + var ownWriter; // Reusable `EmitTextWriter` for basic printing. var write = writeBase; - var commitPendingSemicolon = ts.noop; - var writeSemicolon = writeSemicolonInternal; - var pendingSemicolon = false; - if (printerOptions.omitTrailingSemicolon) { - commitPendingSemicolon = commitPendingSemicolonInternal; - writeSemicolon = deferWriteSemicolon; - } - var syntheticParent = { pos: -1, end: -1 }; - var moduleKind = ts.getEmitModuleKind(printerOptions); - var bundledHelpers = ts.createMap(); var isOwnFileEmit; + // Source Maps + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + // Comments + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; reset(); return { // public API @@ -79387,9 +81714,9 @@ var ts; break; } switch (node.kind) { - case 277 /* SourceFile */: return printFile(node); - case 278 /* Bundle */: return printBundle(node); - case 279 /* UnparsedSource */: return printUnparsedSource(node); + case 279 /* SourceFile */: return printFile(node); + case 280 /* Bundle */: return printBundle(node); + case 281 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -79399,11 +81726,11 @@ var ts; return endPrint(); } function printBundle(bundle) { - writeBundle(bundle, beginPrint()); + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printFile(sourceFile) { - writeFile(sourceFile, beginPrint()); + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printUnparsedSource(unparsed) { @@ -79412,14 +81739,14 @@ var ts; } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(hint, node, sourceFile); reset(); writer = previousWriter; } function writeList(format, nodes, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); if (sourceFile) { setSourceFile(sourceFile); } @@ -79427,18 +81754,18 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output, bundleInfo) { + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { isOwnFileEmit = false; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { var prepend = _b[_a]; - print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); writeLine(); + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); } if (bundleInfo) { bundleInfo.originalOffset = writer.getTextPos(); @@ -79452,15 +81779,15 @@ var ts; } function writeUnparsedSource(unparsed, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); reset(); writer = previousWriter; } - function writeFile(sourceFile, output) { + function writeFile(sourceFile, output, sourceMapGenerator) { isOwnFileEmit = true; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(sourceFile); emitPrologueDirectivesIfNeeded(sourceFile); print(0 /* SourceFile */, sourceFile, sourceFile); @@ -79479,19 +81806,24 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - var pipelinePhase = getPipelinePhase(0 /* Notification */, hint); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; - comments.setSourceFile(sourceFile); - if (onSetSourceFile) { - onSetSourceFile(sourceFile); + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); } } - function setWriter(output) { - writer = output; // TODO: GH#18217 - comments.setWriter(output); + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; } function reset() { nodeIdToGeneratedName = []; @@ -79500,68 +81832,66 @@ var ts; tempFlagsStack = []; tempFlags = 0 /* Auto */; reservedNamesStack = []; - comments.reset(); - setWriter(/*output*/ undefined); + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } function emit(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(4 /* Unspecified */, node); } function emitIdentifierName(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(2 /* IdentifierName */, node); } function emitExpression(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(1 /* Expression */, node); } - function getPipelinePhase(phase, hint) { + function getPipelinePhase(phase, node) { switch (phase) { case 0 /* Notification */: - if (onEmitNode) { + if (onEmitNode !== ts.noEmitNotification) { return pipelineEmitWithNotification; } // falls through - case 1 /* Comments */: - if (emitNodeWithComments && hint !== 0 /* SourceFile */) { + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { return pipelineEmitWithComments; } - return pipelineEmitWithoutComments; - case 2 /* SourceMaps */: - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */) { + // falls through + case 3 /* SourceMaps */: + if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { return pipelineEmitWithSourceMap; } // falls through - case 3 /* Emit */: + case 4 /* Emit */: return pipelineEmitWithHint; default: - return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + return ts.Debug.assertNever(phase); } } - function getNextPipelinePhase(currentPhase, hint) { - return getPipelinePhase(currentPhase + 1, hint); + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); - } - function pipelineEmitWithComments(hint, node) { - ts.Debug.assertDefined(emitNodeWithComments); - ts.Debug.assert(hint !== 0 /* SourceFile */); - emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint)); - } - function pipelineEmitWithoutComments(hint, node) { - var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint); - pipelinePhase(hint, trySubstituteNode(hint, node)); - } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(hint !== 0 /* SourceFile */); - ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node); + onEmitNode(hint, node, pipelinePhase); } function pipelineEmitWithHint(hint, node) { if (hint === 0 /* SourceFile */) @@ -79570,254 +81900,285 @@ var ts; return emitIdentifier(ts.cast(node, ts.isIdentifier)); if (hint === 3 /* MappedTypeParameter */) return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } if (hint === 4 /* Unspecified */) { if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); switch (node.kind) { // Pseudo-literals - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: return emitLiteral(node); - case 279 /* UnparsedSource */: + case 281 /* UnparsedSource */: return emitUnparsedSource(node); // Identifiers - case 71 /* Identifier */: + case 72 /* Identifier */: return emitIdentifier(node); // Parse tree nodes // Names - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return emitQualifiedName(node); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return emitTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return emitParameter(node); - case 150 /* Decorator */: + case 152 /* Decorator */: return emitDecorator(node); // Type members - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return emitPropertySignature(node); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 153 /* MethodSignature */: + case 155 /* MethodSignature */: return emitMethodSignature(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return emitConstructor(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return emitAccessorDeclaration(node); - case 158 /* CallSignature */: + case 160 /* CallSignature */: return emitCallSignature(node); - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return emitConstructSignature(node); - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return emitIndexSignature(node); // Types - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return emitTypePredicate(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return emitTypeReference(node); - case 163 /* FunctionType */: + case 165 /* FunctionType */: return emitFunctionType(node); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return emitJSDocFunctionType(node); - case 164 /* ConstructorType */: + case 166 /* ConstructorType */: return emitConstructorType(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return emitTypeQuery(node); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return emitTypeLiteral(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return emitArrayType(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return emitTupleType(node); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return emitOptionalType(node); - case 171 /* UnionType */: + case 173 /* UnionType */: return emitUnionType(node); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return emitIntersectionType(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return emitConditionalType(node); - case 174 /* InferType */: + case 176 /* InferType */: return emitInferType(node); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return emitParenthesizedType(node); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 176 /* ThisType */: + case 178 /* ThisType */: return emitThisType(); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return emitTypeOperator(node); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return emitMappedType(node); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return emitLiteralType(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return emitImportTypeNode(node); - case 282 /* JSDocAllType */: - write("*"); + case 284 /* JSDocAllType */: + writePunctuation("*"); return; - case 283 /* JSDocUnknownType */: - write("?"); + case 285 /* JSDocUnknownType */: + writePunctuation("?"); return; - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return emitJSDocNullableType(node); - case 285 /* JSDocNonNullableType */: + case 287 /* JSDocNonNullableType */: return emitJSDocNonNullableType(node); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return emitJSDocOptionalType(node); - case 170 /* RestType */: - case 288 /* JSDocVariadicType */: + case 172 /* RestType */: + case 290 /* JSDocVariadicType */: return emitRestOrJSDocVariadicType(node); // Binding patterns - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return emitBindingElement(node); // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return emitTemplateSpan(node); - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 216 /* Block */: + case 218 /* Block */: return emitBlock(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return emitVariableStatement(node); - case 218 /* EmptyStatement */: - return emitEmptyStatement(); - case 219 /* ExpressionStatement */: + case 220 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 221 /* ExpressionStatement */: return emitExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return emitIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return emitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return emitWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return emitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return emitForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return emitForOfStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return emitContinueStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return emitBreakStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return emitReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return emitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return emitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return emitLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return emitThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return emitTryStatement(node); - case 234 /* DebuggerStatement */: + case 236 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return emitClassDeclaration(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return emitModuleBlock(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return emitCaseBlock(node); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return emitImportDeclaration(node); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return emitImportClause(node); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return emitNamespaceImport(node); - case 250 /* NamedImports */: + case 252 /* NamedImports */: return emitNamedImports(node); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return emitImportSpecifier(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return emitExportAssignment(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return emitExportDeclaration(node); - case 254 /* NamedExports */: + case 256 /* NamedExports */: return emitNamedExports(node); - case 255 /* ExportSpecifier */: + case 257 /* ExportSpecifier */: return emitExportSpecifier(node); - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return; // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) - case 10 /* JsxText */: + case 11 /* JsxText */: return emitJsxText(node); - case 260 /* JsxOpeningElement */: - case 263 /* JsxOpeningFragment */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 261 /* JsxClosingElement */: - case 264 /* JsxClosingFragment */: + case 263 /* JsxClosingElement */: + case 266 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return emitJsxAttribute(node); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return emitJsxAttributes(node); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: return emitCaseClause(node); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return emitDefaultClause(node); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return emitHeritageClause(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: return emitEnumMember(node); - // JSDoc nodes (ignored) + // JSDoc nodes (only used in codefixes currently) + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return emitJSDocSimpleTypedTag(node); + case 295 /* JSDocAugmentsTag */: + return emitJSDocAugmentsTag(node); + case 303 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 304 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 297 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 293 /* JSDocSignature */: + return emitJSDocSignature(node); + case 292 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 296 /* JSDocClassTag */: + case 294 /* JSDocTag */: + return emitJSDocSimpleTag(node); + case 291 /* JSDocComment */: + return emitJSDoc(node); // Transformation nodes (ignored) } if (ts.isExpression(node)) { hint = 1 /* Expression */; - node = trySubstituteNode(1 /* Expression */, node); + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } } else if (ts.isToken(node)) { return writeTokenNode(node, writePunctuation); @@ -79827,89 +82188,90 @@ var ts; switch (node.kind) { // Literals case 8 /* NumericLiteral */: - return emitNumericLiteral(node); - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return emitLiteral(node); // Identifiers - case 71 /* Identifier */: + case 72 /* Identifier */: return emitIdentifier(node); // Reserved words - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 101 /* TrueKeyword */: - case 99 /* ThisKeyword */: - case 91 /* ImportKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 102 /* TrueKeyword */: + case 100 /* ThisKeyword */: + case 92 /* ImportKeyword */: writeTokenNode(node, writeKeyword); return; // Expressions - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return emitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return emitNewExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return emitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return emitArrowFunction(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return emitDeleteExpression(node); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return emitVoidExpression(node); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return emitAwaitExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return emitBinaryExpression(node); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return emitConditionalExpression(node); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return emitTemplateExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return emitYieldExpression(node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return emitSpreadExpression(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return emitClassExpression(node); - case 208 /* OmittedExpression */: + case 210 /* OmittedExpression */: return; - case 210 /* AsExpression */: + case 212 /* AsExpression */: return emitAsExpression(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return emitNonNullExpression(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return emitMetaProperty(node); // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: return emitJsxElement(node); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return emitCommaList(node); } } @@ -79921,12 +82283,13 @@ var ts; writeSpace(); emit(node.constraint); } - function trySubstituteNode(hint, node) { - return node && substituteNode && substituteNode(hint, node) || node; + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); + pipelinePhase(hint, substituteNode(hint, node)); } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 278 /* Bundle */ ? node : undefined; + var bundle = node.kind === 280 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -79963,7 +82326,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79975,7 +82338,8 @@ var ts; // Literals/Pseudo-literals // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } // SyntaxKind.StringLiteral @@ -79985,9 +82349,9 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) - && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); } else { @@ -80005,7 +82369,7 @@ var ts; function emitIdentifier(node) { var writeText = node.symbol ? writeSymbol : write; writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); - emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments + emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names @@ -80016,7 +82380,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -80052,7 +82416,7 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 287 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { @@ -80074,7 +82438,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -80084,7 +82448,7 @@ var ts; emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); - writeSemicolon(); + writeTrailingSemicolon(); } function emitMethodSignature(node) { pushNameGenerationScope(node); @@ -80095,7 +82459,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -80114,7 +82478,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 156 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -80126,7 +82490,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -80138,7 +82502,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -80146,10 +82510,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // // Types @@ -80176,22 +82540,22 @@ var ts; popNameGenerationScope(node); } function emitJSDocFunctionType(node) { - write("function"); + writeKeyword("function"); emitParameters(node, node.parameters); - write(":"); + writePunctuation(":"); emit(node.type); } function emitJSDocNullableType(node) { - write("?"); + writePunctuation("?"); emit(node.type); } function emitJSDocNonNullableType(node) { - write("!"); + writePunctuation("!"); emit(node.type); } function emitJSDocOptionalType(node) { emit(node.type); - write("="); + writePunctuation("="); } function emitConstructorType(node) { pushNameGenerationScope(node); @@ -80212,8 +82576,8 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */; - emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); writePunctuation("}"); } function emitArrayType(node) { @@ -80222,23 +82586,23 @@ var ts; writePunctuation("]"); } function emitRestOrJSDocVariadicType(node) { - write("..."); + writePunctuation("..."); emit(node.type); } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 272 /* TupleTypeElements */); + emitList(node, node.elementTypes, 528 /* TupleTypeElements */); writePunctuation("]"); } function emitOptionalType(node) { emit(node.type); - write("?"); + writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 260 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */); } function emitIntersectionType(node) { - emitList(node, node.types, 264 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */); } function emitConditionalType(node) { emit(node.checkType); @@ -80291,25 +82655,25 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) { + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { writeKeyword("readonly"); } writeSpace(); } writePunctuation("["); - var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter); pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); - if (node.questionToken.kind !== 55 /* QuestionToken */) { + if (node.questionToken.kind !== 56 /* QuestionToken */) { writePunctuation("?"); } } writePunctuation(":"); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); if (emitFlags & 1 /* SingleLine */) { writeSpace(); } @@ -80342,12 +82706,12 @@ var ts; // function emitObjectBindingPattern(node) { writePunctuation("{"); - emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); writePunctuation("}"); } function emitArrayBindingPattern(node) { writePunctuation("["); - emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); writePunctuation("]"); } function emitBindingElement(node) { @@ -80365,8 +82729,8 @@ var ts; // function emitArrayLiteralExpression(node) { var elements = node.elements; - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -80374,9 +82738,9 @@ var ts; if (indentedFlag) { increaseIndent(); } - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */; - emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); } @@ -80387,20 +82751,20 @@ var ts; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = ts.createToken(23 /* DotToken */); + var dotToken = ts.createToken(24 /* DotToken */); dotToken.pos = dotRangeStart; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); - increaseIndentIf(indentBeforeDot); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); if (shouldEmitDotDot) { writePunctuation("."); } - emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node); - increaseIndentIf(indentAfterDot); + emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); } @@ -80410,9 +82774,9 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); + && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -80425,21 +82789,21 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); } function emitNewExpression(node) { - emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); @@ -80454,9 +82818,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node); + var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { generateNameIfNeeded(node.name); @@ -80475,22 +82839,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -80515,24 +82879,24 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 200 /* PrefixUnaryExpression */ - && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) - || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); + return operand.kind === 202 /* PrefixUnaryExpression */ + && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */)) + || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; + var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); - increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + increaseIndentIf(indentBeforeOperator, isCommaOperator); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, writeOperator); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - increaseIndentIf(indentAfterOperator, " "); + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); } @@ -80542,28 +82906,28 @@ var ts; var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); - increaseIndentIf(indentBeforeQuestion, " "); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); - increaseIndentIf(indentAfterQuestion, " "); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); - increaseIndentIf(indentBeforeColon, " "); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); - increaseIndentIf(indentAfterColon, " "); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); } function emitTemplateExpression(node) { emit(node.head); - emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - writePunctuation("..."); + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); emitExpression(node.expression); } function emitClassExpression(node) { @@ -80606,36 +82970,45 @@ var ts; emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); } function emitBlockStatements(node, forceSingleLine) { - emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); - var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; emitList(node, node.statements, format); - emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); + emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - writeSemicolon(); + writeTrailingSemicolon(); } - function emitEmptyStatement() { - writeSemicolon(); + function emitEmptyStatement(isEmbeddedStatement) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { - writeSemicolon(); + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); } } function emitIfStatement(node) { - var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 220 /* IfStatement */) { + emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -80645,14 +83018,14 @@ var ts; } } function emitWhileClause(node, startPos) { - var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node); + var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { - emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -80668,45 +83041,45 @@ var ts; emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.condition); - pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.incrementor); - emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(145 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 236 /* VariableDeclarationList */) { + if (node.kind === 238 /* VariableDeclarationList */) { emit(node); } else { @@ -80715,14 +83088,14 @@ var ts; } } function emitContinueStatement(node) { - emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitBreakStatement(node) { - emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { var node = ts.getParseTreeNode(contextNode); @@ -80748,40 +83121,40 @@ var ts; return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitWithStatement(node) { - var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node); + emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTryStatement(node) { - emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -80790,14 +83163,14 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); - writeSemicolon(); + writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); } // // Declarations @@ -80810,7 +83183,7 @@ var ts; function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); writeSpace(); - emitList(node, node.declarations, 272 /* VariableDeclarationList */); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { emitFunctionDeclarationOrExpression(node); @@ -80858,7 +83231,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -80910,7 +83283,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -80922,7 +83295,7 @@ var ts; emitHelpers(body); if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { decreaseIndent(); - emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); increaseIndent(); } else { @@ -80949,7 +83322,7 @@ var ts; emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65 /* ClassMembers */); + emitList(node, node.members, 129 /* ClassMembers */); writePunctuation("}"); if (indentedFlag) { decreaseIndent(); @@ -80962,10 +83335,10 @@ var ts; writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256 /* HeritageClauses */); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65 /* InterfaceMembers */); + emitList(node, node.members, 129 /* InterfaceMembers */); writePunctuation("}"); } function emitTypeAliasDeclaration(node) { @@ -80979,7 +83352,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -80988,7 +83361,7 @@ var ts; emit(node.name); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 81 /* EnumMembers */); + emitList(node, node.members, 145 /* EnumMembers */); writePunctuation("}"); } function emitModuleDeclaration(node) { @@ -81000,8 +83373,8 @@ var ts; emit(node.name); var body = node.body; if (!body) - return writeSemicolon(); - while (body.kind === 242 /* ModuleDeclaration */) { + return writeTrailingSemicolon(); + while (body.kind === 244 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); body = body.body; @@ -81016,23 +83389,23 @@ var ts; popNameGenerationScope(node); } function emitCaseBlock(node) { - emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node); - emitList(node, node.clauses, 65 /* CaseBlockClauses */); - emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node); + emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); - writeSemicolon(); + writeTrailingSemicolon(); } function emitModuleReference(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81041,29 +83414,29 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - emitTokenWithComment(143 /* FromKeyword */, node.importClause.end, writeKeyword, node); + emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); - writeSemicolon(); + writeTrailingSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); + var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node); writeSpace(); - emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node); + emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -81074,45 +83447,45 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node); + emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node); } else { - emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node); + emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitExportDeclaration(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node); + nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); var fromPos = node.exportClause ? node.exportClause.end : nextPos; - emitTokenWithComment(143 /* FromKeyword */, fromPos, writeKeyword, node); + emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamespaceExportDeclaration(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node); writeSpace(); emit(node.name); - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -81122,14 +83495,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -81148,7 +83521,7 @@ var ts; // function emitJsxElement(node) { emit(node.openingElement); - emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); emit(node.closingElement); } function emitJsxSelfClosingElement(node) { @@ -81160,7 +83533,7 @@ var ts; } function emitJsxFragment(node) { emit(node.openingFragment); - emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { @@ -81175,7 +83548,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { @@ -81186,7 +83558,7 @@ var ts; writePunctuation(">"); } function emitJsxAttributes(node) { - emitList(node, node.properties, 131328 /* JsxElementAttributes */); + emitList(node, node.properties, 262656 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); @@ -81206,7 +83578,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81217,13 +83589,13 @@ var ts; // Clauses // function emitCaseClause(node) { - emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node); + var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node); emitCaseOrDefaultClauseRest(node, node.statements, pos); } function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { @@ -81233,14 +83605,14 @@ var ts; ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); - var format = 81985 /* CaseOrDefaultClauseStatements */; + var format = 163969 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode); writeSpace(); - format &= ~(1 /* MultiLine */ | 64 /* Indented */); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); } else { - emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode); } emitList(parentNode, statements, format); } @@ -81248,15 +83620,15 @@ var ts; writeSpace(); writeTokenText(node.token, writeKeyword); writeSpace(); - emitList(node, node.types, 272 /* HeritageClauseTypes */); + emitList(node, node.types, 528 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -81293,7 +83665,7 @@ var ts; } function emitSpreadAssignment(node) { if (node.expression) { - writePunctuation("..."); + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); emitExpression(node.expression); } } @@ -81305,6 +83677,142 @@ var ts; emitInitializer(node.initializer, node.name.end, node); } // + // JSDoc + // + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // // Top-level nodes // function emitSourceFile(node) { @@ -81324,41 +83832,46 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.moduleName) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.amdDependencies) { for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { var dep = _b[_a]; if (dep.name) { - write("/// "); + writeComment("/// "); } else { - write("/// "); + writeComment("/// "); } writeLine(); } } for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { var directive = files_1[_c]; - write("/// "); + writeComment("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; - write("/// "); + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); writeLine(); } } @@ -81377,7 +83890,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 272 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -81417,13 +83930,14 @@ var ts; setSourceFile(sourceFile); emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); } + setSourceFile(undefined); } } function emitShebangIfNeeded(sourceFileOrBundle) { if (ts.isSourceFile(sourceFileOrBundle)) { var shebang = ts.getShebang(sourceFileOrBundle.text); if (shebang) { - write(shebang); + writeComment(shebang); writeLine(); return true; } @@ -81451,7 +83965,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328 /* Modifiers */); + emitList(node, modifiers, 262656 /* Modifiers */); writeSpace(); } } @@ -81465,7 +83979,7 @@ var ts; function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -81502,30 +84016,37 @@ var ts; else { writeLine(); increaseIndent(); - emit(node); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(5 /* EmbeddedStatement */, node); + } + else { + emit(node); + } decreaseIndent(); } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 24577 /* Decorators */); + emitList(parentNode, decorators, 49153 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26896 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures return emitTypeArguments(parentNode, parentNode.typeArguments); } - emitList(parentNode, typeParameters, 26896 /* TypeParameters */); + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1296 /* Parameters */); + emitList(parentNode, parameters, 2576 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81539,14 +84060,14 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); } else { emitParameters(parentNode, parameters); } } function emitParametersForIndexSignature(parentNode, parameters) { - emitList(parentNode, parameters, 4432 /* IndexSignatureParameters */); + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } function emitList(parentNode, children, format, start, count) { emitNodeList(emit, parentNode, children, format, start, count); @@ -81555,7 +84076,7 @@ var ts; emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 } function writeDelimiter(format) { - switch (format & 28 /* DelimitersMask */) { + switch (format & 60 /* DelimitersMask */) { case 0 /* None */: break; case 16 /* CommaDelimited */: @@ -81565,6 +84086,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8 /* AmpersandDelimited */: writeSpace(); writePunctuation("&"); @@ -81575,11 +84101,11 @@ var ts; if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; - if (isUndefined && format & 8192 /* OptionalIfUndefined */) { + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { return; } var isEmpty = children === undefined || start >= children.length || count === 0; - if (isEmpty && format & 16384 /* OptionalIfEmpty */) { + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); } @@ -81588,7 +84114,7 @@ var ts; } return; } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { // TODO: GH#18217 @@ -81603,23 +84129,23 @@ var ts; if (format & 1 /* MultiLine */) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { + else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { writeSpace(); } } else { // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; + var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 writeLine(); shouldEmitInterveningComments = false; } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 256 /* SpaceBetweenBraces */) { writeSpace(); } // Increase the indent, if requested. - if (format & 64 /* Indented */) { + if (format & 128 /* Indented */) { increaseIndent(); } // Emit each child. @@ -81628,14 +84154,19 @@ var ts; for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. - if (previousSibling) { + if (format & 32 /* AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { // i.e // function commentedParameters( // /* Parameter a */ // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -81643,14 +84174,14 @@ var ts; if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new // line, we should increase the indent. - if ((format & (3 /* LinesMask */ | 64 /* Indented */)) === 0 /* SingleLine */) { + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { increaseIndent(); shouldDecreaseIndentAfterEmit = true; } writeLine(); shouldEmitInterveningComments = false; } - else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { + else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { writeSpace(); } } @@ -81672,7 +84203,7 @@ var ts; previousSibling = child; } // Write a trailing comma, if requested. - var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; + var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { writePunctuation(","); } @@ -81682,25 +84213,25 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. - if (format & 64 /* Indented */) { + if (format & 128 /* Indented */) { decreaseIndent(); } // Write the closing line terminator or closing whitespace. if (shouldWriteClosingLineTerminator(parentNode, children, format)) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 256 /* SpaceBetweenBraces */) { writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { if (isEmpty && !isUndefined) { // TODO: GH#18217 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists @@ -81708,73 +84239,55 @@ var ts; writePunctuation(getClosingBracket(format)); } } - function commitPendingSemicolonInternal() { - if (pendingSemicolon) { - writeSemicolonInternal(); - pendingSemicolon = false; - } - } + // Writers function writeLiteral(s) { - commitPendingSemicolon(); writer.writeLiteral(s); } function writeStringLiteral(s) { - commitPendingSemicolon(); writer.writeStringLiteral(s); } function writeBase(s) { - commitPendingSemicolon(); writer.write(s); } function writeSymbol(s, sym) { - commitPendingSemicolon(); writer.writeSymbol(s, sym); } function writePunctuation(s) { - commitPendingSemicolon(); writer.writePunctuation(s); } - function deferWriteSemicolon() { - pendingSemicolon = true; - } - function writeSemicolonInternal() { - writer.writePunctuation(";"); + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); } function writeKeyword(s) { - commitPendingSemicolon(); writer.writeKeyword(s); } function writeOperator(s) { - commitPendingSemicolon(); writer.writeOperator(s); } function writeParameter(s) { - commitPendingSemicolon(); writer.writeParameter(s); } + function writeComment(s) { + writer.writeComment(s); + } function writeSpace() { - commitPendingSemicolon(); writer.writeSpace(" "); } function writeProperty(s) { - commitPendingSemicolon(); writer.writeProperty(s); } function writeLine() { - commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { - commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { - commitPendingSemicolon(); writer.decreaseIndent(); } function writeToken(token, pos, writer, contextNode) { - return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) : writeTokenText(token, writer, pos); } function writeTokenNode(node, writer) { @@ -81802,23 +84315,23 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = ts.guessIndentation(lines); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var lineText = lines_2[_a]; + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); - writeLine(); + writer.rawWrite(newLine); } } } - function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + function increaseIndentIf(value, writeSpaceIfNotIndenting) { if (value) { increaseIndent(); writeLine(); } - else if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); + else if (writeSpaceIfNotIndenting) { + writeSpace(); } } // Helper function to decrease the indent if we previously indented. Allows multiple @@ -81838,7 +84351,7 @@ var ts; return true; } if (format & 2 /* PreserveLines */) { - if (format & 32768 /* PreferNewLine */) { + if (format & 65536 /* PreferNewLine */) { return true; } var firstChild = children[0]; @@ -81877,10 +84390,10 @@ var ts; } function shouldWriteClosingLineTerminator(parentNode, children, format) { if (format & 1 /* MultiLine */) { - return (format & 65536 /* NoTrailingNewLine */) === 0; + return (format & 131072 /* NoTrailingNewLine */) === 0; } else if (format & 2 /* PreserveLines */) { - if (format & 32768 /* PreferNewLine */) { + if (format & 65536 /* PreferNewLine */) { return true; } var lastChild = ts.lastOrUndefined(children); @@ -81902,11 +84415,11 @@ var ts; if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { - return (format & 32768 /* PreferNewLine */) !== 0; + return (format & 65536 /* PreferNewLine */) !== 0; } return startsOnNewLine; } - return (format & 32768 /* PreferNewLine */) !== 0; + return (format & 65536 /* PreferNewLine */) !== 0; } function needsIndentation(parent, node1, node2) { parent = skipSynthesizedParentheses(parent); @@ -81926,7 +84439,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -81938,7 +84451,7 @@ var ts; else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } - else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); } else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { @@ -81946,19 +84459,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { - if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -81991,81 +84504,81 @@ var ts; if (!node) return; switch (node.kind) { - case 216 /* Block */: + case 218 /* Block */: ts.forEach(node.statements, generateNames); break; - case 231 /* LabeledStatement */: - case 229 /* WithStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 233 /* LabeledStatement */: + case 231 /* WithStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: generateNames(node.statement); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 272 /* CatchClause */: + case 274 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: generateNames(node.declarationList); break; - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: generateNames(node.importClause); break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -82074,12 +84587,12 @@ var ts; if (!node) return; switch (node.kind) { - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: generateNameIfNeeded(node.name); break; } @@ -82137,7 +84650,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +84729,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82259,23 +84772,23 @@ var ts; */ function generateNameForNode(node, flags) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 252 /* ExportAssignment */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 254 /* ExportAssignment */: return generateNameForExportDefault(); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return generateNameForClassExpression(); - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0 /* Auto */); @@ -82316,21 +84829,396 @@ var ts; // otherwise, return the original node for the source; return node; } + // Comments + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 238 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + // Source Maps + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, + /*nameIndex*/ undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } } ts.createPrinter = createPrinter; function createBracketsMap() { var brackets = []; - brackets[512 /* Braces */] = ["{", "}"]; - brackets[1024 /* Parenthesis */] = ["(", ")"]; - brackets[2048 /* AngleBrackets */] = ["<", ">"]; - brackets[4096 /* SquareBrackets */] = ["[", "]"]; + brackets[1024 /* Braces */] = ["{", "}"]; + brackets[2048 /* Parenthesis */] = ["(", ")"]; + brackets[4096 /* AngleBrackets */] = ["<", ">"]; + brackets[8192 /* SquareBrackets */] = ["[", "]"]; return brackets; } function getOpeningBracket(format) { - return brackets[format & 7680 /* BracketsMask */][0]; + return brackets[format & 15360 /* BracketsMask */][0]; } function getClosingBracket(format) { - return brackets[format & 7680 /* BracketsMask */][1]; + return brackets[format & 15360 /* BracketsMask */][1]; } // Flags enum to track count of temp variables and a few dedicated names var TempFlags; @@ -82730,17 +85618,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +85651,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +85661,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +85669,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +85681,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +85693,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +85709,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(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); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +85743,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +85770,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +85858,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +85874,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83021,7 +85913,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -83034,7 +85926,7 @@ var ts; result = cache.get(name); } else { - cache.set(name, result = loader(name, containingFile)); + cache.set(name, result = loader(name, containingFile, redirectedReference)); } resolutions.push(result); } @@ -83044,7 +85936,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +85945,11 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + var seenResolvedRefs; + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,9 +85970,39 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || + return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolution(sourceFile.path); } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + // If child project references are upto date, this project reference is uptodate + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { @@ -83084,21 +86011,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83121,7 +86044,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var modifiedFilePaths; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -83149,16 +86072,15 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; - var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; @@ -83170,16 +86092,16 @@ var ts; } else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217 - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; } else { - var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217 - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). @@ -83195,30 +86117,34 @@ var ts; // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files - var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; if (projectReferences) { - for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { - var ref = projectReferences_1[_i]; - var parsedRef = parseProjectReferenceConfigFile(ref); - resolvedProjectReferences.push(parsedRef); - if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); - processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); } } } ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); @@ -83232,7 +86158,7 @@ var ts; // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. - if (!skipDefaultLib) { + if (rootNames.length && !skipDefaultLib) { // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file var defaultLibraryFileName = getDefaultLibraryFileName(); @@ -83257,10 +86183,18 @@ var ts; var oldSourceFiles = oldProgram.getSourceFiles(); for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { var oldSourceFile = oldSourceFiles_1[_a]; - if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { - host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); } // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; @@ -83299,7 +86233,12 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +86272,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83362,13 +86301,13 @@ var ts; } return classifiableNames; } - function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, // the best we can do is fallback to the default logic. - return resolveModuleNamesWorker(moduleNames, containingFile); + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); } - var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { // `file` was created for the new program. // @@ -83378,13 +86317,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83431,7 +86370,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -83442,7 +86381,7 @@ var ts; } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) : ts.emptyArray; // Combine results of resolutions and predicted results if (!result) { @@ -83468,9 +86407,9 @@ var ts; return result; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,24 +86417,35 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); - if (!firstUnmodifiedFile) { + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { return false; } if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); } return true; } } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + // If array of references is changed, we cant resue old program + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return 0 /* Not */; @@ -83516,36 +86466,14 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); - if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } - for (var i = 0; i < projectReferences.length; i++) { - var oldRef = oldRefs[i]; - if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); - if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { - // Resolved project reference has gone missing or changed - return oldProgram.structureIsReused = 0 /* Not */; - } - } - else { - // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { - return oldProgram.structureIsReused = 0 /* Not */; - } - } - } + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0 /* Not */; } - else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; - var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2 /* Completely */; // If the missing file paths are now present, it can change the progam structure, @@ -83564,7 +86492,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,8 +86519,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; - filePaths.push(newSourceFile.path); + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { // If there are 2 different source files for the same package name and at least one of them changes, @@ -83653,15 +86584,23 @@ var ts; if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } - modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } // try to verify results of module resolution - for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { - var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { @@ -83673,8 +86612,9 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -83694,28 +86634,29 @@ var ts; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping - for (var i = 0; i < newSourceFiles.length; i++) { - filesByName.set(filePaths[i], newSourceFiles[i]); + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); // Set the file as found during node modules search if it was found that way in old progra, - if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { - sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { - var modifiedFile = modifiedSourceFiles_2[_c]; + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +86667,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +86682,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +86745,7 @@ var ts; // get any preEmit diagnostics, not just the ones 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) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +86811,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +86902,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -83969,22 +86912,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } // falls through - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 235 /* VariableDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 237 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -83992,41 +86935,41 @@ var ts; } } switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: var heritageClause = node; - if (heritageClause.token === 108 /* ImplementsKeyword */) { + if (heritageClause.token === 109 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 210 /* AsExpression */: + case 212 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; @@ -84039,51 +86982,51 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, 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)); } switch (parent.kind) { - case 238 /* ClassDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 240 /* ClassDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } // falls through - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 217 /* VariableStatement */); + return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */); } break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 115 /* StaticKeyword */) { + if (modifier.kind !== 116 /* StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } return; } break; - case 149 /* Parameter */: + case 151 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 209 /* ExpressionWithTypeArguments */: - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -84100,24 +87043,24 @@ var ts; for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { var modifier = modifiers_1[_i]; switch (modifier.kind) { - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: if (isConstValid) { continue; } // to report error, // falls through - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 124 /* DeclareKeyword */: - case 117 /* AbstractKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 125 /* DeclareKeyword */: + case 118 /* AbstractKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. - case 115 /* StaticKeyword */: - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 116 /* StaticKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: } } } @@ -84165,10 +87108,22 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; } function getGlobalDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; } function getConfigFileParsingDiagnostics() { return configFileParsingDiagnostics || ts.emptyArray; @@ -84180,15 +87135,15 @@ var ts; return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 71 /* Identifier */ - ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText - : b.kind === 9 /* StringLiteral */ && a.text === b.text; + return a.kind === 72 /* Identifier */ + ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 10 /* StringLiteral */ && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84210,12 +87165,9 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, /*inAmbientModule*/ false); - if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(node); - } } if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(file.endOfFileToken); + collectDynamicImportOrRequireCalls(file); } file.imports = imports || ts.emptyArray; file.moduleAugmentations = moduleAugmentations || ts.emptyArray; @@ -84263,24 +87215,37 @@ var ts; } } } - function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { - imports = ts.append(imports, node.arguments[0]); - } - // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. - else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { - imports = ts.append(imports, node.arguments[0]); - } - else if (ts.isLiteralImportTypeNode(node)) { - imports = ts.append(imports, node.argument.literal); - } - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } } } - function collectDynamicImportOrRequireCallsForEachChild(node) { - ts.forEachChild(node, collectDynamicImportOrRequireCalls); + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } } } function getLibFileFromReference(ref) { @@ -84296,7 +87261,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84352,11 +87317,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84371,6 +87339,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84436,9 +87405,9 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); - filesByName.set(path, dupFile); + addFileToFilesByName(dupFile, path, redirectedPath); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); return dupFile; @@ -84449,14 +87418,12 @@ var ts; sourceFileToPackageName.set(path, packageId.name); } } - filesByName.set(path, file); - if (redirectedPath) { - filesByName.set(redirectedPath, file); - } + addFileToFilesByName(file, path, redirectedPath); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84485,25 +87452,90 @@ var ts; } return file; } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { - return undefined; - } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); }); - return result; + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + // Visit project references first + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +87545,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84531,6 +87563,8 @@ var ts; } var saveResolution = true; if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 @@ -84555,6 +87589,8 @@ var ts; processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; } else { fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 @@ -84599,8 +87635,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +87644,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +87664,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,61 +87684,61 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } return allFilesBelongToPath; } function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); return undefined; } - sourceFile.path = toPath(refPath); + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); - return { commandLine: commandLine, sourceFile: sourceFile }; - } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84731,41 +87766,18 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); } } - if (projectReferences) { - for (var i = 0; i < projectReferences.length; i++) { - var ref = projectReferences[i]; - var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; - if (resolvedRefOpts === undefined) { - createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); - continue; - } - if (!resolvedRefOpts.composite) { - createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - } - if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); - } - } - else { - createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); - } - } - } - } + verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +87827,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84833,12 +87845,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -84850,7 +87862,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84863,9 +87875,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84876,19 +87888,19 @@ var ts; // 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; })) { + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -84946,6 +87958,35 @@ var ts; } } } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { var needCompilerDiagnostic = true; var pathsSyntax = getOptionPathsSyntax(); @@ -84996,10 +88037,10 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } - function createDiagnosticForReference(index, message, arg0, arg1) { - var referencesSyntax = getProjectReferencesSyntax(); + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); if (referencesSyntax && referencesSyntax.elements.length > index) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); } else { programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); @@ -85013,22 +88054,6 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } - function getProjectReferencesSyntax() { - if (_referencesArrayLiteralSyntax === undefined) { - _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile) { - var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217 - for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { - var prop = _a[_i]; - if (ts.isArrayLiteralExpression(prop.initializer)) { - _referencesArrayLiteralSyntax = prop.initializer; - break; - } - } - } - } - return _referencesArrayLiteralSyntax; - } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword @@ -85079,7 +88104,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,25 +88121,26 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85153,7 +88179,7 @@ var ts; var res = imports.map(function (i) { return i.text; }); for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9 /* StringLiteral */) { + if (aug.kind === 10 /* StringLiteral */) { res.push(aug.text); } // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. @@ -85184,7 +88210,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +88220,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +88249,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,11 +88260,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85338,6 +88404,11 @@ var ts; var latestSignature; if (sourceFile.isDeclarationFile) { latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } } else { var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); @@ -85403,7 +88474,7 @@ var ts; return getAllFileNames(state, programOfThisState); } // If this is non module emit, or its a global file, it depends on all the source files - if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { return getAllFileNames(state, programOfThisState); } // Get the references, traversing deep from the referenceMap @@ -85462,6 +88533,20 @@ var ts; } return true; } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } /** * Gets all files of the program excluding the default library file */ @@ -85502,7 +88587,7 @@ var ts; * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { - if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } var compilerOptions = programOfThisState.getCompilerOptions(); @@ -85552,8 +88637,9 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && - !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { @@ -85568,6 +88654,8 @@ var ts; // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -85585,6 +88673,13 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } // Unchanged file copy diagnostics var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { @@ -85668,18 +88763,31 @@ var ts; // If there are no more diagnostics from old cache, done return; } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } // If there was change in signature for the changed file, // then delete the semantic diagnostics for files that are affected by using exports of this module if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { return; } ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { return exportedModules && exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); })) { return; } @@ -85687,16 +88795,44 @@ var ts; ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); }); } /** * removes the semantic diagnostics of files referencing referencedPath and * returns true if there are no more semantic diagnostics from old state */ - function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { - return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); }); } /** @@ -85705,7 +88841,7 @@ var ts; */ function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -85752,7 +88888,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +88901,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +89082,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -85971,6 +89114,10 @@ var ts; /*@internal*/ var ts; (function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; ts.maxNumberOfFilesToIterateForInvalidation = 256; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; @@ -85984,11 +89131,11 @@ var ts; // The key in the map is source file's path. // The values are Map of resolutions with key being name lookedup. var resolvedModuleNames = ts.createMap(); - var perDirectoryResolvedModuleNames = ts.createMap(); - var nonRelaticeModuleNameCache = ts.createMap(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); var resolvedTypeReferenceDirectives = ts.createMap(); - var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -86012,6 +89159,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -86073,7 +89221,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -86089,15 +89237,15 @@ var ts; } }); } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { return primaryResult; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86108,10 +89256,11 @@ var ts; // Default return the result from the first pass return primaryResult; } - function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { var path = resolutionHost.toPath(containingFile); var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); var perDirectoryResolution = perDirectoryCache.get(dirPath); if (!perDirectoryResolution) { perDirectoryResolution = ts.createMap(); @@ -86120,22 +89269,28 @@ var ts; var resolvedModules = []; var compilerOptions = resolutionHost.getCompilationSettings(); var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; var seenNamesInFile = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { var name = names_2[_i]; var resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { var existingResolution = resolution; var resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { resolution = resolutionInDirectory; } else { - resolution = loader(name, containingFile, compilerOptions, resolutionHost); + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); @@ -86151,7 +89306,7 @@ var ts; } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217 + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); } // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { @@ -86179,12 +89334,14 @@ var ts; return oldResult.resolvedFileName === newResult.resolvedFileName; } } - function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { - return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, /*reusedNames*/ undefined, /*logChanges*/ false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); } function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); @@ -86227,15 +89384,10 @@ var ts; } return true; } - function filterFSRootDirectoriesToWatch(watchPath, dirPath) { - if (!canWatchDirectory(dirPath)) { - watchPath.ignore = true; - } - return watchPath; - } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86251,13 +89403,13 @@ var ts; } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // If directory path contains node module, get the most parent node_modules directory for watching - while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { + while (ts.pathContainsNodeModules(dirPath)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } // If the directory is node_modules use it to watch, always watch it recursively if (isNodeModulesDirectory(dirPath)) { - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -86275,7 +89427,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive }, dirPath); + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -86304,8 +89456,9 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, nonRecursive = _a.nonRecursive, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; // If the failed lookup location path is not one of the supported extensions, // store it in the custom path if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { @@ -86358,8 +89511,9 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { if (refCount === 1) { @@ -86407,6 +89561,22 @@ var ts; cache.delete(filePath); } } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + // If this file is input file for the referenced project, get it + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } function removeResolutionsOfFile(filePath) { removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); @@ -86468,6 +89638,9 @@ var ts; isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; } else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; // Some file or directory in the watching directory is created // Return early if it does not have any of the watching extension or not the custom failed lookup path var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); @@ -86508,8 +89681,8 @@ var ts; if (isInDirectoryPath(rootPath, typeRootPath)) { return rootPath; } - var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info @@ -86575,121 +89748,118 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +89923,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +89940,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +89961,30 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86827,20 +89993,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86855,12 +90019,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86923,13 +90089,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +90157,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,13 +90165,12 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } return false; } - /** @internal */ ts.screenStartingMessageCodes = [ ts.Diagnostics.Starting_compilation_in_watch_mode.code, ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, @@ -87028,10 +90211,27 @@ var ts; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +90247,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87066,7 +90266,7 @@ var ts; } } if (reportSummary) { - reportSummary(diagnostics.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length); + reportSummary(getErrorCountForSummary(diagnostics)); } if (emitSkipped && diagnostics.length > 0) { // If the emitter didn't emit anything, then pass that value along. @@ -87081,6 +90281,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +90312,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +90326,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87133,15 +90345,7 @@ var ts; function emitFilesAndReportErrorUsingBuilder(builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - var reportSummary = function (errorCount) { - if (errorCount === 1) { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions); - } - else { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions); - } - }; - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); } } /** @@ -87166,18 +90370,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,9 +90405,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87215,7 +90421,8 @@ var ts; fileExists: function (path) { return host.fileExists(path); }, readFile: readFile, getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); @@ -87273,7 +90480,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87282,11 +90490,11 @@ var ts; /*logChangesWhenResolvingModule*/ false); // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names compilerHost.resolveModuleNames = host.resolveModuleNames ? - (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : - (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? - (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : - (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; synchronizeProgram(); // Update the wild card directory watch @@ -87311,9 +90519,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +90546,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87460,8 +90668,8 @@ var ts; var hostSourceFile = sourceFilesCache.get(path); return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); } - function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { - var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); // If this is the source file thats in the cache and new program doesnt need it, // remove the cached entry. // Note we arent deleting entry if file became missing in new program or @@ -87475,8 +90683,10 @@ var ts; if (hostSourceFileInfo.fileWatcher) { hostSourceFileInfo.fileWatcher.close(); } - sourceFilesCache.delete(oldSourceFile.path); - resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } } } } @@ -87519,12 +90729,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87550,7 +90755,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87559,6 +90766,7 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { resolutionCache.invalidateResolutionOfFile(path); } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program scheduleProgramUpdate(); @@ -87599,6 +90807,8 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { @@ -87637,6 +90847,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +90869,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +90887,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +90958,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +90973,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,808 +90994,827 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects - }; - } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } - } - ts.performBuild = performBuild; /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +91850,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +91862,144 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +92007,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88684,7 +92036,6 @@ var ts; : undefined; } server.findArgument = findArgument; - /*@internal*/ function nowString() { // E.g. "12:34:56.789" var d = new Date(); @@ -88698,13 +92049,11 @@ var ts; (function (ts) { var JsTyping; (function (JsTyping) { - /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; - /* @internal */ JsTyping.nodeCoreModuleList = [ "assert", "async_hooks", @@ -88743,7 +92092,6 @@ var ts; "vm", "zlib" ]; - /* @internal */ JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); @@ -88776,7 +92124,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +92209,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +92247,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +92338,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89085,12 +92368,6 @@ var ts; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); /* @internal */ ts.emptyOptions = {}; - var TextChange = /** @class */ (function () { - function TextChange() { - } - return TextChange; - }()); - ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { HighlightSpanKind["none"] = "none"; @@ -89104,6 +92381,32 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + function getDefaultFormatCodeSettings(newLineCharacter) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: newLineCharacter || "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + /* @internal */ + ts.testFormatSettings = getDefaultFormatCodeSettings("\n"); var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89165,8 +92468,9 @@ var ts; TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; - TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; - TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; + TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral"; + TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral"; })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); var ScriptElementKind; (function (ScriptElementKind) { @@ -89249,6 +92553,12 @@ var ts; ScriptElementKindModifier["staticModifier"] = "static"; ScriptElementKindModifier["abstractModifier"] = "abstract"; ScriptElementKindModifier["optionalModifier"] = "optional"; + ScriptElementKindModifier["dtsModifier"] = ".d.ts"; + ScriptElementKindModifier["tsModifier"] = ".ts"; + ScriptElementKindModifier["tsxModifier"] = ".tsx"; + ScriptElementKindModifier["jsModifier"] = ".js"; + ScriptElementKindModifier["jsxModifier"] = ".jsx"; + ScriptElementKindModifier["jsonModifier"] = ".json"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); var ClassificationTypeNames; (function (ClassificationTypeNames) { @@ -89256,6 +92566,7 @@ var ts; ClassificationTypeNames["identifier"] = "identifier"; ClassificationTypeNames["keyword"] = "keyword"; ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["bigintLiteral"] = "bigint"; ClassificationTypeNames["operator"] = "operator"; ClassificationTypeNames["stringLiteral"] = "string"; ClassificationTypeNames["whiteSpace"] = "whitespace"; @@ -89302,6 +92613,7 @@ var ts; ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral"; })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); })(ts || (ts = {})); // These utilities are common to multiple language service features. @@ -89319,36 +92631,37 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 272 /* CatchClause */: - case 265 /* JsxAttribute */: + case 237 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 274 /* CatchClause */: + case 267 /* JsxAttribute */: return 1 /* Value */; - case 148 /* TypeParameter */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 166 /* TypeLiteral */: + case 150 /* TypeParameter */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 168 /* TypeLiteral */: return 2 /* Type */; - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 276 /* EnumMember */: - case 238 /* ClassDeclaration */: + case 278 /* EnumMember */: + case 240 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -89358,26 +92671,26 @@ var ts; else { return 4 /* Namespace */; } - case 241 /* EnumDeclaration */: - case 250 /* NamedImports */: - case 251 /* ImportSpecifier */: - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: - case 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 243 /* EnumDeclaration */: + case 252 /* NamedImports */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89409,11 +92722,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 146 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 246 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + var name = node.kind === 148 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 248 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 146 /* QualifiedName */) { + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -89425,27 +92738,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 146 /* QualifiedName */) { - while (root.parent && root.parent.kind === 146 /* QualifiedName */) { + if (root.parent.kind === 148 /* QualifiedName */) { + while (root.parent && root.parent.kind === 148 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 162 /* TypeReference */ && !isLastClause; + return root.parent.kind === 164 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 187 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 187 /* PropertyAccessExpression */) { + if (root.parent.kind === 189 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 189 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 209 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 271 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 211 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 273 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 238 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || - (decl.kind === 239 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); + return (decl.kind === 240 /* ClassDeclaration */ && root.parent.parent.token === 109 /* ImplementsKeyword */) || + (decl.kind === 241 /* InterfaceDeclaration */ && root.parent.parent.token === 86 /* ExtendsKeyword */); } return false; } @@ -89454,17 +92767,17 @@ var ts; node = node.parent; } switch (node.kind) { - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 176 /* ThisType */: + case 178 /* ThisType */: return true; } switch (node.parent.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return true; - case 181 /* ImportType */: + case 183 /* ImportType */: return !node.parent.isTypeOf; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; @@ -89491,7 +92804,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 231 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 233 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -89499,53 +92812,64 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { - return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; + return node.kind === 72 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; + return node.kind === 72 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; } ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; function isLabelName(node) { return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } ts.isLabelName = isLabelName; + function isTagName(node) { + return ts.isJSDocTag(node.parent) && node.parent.tagName === node; + } + ts.isTagName = isTagName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 242 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 244 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { - return node.kind === 71 /* Identifier */ && + return node.kind === 72 /* Identifier */ && ts.isFunctionLike(node.parent) && node.parent.name === node; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 273 /* PropertyAssignment */: - case 276 /* EnumMember */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 242 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 278 /* EnumMember */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 244 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return true; - case 180 /* LiteralType */: - return node.parent.parent.kind === 178 /* IndexedAccessType */; + case 182 /* LiteralType */: + return node.parent.parent.kind === 180 /* IndexedAccessType */; default: return false; } @@ -89569,17 +92893,17 @@ var ts; return undefined; } switch (node.kind) { - case 277 /* SourceFile */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: return node; } } @@ -89587,51 +92911,54 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return "class" /* classElement */; - case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 240 /* TypeAliasDeclaration */: - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 242 /* TypeAliasDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 241 /* EnumDeclaration */: return "enum" /* enumElement */; - case 235 /* VariableDeclaration */: + case 243 /* EnumDeclaration */: return "enum" /* enumElement */; + case 237 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return "function" /* functionElement */; - case 156 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 157 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 158 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 159 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return "method" /* memberFunctionElement */; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return "property" /* memberVariableElement */; - case 160 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 159 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 158 /* CallSignature */: return "call" /* callSignatureElement */; - case 155 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 148 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 276 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 149 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 246 /* ImportEqualsDeclaration */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: - case 249 /* NamespaceImport */: + case 162 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 161 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 160 /* CallSignature */: return "call" /* callSignatureElement */; + case 157 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 150 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 278 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 151 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + case 251 /* NamespaceImport */: return "alias" /* alias */; - case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: case 0 /* None */: return "" /* unknown */; case 1 /* ExportsProperty */: @@ -89652,7 +92979,7 @@ var ts; return "" /* unknown */; } } - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; @@ -89668,12 +92995,12 @@ var ts; ts.getNodeKind = getNodeKind; function isThis(node) { switch (node.kind) { - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: // case SyntaxKind.ThisType: TODO: GH#9267 return true; - case 71 /* Identifier */: + case 72 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 149 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 151 /* Parameter */; default: return false; } @@ -89738,42 +93065,42 @@ var ts; return false; } switch (n.kind) { - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 186 /* ObjectLiteralExpression */: - case 182 /* ObjectBindingPattern */: - case 166 /* TypeLiteral */: - case 216 /* Block */: - case 243 /* ModuleBlock */: - case 244 /* CaseBlock */: - case 250 /* NamedImports */: - case 254 /* NamedExports */: - return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile); - case 272 /* CatchClause */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 168 /* TypeLiteral */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 246 /* CaseBlock */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); + case 274 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 190 /* NewExpression */: + case 192 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 189 /* CallExpression */: - case 193 /* ParenthesizedExpression */: - case 175 /* ParenthesizedType */: - return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 191 /* CallExpression */: + case 195 /* ParenthesizedExpression */: + case 177 /* ParenthesizedType */: + return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 159 /* ConstructSignature */: - case 158 /* CallSignature */: - case 195 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 197 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -89782,66 +93109,66 @@ var ts; } // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. - return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); - case 242 /* ModuleDeclaration */: + return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); + case 244 /* ModuleDeclaration */: return !!n.body && isCompletedNode(n.body, sourceFile); - case 220 /* IfStatement */: + case 222 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile); - case 185 /* ArrayLiteralExpression */: - case 183 /* ArrayBindingPattern */: - case 188 /* ElementAccessExpression */: - case 147 /* ComputedPropertyName */: - case 168 /* TupleType */: - return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile); - case 160 /* IndexSignature */: + hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); + case 187 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 190 /* ElementAccessExpression */: + case 149 /* ComputedPropertyName */: + case 170 /* TupleType */: + return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); + case 162 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 221 /* DoStatement */: + case 223 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile) - ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile) + return hasChildOfKind(n, 107 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 197 /* TypeOfExpression */: - case 196 /* DeleteExpression */: - case 198 /* VoidExpression */: - case 205 /* YieldExpression */: - case 206 /* SpreadElement */: + case 199 /* TypeOfExpression */: + case 198 /* DeleteExpression */: + case 200 /* VoidExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 253 /* ExportDeclaration */: - case 247 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -89858,7 +93185,7 @@ var ts; if (lastChild.kind === expectedLastToken) { return true; } - else if (lastChild.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -89993,7 +93320,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +93338,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); 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, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +93347,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90084,25 +93409,25 @@ var ts; if (!token) { return false; } - if (token.kind === 10 /* JsxText */) { + if (token.kind === 11 /* JsxText */) { return true; } //
Hello |
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 10 /* JsxText */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) { return true; } //
{ |
or
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 268 /* JsxExpression */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 270 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 268 /* JsxExpression */) { + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 270 /* JsxExpression */) { return true; } //
|
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 261 /* JsxClosingElement */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 263 /* JsxClosingElement */) { return true; } return false; @@ -90116,6 +93441,20 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; + function isInJSXText(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (ts.isJsxText(token)) { + return true; + } + if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + if (token.kind === 28 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + return false; + } + ts.isInJSXText = isInJSXText; function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { var tokenKind = token.kind; var remainingMatchingTokens = 0; @@ -90162,7 +93501,7 @@ var ts; var nTypeArguments = 0; while (token) { switch (token.kind) { - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // Found the beginning of the generic argument expression token = findPrecedingToken(token.getFullStart(), sourceFile); if (!token || !ts.isIdentifier(token)) @@ -90172,53 +93511,54 @@ var ts; } remainingLessThanTokens--; break; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: remainingLessThanTokens = +3; break; - case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: remainingLessThanTokens = +2; break; - case 29 /* GreaterThanToken */: + case 30 /* GreaterThanToken */: remainingLessThanTokens++; break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); + token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile); if (!token) return undefined; break; - case 20 /* CloseParenToken */: + case 21 /* CloseParenToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); + token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile); if (!token) return undefined; break; - case 22 /* CloseBracketToken */: + case 23 /* CloseBracketToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); + token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile); if (!token) return undefined; break; // Valid tokens in a type name. Skip. - case 26 /* CommaToken */: + case 27 /* CommaToken */: nTypeArguments++; break; - case 36 /* EqualsGreaterThanToken */: - case 71 /* Identifier */: - case 9 /* StringLiteral */: + case 37 /* EqualsGreaterThanToken */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 103 /* TypeOfKeyword */: - case 85 /* ExtendsKeyword */: - case 128 /* KeyOfKeyword */: - case 23 /* DotToken */: - case 49 /* BarToken */: - case 55 /* QuestionToken */: - case 56 /* ColonToken */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 104 /* TypeOfKeyword */: + case 86 /* ExtendsKeyword */: + case 129 /* KeyOfKeyword */: + case 24 /* DotToken */: + case 50 /* BarToken */: + case 56 /* QuestionToken */: + case 57 /* ColonToken */: break; default: if (ts.isTypeNode(token)) { @@ -90250,7 +93590,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90273,10 +93613,10 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 162 /* TypeReference */ || node.kind === 189 /* CallExpression */) { + if (node.kind === 164 /* TypeReference */ || node.kind === 191 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 238 /* ClassDeclaration */ || node.kind === 239 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 240 /* ClassDeclaration */ || node.kind === 241 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -90287,8 +93627,8 @@ var ts; } ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { - if (kind === 9 /* StringLiteral */ - || kind === 12 /* RegularExpressionLiteral */ + if (kind === 10 /* StringLiteral */ + || kind === 13 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; } @@ -90296,7 +93636,7 @@ var ts; } ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; function isPunctuation(kind) { - return 17 /* FirstPunctuation */ <= kind && kind <= 70 /* LastPunctuation */; + return 18 /* FirstPunctuation */ <= kind && kind <= 71 /* LastPunctuation */; } ts.isPunctuation = isPunctuation; function isInsideTemplateLiteral(node, position, sourceFile) { @@ -90306,9 +93646,9 @@ var ts; ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: return true; } return false; @@ -90321,18 +93661,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 185 /* ArrayLiteralExpression */ || - node.kind === 186 /* ObjectLiteralExpression */) { + if (node.kind === 187 /* ArrayLiteralExpression */ || + node.kind === 188 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 202 /* BinaryExpression */ && + if (node.parent.kind === 204 /* BinaryExpression */ && node.parent.left === node && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { + node.parent.operatorToken.kind === 59 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 225 /* ForOfStatement */ && + if (node.parent.kind === 227 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -90340,7 +93680,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 273 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 275 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -90364,7 +93704,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +93712,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90384,21 +93724,22 @@ var ts; } ts.createTextChange = createTextChange; ts.typeKeywords = [ - 119 /* AnyKeyword */, - 122 /* BooleanKeyword */, - 86 /* FalseKeyword */, - 128 /* KeyOfKeyword */, - 131 /* NeverKeyword */, - 95 /* NullKeyword */, - 134 /* NumberKeyword */, - 135 /* ObjectKeyword */, - 137 /* StringKeyword */, - 138 /* SymbolKeyword */, - 101 /* TrueKeyword */, - 105 /* VoidKeyword */, - 140 /* UndefinedKeyword */, - 141 /* UniqueKeyword */, - 142 /* UnknownKeyword */, + 120 /* AnyKeyword */, + 146 /* BigIntKeyword */, + 123 /* BooleanKeyword */, + 87 /* FalseKeyword */, + 129 /* KeyOfKeyword */, + 132 /* NeverKeyword */, + 96 /* NullKeyword */, + 135 /* NumberKeyword */, + 136 /* ObjectKeyword */, + 138 /* StringKeyword */, + 139 /* SymbolKeyword */, + 102 /* TrueKeyword */, + 106 /* VoidKeyword */, + 141 /* UndefinedKeyword */, + 142 /* UniqueKeyword */, + 143 /* UnknownKeyword */, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); @@ -90434,7 +93775,7 @@ var ts; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { - return name.kind === 147 /* ComputedPropertyName */ + return name.kind === 149 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.getTextOfIdentifierOrLiteral(name); @@ -90510,19 +93851,20 @@ var ts; } return ts.firstDefined(symbol.declarations, function (decl) { var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined; + return name && name.kind === 72 /* Identifier */ ? name.escapedText : undefined; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { - // See GH#16922 - ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); - return propSymbol.target; - } - return propSymbol; + return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; /** @@ -90575,7 +93917,6 @@ var ts; return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); } ts.findModifier = findModifier; - /* @internal */ function insertImport(changes, sourceFile, importDecl) { var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); if (lastImportDeclaration) { @@ -90599,7 +93940,7 @@ var ts; /* @internal */ (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 149 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 151 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -90625,6 +93966,7 @@ var ts; writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, @@ -90633,7 +93975,7 @@ var ts; writeSymbol: writeSymbol, writeLine: writeLine, write: unknownWrite, - writeTextOfNode: unknownWrite, + writeComment: unknownWrite, getText: function () { return ""; }, getTextPos: function () { return 0; }, getColumn: function () { return 0; }, @@ -90784,7 +94126,6 @@ var ts; return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; - /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -90818,9 +94159,7 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { - return !!location.parent && - (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && - location.parent.propertyName === location; + return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; /** @@ -90866,6 +94205,13 @@ var ts; return position; } ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; + function getPrecedingNonSpaceCharacterPosition(text, position) { + while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) { + position -= 1; + } + return position + 1; + } + ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition; /** * Creates a deep, memberwise clone of a node with no source map location. * @@ -90883,7 +94229,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +94237,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -90906,14 +94252,14 @@ var ts; ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_7 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_7)) { - clone_7.textSourceNode = node; + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_7)) { - clone_7.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_7, node); + return ts.setTextRange(clone_8, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -90932,7 +94278,6 @@ var ts; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - /* @internal */ function suppressLeadingAndTrailingTrivia(node) { suppressLeadingTrivia(node); suppressTrailingTrivia(node); @@ -90941,7 +94286,6 @@ var ts; /** * Sets EmitFlags to suppress leading trivia on the node. */ - /* @internal */ function suppressLeadingTrivia(node) { addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); } @@ -90949,7 +94293,6 @@ var ts; /** * Sets EmitFlags to suppress trailing trivia on the node. */ - /* @internal */ function suppressTrailingTrivia(node) { addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } @@ -90963,7 +94306,6 @@ var ts; function getFirstChild(node) { return node.forEachChild(function (child) { return child; }); } - /* @internal */ function getUniqueName(baseName, sourceFile) { var nameText = baseName; for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { @@ -90977,7 +94319,6 @@ var ts; * to be on the reference, rather than the declaration, because it's closer to where the * user was before extracting it. */ - /* @internal */ function getRenameLocation(edits, renameFilename, name, preferLastLocation) { var delta = 0; var lastPos = -1; @@ -91031,6 +94372,72 @@ var ts; idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 192 /* NewExpression */: + return checker.getContextualType(parent); + case 204 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 271 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + ts.getContextualTypeFromParent = getContextualTypeFromParent; + function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } + } + ts.quote = quote; + function isEqualityOperatorKind(kind) { + switch (kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return true; + default: + return false; + } + } + ts.isEqualityOperatorKind = isEqualityOperatorKind; + function isStringLiteralOrTemplate(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + return true; + default: + return false; + } + } + ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate; + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + ts.hasIndexSignature = hasIndexSignature; + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } + ts.getSwitchedType = getSwitchedType; })(ts || (ts = {})); var ts; (function (ts) { @@ -91069,7 +94476,7 @@ var ts; text = prefix + text; var offset = prefix.length; if (pushTemplate) { - templateStack.push(14 /* TemplateHead */); + templateStack.push(15 /* TemplateHead */); } scanner.setText(text); var endOfLineState = 0 /* None */; @@ -91111,65 +94518,65 @@ var ts; } while (token !== 1 /* EndOfFileToken */); function handleToken() { switch (token) { - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 12 /* RegularExpressionLiteral */) { - token = 12 /* RegularExpressionLiteral */; + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + token = 13 /* RegularExpressionLiteral */; } break; - case 27 /* LessThanToken */: - if (lastNonTriviaToken === 71 /* Identifier */) { + case 28 /* LessThanToken */: + if (lastNonTriviaToken === 72 /* Identifier */) { // Could be the start of something generic. Keep track of that by bumping // up the current count of generic contexts we may be in. angleBracketStack++; } break; - case 29 /* GreaterThanToken */: + case 30 /* GreaterThanToken */: if (angleBracketStack > 0) { // If we think we're currently in something generic, then mark that that // generic entity is complete. angleBracketStack--; } break; - case 119 /* AnyKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: + case 120 /* AnyKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* 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, // causing a noisy experience for the user. - token = 71 /* Identifier */; + token = 72 /* Identifier */; } break; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: templateStack.push(token); break; - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { templateStack.push(token); } break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 14 /* TemplateHead */) { + if (lastTemplateStackToken === 15 /* TemplateHead */) { token = scanner.reScanTemplateToken(); // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. - if (token === 16 /* TemplateTail */) { + if (token === 17 /* TemplateTail */) { templateStack.pop(); } else { - ts.Debug.assertEqual(token, 15 /* TemplateMiddle */, "Should have been a template middle."); + ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle."); } } else { - ts.Debug.assertEqual(lastTemplateStackToken, 17 /* OpenBraceToken */, "Should have been an open brace"); + ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace"); templateStack.pop(); } } @@ -91178,15 +94585,15 @@ var ts; if (!ts.isKeyword(token)) { break; } - if (lastNonTriviaToken === 23 /* DotToken */) { - token = 71 /* Identifier */; + if (lastNonTriviaToken === 24 /* DotToken */) { + token = 72 /* Identifier */; } else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { // We have two keywords in a row. Only treat the second as a keyword if // it's a sequence that could legally occur in the language. Otherwise // treat it as an identifier. This way, if someone writes "private var" // we recognize that 'var' is actually an identifier here. - token = 71 /* Identifier */; + token = 72 /* Identifier */; } } } @@ -91200,22 +94607,23 @@ var ts; /// we have a series of divide operator. this list allows us to be more accurate by ruling out /// locations where a regexp cannot exist. var noRegexTable = ts.arrayToNumericMap([ - 71 /* Identifier */, - 9 /* StringLiteral */, + 72 /* Identifier */, + 10 /* StringLiteral */, 8 /* NumericLiteral */, - 12 /* RegularExpressionLiteral */, - 99 /* ThisKeyword */, - 43 /* PlusPlusToken */, - 44 /* MinusMinusToken */, - 20 /* CloseParenToken */, - 22 /* CloseBracketToken */, - 18 /* CloseBraceToken */, - 101 /* TrueKeyword */, - 86 /* FalseKeyword */, + 9 /* BigIntLiteral */, + 13 /* RegularExpressionLiteral */, + 100 /* ThisKeyword */, + 44 /* PlusPlusToken */, + 45 /* MinusMinusToken */, + 21 /* CloseParenToken */, + 23 /* CloseBracketToken */, + 19 /* CloseBraceToken */, + 102 /* TrueKeyword */, + 87 /* FalseKeyword */, ], function (token) { return token; }, function () { return true; }); function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { switch (token) { - case 9 /* StringLiteral */: { + case 10 /* StringLiteral */: { // Check to see if we finished up on a multiline string literal. if (!scanner.isUnterminated()) return undefined; @@ -91239,15 +94647,15 @@ var ts; return undefined; } switch (token) { - case 16 /* TemplateTail */: + case 17 /* TemplateTail */: return 5 /* InTemplateMiddleOrTail */; - case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; default: return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } - return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; } } function pushEncodedClassification(start, end, offset, classification, result) { @@ -91273,7 +94681,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +94690,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -91296,6 +94704,7 @@ var ts; case 1 /* comment */: return ts.TokenClass.Comment; case 3 /* keyword */: return ts.TokenClass.Keyword; case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral; case 5 /* operator */: return ts.TokenClass.Operator; case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; @@ -91322,10 +94731,10 @@ var ts; return true; } switch (keyword2) { - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 123 /* ConstructorKeyword */: - case 115 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 124 /* ConstructorKeyword */: + case 116 /* StaticKeyword */: return true; // Allow things like "public get", "public constructor" and "public static". default: return false; // Any other keyword following "public" is actually an identifier, not a real keyword. @@ -91358,43 +94767,43 @@ var ts; } function isBinaryExpressionOperatorToken(token) { switch (token) { - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 48 /* AmpersandToken */: - case 50 /* CaretToken */: - case 49 /* BarToken */: - case 53 /* AmpersandAmpersandToken */: - case 54 /* BarBarToken */: - case 69 /* BarEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 58 /* EqualsToken */: - case 26 /* CommaToken */: + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 49 /* AmpersandToken */: + case 51 /* CaretToken */: + case 50 /* BarToken */: + case 54 /* AmpersandAmpersandToken */: + case 55 /* BarBarToken */: + case 70 /* BarEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 59 /* EqualsToken */: + case 27 /* CommaToken */: return true; default: return false; @@ -91402,12 +94811,12 @@ var ts; } function isPrefixUnaryExpressionOperatorToken(token) { switch (token) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: return true; default: return false; @@ -91420,15 +94829,17 @@ var ts; else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { return 5 /* operator */; } - else if (token >= 17 /* FirstPunctuation */ && token <= 70 /* LastPunctuation */) { + else if (token >= 18 /* FirstPunctuation */ && token <= 71 /* LastPunctuation */) { return 10 /* punctuation */; } switch (token) { case 8 /* NumericLiteral */: return 4 /* numericLiteral */; - case 9 /* StringLiteral */: + case 9 /* BigIntLiteral */: + return 25 /* bigintLiteral */; + case 10 /* StringLiteral */: return 6 /* stringLiteral */; - case 12 /* RegularExpressionLiteral */: + case 13 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; case 7 /* ConflictMarkerTrivia */: case 3 /* MultiLineCommentTrivia */: @@ -91437,7 +94848,7 @@ var ts; case 5 /* WhitespaceTrivia */: case 4 /* NewLineTrivia */: return 8 /* whiteSpace */; - case 71 /* Identifier */: + case 72 /* Identifier */: default: if (ts.isTemplateLiteralKind(token)) { return 6 /* stringLiteral */; @@ -91462,10 +94873,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 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -91540,6 +94951,7 @@ var ts; case 2 /* identifier */: return "identifier" /* identifier */; case 3 /* keyword */: return "keyword" /* keyword */; case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */; case 5 /* operator */: return "operator" /* operator */; case 6 /* stringLiteral */: return "string" /* stringLiteral */; case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; @@ -91673,22 +95085,22 @@ var ts; if (tag.pos !== pos) { pushCommentRange(pos, tag.pos - pos); } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); // "@" + pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 297 /* JSDocParameterTag */: + case 299 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; break; - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; break; - case 298 /* JSDocReturnTag */: + case 300 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; break; @@ -91759,10 +95171,10 @@ var ts; return true; } var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 10 /* JsxText */ && classifiedElementName === undefined) { + if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) { return false; } - var tokenStart = node.kind === 10 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { @@ -91775,22 +95187,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -91807,7 +95219,7 @@ var ts; } // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. - if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { + if (tokenKind === 28 /* LessThanToken */ || tokenKind === 30 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { @@ -91817,19 +95229,19 @@ var ts; if (ts.isPunctuation(tokenKind)) { if (token) { var parent = token.parent; - if (tokenKind === 58 /* EqualsToken */) { + if (tokenKind === 59 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (parent.kind === 235 /* VariableDeclaration */ || - parent.kind === 152 /* PropertyDeclaration */ || - parent.kind === 149 /* Parameter */ || - parent.kind === 265 /* JsxAttribute */) { + if (parent.kind === 237 /* VariableDeclaration */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 151 /* Parameter */ || + parent.kind === 267 /* JsxAttribute */) { return 5 /* operator */; } } - if (parent.kind === 202 /* BinaryExpression */ || - parent.kind === 200 /* PrefixUnaryExpression */ || - parent.kind === 201 /* PostfixUnaryExpression */ || - parent.kind === 203 /* ConditionalExpression */) { + if (parent.kind === 204 /* BinaryExpression */ || + parent.kind === 202 /* PrefixUnaryExpression */ || + parent.kind === 203 /* PostfixUnaryExpression */ || + parent.kind === 205 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -91838,11 +95250,14 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 265 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + else if (tokenKind === 9 /* BigIntLiteral */) { + return 25 /* bigintLiteral */; } - else if (tokenKind === 12 /* RegularExpressionLiteral */) { + else if (tokenKind === 10 /* StringLiteral */) { + // TODO: GH#18217 + return token.parent.kind === 267 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + } + else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */; } @@ -91850,38 +95265,38 @@ var ts; // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } - else if (tokenKind === 10 /* JsxText */) { + else if (tokenKind === 11 /* JsxText */) { return 23 /* jsxText */; } - else if (tokenKind === 71 /* Identifier */) { + else if (tokenKind === 72 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 149 /* Parameter */: + case 151 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -91915,37 +95330,245 @@ var ts; (function (ts) { var Completions; (function (Completions) { - var PathCompletions; - (function (PathCompletions) { - function nameAndKind(name, kind) { - return { name: name, kind: kind }; + var StringCompletions; + (function (StringCompletions) { + function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + if (ts.isInReferenceComment(sourceFile, position)) { + var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host), sourceFile, checker, log, preferences); + } + } + StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + if (completion === undefined) { + return undefined; + } + switch (completion.kind) { + case 0 /* Paths */: + return convertPathCompletions(completion.paths); + case 1 /* Properties */: { + var entries = []; + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; + } + case 2 /* Types */: { + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; + } + default: + return ts.Debug.assertNever(completion); + } + } + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + if (!contextToken || !ts.isStringLiteralLike(contextToken)) + return undefined; + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); + } + StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function convertPathCompletions(pathCompletions) { + var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. + var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. + var entries = pathCompletions.map(function (_a) { + var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension; + return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span }); + }); + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function kindModifiersFromExtension(extension) { + switch (extension) { + case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */; + case ".js" /* Js */: return ".js" /* jsModifier */; + case ".json" /* Json */: return ".json" /* jsonModifier */; + case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */; + case ".ts" /* Ts */: return ".ts" /* tsModifier */; + case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */; + case undefined: return "" /* none */; + default: + return ts.Debug.assertNever(extension); + } + } + var StringLiteralCompletionKind; + (function (StringLiteralCompletionKind) { + StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; + })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + var parent = node.parent; + switch (parent.kind) { + case 182 /* LiteralType */: + switch (parent.parent.kind) { + case 164 /* TypeReference */: + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; + case 180 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); + case 183 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 173 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } + default: + return undefined; + } + case 275 /* PropertyAssignment */: + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); + } + return fromContextualType(); + case 190 /* ElementAccessExpression */: { + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return undefined; + } + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through (is `require("")` or `import("")`) + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 259 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + default: + return fromContextualType(); + } + function fromContextualType() { + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; + } + } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } + function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { + var isNewIdentifier = false; + var uniques = ts.createMap(); + var candidates = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + var types = ts.flatMap(candidates, function (candidate) { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + return; + var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); + return getStringLiteralTypes(type, uniques); + }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; + } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: ts.hasIndexSignature(type) }; + } + function getStringLiteralTypes(type, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } + if (!type) + return ts.emptyArray; + type = ts.skipConstraint(type); + return type.isUnion() + ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) + : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) + ? [type] + : ts.emptyArray; + } + function nameAndKind(name, kind, extension) { + return { name: name, kind: kind, extension: extension }; + } + function directoryResult(name) { + return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined); } function addReplacementSpans(text, textStart, names) { var span = getDirectoryFragmentTextSpan(text, textStart); return names.map(function (_a) { - var name = _a.name, kind = _a.kind; - return ({ name: name, kind: kind, span: span }); + var name = _a.name, kind = _a.kind, extension = _a.extension; + return ({ name: name, kind: kind, extension: extension, span: span }); }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); } - PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { - var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); - if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); - } - else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); - } + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + } + function getExtensionOptions(compilerOptions, includeExtensions) { + if (includeExtensions === void 0) { includeExtensions = false; } + return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; + } + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { + var extensionOptions = getExtensionOptions(compilerOptions); + if (compilerOptions.rootDirs) { + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); } } function getSupportedExtensionsForModuleResolution(compilerOptions) { @@ -91958,31 +95581,27 @@ var ts; * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option */ - function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { // Make all paths absolute/normalized if they are not already rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { - return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; + return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined; }); // TODO: GH#18217 // Now find a path for each potential directory that is to be merged with the one containing the script - return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); - var result = []; - for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { - var baseDirectory = baseDirectories_1[_i]; - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); - } - return result; + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); + return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); } /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) { + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { + var extensions = _a.extensions, includeExtensions = _a.includeExtensions; if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; @@ -92003,46 +95622,77 @@ var ts; var absolutePath = ts.resolvePath(scriptPath, fragment); var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - if (tryDirectoryExists(host, baseDirectory)) { - // Enumerate the available files if possible - var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); - if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - var foundFiles = ts.createMap(); - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var filePath = files_3[_i]; - filePath = ts.normalizePath(filePath); - if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { - continue; - } - var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.has(foundFileName)) { - foundFiles.set(foundFileName, true); - } + if (!tryDirectoryExists(host, baseDirectory)) + return result; + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ + var foundFiles = ts.createMap(); // maps file to its extension + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { + continue; } - ts.forEachKey(foundFiles, function (foundFile) { - result.push(nameAndKind(foundFile, "script" /* scriptElement */)); - }); + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); } - // If possible, get folder completion as well - var directories = tryGetDirectories(host, baseDirectory); - if (directories) { - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var directory = directories_1[_a]; - var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - if (directoryName !== "@types") { - result.push(nameAndKind(directoryName, "directory" /* directory */)); - } + foundFiles.forEach(function (ext, foundFile) { + result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext)); + }); + } + // If possible, get folder completion as well + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var directory = directories_1[_b]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + if (directoryName !== "@types") { + result.push(directoryResult(directoryName)); + } + } + } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); } } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind, extension) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind, extension)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; + _loop_10(name, kind, extension); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92053,60 +95703,51 @@ var ts; function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; - var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); + var extensionOptions = getExtensionOptions(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); } } - var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; - result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); + var fragmentDirectory = getFragmentDirectory(fragment); + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; + result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined)); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_11 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; - result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); } } if (!foundGlobal) { ts.forEachAncestorDirectory(scriptPath, function (ancestor) { var nodeModules = ts.combinePaths(ancestor, "node_modules"); if (tryDirectoryExists(host, nodeModules)) { - getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result); } }); } } return result; } + function getFragmentDirectory(fragment) { + return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + } function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. @@ -92118,7 +95759,7 @@ var ts; return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); function justPathMappingName(name) { - return ts.startsWith(name, fragment) ? [{ name: name, kind: "directory" /* directory */ }] : ts.emptyArray; + return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; } } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { @@ -92146,15 +95787,20 @@ var ts; // that encodes the suffix, but we would have to escape the character "?" which readDirectory // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]).map(function (name) { return ({ name: name, kind: "script" /* scriptElement */ }); }); - var directories = tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }).map(function (name) { return ({ name: name, kind: "directory" /* directory */ }); }); - // Trim away prefix and suffix - return ts.mapDefined(ts.concatenate(matches, directories), function (_a) { - var name = _a.name, kind = _a.kind; - var normalizedMatch = ts.normalizePath(name); - var inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix); - return inner !== undefined ? { name: removeLeadingDirectorySeparator(ts.removeFileExtension(inner)), kind: kind } : undefined; + var matches = ts.mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var extension = ts.tryGetExtensionFromPath(match); + var name = trimPrefixAndSuffix(match); + return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension); }); + var directories = ts.mapDefined(tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { + var name = trimPrefixAndSuffix(dir); + return name === undefined ? undefined : directoryResult(name); + }); + return matches.concat(directories); + function trimPrefixAndSuffix(path) { + var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); + return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner); + } } function withoutStartAndEnd(s, start, end) { return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; @@ -92189,62 +95835,48 @@ var ts; } var prefix = match[1], kind = match[2], toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) - : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) - : undefined; - return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) + : ts.Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, names); } - PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; - function getCompletionEntriesFromTypings(host, options, scriptPath, result) { + function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options var seen = ts.createMap(); - if (options.types) { - for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); - pushResult(moduleName); - } + var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; + for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) { + var root = typeRoots_2[_i]; + getCompletionEntriesFromDirectories(root); } - else if (host.getDirectories) { - var typeRoots = void 0; - try { - typeRoots = ts.getEffectiveTypeRoots(options, host); - } - catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ } - if (typeRoots) { - for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { - var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(root); - } - } - // Also get all @types typings installed in visible node_modules directories - for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { - var packageJson = _e[_d]; - var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(typesDir); - } + // Also get all @types typings installed in visible node_modules directories + for (var _a = 0, _b = findPackageJsons(scriptPath, host); _a < _b.length; _a++) { + var packageJson = _b[_a]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); } return result; function getCompletionEntriesFromDirectories(directory) { - ts.Debug.assert(!!host.getDirectories); - if (tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); - pushResult(moduleName); + if (!tryDirectoryExists(host, directory)) + return; + for (var _i = 0, _a = tryGetDirectories(host, directory); _i < _a.length; _i++) { + var typeDirectoryName = _a[_i]; + var packageName = ts.unmangleScopedPackageName(typeDirectoryName); + if (options.types && !ts.contains(options.types, packageName)) + continue; + if (fragmentDirectory === undefined) { + if (!seen.has(packageName)) { + result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + seen.set(packageName, true); + } + } + else { + var baseDirectory = ts.combinePaths(directory, typeDirectoryName); + var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host)); + if (remainingFragment !== undefined) { + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result); } } - } - } - function pushResult(moduleName) { - if (!seen.has(moduleName)) { - result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); - seen.set(moduleName, true); } } } @@ -92259,6 +95891,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92322,27 +95966,27 @@ var ts; return tryIOAndConsumeErrors(host, host.fileExists, path); } function tryDirectoryExists(host, path) { - try { - return ts.directoryProbablyExists(path, host); - } - catch ( /*ignore*/_a) { /*ignore*/ } - return false; + return tryAndIgnoreErrors(function () { return ts.directoryProbablyExists(path, host); }) || false; } function tryIOAndConsumeErrors(host, toApply) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } + return tryAndIgnoreErrors(function () { return toApply && toApply.apply(host, args); }); + } + function tryAndIgnoreErrors(cb) { try { - return toApply && toApply.apply(host, args); + return cb(); + } + catch (_a) { + return undefined; } - catch ( /*ignore*/_a) { /*ignore*/ } - return undefined; } function containsSlash(fragment) { return ts.stringContains(fragment, ts.directorySeparator); } - })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); + })(StringCompletions = Completions.StringCompletions || (Completions.StringCompletions = {})); })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -92366,11 +96010,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92381,20 +96026,15 @@ var ts; function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); - if (ts.isInReferenceComment(sourceFile, position)) { - var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries && convertPathCompletions(entries); - } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; - if (ts.isInString(sourceFile, position, contextToken)) { - return !contextToken || !ts.isStringLiteralLike(contextToken) - ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); + var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); + if (stringCompletions) { + return stringCompletions; } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) - && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { + && (contextToken.kind === 73 /* BreakKeyword */ || contextToken.kind === 78 /* ContinueKeyword */ || contextToken.kind === 72 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined); @@ -92417,35 +96057,6 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { - if (completion === undefined) { - return undefined; - } - switch (completion.kind) { - case 0 /* Paths */: - return convertPathCompletions(completion.paths); - case 1 /* Properties */: { - var entries = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; - } - case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; - } - default: - return ts.Debug.assertNever(completion); - } - } - function convertPathCompletions(pathCompletions) { - var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. - var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. - var entries = pathCompletions.map(function (_a) { - var name = _a.name, kind = _a.kind, span = _a.span; - return ({ name: name, kind: kind, kindModifiers: "" /* none */, sortText: "0", replacementSpan: span }); - }); - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - } function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } @@ -92459,7 +96070,7 @@ var ts; // The completion list at "1" will contain "div>" with type any // And at `
` (with a closing `>`), the completion list will contain "div". var tagName = location.parent.parent.openingElement.tagName; - var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile); + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 30 /* GreaterThanToken */, sourceFile); var entry = { name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), kind: "class" /* classElement */, @@ -92471,7 +96082,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +96090,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +96118,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92523,7 +96135,9 @@ var ts; } }); } - var completionNameForLiteral = JSON.stringify; + var completionNameForLiteral = function (literal) { + return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); + }; function createCompletionEntryForLiteral(literal) { return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" }; } @@ -92536,13 +96150,13 @@ var ts; var insertText; var replacementSpan; if (origin && origin.kind === 0 /* ThisType */) { - insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; + insertText = needsConvertPropertyAccess ? "this[" + ts.quote(name, preferences) + "]" : "this." + name; } // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { - insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]"; - var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); + insertText = needsConvertPropertyAccess ? "[" + ts.quote(name, preferences) + "]" : "[" + name + "]"; + var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); @@ -92577,18 +96191,6 @@ var ts; replacementSpan: replacementSpan, }; } - function quote(text, preferences) { - var quoted = JSON.stringify(text); - switch (preferences.quotePreference) { - case undefined: - case "double": - return quoted; - case "single": - return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; - default: - return ts.Debug.assertNever(preferences.quotePreference); - } - } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; @@ -92626,6 +96228,7 @@ var ts; log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniques; } + Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { var entries = getLabelStatementCompletions(node); if (entries.length) { @@ -92656,120 +96259,6 @@ var ts; } return entries; } - var StringLiteralCompletionKind; - (function (StringLiteralCompletionKind) { - StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; - StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; - StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; - })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); - function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { - case 180 /* LiteralType */: - switch (node.parent.parent.kind) { - case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; - case 178 /* IndexedAccessType */: - // Get all apparent property names - // i.e. interface Foo { - // foo: string; - // bar: string; - // } - // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); - case 181 /* ImportType */: - return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; - default: - return undefined; - } - case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); - } - return fromContextualType(); - case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; - if (node === argumentExpression) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); - } - return undefined; - } - case 189 /* CallExpression */: - case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { - var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); - } - // falls through (is `require("")` or `import("")`) - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 257 /* ExternalModuleReference */: - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - default: - return fromContextualType(); - } - function fromContextualType() { - // Get completion for string literal from string literal type - // i.e. var x: "hi" | "hello" = "/*completion position*/" - return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; - } - } - function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { - var isNewIdentifier = false; - var uniques = ts.createMap(); - var candidates = []; - checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); - var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) - return; - var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); - isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); - return getStringLiteralTypes(type, uniques); - }); - return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; - } - function stringLiteralCompletionsFromProperties(type) { - return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; - } - function getStringLiteralTypes(type, uniques) { - if (uniques === void 0) { uniques = ts.createMap(); } - if (!type) - return ts.emptyArray; - type = ts.skipConstraint(type); - return type.isUnion() - ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) - : type.isStringLiteral() && !(type.flags & 512 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) - ? [type] - : ts.emptyArray; - } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { var compilerOptions = program.getCompilerOptions(); var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); @@ -92808,10 +96297,7 @@ var ts; var name = entryId.name; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { - var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) - ? undefined - : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); - return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); @@ -92855,25 +96341,11 @@ var ts; }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } - function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { - switch (completion.kind) { - case 0 /* Paths */: { - var match = ts.find(completion.paths, function (p) { return p.name === name; }); - return match && createCompletionDetails(name, "" /* none */, match.kind, [ts.textPart(name)]); - } - case 1 /* Properties */: { - var match = ts.find(completion.symbols, function (s) { return s.name === name; }); - return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); - } - case 2 /* Types */: - return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; - default: - return ts.Debug.assertNever(completion); - } - } + Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; } + Completions.createCompletionDetails = createCompletionDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { @@ -92904,7 +96376,7 @@ var ts; CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; CompletionKind[CompletionKind["String"] = 4] = "String"; CompletionKind[CompletionKind["None"] = 5] = "None"; - })(CompletionKind || (CompletionKind = {})); + })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {})); function getRecommendedCompletion(previousToken, contextualType, checker) { // For a union, return the first one with a recommended completion. return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { @@ -92918,56 +96390,36 @@ var ts; function getContextualType(previousToken, position, sourceFile, checker) { var parent = previousToken.parent; switch (previousToken.kind) { - case 71 /* Identifier */: - return getContextualTypeFromParent(previousToken, checker); - case 58 /* EqualsToken */: + case 72 /* Identifier */: + return ts.getContextualTypeFromParent(previousToken, checker); + case 59 /* EqualsToken */: switch (parent.kind) { - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return checker.getContextualType(parent.initializer); // TODO: GH#18217 - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; } - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: return checker.getContextualType(parent); - case 73 /* CaseKeyword */: - return getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); - case 17 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 258 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + case 74 /* CaseKeyword */: + return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); + case 18 /* OpenBraceToken */: + return ts.isJsxExpression(parent) && parent.parent.kind !== 260 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo // At `,`, treat this as the next argument after the comma. - ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 26 /* CommaToken */ ? 1 : 0)) - : isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) + : ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) // completion at `x ===/**/` should be for the right side ? checker.getTypeAtLocation(parent.left) : checker.getContextualType(previousToken); } } - function getContextualTypeFromParent(node, checker) { - var parent = node.parent; - switch (parent.kind) { - case 190 /* NewExpression */: - return checker.getContextualType(parent); - case 202 /* BinaryExpression */: { - var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; - return isEqualityOperatorKind(operatorToken.kind) - ? checker.getTypeAtLocation(node === right ? left : right) - : checker.getContextualType(node); - } - case 269 /* CaseClause */: - return parent.expression === node ? getSwitchedType(parent, checker) : undefined; - default: - return checker.getContextualType(node); - } - } - function getSwitchedType(caseClause, checker) { - return checker.getTypeAtLocation(caseClause.parent.parent.expression); - } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); if (chain) @@ -92975,7 +96427,7 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 277 /* SourceFile */; }); + return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; }); } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { var typeChecker = program.getTypeChecker(); @@ -93026,11 +96478,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 281 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 303 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -93056,9 +96508,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.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { - var start_4 = ts.timestamp(); + var start_3 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 - log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -93077,21 +96529,21 @@ var ts; return undefined; } var parent = contextToken.parent; - if (contextToken.kind === 23 /* DotToken */) { + if (contextToken.kind === 24 /* DotToken */) { isRightOfDot = true; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; break; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: node = parent.left; break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: node = parent.name; break; - case 181 /* ImportType */: - case 212 /* MetaProperty */: + case 183 /* ImportType */: + case 214 /* MetaProperty */: node = parent; break; default: @@ -93104,53 +96556,56 @@ var ts; // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 187 /* PropertyAccessExpression */) { + if (parent && parent.kind === 189 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } // Fix location if (currentToken.parent === location) { switch (currentToken.kind) { - case 29 /* GreaterThanToken */: - if (currentToken.parent.kind === 258 /* JsxElement */ || currentToken.parent.kind === 260 /* JsxOpeningElement */) { + case 30 /* GreaterThanToken */: + if (currentToken.parent.kind === 260 /* JsxElement */ || currentToken.parent.kind === 262 /* JsxOpeningElement */) { location = currentToken; } break; - case 41 /* SlashToken */: - if (currentToken.parent.kind === 259 /* JsxSelfClosingElement */) { + case 42 /* SlashToken */: + if (currentToken.parent.kind === 261 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 261 /* JsxClosingElement */: - if (contextToken.kind === 41 /* SlashToken */) { + case 263 /* JsxClosingElement */: + if (contextToken.kind === 42 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 259 /* JsxSelfClosingElement */: - case 258 /* JsxElement */: - case 260 /* JsxOpeningElement */: - if (contextToken.kind === 27 /* LessThanToken */) { + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + case 262 /* JsxOpeningElement */: + if (contextToken.kind === 28 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: switch (previousToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: isJsxInitializer = true; break; - case 71 /* Identifier */: + case 72 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 59 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +96627,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +96636,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93196,11 +96653,11 @@ var ts; return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: - case 298 /* JSDocReturnTag */: - case 300 /* JSDocTypeTag */: - case 302 /* JSDocTypedefTag */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 304 /* JSDocTypedefTag */: return true; default: return false; @@ -93240,15 +96697,15 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 277 /* SourceFile */ && d.kind !== 242 /* ModuleDeclaration */ && d.kind !== 241 /* EnumDeclaration */; })) { + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; } } } - if (ts.isMetaProperty(node) && (node.keywordToken === 94 /* NewKeyword */ || node.keywordToken === 91 /* ImportKeyword */)) { - var completion = (node.keywordToken === 94 /* NewKeyword */) ? "target" : "meta"; + if (ts.isMetaProperty(node) && (node.keywordToken === 95 /* NewKeyword */ || node.keywordToken === 92 /* ImportKeyword */)) { + var completion = (node.keywordToken === 95 /* NewKeyword */) ? "target" : "meta"; symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); return; } @@ -93269,7 +96726,7 @@ var ts; else { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 181 /* ImportType */ ? node : node.parent, type, symbol)) { + if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 183 /* ImportType */ ? node : node.parent, type, symbol)) { addPropertySymbol(symbol); } } @@ -93317,24 +96774,22 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { var jsxContainer = tryGetContainingJsxElement(contextToken); // Cursor is inside a JSX self-closing element or opening element - var attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); if (!attrsType) return 0 /* Continue */; - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties); completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,10 +96826,11 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var isTypeOnly = isTypeOnlyCompletion(); + var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode); if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { @@ -93399,31 +96855,31 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 277 /* SourceFile */: - case 204 /* TemplateExpression */: - case 268 /* JsxExpression */: - case 216 /* Block */: + case 279 /* SourceFile */: + case 206 /* TemplateExpression */: + case 270 /* JsxExpression */: + case 218 /* Block */: return true; default: return ts.isStatement(scopeNode); } } function filterGlobalCompletion(symbols) { - var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); - if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + var isTypeOnly = isTypeOnlyCompletion(); + var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); + if (isTypeOnly) + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93438,52 +96894,49 @@ var ts; if (allowTypes) { // Its a type, but you can reach it by namespace.type as well var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); - if (symbolAllowedAsType || isTypeOnlyCompletion) { + if (symbolAllowedAsType || isTypeOnly) { return symbolAllowedAsType; } } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } + function isTypeOnlyCompletion() { + return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 103 /* TypeOfKeyword */ && - (contextToken.parent.kind === 165 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + contextToken.kind === 104 /* TypeOfKeyword */ && + (contextToken.parent.kind === 167 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { - case 56 /* ColonToken */: - return parentKind === 152 /* PropertyDeclaration */ || - parentKind === 151 /* PropertySignature */ || - parentKind === 149 /* Parameter */ || - parentKind === 235 /* VariableDeclaration */ || + case 57 /* ColonToken */: + return parentKind === 154 /* PropertyDeclaration */ || + parentKind === 153 /* PropertySignature */ || + parentKind === 151 /* Parameter */ || + parentKind === 237 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); - case 58 /* EqualsToken */: - return parentKind === 240 /* TypeAliasDeclaration */; - case 118 /* AsKeyword */: - return parentKind === 210 /* AsExpression */; + case 59 /* EqualsToken */: + return parentKind === 242 /* TypeAliasDeclaration */; + case 119 /* AsKeyword */: + return parentKind === 212 /* AsExpression */; } } return false; } - function symbolCanBeReferencedAtTypeLocation(symbol) { - symbol = symbol.exportSymbol || symbol; - // This is an alias, follow what it aliases - symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { - return true; - } - if (symbol.flags & 1536 /* Module */) { - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - // If the exported symbols contains type, - // symbol can be referenced at locations where type is allowed - return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); - } - return false; + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { + if (seenModules === void 0) { seenModules = ts.createMap(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); + return !!(sym.flags & 67897832 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { var tokenTextLowerCase = tokenText.toLowerCase(); @@ -93498,19 +96951,29 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details. // This is just to avoid adding duplicate completion entries. // - // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. - // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + // If `symbol.parent !== ...`, this is an `export * from "foo"` re-export. Those don't create new symbols. if (typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol - || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + || ts.some(symbol.declarations, function (d) { + // If `!!d.name.originalKeywordKind`, this is `export { _break as break };` -- skip this and prefer the keyword completion. + // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + return ts.isExportSpecifier(d) && (d.propertyName ? ts.isIdentifierANonContextualKeyword(d.name) : !!d.parent.parent.moduleSpecifier); + })) { continue; } - var isDefaultExport = symbol.name === "default" /* Default */; + var isDefaultExport = symbol.escapedName === "default" /* Default */; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } @@ -93564,15 +97027,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 10 /* JsxText */) { + if (contextToken.kind === 11 /* JsxText */) { return true; } - if (contextToken.kind === 29 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 260 /* JsxOpeningElement */) { + if (contextToken.kind === 30 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 262 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 261 /* JsxClosingElement */ || contextToken.parent.kind === 259 /* JsxSelfClosingElement */) { - return !!contextToken.parent.parent && contextToken.parent.parent.kind === 258 /* JsxElement */; + if (contextToken.parent.kind === 263 /* JsxClosingElement */ || contextToken.parent.kind === 261 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 260 /* JsxElement */; } } return false; @@ -93582,41 +97045,41 @@ var ts; var containingNodeKind = previousToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(previousToken)) { - case 26 /* CommaToken */: - return containingNodeKind === 189 /* CallExpression */ // func( a, | - || containingNodeKind === 155 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 190 /* NewExpression */ // new C(a, | - || containingNodeKind === 185 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 202 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 163 /* FunctionType */; // var x: (s: string, list| - case 19 /* OpenParenToken */: - return containingNodeKind === 189 /* CallExpression */ // func( | - || containingNodeKind === 155 /* Constructor */ // constructor( | - || containingNodeKind === 190 /* NewExpression */ // new C(a| - || containingNodeKind === 193 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 175 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ - case 21 /* OpenBracketToken */: - return containingNodeKind === 185 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 160 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 147 /* ComputedPropertyName */; // [ | /* this can become an index signature */ - case 129 /* ModuleKeyword */: // module | - case 130 /* NamespaceKeyword */: // namespace | + case 27 /* CommaToken */: + return containingNodeKind === 191 /* CallExpression */ // func( a, | + || containingNodeKind === 157 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 192 /* NewExpression */ // new C(a, | + || containingNodeKind === 187 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 204 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 165 /* FunctionType */; // var x: (s: string, list| + case 20 /* OpenParenToken */: + return containingNodeKind === 191 /* CallExpression */ // func( | + || containingNodeKind === 157 /* Constructor */ // constructor( | + || containingNodeKind === 192 /* NewExpression */ // new C(a| + || containingNodeKind === 195 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 177 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 22 /* OpenBracketToken */: + return containingNodeKind === 187 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 162 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 149 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 130 /* ModuleKeyword */: // module | + case 131 /* NamespaceKeyword */: // namespace | return true; - case 23 /* DotToken */: - return containingNodeKind === 242 /* ModuleDeclaration */; // module A.| - case 17 /* OpenBraceToken */: - return containingNodeKind === 238 /* ClassDeclaration */; // class A{ | - case 58 /* EqualsToken */: - return containingNodeKind === 235 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 202 /* BinaryExpression */; // x = a| - case 14 /* TemplateHead */: - return containingNodeKind === 204 /* TemplateExpression */; // `aa ${| - case 15 /* TemplateMiddle */: - return containingNodeKind === 214 /* TemplateSpan */; // `aa ${10} dd ${| - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - return containingNodeKind === 152 /* PropertyDeclaration */; // class A{ public | + case 24 /* DotToken */: + return containingNodeKind === 244 /* ModuleDeclaration */; // module A.| + case 18 /* OpenBraceToken */: + return containingNodeKind === 240 /* ClassDeclaration */; // class A{ | + case 59 /* EqualsToken */: + return containingNodeKind === 237 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 204 /* BinaryExpression */; // x = a| + case 15 /* TemplateHead */: + return containingNodeKind === 206 /* TemplateExpression */; // `aa ${| + case 16 /* TemplateMiddle */: + return containingNodeKind === 216 /* TemplateSpan */; // `aa ${10} dd ${| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */; // class A{ public | } } return false; @@ -93643,16 +97106,16 @@ var ts; completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 186 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 188 /* ObjectLiteralExpression */) { var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return 2 /* Fail */; - isNewIdentifierLocation = hasIndexSignature(typeForObject); + isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker); existingMembers = objectLikeContainer.properties; } else { - ts.Debug.assert(objectLikeContainer.kind === 182 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 184 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -93663,12 +97126,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 225 /* ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 149 /* Parameter */) { + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 227 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 151 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 154 /* MethodDeclaration */ || rootDeclaration.parent.kind === 157 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 156 /* MethodDeclaration */ || rootDeclaration.parent.kind === 159 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -93704,13 +97167,13 @@ var ts; */ function tryGetImportOrExportClauseCompletionSymbols() { // `import { |` or `import { a as 0, | }` - var namedImportsOrExports = contextToken && (contextToken.kind === 17 /* OpenBraceToken */ || contextToken.kind === 26 /* CommaToken */) + var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; if (!namedImportsOrExports) return 0 /* Continue */; // cursor is in an import clause // try to show exported member for imported module - var moduleSpecifier = (namedImportsOrExports.kind === 250 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifier = (namedImportsOrExports.kind === 252 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -93733,14 +97196,15 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 40 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; var classElement = contextToken.parent; var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; // If this is context token is not something we are editing now, consider if this would lead to be modifier - if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + if (contextToken.kind === 72 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { switch (contextToken.getText()) { case "private": classElementModifierFlags = classElementModifierFlags | 8 /* Private */; @@ -93767,14 +97231,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { - case 17 /* OpenBraceToken */: // const x = { | - case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; + case 18 /* OpenBraceToken */: // const x = { | + case 27 /* CommaToken */: // const x = { a: 0, | if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 40 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 72 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93791,8 +97260,8 @@ var ts; if (contextToken) { var parent = contextToken.parent; switch (contextToken.kind) { - case 19 /* OpenParenToken */: - case 26 /* CommaToken */: + case 20 /* OpenParenToken */: + case 27 /* CommaToken */: return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; default: if (isConstructorParameterCompletion(contextToken)) { @@ -93822,17 +97291,23 @@ var ts; if (contextToken) { var parent = contextToken.parent; switch (contextToken.kind) { - case 28 /* LessThanSlashToken */: - case 41 /* SlashToken */: - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: - case 266 /* JsxAttributes */: - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 259 /* JsxSelfClosingElement */ || parent.kind === 260 /* JsxOpeningElement */)) { + case 30 /* GreaterThanToken */: // End of a type argument list + case 29 /* LessThanSlashToken */: + case 42 /* SlashToken */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 268 /* JsxAttributes */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) { + if (contextToken.kind === 30 /* GreaterThanToken */) { + var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); + if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */)) + break; + } return parent; } - else if (parent.kind === 265 /* JsxAttribute */) { + else if (parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93843,8 +97318,8 @@ var ts; // 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 && ((parent.kind === 265 /* JsxAttribute */) || (parent.kind === 267 /* JsxSpreadAttribute */))) { + case 10 /* StringLiteral */: + if (parent && ((parent.kind === 267 /* JsxAttribute */) || (parent.kind === 269 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93852,10 +97327,10 @@ var ts; return parent.parent.parent; } break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: if (parent && - parent.kind === 268 /* JsxExpression */ && - parent.parent && parent.parent.kind === 265 /* JsxAttribute */) { + parent.kind === 270 /* JsxExpression */ && + parent.parent && parent.parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93863,7 +97338,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 267 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 269 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93882,67 +97357,66 @@ var ts; var parent = contextToken.parent; var containingNodeKind = parent.kind; switch (contextToken.kind) { - case 26 /* CommaToken */: - return containingNodeKind === 235 /* VariableDeclaration */ || - containingNodeKind === 236 /* VariableDeclarationList */ || - containingNodeKind === 217 /* VariableStatement */ || - containingNodeKind === 241 /* EnumDeclaration */ || // enum a { foo, | + case 27 /* CommaToken */: + return containingNodeKind === 237 /* VariableDeclaration */ || + containingNodeKind === 238 /* VariableDeclarationList */ || + containingNodeKind === 219 /* VariableStatement */ || + containingNodeKind === 243 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A= contextToken.pos); - case 23 /* DotToken */: - return containingNodeKind === 183 /* ArrayBindingPattern */; // var [.| - case 56 /* ColonToken */: - return containingNodeKind === 184 /* BindingElement */; // var {x :html| - case 21 /* OpenBracketToken */: - return containingNodeKind === 183 /* ArrayBindingPattern */; // var [x| - case 19 /* OpenParenToken */: - return containingNodeKind === 272 /* CatchClause */ || + case 24 /* DotToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [.| + case 57 /* ColonToken */: + return containingNodeKind === 186 /* BindingElement */; // var {x :html| + case 22 /* OpenBracketToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [x| + case 20 /* OpenParenToken */: + return containingNodeKind === 274 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); - case 17 /* OpenBraceToken */: - return containingNodeKind === 241 /* EnumDeclaration */; // enum a { | - case 27 /* LessThanToken */: - return containingNodeKind === 238 /* ClassDeclaration */ || // class A< | - containingNodeKind === 207 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 240 /* TypeAliasDeclaration */ || // type List< | + case 18 /* OpenBraceToken */: + return containingNodeKind === 243 /* EnumDeclaration */; // enum a { | + case 28 /* LessThanToken */: + return containingNodeKind === 240 /* ClassDeclaration */ || // class A< | + containingNodeKind === 209 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 242 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); - case 115 /* StaticKeyword */: - return containingNodeKind === 152 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); - case 24 /* DotDotDotToken */: - return containingNodeKind === 149 /* Parameter */ || - (!!parent.parent && parent.parent.kind === 183 /* ArrayBindingPattern */); // var [...z| - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - return containingNodeKind === 149 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); - case 118 /* AsKeyword */: - return containingNodeKind === 251 /* ImportSpecifier */ || - containingNodeKind === 255 /* ExportSpecifier */ || - containingNodeKind === 249 /* NamespaceImport */; - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 109 /* InterfaceKeyword */: - case 89 /* FunctionKeyword */: - case 104 /* VarKeyword */: - case 91 /* ImportKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 116 /* YieldKeyword */: - case 139 /* TypeKeyword */: // type htm| + case 116 /* StaticKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + case 25 /* DotDotDotToken */: + return containingNodeKind === 151 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 185 /* ArrayBindingPattern */); // var [...z| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 151 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + case 119 /* AsKeyword */: + return containingNodeKind === 253 /* ImportSpecifier */ || + containingNodeKind === 257 /* ExportSpecifier */ || + containingNodeKind === 251 /* NamespaceImport */; + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return !isFromObjectTypeDeclaration(contextToken); + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 110 /* InterfaceKeyword */: + case 90 /* FunctionKeyword */: + case 105 /* VarKeyword */: + case 92 /* ImportKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 117 /* YieldKeyword */: + case 140 /* TypeKeyword */: // type htm| return true; + case 40 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93962,22 +97436,23 @@ var ts; } // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 75 /* ClassKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 83 /* EnumKeyword */: - case 89 /* FunctionKeyword */: - case 109 /* InterfaceKeyword */: - case 110 /* LetKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 115 /* StaticKeyword */: - case 104 /* VarKeyword */: - case 116 /* YieldKeyword */: + case 118 /* AbstractKeyword */: + case 76 /* ClassKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 90 /* FunctionKeyword */: + case 110 /* InterfaceKeyword */: + case 111 /* LetKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 116 /* StaticKeyword */: + case 105 /* VarKeyword */: + case 117 /* YieldKeyword */: return true; + case 121 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -93986,7 +97461,7 @@ var ts; && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 155 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 157 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -94009,12 +97484,12 @@ 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 !== 273 /* PropertyAssignment */ && - m.kind !== 274 /* ShorthandPropertyAssignment */ && - m.kind !== 184 /* BindingElement */ && - m.kind !== 154 /* MethodDeclaration */ && - m.kind !== 156 /* GetAccessor */ && - m.kind !== 157 /* SetAccessor */) { + if (m.kind !== 275 /* PropertyAssignment */ && + m.kind !== 276 /* ShorthandPropertyAssignment */ && + m.kind !== 186 /* BindingElement */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -94024,7 +97499,7 @@ var ts; var existingName = void 0; if (ts.isBindingElement(m) && m.propertyName) { // include only identifiers in completion list - if (m.propertyName.kind === 71 /* Identifier */) { + if (m.propertyName.kind === 72 /* Identifier */) { existingName = m.propertyName.escapedText; } } @@ -94049,10 +97524,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 152 /* PropertyDeclaration */ && - m.kind !== 154 /* MethodDeclaration */ && - m.kind !== 156 /* GetAccessor */ && - m.kind !== 157 /* SetAccessor */) { + if (m.kind !== 154 /* PropertyDeclaration */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -94092,7 +97567,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 265 /* JsxAttribute */) { + if (attr.kind === 267 /* JsxAttribute */) { seenNames.set(attr.name.escapedText, true); } } @@ -94136,7 +97611,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 72 /* FirstKeyword */; i <= 145 /* LastKeyword */; i++) { + for (var i = 73 /* FirstKeyword */; i <= 147 /* LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -94151,17 +97626,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 121 /* AsyncKeyword */ || 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 125 /* DeclareKeyword */ || kind === 130 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 141 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94169,37 +97646,26 @@ var ts; })); } function isInterfaceOrTypeLiteralCompletionKeyword(kind) { - return kind === 132 /* ReadonlyKeyword */; + return kind === 133 /* ReadonlyKeyword */; } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 117 /* AbstractKeyword */: - case 123 /* ConstructorKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 120 /* AsyncKeyword */: + case 118 /* AbstractKeyword */: + case 124 /* ConstructorKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 121 /* AsyncKeyword */: return true; default: return ts.isClassMemberModifier(kind); } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 121 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } - function isEqualityOperatorKind(kind) { - switch (kind) { - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - return true; - default: - return false; - } - } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { var jsdoc = ts.findAncestor(node, ts.isJSDoc); @@ -94209,7 +97675,7 @@ var ts; return contextualType.isUnion() ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. - return !(memberType.flags & 32764 /* Primitive */ || + return !(memberType.flags & 131068 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker) || checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); @@ -94232,31 +97698,31 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 304 /* SyntaxList */: + case 306 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); - if (cls && !ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile)) { + if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) { return cls; } } if (!contextToken) return undefined; switch (contextToken.kind) { - case 25 /* SemicolonToken */: // class c {getValue(): number; | } - case 18 /* CloseBraceToken */: // class c { method() { } | } + case 26 /* SemicolonToken */: // class c {getValue(): number; | } + case 19 /* CloseBraceToken */: // class c { method() { } | } // class c { method() { } b| } return isFromObjectTypeDeclaration(location) && location.parent.name === location ? location.parent.parent : ts.tryCast(location, ts.isObjectTypeDeclaration); - case 17 /* OpenBraceToken */: // class c { | - case 26 /* CommaToken */: // class c {getValue(): number, | } + case 18 /* OpenBraceToken */: // class c { | + case 27 /* CommaToken */: // class c {getValue(): number, | } return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); default: if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 40 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94264,9 +97730,6 @@ var ts; function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); } - function hasIndexSignature(type) { - return !!type.getStringIndexType() || !!type.getNumberIndexType(); - } function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { case ".": @@ -94276,14 +97739,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 28 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 42 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94292,17 +97755,6 @@ var ts; var left = _a.left; return ts.nodeIsMissing(left); } - function isStringLiteralOrTemplate(node) { - switch (node.kind) { - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 191 /* TaggedTemplateExpression */: - return true; - default: - return false; - } - } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -94355,40 +97807,40 @@ var ts; } function getHighlightSpans(node, sourceFile) { switch (node.kind) { - case 90 /* IfKeyword */: - case 82 /* ElseKeyword */: + case 91 /* IfKeyword */: + case 83 /* ElseKeyword */: return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; - case 96 /* ReturnKeyword */: + case 97 /* ReturnKeyword */: return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); - case 100 /* ThrowKeyword */: + case 101 /* ThrowKeyword */: return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); - case 102 /* TryKeyword */: - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: - var tryStatement = node.kind === 74 /* CatchKeyword */ ? node.parent.parent : node.parent; + case 103 /* TryKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + var tryStatement = node.kind === 75 /* CatchKeyword */ ? node.parent.parent : node.parent; return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); - case 98 /* SwitchKeyword */: + case 99 /* SwitchKeyword */: return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); - case 73 /* CaseKeyword */: - case 79 /* DefaultKeyword */: + case 74 /* CaseKeyword */: + case 80 /* DefaultKeyword */: return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); - case 72 /* BreakKeyword */: - case 77 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 78 /* ContinueKeyword */: return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); - case 88 /* ForKeyword */: - case 106 /* WhileKeyword */: - case 81 /* DoKeyword */: + case 89 /* ForKeyword */: + case 107 /* WhileKeyword */: + case 82 /* DoKeyword */: return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); - case 123 /* ConstructorKeyword */: - return getFromAllDeclarations(ts.isConstructorDeclaration, [123 /* ConstructorKeyword */]); - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]); - case 121 /* AwaitKeyword */: + case 124 /* ConstructorKeyword */: + return getFromAllDeclarations(ts.isConstructorDeclaration, [124 /* ConstructorKeyword */]); + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return getFromAllDeclarations(ts.isAccessor, [126 /* GetKeyword */, 137 /* SetKeyword */]); + case 122 /* AwaitKeyword */: return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: return highlightSpans(getAsyncAndAwaitOccurrences(node)); - case 116 /* YieldKeyword */: + case 117 /* YieldKeyword */: return highlightSpans(getYieldOccurrences(node)); default: return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) @@ -94431,7 +97883,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 277 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -94463,16 +97915,16 @@ var ts; function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 230 /* SwitchStatement */: - if (statement.kind === 226 /* ContinueStatement */) { + case 232 /* SwitchStatement */: + if (statement.kind === 228 /* ContinueStatement */) { return false; } // falls through - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. @@ -94488,11 +97940,11 @@ var ts; // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 243 /* ModuleBlock */: - case 277 /* SourceFile */: - case 216 /* Block */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 218 /* Block */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return declaration.members.concat([declaration]); @@ -94500,12 +97952,12 @@ var ts; else { return container.statements; } - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 237 /* FunctionDeclaration */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: var 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. @@ -94536,12 +97988,12 @@ var ts; } function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) { + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 89 /* ForKeyword */, 107 /* WhileKeyword */, 82 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 221 /* DoStatement */) { + if (loopNode.kind === 223 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) { + if (pushKeywordIf(keywords, loopTokens[i], 107 /* WhileKeyword */)) { break; } } @@ -94549,7 +98001,7 @@ var ts; } ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) { if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */, 77 /* ContinueKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */, 78 /* ContinueKeyword */); } }); return keywords; @@ -94558,13 +98010,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -94572,13 +98024,13 @@ var ts; } function getSwitchCaseDefaultOccurrences(switchStatement) { var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 98 /* SwitchKeyword */); + pushKeywordIf(keywords, switchStatement.getFirstToken(), 99 /* SwitchKeyword */); // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 73 /* CaseKeyword */, 79 /* DefaultKeyword */); + pushKeywordIf(keywords, clause.getFirstToken(), 74 /* CaseKeyword */, 80 /* DefaultKeyword */); ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) { if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */); } }); }); @@ -94586,13 +98038,13 @@ var ts; } function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 102 /* TryKeyword */); + pushKeywordIf(keywords, tryStatement.getFirstToken(), 103 /* TryKeyword */); if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 74 /* CatchKeyword */); + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 75 /* CatchKeyword */); } if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 87 /* FinallyKeyword */); + var finallyKeyword = ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 88 /* FinallyKeyword */); } return keywords; } @@ -94603,13 +98055,13 @@ var ts; } var keywords = []; ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - keywords.push(ts.findChildOfKind(throwStatement, 100 /* ThrowKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); }); // If the "owner" is a function, then we equate 'return' and 'throw' statements in their // ability to "jump out" of the function, and include occurrences for both. if (ts.isFunctionBlock(owner)) { ts.forEachReturnStatement(owner, function (returnStatement) { - keywords.push(ts.findChildOfKind(returnStatement, 96 /* ReturnKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); }); } return keywords; @@ -94621,11 +98073,11 @@ var ts; } var keywords = []; ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { - keywords.push(ts.findChildOfKind(returnStatement, 96 /* ReturnKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); }); // Include 'throw' statements that do not occur within a try block. ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - keywords.push(ts.findChildOfKind(throwStatement, 100 /* ThrowKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); }); return keywords; } @@ -94637,13 +98089,13 @@ var ts; var keywords = []; if (func.modifiers) { func.modifiers.forEach(function (modifier) { - pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */); + pushKeywordIf(keywords, modifier, 121 /* AsyncKeyword */); }); } ts.forEachChild(func, function (child) { traverseWithoutCrossingFunction(child, function (node) { if (ts.isAwaitExpression(node)) { - pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */); + pushKeywordIf(keywords, node.getFirstToken(), 122 /* AwaitKeyword */); } }); }); @@ -94658,7 +98110,7 @@ var ts; ts.forEachChild(func, function (child) { traverseWithoutCrossingFunction(child, function (node) { if (ts.isYieldExpression(node)) { - pushKeywordIf(keywords, node.getFirstToken(), 116 /* YieldKeyword */); + pushKeywordIf(keywords, node.getFirstToken(), 117 /* YieldKeyword */); } }); }); @@ -94677,7 +98129,7 @@ var ts; // We'd like to highlight else/ifs together if they are only separated by whitespace // (i.e. the keywords are separated by no comments, no newlines). for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 82 /* ElseKeyword */ && i < keywords.length - 1) { + if (keywords[i].kind === 83 /* ElseKeyword */ && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. var shouldCombineElseAndIf = true; @@ -94712,10 +98164,10 @@ var ts; // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. while (true) { var children = ifStatement.getChildren(sourceFile); - pushKeywordIf(keywords, children[0], 90 /* IfKeyword */); + pushKeywordIf(keywords, children[0], 91 /* IfKeyword */); // Generally the 'else' keyword is second-to-last, so we traverse backwards. for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 82 /* ElseKeyword */)) { + if (pushKeywordIf(keywords, children[i], 83 /* ElseKeyword */)) { break; } } @@ -94748,16 +98200,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } - function getBucketForCompilationSettings(key, createIfMissing) { - var bucket = buckets.get(key); - if (!bucket && createIfMissing) { - buckets.set(key, bucket = ts.createMap()); - } - return bucket; // TODO: GH#18217 - } function reportStats() { var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = buckets.get(name); @@ -94793,9 +98235,9 @@ var ts; return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); + var bucket = ts.getOrUpdate(buckets, key, ts.createMap); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +98251,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94847,8 +98289,7 @@ var ts; return releaseDocumentWithKey(path, key); } function releaseDocumentWithKey(path, key) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); - ts.Debug.assert(bucket !== undefined); + var bucket = ts.Debug.assertDefined(buckets.get(key)); var entry = bucket.get(path); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); @@ -94876,6 +98317,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -94939,12 +98383,12 @@ var ts; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 235 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 237 /* VariableDeclaration */) { var name = parent.name; - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { directImports.push(name); break; } @@ -94953,22 +98397,22 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; - case 71 /* Identifier */: // for 'const x = require("y"); + case 72 /* Identifier */: // for 'const x = require("y"); break; // TODO: GH#23879 - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 251 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); @@ -94978,7 +98422,7 @@ var ts; directImports.push(direct); } break; - case 181 /* ImportType */: + case 183 /* ImportType */: directImports.push(direct); break; default: @@ -94995,7 +98439,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 277 /* SourceFile */ || sourceFileLike.kind === 242 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -95050,17 +98494,17 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 246 /* ImportEqualsDeclaration */) { + if (decl.kind === 248 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } return; } - if (decl.kind === 71 /* Identifier */) { + if (decl.kind === 72 /* Identifier */) { handleNamespaceImportLike(decl); return; } - if (decl.kind === 181 /* ImportType */) { + if (decl.kind === 183 /* ImportType */) { if (decl.qualifier) { if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { singleReferences.push(decl.qualifier); @@ -95072,20 +98516,20 @@ var ts; return; } // Ignore if there's a grammar error - if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) { + if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { return; } - if (decl.kind === 253 /* ExportDeclaration */) { + if (decl.kind === 255 /* ExportDeclaration */) { searchForNamedImport(decl.exportClause); return; } var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: handleNamespaceImportLike(namedBindings.name); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: // 'default' might be accessed as a named import `{ default as foo }`. if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { searchForNamedImport(namedBindings); @@ -95135,7 +98579,7 @@ var ts; } } else { - var localSymbol = element.kind === 255 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 257 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -95161,10 +98605,10 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 277 /* SourceFile */) { + if (searchSourceFile.kind === 279 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -95192,8 +98636,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95212,7 +98656,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 277 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -95227,15 +98671,15 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 253 /* ExportDeclaration */: - case 247 /* ImportDeclaration */: { + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 246 /* ImportEqualsDeclaration */: { + case 248 /* ImportEqualsDeclaration */: { var decl = statement; if (isExternalModuleImportEquals(decl)) { action(decl, decl.moduleReference.expression); @@ -95259,7 +98703,7 @@ var ts; var parent = node.parent; var grandParent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 187 /* PropertyAccessExpression */) { + if (parent.kind === 189 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) @@ -95279,7 +98723,7 @@ var ts; return undefined; } var lhsSymbol = checker.getSymbolAtLocation(exportNode.name); - return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false }; + return { kind: 0 /* Import */, symbol: lhsSymbol }; } else { return exportInfo(symbol, getExportKindForDeclaration(exportNode)); @@ -95312,7 +98756,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95349,7 +98793,7 @@ var ts; // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { - return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); + return { kind: 0 /* Import */, symbol: importedSymbol }; } } function exportInfo(symbol, kind) { @@ -95381,10 +98825,10 @@ var ts; // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent, node) { - if (parent.kind === 235 /* VariableDeclaration */) { + if (parent.kind === 237 /* VariableDeclaration */) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 272 /* CatchClause */ ? undefined : p.parent.parent.kind === 217 /* VariableStatement */ ? p.parent.parent : undefined; + p.parent.kind === 274 /* CatchClause */ ? undefined : p.parent.parent.kind === 219 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -95393,19 +98837,17 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 246 /* ImportEqualsDeclaration */: - return parent.name === node && isExternalModuleImportEquals(parent) - ? { isNamedImport: false } - : undefined; - case 251 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + return parent.name === node && isExternalModuleImportEquals(parent); + case 253 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. - return parent.propertyName ? undefined : { isNamedImport: true }; - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: + return !parent.propertyName; + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: ts.Debug.assert(parent.name === node); - return { isNamedImport: false }; + return true; default: - return undefined; + return false; } } function getExportInfo(exportSymbol, exportKind, checker) { @@ -95434,21 +98876,21 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 277 /* SourceFile */) { + if (parent.kind === 279 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 243 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 245 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; + return node.kind === 244 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; } function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 257 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */; + return eq.moduleReference.kind === 259 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95457,8 +98899,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95483,18 +98942,18 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } - else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" var symbol = checker.getSymbolAtLocation(node); @@ -95505,10 +98964,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95521,28 +98980,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95556,28 +99015,67 @@ var ts; } function getDefinitionKindAndDisplayParts(symbol, checker, node) { var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); - var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node; + var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode, checker) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), - isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + isDefinition: node.kind === 80 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode, checker) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + var prefixColon = { prefixText: name + ": " }; + var suffixColon = { suffixText: ": " + name }; + return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon + : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : isShorthandAssignment ? suffixColon : prefixColon; + } + else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + // If the original symbol was using this alias, just rename the alias. + var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); + return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions; + } + else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name }; + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95592,16 +99090,16 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 186 /* ObjectLiteralExpression */) { + else if (node.kind === 188 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, - displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] }; } - else if (node.kind === 207 /* ClassExpression */) { + else if (node.kind === 209 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, - displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] }; } else { @@ -95609,17 +99107,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95627,7 +99125,7 @@ var ts; function getTextSpan(node, sourceFile) { var start = node.getStart(sourceFile); var end = node.getEnd(); - if (node.kind === 9 /* StringLiteral */) { + if (node.kind === 10 /* StringLiteral */) { start += 1; end -= 1; } @@ -95635,7 +99133,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 80 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 204 /* BinaryExpression */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 80 /* DefaultKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 257 /* ExportSpecifier */: + case 250 /* ImportClause */: // default import + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 241 /* InterfaceDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 267 /* JsxAttribute */: + case 244 /* ModuleDeclaration */: + case 247 /* NamespaceExportDeclaration */: + case 251 /* NamespaceImport */: + case 151 /* Parameter */: + case 276 /* ShorthandPropertyAssignment */: + case 242 /* TypeAliasDeclaration */: + case 150 /* TypeParameter */: + return true; + case 275 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return !!decl.body; + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 155 /* MethodSignature */: + case 153 /* PropertySignature */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95668,6 +99221,9 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } + if (symbol.escapedName === "export=" /* ExportEquals */) { + return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } var moduleReferences = ts.emptyArray; var moduleSourceFile = isModuleSymbol(symbol); var referencedNode = node; @@ -95699,11 +99255,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95712,12 +99268,12 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95725,7 +99281,23 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + var exported = symbol.exports.get("export=" /* ExportEquals */); + if (exported) { + for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { + var decl = _c[_b]; + var sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + // At `module.exports = ...`, reference node is `module` + var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) + ? decl.left.expression + : ts.isExportAssignment(decl) + ? ts.Debug.assertDefined(ts.findChildOfKind(decl, 85 /* ExportKeyword */, sourceFile)) + : ts.getNameOfDeclaration(decl) || decl; + references.push(FindAllReferences.nodeEntry(node)); + } + } + } + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95746,24 +99318,29 @@ var ts; if (ts.isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); } - if (node.kind === 97 /* SuperKeyword */) { + if (node.kind === 98 /* SuperKeyword */) { return getReferencesForSuperKeyword(node); } return undefined; } /** Core find-all-references algorithm for a normal symbol. */ - function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; // Compute the meaning from the location and the symbol it references var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - if (node && node.kind === 79 /* DefaultKeyword */) { + var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + if (exportSpecifier) { + // When renaming at an export specifier, rename the export and not the thing being exported. + getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); + } + else if (node && node.kind === 80 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -95783,9 +99360,9 @@ var ts; } function getSpecialSearchKind(node) { switch (node.kind) { - case 123 /* ConstructorKeyword */: + case 124 /* ConstructorKeyword */: return 1 /* Constructor */; - case 71 /* Identifier */: + case 72 /* Identifier */: if (ts.isClassLike(node.parent)) { ts.Debug.assert(node.parent.name === node); return 2 /* Class */; @@ -95796,15 +99373,11 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { var parent = node.parent; - if (ts.isExportSpecifier(parent)) { + if (ts.isExportSpecifier(parent) && !isForRename) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); } - if (ts.isImportSpecifier(parent) && parent.propertyName === node) { - // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. - return checker.getImmediateAliasedSymbol(symbol); - } // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. return ts.firstDefined(symbol.declarations, function (decl) { if (!decl.parent) { @@ -95894,15 +99467,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -95967,7 +99540,8 @@ var ts; var indirectUser = indirectUsers_2[_b]; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; - if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) { + // Import specifiers should be handled by importSearches + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { cb(node); } } @@ -95983,7 +99557,7 @@ var ts; if (!ts.isIdentifier(singleRef)) return false; // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */); } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { @@ -96005,19 +99579,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -96030,7 +99591,7 @@ 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 declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 194 /* FunctionExpression */ || valueDeclaration.kind === 207 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 196 /* FunctionExpression */ || valueDeclaration.kind === 209 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -96040,14 +99601,14 @@ var ts; if (flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 238 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 240 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -96062,14 +99623,14 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -96090,7 +99651,9 @@ var ts; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { - var symbol = checker.getSymbolAtLocation(definition); + var symbol = ts.isParameterPropertyDeclaration(definition.parent) + ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) + : checker.getSymbolAtLocation(definition); if (!symbol) return undefined; for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { @@ -96112,8 +99675,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,21 +99733,21 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node.text.length === searchSymbolName.length; - case 9 /* StringLiteral */: { + case 10 /* StringLiteral */: { var str = node; - return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && str.text.length === searchSymbolName.length; } case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; - case 79 /* DefaultKeyword */: + case 80 /* DefaultKeyword */: return "default".length === searchSymbolName.length; default: return false; @@ -96197,7 +99760,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96248,7 +99811,7 @@ var ts; return; } if (ts.isExportSpecifier(parent)) { - ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */); + ts.Debug.assert(referenceLocation.kind === 72 /* Identifier */); getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); return; } @@ -96273,16 +99836,16 @@ var ts; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) { + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); - if (!search.includes(localSymbol)) { + if (!alwaysGetReferences && !search.includes(localSymbol)) { return; } if (!propertyName) { // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) - if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) { + if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) { addRef(); } } @@ -96293,7 +99856,7 @@ var ts; addRef(); } if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { - addReference(name, referenceSymbol, state); + addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state); } } else { @@ -96302,15 +99865,14 @@ var ts; } } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!(referenceLocation === propertyName && state.options.isForRename)) { - var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; - var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); - if (!exportInfo) - return ts.Debug.fail(); - searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); + if (!state.options.isForRename || alwaysGetReferences) { + var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; + var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); + var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. - if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) { + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (imported) searchForImportedSymbol(imported, state); @@ -96342,12 +99904,11 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0 /* Import */) { - if (!state.options.isForRename || importOrExport.isNamedImport) { + if (!state.options.isForRename) { searchForImportedSymbol(symbol, state); } } else { - // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching. searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); } } @@ -96367,12 +99928,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96382,7 +99944,7 @@ var ts; } var pusher = function () { return state.referenceAdder(search.symbol); }; if (ts.isClassLike(referenceLocation.parent)) { - ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); + ts.Debug.assert(referenceLocation.kind === 80 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. findOwnConstructorReferences(search.symbol, sourceFile, pusher()); } @@ -96408,7 +99970,7 @@ var ts; } if (member.body) { member.body.forEachChild(function cb(node) { - if (node.kind === 99 /* ThisKeyword */) { + if (node.kind === 100 /* ThisKeyword */) { addRef(node); } else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { @@ -96425,16 +99987,16 @@ var ts; function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 155 /* Constructor */ && !!ctrKeyword); + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 154 /* MethodDeclaration */) { + if (decl && decl.kind === 156 /* MethodDeclaration */) { var body = decl.body; if (body) { - forEachDescendantOfKind(body, 99 /* ThisKeyword */, function (thisKeyword) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { if (ts.isNewExpressionTarget(thisKeyword)) { addNode(thisKeyword); } @@ -96451,10 +100013,10 @@ var ts; } for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 155 /* Constructor */); + ts.Debug.assert(decl.kind === 157 /* Constructor */); var body = decl.body; if (body) { - forEachDescendantOfKind(body, 97 /* SuperKeyword */, function (node) { + forEachDescendantOfKind(body, 98 /* SuperKeyword */, function (node) { if (ts.isCallExpressionTarget(node)) { addNode(node); } @@ -96468,10 +100030,10 @@ var ts; addReference(refNode); return; } - if (refNode.kind !== 71 /* Identifier */) { + if (refNode.kind !== 72 /* Identifier */) { return; } - if (refNode.parent.kind === 274 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 276 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -96491,7 +100053,7 @@ var ts; } else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { var body = typeHavingNode.body; - if (body.kind === 216 /* Block */) { + if (body.kind === 218 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression) addIfImplementation(returnStatement.expression); @@ -96519,13 +100081,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 195 /* ArrowFunction */: - case 194 /* FunctionExpression */: - case 186 /* ObjectLiteralExpression */: - case 207 /* ClassExpression */: - case 185 /* ArrayLiteralExpression */: + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 187 /* ArrayLiteralExpression */: return true; default: return false; @@ -96578,13 +100140,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -96593,7 +100155,7 @@ var ts; } var sourceFile = searchSpaceNode.getSourceFile(); var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) { - if (node.kind !== 97 /* SuperKeyword */) { + if (node.kind !== 98 /* SuperKeyword */) { return; } var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); @@ -96602,41 +100164,41 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // falls through - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // falls through - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* 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. default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 277 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -96644,24 +100206,25 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: return searchSpaceNode.symbol === container.symbol; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; - case 277 /* SourceFile */: - return container.kind === 277 /* SourceFile */ && !ts.isExternalModule(container); + case 279 /* SourceFile */: + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96669,39 +100232,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // 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 - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96713,8 +100262,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // 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 + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96727,11 +100294,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96739,19 +100308,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96777,8 +100346,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_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +100409,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96855,7 +100424,7 @@ var ts; function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); return function (path) { - var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 }); var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); return originalPath ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) @@ -96874,7 +100443,7 @@ var ts; var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); return combinePathsSafe(ts.getDirectoryPath(a1), rel); } - function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; if (!configFile) return; @@ -96892,7 +100461,8 @@ var ts; var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); // If there isn't some include for this, add a new one. - if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if (ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); } } @@ -96943,9 +100513,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_12 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +100541,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_12(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +100571,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +100601,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +100643,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97078,7 +100655,7 @@ var ts; else { var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; // For a 'super()' call, put the signature first, else put the variable first. - return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); + return node.kind === 98 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -97086,7 +100663,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; } @@ -97239,18 +100816,18 @@ var ts; // (2) when the aliased symbol is originating from an import. // function shouldSkipAlias(node, declaration) { - if (node.kind !== 71 /* Identifier */) { + if (node.kind !== 72 /* Identifier */) { return false; } if (node.parent === declaration) { return true; } switch (declaration.kind) { - case 248 /* ImportClause */: - case 246 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: return true; - case 251 /* ImportSpecifier */: - return declaration.parent.kind === 250 /* NamedImports */; + case 253 /* ImportSpecifier */: + return declaration.parent.kind === 252 /* NamedImports */; default: return false; } @@ -97260,7 +100837,7 @@ var ts; function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */)) { + if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 124 /* ConstructorKeyword */)) { var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } @@ -97332,6 +100909,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97444,11 +101031,11 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: return [declaration]; - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -97469,16 +101056,16 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return withNode(tag.class); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 303 /* JSDocPropertyTag */: - case 297 /* JSDocParameterTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -97542,7 +101129,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +101162,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +101225,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97655,7 +101242,7 @@ var ts; function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { return parameters.map(function (_a, i) { var name = _a.name, dotDotDotToken = _a.dotDotDotToken; - var paramName = name.kind === 71 /* Identifier */ ? name.text : "param" + i; + var paramName = name.kind === 72 /* Identifier */ ? name.text : "param" + i; var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; return indentationStr + " * @param " + type + paramName + newLine; }).join(""); @@ -97665,23 +101252,23 @@ var ts; } function getCommentOwnerInfoWorker(commentOwner) { switch (commentOwner.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 155 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return getCommentOwnerInfoWorker(commentOwner.initializer); - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 151 /* PropertySignature */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 240 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 153 /* PropertySignature */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 242 /* TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer @@ -97689,16 +101276,16 @@ var ts; : undefined; return { commentOwner: commentOwner, parameters: parameters_1 }; } - case 277 /* SourceFile */: + case 279 /* SourceFile */: return "quit"; - case 242 /* ModuleDeclaration */: + case 244 /* 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 { }'. - return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 202 /* BinaryExpression */: { + return commentOwner.parent.kind === 244 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 204 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97715,14 +101302,14 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 193 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 195 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return rightHandSide.parameters; - case 207 /* ClassExpression */: { + case 209 /* ClassExpression */: { var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); return ctr ? ctr.parameters : ts.emptyArray; } @@ -97741,7 +101328,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +101338,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +101353,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -97784,9 +101371,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 248 /* ImportClause */: - case 251 /* ImportSpecifier */: - case 246 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -97796,7 +101383,7 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - return !!name && (pushLiteral(name, containers) || name.kind === 147 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + return !!name && (pushLiteral(name, containers) || name.kind === 149 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // @@ -97813,7 +101400,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + if (name && name.kind === 149 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } // Don't include the last portion. @@ -97982,7 +101569,7 @@ var ts; return; } switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -97994,21 +101581,21 @@ var ts; } } break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 155 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -98020,7 +101607,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings.kind === 251 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -98031,8 +101618,8 @@ var ts; } } break; - case 184 /* BindingElement */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); @@ -98053,12 +101640,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -98068,9 +101655,9 @@ var ts; } endNode(); break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -98078,19 +101665,19 @@ var ts; } endNode(); break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 255 /* ExportSpecifier */: - case 246 /* ImportEqualsDeclaration */: - case 160 /* IndexSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 240 /* TypeAliasDeclaration */: + case 257 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 162 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 242 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: { + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98101,6 +101688,9 @@ var ts; case 4 /* ThisProperty */: case 5 /* Property */: case 0 /* None */: + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: break; default: ts.Debug.assertNever(special); @@ -98168,12 +101758,12 @@ var ts; return false; } switch (a.kind) { - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return areSameModule(a, b); default: return true; @@ -98189,7 +101779,7 @@ var ts; // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { // TODO: GH#18217 - return a.body.kind === b.body.kind && (a.body.kind !== 242 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 244 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { @@ -98219,7 +101809,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 242 /* ModuleDeclaration */) { + if (node.kind === 244 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -98227,16 +101817,16 @@ var ts; return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 207 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: return getFunctionOrClassName(node); default: return undefined; } } function getItemName(node, name) { - if (node.kind === 242 /* ModuleDeclaration */) { + if (node.kind === 244 /* ModuleDeclaration */) { return getModuleName(node); } if (name) { @@ -98246,16 +101836,16 @@ var ts; } } switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -98263,13 +101853,13 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the // navigation bar. return getFunctionOrClassName(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return "constructor"; - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return "new()"; - case 158 /* CallSignature */: + case 160 /* CallSignature */: return "()"; - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return "[]"; default: return ""; @@ -98293,25 +101883,25 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 241 /* EnumDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 277 /* SourceFile */: - case 240 /* TypeAliasDeclaration */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 242 /* TypeAliasDeclaration */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return true; - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 235 /* VariableDeclaration */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 237 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -98321,10 +101911,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 243 /* ModuleBlock */: - case 277 /* SourceFile */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: return true; default: return hasSomeImportantChild(item); @@ -98333,7 +101923,7 @@ var ts; function hasSomeImportantChild(item) { return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 235 /* VariableDeclaration */ && childKind !== 184 /* BindingElement */; + return childKind !== 237 /* VariableDeclaration */ && childKind !== 186 /* BindingElement */; }); } } @@ -98390,7 +101980,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -98404,47 +101994,68 @@ var ts; return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 147 /* ComputedPropertyName */; + return !member.name || member.name.kind === 149 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 277 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 235 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 195 /* ArrowFunction */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: return true; default: return false; @@ -98571,7 +102182,7 @@ var ts; ? specifier.text : undefined; } - /* @internal */ // Internal for testing + // Internal for testing /** * @param importGroup a list of ImportDeclarations, all with the same module name. */ @@ -98670,7 +102281,7 @@ var ts; } } OrganizeImports.coalesceImports = coalesceImports; - /* @internal */ // Internal for testing + // Internal for testing /** * @param exportGroup a list of ExportDeclarations, all with the same module name. */ @@ -98773,7 +102384,7 @@ var ts; } var lastImport = current - 1; if (lastImport !== firstImport) { - out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 92 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); } } function visitNonImportNode(n) { @@ -98880,31 +102491,31 @@ var ts; } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(n)) { - return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 195 /* ArrowFunction */); + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 197 /* ArrowFunction */); } // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { - case 221 /* DoStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 220 /* IfStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 272 /* CatchClause */: + case 223 /* DoStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 274 /* CatchClause */: return spanForNode(n.parent); - case 233 /* TryStatement */: + case 235 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { return spanForNode(n.parent); } else if (tryStatement.finallyBlock === n) { - return spanForNode(ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile)); + return spanForNode(ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile)); } // falls through default: @@ -98912,21 +102523,21 @@ var ts; // the span of the block, independent of any parent span. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return spanForNode(n.parent); - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 244 /* CaseBlock */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 246 /* CaseBlock */: return spanForNode(n); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 185 /* ArrayLiteralExpression */: - return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); - case 258 /* JsxElement */: + case 187 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); + case 260 /* JsxElement */: return spanForJSXElement(n); - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); } function spanForJSXElement(node) { @@ -98942,7 +102553,7 @@ var ts; return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } function spanForObjectOrArrayLiteral(node, open) { - if (open === void 0) { open = 17 /* OpenBraceToken */; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } // If the block has no leading keywords and is inside an array literal, // we only want to collapse the span of the block. // Otherwise, the collapsed section will include the end of the previous line. @@ -98951,9 +102562,9 @@ var ts; function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { if (autoCollapse === void 0) { autoCollapse = false; } if (useFullStart === void 0) { useFullStart = true; } - if (open === void 0) { open = 17 /* OpenBraceToken */; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } var openToken = ts.findChildOfKind(n, open, sourceFile); - var close = open === 17 /* OpenBraceToken */ ? 18 /* CloseBraceToken */ : 22 /* CloseBracketToken */; + var close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; var closeToken = ts.findChildOfKind(n, close, sourceFile); if (!openToken || !closeToken) { return undefined; @@ -99248,13 +102859,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_14 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_14(start); if (typeof state_3 === "object") return state_3.value; } @@ -99312,11 +102923,11 @@ var ts; characterSpans: breakIntoCharacterSpans(text) }; } - /* @internal */ function breakIntoCharacterSpans(identifier) { + function breakIntoCharacterSpans(identifier) { return breakIntoSpans(identifier, /*word:*/ false); } ts.breakIntoCharacterSpans = breakIntoCharacterSpans; - /* @internal */ function breakIntoWordSpans(identifier) { + function breakIntoWordSpans(identifier) { return breakIntoSpans(identifier, /*word:*/ true); } ts.breakIntoWordSpans = breakIntoWordSpans; @@ -99456,10 +103067,10 @@ var ts; function nextToken() { lastToken = currentToken; currentToken = ts.scanner.scan(); - if (currentToken === 17 /* OpenBraceToken */) { + if (currentToken === 18 /* OpenBraceToken */) { braceNesting++; } - else if (currentToken === 18 /* CloseBraceToken */) { + else if (currentToken === 19 /* CloseBraceToken */) { braceNesting--; } return currentToken; @@ -99489,12 +103100,12 @@ var ts; */ function tryConsumeDeclare() { var token = ts.scanner.getToken(); - if (token === 124 /* DeclareKeyword */) { + if (token === 125 /* DeclareKeyword */) { // declare module "mod" token = nextToken(); - if (token === 129 /* ModuleKeyword */) { + if (token === 130 /* ModuleKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { recordAmbientExternalModule(); } } @@ -99506,42 +103117,42 @@ var ts; * Returns true if at least one token was consumed from the stream */ function tryConsumeImport() { - if (lastToken === 23 /* DotToken */) { + if (lastToken === 24 /* DotToken */) { return false; } var token = ts.scanner.getToken(); - if (token === 91 /* ImportKeyword */) { + if (token === 92 /* ImportKeyword */) { token = nextToken(); - if (token === 19 /* OpenParenToken */) { + if (token === 20 /* OpenParenToken */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import("mod"); recordModuleName(); return true; } } - else if (token === 9 /* StringLiteral */) { + else if (token === 10 /* StringLiteral */) { // import "mod"; recordModuleName(); return true; } else { - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import d from "mod"; recordModuleName(); return true; } } - else if (token === 58 /* EqualsToken */) { + else if (token === 59 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } - else if (token === 26 /* CommaToken */) { + else if (token === 27 /* CommaToken */) { // consume comma and keep going token = nextToken(); } @@ -99550,18 +103161,18 @@ var ts; return true; } } - if (token === 17 /* OpenBraceToken */) { + if (token === 18 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure that it stops on EOF - while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import {a as A} from "mod"; // import d, {a, b as B} from "mod" recordModuleName(); @@ -99569,15 +103180,15 @@ var ts; } } } - else if (token === 39 /* AsteriskToken */) { + else if (token === 40 /* AsteriskToken */) { token = nextToken(); - if (token === 118 /* AsKeyword */) { + if (token === 119 /* AsKeyword */) { token = nextToken(); - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import * as NS from "mod" // import d, * as NS from "mod" recordModuleName(); @@ -99593,21 +103204,21 @@ var ts; } function tryConsumeExport() { var token = ts.scanner.getToken(); - if (token === 84 /* ExportKeyword */) { + if (token === 85 /* ExportKeyword */) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 17 /* OpenBraceToken */) { + if (token === 18 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure it stops on EOF - while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // export {a as A} from "mod"; // export {a, b as B} from "mod" recordModuleName(); @@ -99615,21 +103226,21 @@ var ts; } } } - else if (token === 39 /* AsteriskToken */) { + else if (token === 40 /* AsteriskToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // export * from "mod" recordModuleName(); } } } - else if (token === 91 /* ImportKeyword */) { + else if (token === 92 /* ImportKeyword */) { token = nextToken(); - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 58 /* EqualsToken */) { + if (token === 59 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } @@ -99642,11 +103253,11 @@ var ts; } function tryConsumeRequireCall(skipCurrentToken) { var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); - if (token === 133 /* RequireKeyword */) { + if (token === 134 /* RequireKeyword */) { token = nextToken(); - if (token === 19 /* OpenParenToken */) { + if (token === 20 /* OpenParenToken */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // require("mod"); recordModuleName(); } @@ -99657,16 +103268,16 @@ var ts; } function tryConsumeDefine() { var token = ts.scanner.getToken(); - if (token === 71 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + if (token === 72 /* Identifier */ && ts.scanner.getTokenValue() === "define") { token = nextToken(); - if (token !== 19 /* OpenParenToken */) { + if (token !== 20 /* OpenParenToken */) { return true; } token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // looks like define ("modname", ... - skip string literal and comma token = nextToken(); - if (token === 26 /* CommaToken */) { + if (token === 27 /* CommaToken */) { token = nextToken(); } else { @@ -99675,15 +103286,15 @@ var ts; } } // should be start of dependency list - if (token !== 21 /* OpenBracketToken */) { + if (token !== 22 /* OpenBracketToken */) { return true; } // skip open bracket token = nextToken(); // scan until ']' or EOF - while (token !== 22 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { // record string literals as module names - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { recordModuleName(); } token = nextToken(); @@ -99791,47 +103402,61 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; - if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + if (ts.isIdentifier(node) && node.originalKeywordKind === 80 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); var width = node.getWidth(sourceFile); - if (node.kind === 9 /* StringLiteral */) { + if (node.kind === 10 /* StringLiteral */) { // Exclude the quotes start += 1; width -= 2; @@ -99840,9 +103465,9 @@ var ts; } function nodeIsEligibleForRename(node) { switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 99 /* ThisKeyword */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: return true; case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); @@ -99877,22 +103502,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // 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. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +103536,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99921,19 +103560,19 @@ var ts; return false; var invocationChildren = node.getChildren(sourceFile); switch (startingToken.kind) { - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return ts.contains(invocationChildren, startingToken); - case 26 /* CommaToken */: { + case 27 /* CommaToken */: { var containingList = ts.findContainingList(startingToken); return !!containingList && ts.contains(invocationChildren, containingList); } - case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + case 28 /* LessThanToken */: + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +103589,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -99973,7 +103612,7 @@ var ts; return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; } function getArgumentOrParameterListAndIndex(node, sourceFile) { - if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { + if (node.kind === 28 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; @@ -100026,10 +103665,10 @@ var ts; } return undefined; } - else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) { + else if (ts.isTemplateHead(node) && parent.parent.kind === 193 /* TaggedTemplateExpression */) { var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 204 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 206 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } @@ -100092,24 +103731,24 @@ var ts; return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) { - if (startingToken.kind !== 19 /* OpenParenToken */ && startingToken.kind !== 26 /* CommaToken */) + if (startingToken.kind !== 20 /* OpenParenToken */ && startingToken.kind !== 27 /* CommaToken */) return undefined; var parent = startingToken.parent; switch (parent.kind) { - case 193 /* ParenthesizedExpression */: - case 154 /* MethodDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ParenthesizedExpression */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: var info = getArgumentOrParameterListInfo(startingToken, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var highestBinary = getHighestBinary(parent); var contextualType_1 = checker.getContextualType(highestBinary); - var argumentIndex_1 = startingToken.kind === 19 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; + var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; var argumentCount_1 = countBinaryExpressionParameters(highestBinary); return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) }; } @@ -100141,7 +103780,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 26 /* CommaToken */) { + if (child.kind !== 27 /* CommaToken */) { argumentIndex++; } } @@ -100160,8 +103799,8 @@ var ts; // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. var listChildren = argumentsList.getChildren(); - var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 26 /* CommaToken */; }); - if (listChildren.length > 0 && ts.last(listChildren).kind === 26 /* CommaToken */) { + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; }); + if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -100230,7 +103869,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 === 204 /* TemplateExpression */) { + if (template.kind === 206 /* TemplateExpression */) { var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -100238,8 +103877,8 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100248,8 +103887,8 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +103903,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } - var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +103920,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(28 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(30 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100307,9 +103966,9 @@ var ts; var parameterParts = ts.mapToDisplayParts(function (writer) { var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); + printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer); }); - return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(27 /* LessThanToken */)], suffix: [ts.punctuationPart(29 /* GreaterThanToken */)].concat(parameterParts) }; + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { var isVariadic = candidateSignature.hasRestParameter; @@ -100317,11 +103976,11 @@ var ts; var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); - printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); + printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); - return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(19 /* OpenParenToken */)]), suffix: [ts.punctuationPart(20 /* CloseParenToken */)] }; + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] }; } function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { @@ -100336,60 +103995,53 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); /* @internal */ var ts; (function (ts) { - // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) - var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; - var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) { + function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var sourcemappedFileCache; - return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + var mappedFile = sourcemappedFileCache.get(toPath(fileName)); if (!mappedFile) { return; } - var starts = ts.getLineStarts(mappedFile); - for (var index = starts.length - 1; index >= 0; index--) { - var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); - var comment = sourceMapCommentRegExp.exec(lineText); - if (comment) { - return comment[1]; - } - // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file - else if (!lineText.match(whitespaceOrMapCommentRegExp)) { - break; - } - } + return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); } function convertDocumentToSourceMapper(file, contents, mapFileName) { - var maps; - try { - maps = JSON.parse(contents); - } - catch (_a) { - // swallow error - } - if (!maps || !maps.sources || !maps.file || !maps.mappings) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { // obviously invalid map - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } - return file.sourceMapper = ts.sourcemaps.decode({ - readFile: function (s) { return host.readFile(s); }, - fileExists: function (s) { return host.fileExists(s); }, + var program = getProgram(); + return file.sourceMapper = ts.createDocumentPositionMapper({ + getSourceFileLike: function (s) { + // Lookup file in program, if provided + var file = program && program.getSourceFileByPath(s); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (file === undefined || file.resolvedPath !== s) { + // Otherwise check the cache (which may hit disk) + return sourcemappedFileCache.get(s); + } + return file; + }, getCanonicalFileName: getCanonicalFileName, log: log, - }, mapFileName, maps, getProgram(), sourcemappedFileCache); + }, map, mapFileName); } function getSourceMapper(fileName, file) { if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } if (file.sourceMapper) { return file.sourceMapper; @@ -100418,20 +104070,24 @@ var ts; return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 } } - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } - function tryGetOriginalLocation(info) { + function tryGetSourcePosition(info) { if (!ts.isDeclarationFileName(info.fileName)) return undefined; var file = getFile(info.fileName); if (!file) return undefined; - var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); - return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); + return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; } - function tryGetGeneratedLocation(info) { + function tryGetGeneratedPosition(info) { var program = getProgram(); - var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + var options = program.getCompilerOptions(); + var outPath = options.outFile || options.out; + var declarationPath = outPath ? + ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : + ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); if (declarationPath === undefined) return undefined; var declarationFile = getFile(declarationPath); @@ -100441,18 +104097,45 @@ var ts; return newLoc === info ? undefined : newLoc; } function getFile(fileName) { - return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + var path = toPath(fileName); + var file = getProgram().getSourceFileByPath(path); + if (file && file.resolvedPath === path) { + return file; + } + return sourcemappedFileCache.get(path); } function toLineColumnOffset(fileName, position) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 + var file = getFile(fileName); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } function clearCache() { - sourcemappedFileCache = ts.createSourceFileLikeCache(host); + sourcemappedFileCache = createSourceFileLikeCache(host); } } ts.getSourceMapper = getSourceMapper; + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } })(ts || (ts = {})); /* @internal */ var ts; @@ -100460,13 +104143,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100488,8 +104171,8 @@ var ts; function check(node) { if (isJsFile) { switch (node.kind) { - case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + case 196 /* FunctionExpression */: + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100498,7 +104181,7 @@ var ts; } } // falls through if no diagnostic was created - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: var symbol = node.symbol; if (symbol.members && (symbol.members.size > 0)) { diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); @@ -100531,15 +104214,15 @@ var ts; function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 - case 219 /* ExpressionStatement */: { + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 221 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100552,66 +104235,74 @@ var ts; } function importNameForConvertToDefaultImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 249 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 251 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node.name; default: return undefined; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { - return; + if (!ts.isAsyncFunction(node) && + node.body && + ts.isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker)) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } + } + function returnsPromise(node, checker) { + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; - if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { - return; - } - // collect all the return statements - // check that a property access expression exists in there and that it is a handler - var returnStatements = getReturnStatementsWithPromiseHandlers(node); - if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); - } + return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - /** @internal */ - function getReturnStatementsWithPromiseHandlers(node) { - var returnStatements = []; - if (ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - else { - visit(node); - } - function visit(child) { - if (ts.isFunctionLike(child)) { - return; - } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } - } - ts.forEachChild(child, visit); - } - return returnStatements; + function hasReturnStatementWithPromiseHandler(body) { + return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); } - ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + function isReturnStatementWithFixablePromiseHandler(node) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + } + ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + ts.isFixablePromiseHandler = isFixablePromiseHandler; function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100627,7 +104318,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -100664,7 +104355,7 @@ var ts; if (typeChecker.isArgumentsSymbol(symbol)) { return "local var" /* localVariableElement */; } - if (location.kind === 99 /* ThisKeyword */ && ts.isExpression(location)) { + if (location.kind === 100 /* ThisKeyword */ && ts.isExpression(location)) { return "parameter" /* parameterElement */; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); @@ -100715,11 +104406,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 260 /* JsxOpeningElement */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 265 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + return location.kind === 72 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 267 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -100744,13 +104435,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 100 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 100 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(100 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100759,7 +104453,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 187 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 189 /* 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)) { @@ -100780,7 +104474,7 @@ var ts; if (callExpressionLike) { var candidateSignatures = []; signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 - var useConstructSignatures = callExpressionLike.kind === 190 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 192 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 98 /* 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 @@ -100798,7 +104492,7 @@ var ts; pushSymbolKind(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addFullSymbolName(symbol); @@ -100815,14 +104509,14 @@ var ts; case "parameter" /* parameterElement */: case "local var" /* localVariableElement */: // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(56 /* ColonToken */)); + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); displayParts.push(ts.spacePart()); if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); @@ -100835,29 +104529,29 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 155 /* Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 124 /* ConstructorKeyword */ && location.parent.kind === 157 /* Constructor */)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { - return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + return declaration === (location.kind === 124 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 155 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 157 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 155 /* Constructor */) { + if (functionDeclaration_1.kind === 157 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 158 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 160 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -100867,7 +104561,7 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 209 /* 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 @@ -100875,7 +104569,7 @@ var ts; } else { // Class declaration has name which is not local. - displayParts.push(ts.keywordPart(75 /* ClassKeyword */)); + displayParts.push(ts.keywordPart(76 /* ClassKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -100883,45 +104577,45 @@ var ts; } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); + displayParts.push(ts.keywordPart(110 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { - displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); + displayParts.push(ts.keywordPart(77 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } - displayParts.push(ts.keywordPart(83 /* EnumKeyword */)); + displayParts.push(ts.keywordPart(84 /* EnumKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 242 /* ModuleDeclaration */); - var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 130 /* NamespaceKeyword */ : 129 /* ModuleKeyword */)); + var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 131 /* NamespaceKeyword */ : 130 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); if (symbol.parent) { @@ -100932,7 +104626,7 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 148 /* TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 150 /* TypeParameter */); if (decl === undefined) return ts.Debug.fail(); var declaration = decl.parent; @@ -100940,21 +104634,21 @@ var ts; if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 - if (declaration.kind === 159 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + if (declaration.kind === 161 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 158 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 160 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 240 /* TypeAliasDeclaration */) { + else if (declaration.kind === 242 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path addInPrefix(); - displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -100966,11 +104660,11 @@ var ts; symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 276 /* EnumMember */) { + if (declaration.kind === 278 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } @@ -100996,41 +104690,41 @@ var ts; } } switch (symbol.declarations[0].kind) { - case 245 /* NamespaceExportDeclaration */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 247 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(130 /* NamespaceKeyword */)); + displayParts.push(ts.keywordPart(131 /* NamespaceKeyword */)); break; - case 252 /* ExportAssignment */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 254 /* ExportAssignment */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 59 /* EqualsToken */ : 80 /* DefaultKeyword */)); break; - case 255 /* ExportSpecifier */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 257 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); break; default: - displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); + displayParts.push(ts.keywordPart(92 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 246 /* ImportEqualsDeclaration */) { + if (declaration.kind === 248 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(133 /* RequireKeyword */)); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.keywordPart(134 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); } else { var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(internalAliasSymbol, enclosingDeclaration); } @@ -101044,7 +104738,7 @@ var ts; if (type) { if (isThisExpression) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); + displayParts.push(ts.keywordPart(100 /* ThisKeyword */)); } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); @@ -101055,7 +104749,7 @@ var ts; symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || isThisExpression) { - displayParts.push(ts.punctuationPart(56 /* ColonToken */)); + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); displayParts.push(ts.spacePart()); // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { @@ -101093,10 +104787,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 277 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 202 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -101118,7 +104812,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101139,7 +104833,7 @@ var ts; } function addInPrefix() { displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(92 /* InKeyword */)); + displayParts.push(ts.keywordPart(93 /* InKeyword */)); displayParts.push(ts.spacePart()); } function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { @@ -101149,7 +104843,7 @@ var ts; var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); if (symbol.flags & 16777216 /* Optional */) { - displayParts.push(ts.punctuationPart(55 /* QuestionToken */)); + displayParts.push(ts.punctuationPart(56 /* QuestionToken */)); } } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { @@ -101172,9 +104866,9 @@ var ts; displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); return; } } @@ -101183,20 +104877,21 @@ var ts; ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); - displayParts.push(ts.operatorPart(37 /* PlusToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(38 /* PlusToken */)); displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); displayParts.push(ts.spacePart()); displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); - getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -101208,16 +104903,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 194 /* FunctionExpression */) { + if (declaration.kind === 196 /* FunctionExpression */) { return true; } - if (declaration.kind !== 235 /* VariableDeclaration */ && declaration.kind !== 237 /* FunctionDeclaration */) { + if (declaration.kind !== 237 /* VariableDeclaration */ && declaration.kind !== 239 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 277 /* SourceFile */ || parent.kind === 243 /* ModuleBlock */) { + if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) { return false; } } @@ -101257,6 +104952,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +105026,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_16 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +105045,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_16(opt); } return options; } @@ -101376,16 +105072,11 @@ var ts; this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { - ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); - ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); - ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); - ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); - ts.Debug.assert(commonParent !== undefined, "commonParent is null"); - this.currentTokenSpan = currentRange; - this.currentTokenParent = currentTokenParent; - this.nextTokenSpan = nextRange; - this.nextTokenParent = nextTokenParent; - this.contextNode = commonParent; + this.currentTokenSpan = ts.Debug.assertDefined(currentRange); + this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent); + this.nextTokenSpan = ts.Debug.assertDefined(nextRange); + this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent); + this.contextNode = ts.Debug.assertDefined(commonParent); // drop cached results this.contextNodeAllOnSameLine = undefined; this.nextNodeAllOnSameLine = undefined; @@ -101431,8 +105122,8 @@ var ts; return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 17 /* OpenBraceToken */, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 18 /* CloseBraceToken */, this.sourceFile); + var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile); if (openBrace && closeBrace) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; @@ -101514,11 +105205,11 @@ var ts; } function shouldRescanGreaterThanToken(node) { switch (node.kind) { - case 31 /* GreaterThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 46 /* GreaterThanGreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: return true; } return false; @@ -101526,28 +105217,28 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 265 /* JsxAttribute */: - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 267 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. - return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; + return ts.isKeyword(node.kind) || node.kind === 72 /* Identifier */; } } return false; } function shouldRescanJsxText(node) { - return node.kind === 10 /* JsxText */; + return node.kind === 11 /* JsxText */; } function shouldRescanSlashToken(container) { - return container.kind === 12 /* RegularExpressionLiteral */; + return container.kind === 13 /* RegularExpressionLiteral */; } function shouldRescanTemplateToken(container) { - return container.kind === 15 /* TemplateMiddle */ || - container.kind === 16 /* TemplateTail */; + return container.kind === 16 /* TemplateMiddle */ || + container.kind === 17 /* TemplateTail */; } function startsWithSlashToken(t) { - return t === 41 /* SlashToken */ || t === 63 /* SlashEqualsToken */; + return t === 42 /* SlashToken */ || t === 64 /* SlashEqualsToken */; } function readTokenInfo(n) { ts.Debug.assert(isOnToken()); @@ -101617,7 +105308,7 @@ var ts; lastScanAction = 0 /* Scan */; switch (expectedScanAction) { case 1 /* RescanGreaterThanToken */: - if (token === 29 /* GreaterThanToken */) { + if (token === 30 /* GreaterThanToken */) { lastScanAction = 1 /* RescanGreaterThanToken */; var newToken = scanner.reScanGreaterToken(); ts.Debug.assert(n.kind === newToken); @@ -101633,7 +105324,7 @@ var ts; } break; case 3 /* RescanTemplateToken */: - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { lastScanAction = 3 /* RescanTemplateToken */; return scanner.reScanTemplateToken(); } @@ -101706,7 +105397,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 145 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 147 /* LastToken */; token++) { allTokens.push(token); } function anyTokenExcept() { @@ -101718,255 +105409,255 @@ var ts; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); - var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 145 /* LastKeyword */); - var binaryOperators = tokenRangeFromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 145 /* OfKeyword */, 118 /* AsKeyword */, 127 /* IsKeyword */]; - var unaryPrefixOperators = [43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]; + var keywords = tokenRangeFromRange(73 /* FirstKeyword */, 147 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(28 /* FirstBinaryOperator */, 71 /* LastBinaryOperator */); + var binaryKeywordOperators = [93 /* InKeyword */, 94 /* InstanceOfKeyword */, 147 /* OfKeyword */, 119 /* AsKeyword */, 128 /* IsKeyword */]; + var unaryPrefixOperators = [44 /* PlusPlusToken */, 45 /* MinusMinusToken */, 53 /* TildeToken */, 52 /* ExclamationToken */]; var unaryPrefixExpressions = [ - 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, - 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 72 /* Identifier */, 20 /* OpenParenToken */, + 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */ ]; - var unaryPreincrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; - var unaryPostincrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; - var unaryPredecrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; - var unaryPostdecrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; + var unaryPreincrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostincrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var unaryPredecrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostdecrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; - var typeNames = [71 /* Identifier */].concat(ts.typeKeywords); + var typeNames = [72 /* Identifier */].concat(ts.typeKeywords); // Place a space before open brace in a function declaration // TypeScript: Function can have return types, which can be made of tons of different token kinds var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) - var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([72 /* Identifier */, 3 /* MultiLineCommentTrivia */, 76 /* ClassKeyword */, 85 /* ExportKeyword */, 92 /* ImportKeyword */]); // Place a space before open brace in a control flow construct - var controlOpenBraceLeftTokenRange = tokenRangeFrom([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); + var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 82 /* DoKeyword */, 103 /* TryKeyword */, 88 /* FinallyKeyword */, 83 /* ElseKeyword */]); // These rules are higher in priority than user-configurable var highPriorityCommonRules = [ // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), - rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), - rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), - rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NotSpaceBeforeColon", anyToken, 57 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), + rule("SpaceAfterColon", 57 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 56 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // insert space after '?' only when it is used in conditional operator - rule("SpaceAfterQuestionMarkInConditionalOperator", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + rule("SpaceAfterQuestionMarkInConditionalOperator", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), // in other cases there should be no space between '?' and next token - rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), + rule("NoSpaceAfterQuestionMark", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 92 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), - rule("NoSpaceAfterUnaryPreincrementOperator", 43 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterUnaryPredecrementOperator", 44 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 44 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 45 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 45 /* MinusMinusToken */, [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 - rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterPostincrementWhenFollowedByAdd", 44 /* PlusPlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 38 /* PlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 38 /* PlusToken */, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 45 /* MinusMinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 39 /* MinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 39 /* MinusToken */, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // For functions and control block place } on a new line [multi-line rule] - rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), // Space/new line after }. - rule("SpaceAfterCloseBrace", 18 /* CloseBraceToken */, anyTokenExcept(20 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, 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 // Also should not apply to }) - rule("SpaceBetweenCloseBraceAndElse", 18 /* CloseBraceToken */, 82 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenCloseBraceAndWhile", 18 /* CloseBraceToken */, 106 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 83 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 107 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' - rule("SpaceAfterConditionalClosingParen", 20 /* CloseParenToken */, 21 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), - rule("NoSpaceBetweenFunctionKeywordAndStar", 89 /* FunctionKeyword */, 39 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), - rule("SpaceAfterStarInGeneratorDeclaration", 39 /* AsteriskToken */, [71 /* Identifier */, 19 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), - rule("SpaceAfterFunctionInFuncDecl", 89 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 90 /* FunctionKeyword */, 40 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 40 /* AsteriskToken */, [72 /* Identifier */, 20 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 90 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), // Insert new line after { and before } in multi-line contexts. - rule("NewLineAfterOpenBraceInBlockContext", 17 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: // get x() {} // set x(val) {} - rule("SpaceAfterGetSetInMember", [125 /* GetKeyword */, 136 /* SetKeyword */], 71 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceBetweenYieldKeywordAndStar", 116 /* YieldKeyword */, 39 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), - rule("SpaceBetweenYieldOrYieldStarAndOperand", [116 /* YieldKeyword */, 39 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), - rule("NoSpaceBetweenReturnAndSemicolon", 96 /* ReturnKeyword */, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterCertainKeywords", [104 /* VarKeyword */, 100 /* ThrowKeyword */, 94 /* NewKeyword */, 80 /* DeleteKeyword */, 96 /* ReturnKeyword */, 103 /* TypeOfKeyword */, 121 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceAfterLetConstInVariableDeclaration", [110 /* LetKeyword */, 76 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), - rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), + rule("SpaceAfterGetSetInMember", [126 /* GetKeyword */, 137 /* SetKeyword */], 72 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 117 /* YieldKeyword */, 40 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [117 /* YieldKeyword */, 40 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 97 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [105 /* VarKeyword */, 101 /* ThrowKeyword */, 95 /* NewKeyword */, 81 /* DeleteKeyword */, 97 /* ReturnKeyword */, 104 /* TypeOfKeyword */, 122 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [111 /* LetKeyword */, 77 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterVoidOperator", 105 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 106 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), // Async-await - rule("SpaceBetweenAsyncAndOpenParen", 120 /* AsyncKeyword */, 19 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 120 /* AsyncKeyword */, 89 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndOpenParen", 121 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 121 /* AsyncKeyword */, 90 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), // Template string - rule("NoSpaceBetweenTagAndTemplateString", [71 /* Identifier */, 20 /* CloseParenToken */], [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenTagAndTemplateString", [72 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // JSX opening elements - rule("SpaceBeforeJsxAttribute", anyToken, 71 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 41 /* SlashToken */, 29 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 58 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterEqualInJsxAttribute", 58 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeJsxAttribute", anyToken, 72 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 42 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 42 /* SlashToken */, 30 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 59 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 59 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), // TypeScript-specific rules // Use of module as a function call. e.g.: import m2 = module("m2"); - rule("NoSpaceAfterModuleImport", [129 /* ModuleKeyword */, 133 /* RequireKeyword */], 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterModuleImport", [130 /* ModuleKeyword */, 134 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Add a space around certain TypeScript keywords rule("SpaceAfterCertainTypeScriptKeywords", [ - 117 /* AbstractKeyword */, - 75 /* ClassKeyword */, - 124 /* DeclareKeyword */, - 79 /* DefaultKeyword */, - 83 /* EnumKeyword */, - 84 /* ExportKeyword */, - 85 /* ExtendsKeyword */, - 125 /* GetKeyword */, - 108 /* ImplementsKeyword */, - 91 /* ImportKeyword */, - 109 /* InterfaceKeyword */, - 129 /* ModuleKeyword */, - 130 /* NamespaceKeyword */, - 112 /* PrivateKeyword */, - 114 /* PublicKeyword */, - 113 /* ProtectedKeyword */, - 132 /* ReadonlyKeyword */, - 136 /* SetKeyword */, - 115 /* StaticKeyword */, - 139 /* TypeKeyword */, - 143 /* FromKeyword */, - 128 /* KeyOfKeyword */, - 126 /* InferKeyword */, + 118 /* AbstractKeyword */, + 76 /* ClassKeyword */, + 125 /* DeclareKeyword */, + 80 /* DefaultKeyword */, + 84 /* EnumKeyword */, + 85 /* ExportKeyword */, + 86 /* ExtendsKeyword */, + 126 /* GetKeyword */, + 109 /* ImplementsKeyword */, + 92 /* ImportKeyword */, + 110 /* InterfaceKeyword */, + 130 /* ModuleKeyword */, + 131 /* NamespaceKeyword */, + 113 /* PrivateKeyword */, + 115 /* PublicKeyword */, + 114 /* ProtectedKeyword */, + 133 /* ReadonlyKeyword */, + 137 /* SetKeyword */, + 116 /* StaticKeyword */, + 140 /* TypeKeyword */, + 144 /* FromKeyword */, + 129 /* KeyOfKeyword */, + 127 /* InferKeyword */, ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 143 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [86 /* ExtendsKeyword */, 109 /* ImplementsKeyword */, 144 /* FromKeyword */], [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" { - rule("SpaceAfterModuleName", 9 /* StringLiteral */, 17 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), + rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), // Lambda expressions - rule("SpaceBeforeArrow", anyToken, 36 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceAfterArrow", 36 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeArrow", anyToken, 37 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 37 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Optional parameters and let args - rule("NoSpaceAfterEllipsis", 24 /* DotDotDotToken */, 71 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOptionalParameters", 55 /* QuestionToken */, [20 /* CloseParenToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 72 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 56 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // Remove spaces in empty interface literals. e.g.: x: {} - rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), // generics and type assertions - rule("NoSpaceBeforeOpenAngularBracket", typeNames, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceBetweenCloseParenAndAngularBracket", 20 /* CloseParenToken */, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterOpenAngularBracket", 27 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 28 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 30 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 30 /* GreaterThanToken */, [20 /* OpenParenToken */, 22 /* OpenBracketToken */, 30 /* GreaterThanToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), // decorators - rule("SpaceBeforeAt", [20 /* CloseParenToken */, 71 /* Identifier */], 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeAt", [21 /* CloseParenToken */, 72 /* Identifier */], 58 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 58 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after @ in decorator rule("SpaceAfterDecorator", anyToken, [ - 117 /* AbstractKeyword */, - 71 /* Identifier */, - 84 /* ExportKeyword */, - 79 /* DefaultKeyword */, - 75 /* ClassKeyword */, - 115 /* StaticKeyword */, - 114 /* PublicKeyword */, - 112 /* PrivateKeyword */, - 113 /* ProtectedKeyword */, - 125 /* GetKeyword */, - 136 /* SetKeyword */, - 21 /* OpenBracketToken */, - 39 /* AsteriskToken */, + 118 /* AbstractKeyword */, + 72 /* Identifier */, + 85 /* ExportKeyword */, + 80 /* DefaultKeyword */, + 76 /* ClassKeyword */, + 116 /* StaticKeyword */, + 115 /* PublicKeyword */, + 113 /* PrivateKeyword */, + 114 /* ProtectedKeyword */, + 126 /* GetKeyword */, + 137 /* SetKeyword */, + 22 /* OpenBracketToken */, + 40 /* AsteriskToken */, ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), - rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 51 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterNewKeywordOnConstructorSignature", 94 /* NewKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 52 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 95 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), ]; // These rules are applied after high priority var userConfigurableRules = [ // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses - rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), - rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), + rule("SpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), // Insert space after function keyword for anonymous functions - rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), + rule("SpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), // Insert space after keywords in control flow statements - rule("SpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), - rule("NoSpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), + rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), // Insert space after opening and before closing nonempty parenthesis - rule("SpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenOpenParens", 19 /* OpenParenToken */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenParens", 19 /* OpenParenToken */, 20 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing nonempty brackets - rule("SpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenBrackets", 21 /* OpenBracketToken */, 22 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - rule("SpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), - rule("SpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), - rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), - rule("NoSpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing template string braces - rule("SpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // No space after { and before } in JSX expression - rule("SpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), - rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), - rule("NoSpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), // Insert space after semicolon in for statement - rule("SpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), - rule("NoSpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), // Insert space before and after binary operators rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), - rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), // Open Brace braces after control block - rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), // Open Brace braces after function // TypeScript: Function can have return types, which can be made of tons of different token kinds - rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), // Open Brace braces after TypeScript module/class/interface - rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), - rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), - rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), - rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), - rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), ]; // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. var lowPriorityCommonRules = [ // Space after keyword but not before ; or : or ? - rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // No space before and after indexer `x[]` - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), - rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(121 /* AsyncKeyword */, 74 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Remove extra space between for and await - rule("SpaceBetweenForAndAwaitKeyword", 88 /* ForKeyword */, 121 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenForAndAwaitKeyword", 89 /* ForKeyword */, 122 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), // 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] - rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), + rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 82 /* DoKeyword */, 83 /* ElseKeyword */, 74 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterTryFinally", [103 /* TryKeyword */, 88 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), ]; return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); } @@ -102010,45 +105701,45 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 223 /* ForStatement */; + return context.contextNode.kind === 225 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 202 /* BinaryExpression */: - case 203 /* ConditionalExpression */: - case 173 /* ConditionalType */: - case 210 /* AsExpression */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 161 /* TypePredicate */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 175 /* ConditionalType */: + case 212 /* AsExpression */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 163 /* TypePredicate */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 184 /* BindingElement */: + case 186 /* BindingElement */: // equals in type X = ... - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: // equal in p = 0; - case 149 /* Parameter */: - case 276 /* EnumMember */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; + case 151 /* Parameter */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] - case 148 /* TypeParameter */: - return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; + case 150 /* TypeParameter */: + return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 225 /* ForOfStatement */: - return context.currentTokenSpan.kind === 145 /* OfKeyword */ || context.nextTokenSpan.kind === 145 /* OfKeyword */; + case 227 /* ForOfStatement */: + return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */; } return false; } @@ -102060,22 +105751,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 152 /* PropertyDeclaration */ || - contextKind === 151 /* PropertySignature */ || - contextKind === 149 /* Parameter */ || - contextKind === 235 /* VariableDeclaration */ || + return contextKind === 154 /* PropertyDeclaration */ || + contextKind === 153 /* PropertySignature */ || + contextKind === 151 /* Parameter */ || + contextKind === 237 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 203 /* ConditionalExpression */ || - context.contextNode.kind === 173 /* ConditionalType */; + return context.contextNode.kind === 205 /* ConditionalExpression */ || + context.contextNode.kind === 175 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 182 /* ObjectBindingPattern */ || - context.contextNode.kind === 179 /* MappedType */ || + return context.contextNode.kind === 184 /* ObjectBindingPattern */ || + context.contextNode.kind === 181 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -102101,31 +105792,31 @@ var ts; return true; } switch (node.kind) { - case 216 /* Block */: - case 244 /* CaseBlock */: - case 186 /* ObjectLiteralExpression */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 188 /* ObjectLiteralExpression */: + case 245 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // case SyntaxKind.MethodSignature: - case 158 /* CallSignature */: - case 194 /* FunctionExpression */: - case 155 /* Constructor */: - case 195 /* ArrowFunction */: + case 160 /* CallSignature */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 197 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 239 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 241 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -102134,40 +105825,40 @@ var ts; return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 237 /* FunctionDeclaration */ || context.contextNode.kind === 194 /* FunctionExpression */; + return context.contextNode.kind === 239 /* FunctionDeclaration */ || context.contextNode.kind === 196 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 166 /* TypeLiteral */: - case 242 /* ModuleDeclaration */: - case 253 /* ExportDeclaration */: - case 254 /* NamedExports */: - case 247 /* ImportDeclaration */: - case 250 /* NamedImports */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 168 /* TypeLiteral */: + case 244 /* ModuleDeclaration */: + case 255 /* ExportDeclaration */: + case 256 /* NamedExports */: + case 249 /* ImportDeclaration */: + case 252 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 272 /* CatchClause */: - case 243 /* ModuleBlock */: - case 230 /* SwitchStatement */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 274 /* CatchClause */: + case 245 /* ModuleBlock */: + case 232 /* SwitchStatement */: return true; - case 216 /* Block */: { + case 218 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 195 /* ArrowFunction */ && blockParent.kind !== 194 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 197 /* ArrowFunction */ && blockParent.kind !== 196 /* FunctionExpression */) { return true; } } @@ -102176,64 +105867,64 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 220 /* IfStatement */: - case 230 /* SwitchStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: - case 233 /* TryStatement */: - case 221 /* DoStatement */: - case 229 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 231 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 272 /* CatchClause */: + case 274 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 186 /* ObjectLiteralExpression */; + return context.contextNode.kind === 188 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 189 /* CallExpression */; + return context.contextNode.kind === 191 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 190 /* NewExpression */; + return context.contextNode.kind === 192 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); } function isPreviousTokenNotComma(context) { - return context.currentTokenSpan.kind !== 26 /* CommaToken */; + return context.currentTokenSpan.kind !== 27 /* CommaToken */; } function isNextTokenNotCloseBracket(context) { - return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; + return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 195 /* ArrowFunction */; + return context.contextNode.kind === 197 /* ArrowFunction */; } function isImportTypeContext(context) { - return context.contextNode.kind === 181 /* ImportType */; + return context.contextNode.kind === 183 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; + return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 258 /* JsxElement */ && context.contextNode.kind !== 262 /* JsxFragment */; + return context.contextNode.kind !== 260 /* JsxElement */ && context.contextNode.kind !== 264 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 268 /* JsxExpression */ || context.contextNode.kind === 267 /* JsxSpreadAttribute */; + return context.contextNode.kind === 270 /* JsxExpression */ || context.contextNode.kind === 269 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 265 /* JsxAttribute */; + return context.nextTokenParent.kind === 267 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 265 /* JsxAttribute */; + return context.contextNode.kind === 267 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 259 /* JsxSelfClosingElement */; + return context.contextNode.kind === 261 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -102248,45 +105939,45 @@ var ts; while (ts.isExpressionNode(node)) { node = node.parent; } - return node.kind === 150 /* Decorator */; + return node.kind === 152 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 236 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 238 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 242 /* ModuleDeclaration */; + return context.contextNode.kind === 244 /* ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 166 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 168 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 159 /* ConstructSignature */; + return context.contextNode.kind === 161 /* ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { - if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { + if (token.kind !== 28 /* LessThanToken */ && token.kind !== 30 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 162 /* TypeReference */: - case 192 /* TypeAssertionExpression */: - case 240 /* TypeAliasDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 209 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 194 /* TypeAssertionExpression */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -102297,16 +105988,16 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 192 /* TypeAssertionExpression */; + return context.contextNode.kind === 194 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 198 /* VoidExpression */; + return context.currentTokenSpan.kind === 106 /* VoidKeyword */ && context.currentTokenParent.kind === 200 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 205 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 207 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 211 /* NonNullExpression */; + return context.contextNode.kind === 213 /* NonNullExpression */; } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -102357,12 +106048,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 145 /* LastKeyword */ && column <= 145 /* LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 147 /* LastKeyword */ && column <= 147 /* LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 145 /* LastToken */ + 1; + var mapRowLength = 147 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; @@ -102451,12 +106142,12 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, formatContext) { - var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25 /* SemicolonToken */, sourceFile); + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; function formatOnOpeningCurly(position, sourceFile, formatContext) { - var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17 /* OpenBraceToken */, sourceFile); + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile); if (!openingCurly) { return []; } @@ -102482,7 +106173,7 @@ var ts; } formatting.formatOnOpeningCurly = formatOnOpeningCurly; function formatOnClosingCurly(position, sourceFile, formatContext) { - var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18 /* CloseBraceToken */, sourceFile); + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; @@ -102540,17 +106231,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 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: var body = parent.body; - return !!body && body.kind === 243 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 277 /* SourceFile */: - case 216 /* Block */: - case 243 /* ModuleBlock */: + return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 279 /* SourceFile */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -102663,7 +106354,6 @@ var ts; } return 0; } - /* @internal */ function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { var range = { pos: 0, end: sourceFileLike.text.length }; return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors @@ -102693,7 +106383,7 @@ var ts; var previousParent; var previousRangeStartLine; var lastIndentedLine; - var indentationOnLastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -102707,7 +106397,7 @@ var ts; if (!formattingScanner.isOnToken()) { var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); // TODO: GH#18217 + indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); trimTrailingWhitespacesForRemainingRange(); } } @@ -102752,7 +106442,7 @@ var ts; }; } else if (inheritedIndentation === -1 /* Unknown */) { - if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) { + if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) { // the is used for chaining methods formatting // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; @@ -102773,19 +106463,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 238 /* ClassDeclaration */: return 75 /* ClassKeyword */; - case 239 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; - case 237 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; - case 241 /* EnumDeclaration */: return 241 /* EnumDeclaration */; - case 156 /* GetAccessor */: return 125 /* GetKeyword */; - case 157 /* SetAccessor */: return 136 /* SetKeyword */; - case 154 /* MethodDeclaration */: + case 240 /* ClassDeclaration */: return 76 /* ClassKeyword */; + case 241 /* InterfaceDeclaration */: return 110 /* InterfaceKeyword */; + case 239 /* FunctionDeclaration */: return 90 /* FunctionKeyword */; + case 243 /* EnumDeclaration */: return 243 /* EnumDeclaration */; + case 158 /* GetAccessor */: return 126 /* GetKeyword */; + case 159 /* SetAccessor */: return 137 /* SetKeyword */; + case 156 /* MethodDeclaration */: if (node.asteriskToken) { - return 39 /* AsteriskToken */; + return 40 /* AsteriskToken */; } // falls through - case 152 /* PropertyDeclaration */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: var name = ts.getNameOfDeclaration(node); if (name) { return name.kind; @@ -102800,15 +106490,25 @@ var ts; // .. { // // comment // } - case 18 /* CloseBraceToken */: - case 22 /* CloseBracketToken */: - case 20 /* CloseParenToken */: + case 19 /* CloseBraceToken */: + case 23 /* CloseBracketToken */: + case 21 /* CloseParenToken */: return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind, container) { - return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; + // if list end token is LessThanToken '>' then its delta should be explicitly suppressed + // so that LessThanToken as a binary operator can still be indented. + // foo.then + // < + // number, + // string, + // >(); + // vs + // var a = xValue + // > yValue; + getIndentationForToken: function (line, kind, container, suppressDelta) { + return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, getDelta: getDelta, @@ -102822,26 +106522,25 @@ var ts; function shouldAddDelta(line, kind, container) { switch (kind) { // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 17 /* OpenBraceToken */: - case 18 /* CloseBraceToken */: - case 19 /* OpenParenToken */: - case 20 /* CloseParenToken */: - case 82 /* ElseKeyword */: - case 106 /* WhileKeyword */: - case 57 /* AtToken */: + case 18 /* OpenBraceToken */: + case 19 /* CloseBraceToken */: + case 21 /* CloseParenToken */: + case 83 /* ElseKeyword */: + case 107 /* WhileKeyword */: + case 58 /* AtToken */: return false; - case 41 /* SlashToken */: - case 29 /* GreaterThanToken */: + case 42 /* SlashToken */: + case 30 /* GreaterThanToken */: switch (container.kind) { - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: return false; } break; - case 21 /* OpenBracketToken */: - case 22 /* CloseBracketToken */: - if (container.kind !== 179 /* MappedType */) { + case 22 /* OpenBracketToken */: + case 23 /* CloseBracketToken */: + if (container.kind !== 181 /* MappedType */) { return false; } break; @@ -102926,22 +106625,22 @@ var ts; return inheritedIndentation; } // JSX text shouldn't affect indenting - if (ts.isToken(child) && child.kind !== 10 /* JsxText */) { + if (ts.isToken(child) && child.kind !== 11 /* JsxText */) { // 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, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 150 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 152 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); - if (child.kind === 10 /* JsxText */) { + if (child.kind === 11 /* JsxText */) { var range = { pos: child.getStart(), end: child.getEnd() }; indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); } childContextNode = node; - if (isFirstListItem && parent.kind === 185 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 187 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -102962,9 +106661,20 @@ var ts; else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta); - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + var indentationOnListStartToken = void 0; + if (indentationOnLastIndentedLine !== -1 /* Unknown */) { + // scanner just processed list start token so consider last indentation as list indentation + // function foo(): { // last indentation was 0, list item will be indented based on this value + // foo: number; + // }: {}; + indentationOnListStartToken = indentationOnLastIndentedLine; + } + else { + var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile); + indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options); + } + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217 } else { // consume any tokens that precede the list as child elements of 'node' using its indentation scope @@ -102980,21 +106690,21 @@ var ts; var listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); - if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true); } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -103026,32 +106736,12 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : -1 /* Unknown */; var indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); - for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { - var triviaItem = _a[_i]; - var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); - switch (triviaItem.kind) { - case 3 /* MultiLineCommentTrivia */: - if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); - } - indentNextTokenOrTrivia = false; - break; - case 2 /* SingleLineCommentTrivia */: - if (indentNextTokenOrTrivia && triviaInRange) { - insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); - } - indentNextTokenOrTrivia = false; - break; - case 4 /* NewLineTrivia */: - indentNextTokenOrTrivia = true; - break; - } - } + var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); }); } // indent token only if is it is in target range and does not overlap with any error ranges if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { @@ -103064,16 +106754,39 @@ var ts; childContextNode = parent; } } - function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) { for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { var triviaItem = trivia_1[_i]; + var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); + switch (triviaItem.kind) { + case 3 /* MultiLineCommentTrivia */: + if (triviaInRange) { + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + } + indentNextTokenOrTrivia = false; + break; + case 2 /* SingleLineCommentTrivia */: + if (indentNextTokenOrTrivia && triviaInRange) { + indentSingleLine(triviaItem); + } + indentNextTokenOrTrivia = false; + break; + case 4 /* NewLineTrivia */: + indentNextTokenOrTrivia = true; + break; + } + } + return indentNextTokenOrTrivia; + } + function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) { + var triviaItem = trivia_2[_i]; if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); } } } - // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAction = 0 /* None */; @@ -103245,7 +106958,10 @@ var ts; * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - var startPosition = previousRange ? previousRange.end : originalRange.pos; + if (!previousRange) { + return; + } + var startPosition = previousRange.end; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); @@ -103345,41 +107061,46 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 195 /* ArrowFunction */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 197 /* ArrowFunction */: if (node.typeParameters === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } else if (node.parameters === list) { - return 19 /* OpenParenToken */; + return 20 /* OpenParenToken */; } break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: if (node.typeArguments === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } else if (node.arguments === list) { - return 19 /* OpenParenToken */; + return 20 /* OpenParenToken */; } break; - case 162 /* TypeReference */: + case 164 /* TypeReference */: if (node.typeArguments === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } + break; + case 168 /* TypeLiteral */: + return 18 /* OpenBraceToken */; } return 0 /* Unknown */; } function getCloseTokenForOpenToken(kind) { switch (kind) { - case 19 /* OpenParenToken */: - return 20 /* CloseParenToken */; - case 27 /* LessThanToken */: - return 29 /* GreaterThanToken */; + case 20 /* OpenParenToken */: + return 21 /* CloseParenToken */; + case 28 /* LessThanToken */: + return 30 /* GreaterThanToken */; + case 18 /* OpenBraceToken */: + return 19 /* CloseBraceToken */; } return 0 /* Unknown */; } @@ -103484,13 +107205,18 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 202 /* BinaryExpression */) { + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 204 /* 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 */) { return actualIndentation; } } + var containerList = getListByPosition(position, precedingToken.parent, sourceFile); + // use list position if the preceding token is before any list items + if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) { + return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217 + } return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); } SmartIndenter.getIndentation = getIndentation; @@ -103501,12 +107227,12 @@ var ts; if (previousLine <= commentStartLine) { return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); } - var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); - var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; if (column === 0) { return column; } - var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; } function getBlockIndent(sourceFile, position, options) { @@ -103539,14 +107265,13 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 } // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); + // do not consider parent-child line sharing yet: + // function foo(a + // | preceding node 'a' does share line with its parent but indentation is expected + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } - actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); - if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; // TODO: GH#18217 - } previous = current; current = current.parent; } @@ -103573,23 +107298,17 @@ var ts; var start = current.getStart(sourceFile); useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; } - if (useActualIndentation) { - // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); - if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + indentationDelta; - } - } var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { - // try to fetch actual indentation for current node from source text - var actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); + // check if current node is a list item - if yes, take indentation from it + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } - actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + // try to fetch actual indentation for current node from source text + actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -103640,7 +107359,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.isStatementButNotDeclaration(current)) && - (parent.kind === 277 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -103657,11 +107376,11 @@ var ts; if (!nextToken) { return 0 /* Unknown */; } - if (nextToken.kind === 17 /* OpenBraceToken */) { + if (nextToken.kind === 18 /* OpenBraceToken */) { // open braces are always indented at the parent level return 1 /* OpenBrace */; } - else if (nextToken.kind === 18 /* CloseBraceToken */) { + else if (nextToken.kind === 19 /* CloseBraceToken */) { // close braces are indented at the parent level if they are located on the same line with cursor // this means that if new line will be added at $ position, this case will be indented // class A { @@ -103688,8 +107407,8 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 220 /* IfStatement */ && parent.elseStatement === child) { - var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile); + if (parent.kind === 222 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 83 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; @@ -103697,103 +107416,87 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; - function getListIfStartEndIsInListRange(list, start, end) { - return list && ts.rangeContainsStartEnd(list, start, end) ? list : undefined; - } function getContainingList(node, sourceFile) { - if (node.parent) { - var end = node.end; - switch (node.parent.kind) { - case 162 /* TypeReference */: - return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); - case 186 /* ObjectLiteralExpression */: - return node.parent.properties; - case 185 /* ArrayLiteralExpression */: - return node.parent.elements; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 155 /* Constructor */: - case 164 /* ConstructorType */: - case 159 /* ConstructSignature */: { - var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || - getListIfStartEndIsInListRange(node.parent.parameters, start, end); - } - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: { - var typeParameters = node.parent.typeParameters; - return getListIfStartEndIsInListRange(typeParameters, node.getStart(sourceFile), end); - } - case 190 /* NewExpression */: - case 189 /* CallExpression */: { - var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || - getListIfStartEndIsInListRange(node.parent.arguments, start, end); - } - case 236 /* VariableDeclarationList */: - return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); - case 250 /* NamedImports */: - case 254 /* NamedExports */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); - } - } - return undefined; + return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile); } SmartIndenter.getContainingList = getContainingList; - function getActualIndentationForListItem(node, sourceFile, options) { + function getListByPosition(pos, node, sourceFile) { + return node && getListByRange(pos, pos, node, sourceFile); + } + function getListByRange(start, end, node, sourceFile) { + switch (node.kind) { + case 164 /* TypeReference */: + return getList(node.typeArguments); + case 188 /* ObjectLiteralExpression */: + return getList(node.properties); + case 187 /* ArrayLiteralExpression */: + return getList(node.elements); + case 168 /* TypeLiteral */: + return getList(node.members); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return getList(node.typeParameters) || getList(node.parameters); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + return getList(node.typeParameters); + case 192 /* NewExpression */: + case 191 /* CallExpression */: + return getList(node.typeArguments) || getList(node.arguments); + case 238 /* VariableDeclarationList */: + return getList(node.declarations); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return getList(node.elements); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return getList(node.elements); + } + function getList(list) { + return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined; + } + } + function getVisualListRange(node, list, sourceFile) { + var children = node.getChildren(sourceFile); + for (var i = 1; i < children.length - 1; i++) { + if (children[i].pos === list.pos && children[i].end === list.end) { + return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) }; + } + } + return list; + } + function getActualIndentationForListStartLine(list, sourceFile, options) { + if (!list) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); + } + function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { + if (node.parent && node.parent.kind === 238 /* VariableDeclarationList */) { + // VariableDeclarationList has no wrapping tokens + return -1 /* Unknown */; + } var containingList = getContainingList(node, sourceFile); if (containingList) { var index = containingList.indexOf(node); if (index !== -1) { - return deriveActualIndentationFromList(containingList, index, sourceFile, options); - } - } - return -1 /* Unknown */; - } - function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { - // actual indentation should not be used when: - // - node is close parenthesis - this is the end of the expression - if (node.kind === 20 /* CloseParenToken */) { - return -1 /* Unknown */; - } - if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { - var fullCallOrNewExpression = node.parent.expression; - var startingExpression = getStartingExpression(fullCallOrNewExpression); - if (fullCallOrNewExpression === startingExpression) { - return -1 /* Unknown */; - } - var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); - var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); - if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { - return -1 /* Unknown */; - } - return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); - } - return -1 /* Unknown */; - function getStartingExpression(node) { - while (true) { - switch (node.kind) { - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - node = node.expression; - break; - default: - return node; + var result = deriveActualIndentationFromList(containingList, index, sourceFile, options); + if (result !== -1 /* Unknown */) { + return result; } } + return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217 } + return -1 /* Unknown */; } function deriveActualIndentationFromList(list, index, sourceFile, options) { ts.Debug.assert(index >= 0 && index < list.length); @@ -103802,7 +107505,7 @@ var ts; // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for (var i = index - 1; i >= 0; i--) { - if (list[i].kind === 26 /* CommaToken */) { + if (list[i].kind === 27 /* CommaToken */) { continue; } // skip list items that ends on the same line with the current list element @@ -103851,83 +107554,83 @@ var ts; function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 219 /* ExpressionStatement */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 185 /* ArrayLiteralExpression */: - case 216 /* Block */: - case 243 /* ModuleBlock */: - case 186 /* ObjectLiteralExpression */: - case 166 /* TypeLiteral */: - case 179 /* MappedType */: - case 168 /* TupleType */: - case 244 /* CaseBlock */: - case 270 /* DefaultClause */: - case 269 /* CaseClause */: - case 193 /* ParenthesizedExpression */: - case 187 /* PropertyAccessExpression */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 217 /* VariableStatement */: - case 252 /* ExportAssignment */: - case 228 /* ReturnStatement */: - case 203 /* ConditionalExpression */: - case 183 /* ArrayBindingPattern */: - case 182 /* ObjectBindingPattern */: - case 260 /* JsxOpeningElement */: - case 263 /* JsxOpeningFragment */: - case 259 /* JsxSelfClosingElement */: - case 268 /* JsxExpression */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 149 /* Parameter */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 175 /* ParenthesizedType */: - case 191 /* TaggedTemplateExpression */: - case 199 /* AwaitExpression */: - case 254 /* NamedExports */: - case 250 /* NamedImports */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 152 /* PropertyDeclaration */: + case 221 /* ExpressionStatement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 187 /* ArrayLiteralExpression */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 181 /* MappedType */: + case 170 /* TupleType */: + case 246 /* CaseBlock */: + case 272 /* DefaultClause */: + case 271 /* CaseClause */: + case 195 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 219 /* VariableStatement */: + case 254 /* ExportAssignment */: + case 230 /* ReturnStatement */: + case 205 /* ConditionalExpression */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + case 261 /* JsxSelfClosingElement */: + case 270 /* JsxExpression */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 151 /* Parameter */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 177 /* ParenthesizedType */: + case 193 /* TaggedTemplateExpression */: + case 201 /* AwaitExpression */: + case 256 /* NamedExports */: + case 252 /* NamedImports */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 154 /* PropertyDeclaration */: return true; - case 235 /* VariableDeclaration */: - case 273 /* PropertyAssignment */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 186 /* ObjectLiteralExpression */) { // TODO: GH#18217 + case 237 /* VariableDeclaration */: + case 275 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 188 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } return true; - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 220 /* IfStatement */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 195 /* ArrowFunction */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return childKind !== 216 /* Block */; - case 253 /* ExportDeclaration */: - return childKind !== 254 /* NamedExports */; - case 247 /* ImportDeclaration */: - return childKind !== 248 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 250 /* NamedImports */); - case 258 /* JsxElement */: - return childKind !== 261 /* JsxClosingElement */; - case 262 /* JsxFragment */: - return childKind !== 264 /* JsxClosingFragment */; - case 172 /* IntersectionType */: - case 171 /* UnionType */: - if (childKind === 166 /* TypeLiteral */) { + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return childKind !== 218 /* Block */; + case 255 /* ExportDeclaration */: + return childKind !== 256 /* NamedExports */; + case 249 /* ImportDeclaration */: + return childKind !== 250 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 252 /* NamedImports */); + case 260 /* JsxElement */: + return childKind !== 263 /* JsxClosingElement */; + case 264 /* JsxFragment */: + return childKind !== 266 /* JsxClosingFragment */; + case 174 /* IntersectionType */: + case 173 /* UnionType */: + if (childKind === 168 /* TypeLiteral */) { return false; } // falls through @@ -103938,11 +107641,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: - return parent.kind !== 216 /* Block */; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return parent.kind !== 218 /* Block */; default: return false; } @@ -104070,7 +107773,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 186 /* ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 188 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -104099,7 +107802,6 @@ var ts; }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); - return this; }; ChangeTracker.prototype.delete = function (sourceFile, node) { this.deletedNodes.push({ sourceFile: sourceFile, node: node }); @@ -104112,7 +107814,6 @@ var ts; var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - return this; }; ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { if (options === void 0) { options = {}; } @@ -104123,11 +107824,10 @@ var ts; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); - return this; }; ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } @@ -104136,31 +107836,33 @@ var ts; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); - return this; }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + }; + ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) { + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); - return next && next.kind === 26 /* CommaToken */ ? next : undefined; + return next && next.kind === 27 /* CommaToken */ ? next : undefined; }; ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); - return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); + this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -104175,7 +107877,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -104190,17 +107900,32 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) { + var fnStart = node.getStart(sourceFile); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsdoc = _a[_i]; + this.deleteRange(sourceFile, { + pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + }); + } + } + var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); + var indent = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { var endNode; if (ts.isFunctionLike(node)) { - endNode = ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile); + endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) return; // Function missing parentheses, give up @@ -104209,13 +107934,13 @@ var ts; } } else { - endNode = node.kind !== 235 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + endNode = node.kind !== 237 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter - var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); }; ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { @@ -104256,30 +107981,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +108034,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104314,18 +108046,18 @@ var ts; }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - case 235 /* VariableDeclaration */: - case 9 /* StringLiteral */: - case 71 /* Identifier */: + case 237 /* VariableDeclaration */: + case 10 /* StringLiteral */: + case 72 /* Identifier */: return { prefix: ", " }; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return { suffix: "," + this.newLineCharacter }; - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: return { prefix: " " }; - case 149 /* Parameter */: + case 151 /* Parameter */: return {}; default: ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it @@ -104334,28 +108066,28 @@ var ts; }; ChangeTracker.prototype.insertName = function (sourceFile, node, name) { ts.Debug.assert(!node.name); - if (node.kind === 195 /* ArrowFunction */) { - var arrow = ts.findChildOfKind(node, 36 /* EqualsGreaterThanToken */, sourceFile); - var lparen = ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile); + if (node.kind === 197 /* ArrowFunction */) { + var arrow = ts.findChildOfKind(node, 37 /* EqualsGreaterThanToken */, sourceFile); + var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); if (lparen) { // `() => {}` --> `function f() {}` - this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(89 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(90 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); deleteNode(this, sourceFile, arrow); } else { // `x => {}` -> `function f(x) {}` this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` - this.replaceRange(sourceFile, arrow, ts.createToken(20 /* CloseParenToken */)); + this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */)); } - if (node.body.kind !== 216 /* Block */) { + if (node.body.kind !== 218 /* Block */) { // `() => 0` => `function f() { return 0; }` - this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(17 /* OpenBraceToken */), ts.createToken(96 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); - this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(25 /* SemicolonToken */), ts.createToken(18 /* CloseBraceToken */)], { joiner: " " }); + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(97 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); + this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " }); } } else { - var pos = ts.findChildOfKind(node, node.kind === 194 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end; + var pos = ts.findChildOfKind(node, node.kind === 196 /* FunctionExpression */ ? 90 /* FunctionKeyword */ : 76 /* ClassKeyword */, sourceFile).end; this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } }; @@ -104371,11 +108103,11 @@ var ts; if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } if (!containingList) { ts.Debug.fail("node is not a list element"); - return this; + return; } var index = ts.indexOfNode(containingList, after); if (index < 0) { - return this; + return; } var end = after.getEnd(); if (index !== containingList.length - 1) { @@ -104427,7 +108159,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104443,12 +108175,12 @@ var ts; // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise // i.e. var x = 1 // this is x // | new element will be inserted at this position - separator = 26 /* CommaToken */; + separator = 27 /* CommaToken */; } else { // element has more than one element, pick separator from the list var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile); - separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 26 /* CommaToken */; + separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */; // determine if list is multiline by checking lines of after element and element that precedes it. var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile); multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition; @@ -104459,7 +108191,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +108199,28 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } - return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; - var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var _loop_17 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +108233,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_17(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +108272,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { - return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; + function getClassOrObjectBraceEnds(cls, sourceFile) { + return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +108290,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +108307,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes) + newLineCharacter; + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,9 +108356,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -104698,6 +108441,9 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeComment = function (s) { + this.writer.writeComment(s); + }; Writer.prototype.writeKeyword = function (s) { this.writer.writeKeyword(s); this.setLastNonTriviaPosition(s, /*force*/ false); @@ -104710,6 +108456,10 @@ var ts; this.writer.writePunctuation(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeTrailingSemicolon = function (s) { + this.writer.writeTrailingSemicolon(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; Writer.prototype.writeParameter = function (s) { this.writer.writeParameter(s); this.setLastNonTriviaPosition(s, /*force*/ false); @@ -104730,9 +108480,6 @@ var ts; this.writer.writeSymbol(s, sym); this.setLastNonTriviaPosition(s, /*force*/ false); }; - Writer.prototype.writeTextOfNode = function (text, node) { - this.writer.writeTextOfNode(text, node); - }; Writer.prototype.writeLine = function () { this.writer.writeLine(); }; @@ -104774,10 +108521,25 @@ var ts; }; return Writer; }()); - function getInsertionPositionAtSourceFileTop(_a) { - var text = _a.text; - var shebang = ts.getShebang(text); + function getInsertionPositionAtSourceFileTop(sourceFile) { + var lastPrologue; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + if (ts.isPrologueDirective(node)) { + lastPrologue = node; + } + else { + break; + } + } var position = 0; + var text = sourceFile.text; + if (lastPrologue) { + position = lastPrologue.end; + advancePastLineBreak(); + return position; + } + var shebang = ts.getShebang(text); if (shebang !== undefined) { position = shebang.length; advancePastLineBreak(); @@ -104793,8 +108555,8 @@ var ts; ranges = ranges.slice(1); } // As well as any triple slash references - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; + for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) { + var range = ranges_1[_b]; if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { position = range.end; advancePastLineBreak(); @@ -104816,45 +108578,40 @@ var ts; } } function isValidLocationToAddComment(sourceFile, position) { - return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position); } textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; function needSemicolonBetween(a, b) { - return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 147 /* ComputedPropertyName */ + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 149 /* ComputedPropertyName */ || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` } var deleteDeclaration; (function (deleteDeclaration_1) { function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { switch (node.kind) { - case 149 /* Parameter */: { + case 151 /* Parameter */: { var oldFunction = node.parent; - if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + if (ts.isArrowFunction(oldFunction) && + oldFunction.parameters.length === 1 && + !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the // case if the parameter is simply removed (e.g. in `x => 1`). - var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, - /*parameters*/ undefined, // TODO: GH#18217 - oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); - // Drop leading and trailing trivia of the new function because we're only going - // to replace the span (vs the full span) of the old function - the old leading - // and trailing trivia will remain. - ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction); + changes.replaceNodeWithText(sourceFile, node, "()"); } else { deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; } - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: deleteNode(changes, sourceFile, node, // For first import, leave header comment in place node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: var pattern = node.parent; - var preserveComma = pattern.kind === 183 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + var preserveComma = pattern.kind === 185 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); if (preserveComma) { deleteNode(changes, sourceFile, node); } @@ -104862,13 +108619,13 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { deleteImportBinding(changes, sourceFile, namedImports); @@ -104877,7 +108634,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; default: @@ -104888,7 +108645,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } else { - deleteNode(changes, sourceFile, node, node.kind === 25 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); } } } @@ -104902,7 +108659,7 @@ var ts; // import |d,| * as ns from './file' var start = importClause.name.getStart(sourceFile); var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { + if (nextToken && nextToken.kind === 27 /* CommaToken */) { // shift first non-whitespace position after comma to the start position of the node var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); changes.deleteRange(sourceFile, { pos: start, end: end }); @@ -104924,15 +108681,15 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(node, 247 /* ImportDeclaration */); + var importDecl = ts.getAncestor(node, 249 /* ImportDeclaration */); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { var parent = node.parent; - if (parent.kind === 272 /* CatchClause */) { + if (parent.kind === 274 /* CatchClause */) { // TODO: There's currently no unused diagnostic for this, could be a suggestion - changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 19 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 20 /* CloseParenToken */, sourceFile)); + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); return; } if (parent.declarations.length !== 1) { @@ -104941,14 +108698,14 @@ var ts; } var gp = parent.parent; switch (gp.kind) { - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: deleteNode(changes, sourceFile, parent); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: deleteNode(changes, sourceFile, gp); break; default: @@ -105093,6 +108850,32 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addConvertToUnknownForNonOverlappingTypes"; + var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var assertion = ts.Debug.assertDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); })); + var replacement = ts.isAsExpression(assertion) + ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(143 /* UnknownKeyword */)) + : ts.createTypeAssertion(ts.createKeywordTypeNode(143 /* UnknownKeyword */), assertion.expression); + changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -105160,9 +108943,9 @@ var ts; if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } - var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile); if (needParens) - changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(19 /* OpenParenToken */)); + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */)); for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { var param = _a[_i]; if (!param.type) { @@ -105172,7 +108955,7 @@ var ts; } } if (needParens) - changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(20 /* CloseParenToken */)); + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */)); if (!decl.type) { var returnType = ts.getJSDocReturnType(decl); if (returnType) @@ -105187,26 +108970,26 @@ var ts; } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 235 /* VariableDeclaration */ || - node.kind === 151 /* PropertySignature */ || - node.kind === 152 /* PropertyDeclaration */; + node.kind === 237 /* VariableDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 154 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 285 /* JSDocNonNullableType */: + case 287 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return transformJSDocFunctionType(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return transformJSDocTypeReference(node); default: var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 @@ -105228,9 +109011,9 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 288 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); - var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; + var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); } function transformJSDocTypeReference(node) { @@ -105268,8 +109051,8 @@ var ts; var index = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s", - /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []), + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "number" : "string", []), /*initializer*/ undefined); var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); ts.setEmitFlags(indexSignature, 1 /* SingleLine */); @@ -105279,6 +109062,784 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var token = ts.getTokenAtPosition(sourceFile, start); + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var markSeen = ts.nodeSeenTracker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + }); + }, + }); + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; + default: + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode) { + switch (errorCode) { + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 72 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 100 /* ThisKeyword */) { + return undefined; + } + var parent = token.parent; + errorCode = mapSuggestionDiagnostic(errorCode); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags + var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ ""); + addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + } + return parent; + } + return undefined; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + return symbol.valueDeclaration; + } + return undefined; + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + return param; + } + return undefined; + // Get Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: + case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + return containingFunction; + } + return undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + return undefined; + default: + return ts.Debug.fail(String(errorCode)); + } + } + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + } + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + return true; + case 196 /* FunctionExpression */: + var parent = declaration.parent; + return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) || !!declaration.name; + } + return false; + } + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return; + } + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } + } + } + } + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } + } + } + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) { + var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; + if (!parent) { + return; + } + var typeExpression = ts.createJSDocTypeExpression(typeNode); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } + } + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + var paramTags = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + // only infer parameters that have (1) no type and (2) an accessible inferred type + if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name)) + return; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + var name = ts.getSynthesizedClone(param.name); + ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), ""); + }); + addJSDocTags(changes, sourceFile, signature, paramTags); + } + function addJSDocTags(changes, sourceFile, parent, newTags) { + var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags))); + changes.insertJsdocCommentBefore(sourceFile, parent, tag); + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 299 /* JSDocParameterTag */: { + var oldParam = oldTag; + var newParam = newTag; + return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + : undefined; + } + case 300 /* JSDocReturnTag */: + return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); + } + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } + }); + return typeIsAccessible ? res : undefined; + } + function getReferences(token, program, cancellationToken) { + // Position shouldn't matter since token is not a SourceFile. + return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + }); + } + function inferTypeForVariableFromUsage(token, program, cancellationToken) { + var references = getReferences(token, program, cancellationToken); + var checker = program.getTypeChecker(); + var types = InferFromReference.inferTypesFromReferences(references, checker, cancellationToken); + return InferFromReference.unifyFromContext(types, checker); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + var searchToken; + switch (containingFunction.kind) { + case 157 /* Constructor */: + searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); + break; + case 196 /* FunctionExpression */: + var parent = containingFunction.parent; + searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + searchToken = containingFunction.name; + break; + } + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypesFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return inferFromContext(usageContext, checker); + } + InferFromReference.inferTypesFromReferences = inferTypesFromReferences; + function inferTypeForParametersFromReferences(references, declaration, program, cancellationToken) { + var checker = program.getTypeChecker(); + if (references.length === 0) { + return undefined; + } + if (!declaration.parameters) { + return undefined; + } + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []); + return declaration.parameters.map(function (parameter, parameterIndex) { + var types = []; + var isRest = ts.isRestParameter(parameter); + var isOptional = false; + for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { + var callContext = callContexts_1[_i]; + if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); + types.push(checker.getUndefinedType()); + } + else if (isRest) { + for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + } + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + if (ts.isIdentifier(parameter.name)) { + var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken); + types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); + } + var type = unifyFromContext(types, checker); + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; + }); + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 203 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 202 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 204 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 189 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 190 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + case 237 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + usageContext.isNumber = true; + break; + case 38 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + // case SyntaxKind.ExclamationToken: + // no inferences here; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 41 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + // ShiftOperator + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 49 /* AmpersandToken */: + case 50 /* BarToken */: + case 51 /* CaretToken */: + // CompoundAssignmentOperator + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 70 /* BarEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 39 /* MinusToken */: + // RelationalOperator + case 28 /* LessThanToken */: + case 31 /* LessThanEqualsToken */: + case 30 /* GreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 60 /* PlusEqualsToken */: + case 38 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 296 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 132 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 59 /* EqualsToken */: + case 33 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 93 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 55 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 237 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + case 94 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 191 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent.argumentExpression); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 296 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function removeLowPriorityInferences(inferences, priorities) { + var toRemove = []; + for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) { + var i = inferences_2[_i]; + for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) { + var _b = priorities_1[_a], high = _b.high, low = _b.low; + if (high(i)) { + ts.Debug.assert(!low(i)); + toRemove.push(low); + } + } + } + return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); }); + } + function unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + // 1. string or number individually override string | number + // 2. non-any, non-void overrides any or void + // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types + var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); + var priorities = [ + { + high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); }, + low: function (t) { return t === stringNumber; } + }, + { + high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); }, + low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); } + }, + { + high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); }, + low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); } + } + ]; + var good = removeLowPriorityInferences(inferences, priorities); + var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + if (anons.length) { + good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + good.push(unifyAnonymousTypes(anons, checker)); + } + return checker.getWidenedType(checker.getUnionType(good)); + } + InferFromReference.unifyFromContext = unifyFromContext; + function unifyAnonymousTypes(anons, checker) { + if (anons.length === 1) { + return anons[0]; + } + var calls = []; + var constructs = []; + var stringIndices = []; + var numberIndices = []; + var stringIndexReadonly = false; + var numberIndexReadonly = false; + var props = ts.createMultiMap(); + for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) { + var anon = anons_1[_i]; + for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { + var p = _b[_a]; + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); + constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } + } + var members = ts.mapEntries(props, function (name, types) { + var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; + var s = checker.createSymbol(4 /* Property */ | isOptional, name); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + function inferFromContext(usageContext, checker) { + var types = []; + if (usageContext.isNumber) { + types.push(checker.getNumberType()); + } + if (usageContext.isString) { + types.push(checker.getStringType()); + } + if (usageContext.isNumberOrString) { + types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); + } + types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 + var types_19 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + types_19.push(checker.createPromiseType(types_19.length ? checker.getUnionType(types_19, 2 /* Subtype */) : checker.getAnyType())); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker))); + } + if (usageContext.numberIndexContext) { + types.push(checker.createArrayType(recur(usageContext.numberIndexContext))); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { + var members_6 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = recur(context); + members_6.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); + } + types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 + } + return types; + function recur(innerContext) { + return unifyFromContext(inferFromContext(innerContext, checker), checker); + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = unifyFromContext(inferFromContext(callContext.returnType, checker), checker, checker.getVoidType()); + // TODO: GH#18217 + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return !!usageContext && !!usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -105303,12 +109864,12 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: precedingNode = ctorDeclaration; changes.delete(sourceFile, ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: precedingNode = ctorDeclaration.parent.parent; newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { @@ -105340,7 +109901,7 @@ var ts; // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); + var memberElement = createClassElement(member, [ts.createToken(116 /* StaticKeyword */)]); if (memberElement) { memberElements.push(memberElement); } @@ -105363,7 +109924,7 @@ var ts; return; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 219 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 221 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentBinaryExpression.right) { @@ -105371,27 +109932,27 @@ var ts; /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 194 /* FunctionExpression */: { + case 196 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); ts.copyComments(assignmentBinaryExpression, method, sourceFile); return method; } - case 195 /* ArrowFunction */: { + case 197 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 216 /* Block */) { + if (arrowFunctionBody.kind === 218 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] else { bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); } - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); ts.copyComments(assignmentBinaryExpression, method, sourceFile); @@ -105399,7 +109960,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105412,17 +109973,17 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 194 /* FunctionExpression */) { + if (!initializer || initializer.kind !== 196 /* FunctionExpression */) { return undefined; } - if (node.name.kind !== 71 /* Identifier */) { + if (node.name.kind !== 72 /* Identifier */) { return undefined; } var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */); + var modifiers = getModifierKindFromSource(precedingNode, 85 /* ExportKeyword */); var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place @@ -105433,7 +109994,7 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); } - var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */); + var modifiers = getModifierKindFromSource(node, 85 /* ExportKeyword */); var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place @@ -105452,59 +110013,73 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); - var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 121 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_19(statement); } } + function getReturnStatementsWithPromiseHandlers(body) { + var res = []; + ts.forEachReturnStatement(body, function (ret) { + if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + res.push(ret); + }); + return res; + } // Returns the identifiers that are never reassigned in the refactor function getConstIdentifiers(synthNamesMap) { var constIdentifiers = []; @@ -105549,7 +110124,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +110138,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +110152,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +110178,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +110201,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +110211,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,7 +110245,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105670,17 +110261,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +110288,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +110304,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,100 +110317,134 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 96 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 72 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; - if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } + if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; - var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); + var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105837,12 +110465,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +110472,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105912,10 +110532,10 @@ var ts; } var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); } @@ -105941,7 +110561,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -105961,29 +110581,29 @@ var ts; sourceFile.forEachChild(function recur(node) { if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { var parent = node.parent; - cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 59 /* EqualsToken */); } node.forEachChild(recur); }); } function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 219 /* ExpressionStatement */: { + case 221 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 189 /* CallExpression */: { + case 191 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var operatorToken = expression.operatorToken; - return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); + return operatorToken.kind === 59 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); } } } @@ -106023,8 +110643,8 @@ var ts; /** Converts `const name = require("moduleSpecifier").propertyName` */ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ @@ -106032,7 +110652,7 @@ var ts; makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } - case 71 /* Identifier */: + case 72 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; default: @@ -106058,7 +110678,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106075,16 +110695,16 @@ var ts; function tryChangeModuleExportsObject(object) { var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. - case 274 /* ShorthandPropertyAssignment */: - case 275 /* SpreadAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 277 /* SpreadAssignment */: return undefined; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); - case 154 /* MethodDeclaration */: - return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); + case 156 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(85 /* ExportKeyword */)], prop); default: ts.Debug.assertNever(prop); } @@ -106133,23 +110753,23 @@ var ts; var name = left.name.text; if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) { // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. - changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(84 /* ExportKeyword */), { suffix: " " }); + changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(85 /* ExportKeyword */), { suffix: " " }); if (!right.name) changes.insertName(sourceFile, right, name); - var semi = ts.findChildOfKind(parent, 25 /* SemicolonToken */, sourceFile); + var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile); if (semi) changes.delete(sourceFile, semi); } else { // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` - changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 23 /* DotToken */, sourceFile), [ts.createToken(84 /* ExportKeyword */), ts.createToken(76 /* ConstKeyword */)], { joiner: " ", suffix: " " }); + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(85 /* ExportKeyword */), ts.createToken(77 /* ConstKeyword */)], { joiner: " ", suffix: " " }); } } // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node. function convertExportsDotXEquals_replaceNode(name, exported) { - var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + var modifiers = [ts.createToken(85 /* ExportKeyword */)]; switch (exported.kind) { - case 194 /* FunctionExpression */: { + case 196 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -106157,10 +110777,10 @@ var ts; } } // falls through - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported); default: @@ -106178,7 +110798,7 @@ var ts; */ function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: { + case 184 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined @@ -106189,7 +110809,7 @@ var ts; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 183 /* ArrayBindingPattern */: { + case 185 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; @@ -106200,7 +110820,7 @@ var ts; makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } - case 71 /* Identifier */: + case 72 /* Identifier */: return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); default: return ts.Debug.assertNever(name); @@ -106272,11 +110892,11 @@ var ts; function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return parent.name !== node; - case 184 /* BindingElement */: + case 186 /* BindingElement */: return parent.propertyName !== node; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -106544,33 +111164,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106608,21 +111235,21 @@ var ts; function tryAddToExistingImport(existingImports) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind !== 247 /* ImportDeclaration */) + if (declaration.kind !== 249 /* ImportDeclaration */) return undefined; var importClause = declaration.importClause; if (!importClause) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; - return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */) + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 252 /* NamedImports */) ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } : undefined; }); } function getNamespaceImportName(declaration) { - if (declaration.kind === 247 /* ImportDeclaration */) { + if (declaration.kind === 249 /* ImportDeclaration */) { var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 249 /* NamespaceImport */ ? namedBindings.name : undefined; + return namedBindings && namedBindings.kind === 251 /* NamespaceImport */ ? namedBindings.name : undefined; } else { return declaration.name; @@ -106631,24 +111258,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) + return (i.kind === 249 /* ImportDeclaration */ || i.kind === 248 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return ts.sort(choicesForEachExportingModule, function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106656,9 +111283,9 @@ var ts; } function newImportInfoFromExistingSpecifier(_a) { var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 247 /* ImportDeclaration */ + var expression = declaration.kind === 249 /* ImportDeclaration */ ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 257 /* ExternalModuleReference */ + : declaration.moduleReference.kind === 259 /* ExternalModuleReference */ ? declaration.moduleReference.expression : undefined; return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; @@ -106690,7 +111317,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106738,17 +111365,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +111381,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +111404,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -106975,12 +111613,12 @@ var ts; var checker = context.program.getTypeChecker(); var suggestion; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71 /* Identifier */); + ts.Debug.assert(node.kind === 72 /* Identifier */); var containingType = checker.getTypeAtLocation(node.parent.expression); suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); } else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71 /* Identifier */); + ts.Debug.assert(node.kind === 72 /* Identifier */); var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { @@ -107009,10 +111647,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107035,6 +111673,9 @@ var ts; var errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code ]; var fixId = "addMissingMember"; codefix.registerCodeFix({ @@ -107051,7 +111692,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +111721,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_20 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +111748,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_20(info); } }); })); @@ -107151,7 +111792,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,14 +111802,14 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { - if (classDeclaration.kind === 207 /* ClassExpression */) { + if (classDeclaration.kind === 209 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -107194,13 +111835,17 @@ var ts; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 202 /* BinaryExpression */) { + if (token.parent.parent.kind === 204 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } - return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); + else { + var contextualType = checker.getContextualType(token.parent); + typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + } + return typeNode || ts.createKeywordTypeNode(120 /* AnyKeyword */); } function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); @@ -107209,7 +111854,7 @@ var ts; function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); var lastProp = getNodeToInsertPropertyAfter(classDeclaration); @@ -107233,7 +111878,7 @@ var ts; } function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. - var stringTypeNode = ts.createKeywordTypeNode(137 /* StringKeyword */); + var stringTypeNode = ts.createKeywordTypeNode(138 /* StringKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -107253,7 +111898,7 @@ var ts; } function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); - var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */); + var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); } @@ -107269,7 +111914,7 @@ var ts; */ var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { var type = checker.getTypeAtLocation(member); - return !!(type && type.flags & 68 /* StringLike */); + return !!(type && type.flags & 132 /* StringLike */); }); var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); @@ -107281,7 +111926,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +111938,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -107406,7 +112163,7 @@ var ts; } function getNodes(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - if (token.kind !== 99 /* ThisKeyword */) + if (token.kind !== 100 /* ThisKeyword */) return undefined; var constructor = ts.getContainingFunction(token); var superCall = findSuperCall(constructor.body); @@ -107445,7 +112202,7 @@ var ts; }); function getNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */); + ts.Debug.assert(token.kind === 124 /* ConstructorKeyword */); return token.parent; } function doChange(changes, sourceFile, ctr) { @@ -107483,17 +112240,17 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); var heritageClauses = ts.getContainingClass(token).heritageClauses; var extendsToken = heritageClauses[0].getFirstToken(); - return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + return extendsToken.kind === 86 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; } function doChanges(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); + changes.replaceNode(sourceFile, extendsToken, ts.createToken(109 /* ImplementsKeyword */)); // If there is already an implements clause, replace the implements keyword with a comma. if (heritageClauses.length === 2 && - heritageClauses[0].token === 85 /* ExtendsKeyword */ && - heritageClauses[1].token === 108 /* ImplementsKeyword */) { + heritageClauses[0].token === 86 /* ExtendsKeyword */ && + heritageClauses[1].token === 109 /* ImplementsKeyword */) { var implementsToken = heritageClauses[1].getFirstToken(); var implementsFullStart = implementsToken.getFullStart(); - changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(26 /* CommaToken */)); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */)); // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. // (Trailing because leading might be indentation, which is more sensitive.) var text = sourceFile.text; @@ -107577,7 +112334,7 @@ var ts; if (ts.isJSDocTemplateTag(token)) { return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; } - if (token.kind === 27 /* LessThanToken */) { + if (token.kind === 28 /* LessThanToken */) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; } @@ -107597,7 +112354,7 @@ var ts; return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; } var result = []; - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); @@ -107629,7 +112386,7 @@ var ts; tryPrefixDeclaration(changes, diag.code, sourceFile, token); break; case fixIdDelete: { - if (token.kind === 126 /* InferKeyword */) + if (token.kind === 127 /* InferKeyword */) break; // Can't delete var importDecl = tryGetFullImport(token); if (importDecl) { @@ -107638,7 +112395,7 @@ var ts; else if (ts.isJSDocTemplateTag(token)) { changes.delete(sourceFile, token); } - else if (token.kind === 27 /* LessThanToken */) { + else if (token.kind === 28 /* LessThanToken */) { deleteTypeParameters(changes, sourceFile, token); } else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && @@ -107648,7 +112405,7 @@ var ts; break; } case fixIdInfer: - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { changeInferToUnknown(changes, sourceFile, token); } break; @@ -107659,7 +112416,7 @@ var ts; }, }); function changeInferToUnknown(changes, sourceFile, token) { - changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(142 /* UnknownKeyword */)); + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(143 /* UnknownKeyword */)); } function createDeleteFix(changes, diag) { return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); @@ -107669,13 +112426,13 @@ var ts; } // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(token) { - return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; + return token.kind === 92 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; } function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { - if (token.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) + if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) return false; var decl = token.parent.parent; - if (decl.kind === 149 /* Parameter */) { + if (decl.kind === 151 /* Parameter */) { tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); } else { @@ -107686,7 +112443,7 @@ var ts; function tryDeleteFullVariableStatement(sourceFile, token, changes) { var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { - changes.delete(sourceFile, declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList); + changes.delete(sourceFile, declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList); return true; } return false; @@ -107695,7 +112452,7 @@ var ts; // Don't offer to prefix a property. if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) return; - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; } if (ts.isIdentifier(token) && canPrefix(token)) { @@ -107704,14 +112461,14 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 149 /* Parameter */: - case 148 /* TypeParameter */: + case 151 /* Parameter */: + case 150 /* TypeParameter */: return true; - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: return true; } } @@ -107725,9 +112482,9 @@ var ts; } function deleteAssignments(changes, sourceFile, token, checker) { ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { - if (ref.parent.kind === 187 /* PropertyAccessExpression */) + if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent; - if (ref.parent.kind === 202 /* BinaryExpression */ && ref.parent.parent.kind === 219 /* ExpressionStatement */) { + if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) { changes.delete(sourceFile, ref.parent.parent); } }); @@ -107743,33 +112500,41 @@ var ts; } function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { if (mayDeleteParameter(p, checker, isFixAll)) { - changes.delete(sourceFile, p); - deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + if (p.modifiers && p.modifiers.length > 0 + && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + p.modifiers.forEach(function (modifier) { + changes.deleteModifier(sourceFile, modifier); + }); + } + else { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + } } } function mayDeleteParameter(p, checker, isFixAll) { var parent = p.parent; switch (parent.kind) { - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // Don't remove a parameter if this overrides something. var symbol = checker.getSymbolAtLocation(parent.name); if (ts.isMemberSymbolInBaseType(symbol, checker)) return false; // falls through - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: return true; - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. var parameters = parent.parameters; var index = parameters.indexOf(p); ts.Debug.assert(index !== -1); return isFixAll - ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 71 /* Identifier */ && !p.symbol.isReferenced; }) + ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 72 /* Identifier */ && !p.symbol.isReferenced; }) : index === parameters.length - 1; } - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: // Setter must have a parameter return false; default: @@ -107809,7 +112574,7 @@ var ts; var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { switch (container.kind) { - case 220 /* IfStatement */: + case 222 /* IfStatement */: if (container.elseStatement) { if (ts.isBlock(statement.parent)) { break; @@ -107820,8 +112585,8 @@ var ts; return; } // falls through - case 222 /* WhileStatement */: - case 223 /* ForStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: changes.delete(sourceFile, container); return; } @@ -107870,7 +112635,7 @@ var ts; var statementPos = labeledStatement.statement.getStart(sourceFile); // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos - : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 57 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); changes.deleteRange(sourceFile, { pos: pos, end: end }); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -107894,10 +112659,10 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 284 /* JSDocNullableType */) { + if (typeNode.kind === 286 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - actions.push(fix(checker.getNullableType(type, 8192 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); + actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; function fix(type, fixId, fixAllDescription) { @@ -107914,7 +112679,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 284 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type; + var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -107931,22 +112696,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 210 /* AsExpression */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 237 /* FunctionDeclaration */: - case 156 /* GetAccessor */: - case 160 /* IndexSignature */: - case 179 /* MappedType */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 157 /* SetAccessor */: - case 240 /* TypeAliasDeclaration */: - case 192 /* TypeAssertionExpression */: - case 235 /* VariableDeclaration */: + case 212 /* AsExpression */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 239 /* FunctionDeclaration */: + case 158 /* GetAccessor */: + case 162 /* IndexSignature */: + case 181 /* MappedType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 194 /* TypeAssertionExpression */: + case 237 /* VariableDeclaration */: return true; default: return false; @@ -108000,15 +112765,15 @@ var ts; } var insertBefore; switch (containingFunction.kind) { - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 90 /* FunctionKeyword */, sourceFile); break; - case 195 /* ArrowFunction */: - insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + case 197 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: return; @@ -108022,11 +112787,11 @@ var ts; var insertBefore = _a.insertBefore, returnType = _a.returnType; if (returnType) { var entityName = ts.getEntityNameFromTypeNode(returnType); - if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") { + if (!entityName || entityName.kind !== 72 /* Identifier */ || entityName.text !== "Promise") { changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); } } - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore); + changes.insertModifierBefore(sourceFile, 121 /* AsyncKeyword */, insertBefore); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -108045,7 +112810,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108116,17 +112881,17 @@ var ts; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 151 /* PropertySignature */: - case 152 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 153 /* PropertySignature */: + case 154 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); out(ts.createProperty( - /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, + /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 153 /* MethodSignature */: - case 154 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 156 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -108144,8 +112909,8 @@ var ts; outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } - for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { - var signature = signatures_8[_i]; + for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) { + var signature = signatures_7[_i]; // Need to ensure nodes are fresh each time so they can have different positions. outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); } @@ -108166,43 +112931,40 @@ var ts; } } function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 154 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); if (!signatureDeclaration) { return undefined; } signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; signatureDeclaration.name = name; - signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; + signatureDeclaration.questionToken = optional ? ts.createToken(56 /* QuestionToken */) : undefined; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, - /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(39 /* AsteriskToken */) : undefined, methodName, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(40 /* AsteriskToken */) : undefined, methodName, /*questionToken*/ undefined, /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108213,8 +112975,8 @@ var ts; /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || "arg" + i, - /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, - /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(119 /* AnyKeyword */), + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(120 /* AnyKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -108228,8 +112990,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { - var sig = signatures_9[_i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var sig = signatures_8[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -108242,11 +113004,11 @@ var ts; var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { - var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); + var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(120 /* AnyKeyword */)); var restParameter = ts.createParameter( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", - /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, anyArrayType, + /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", + /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, anyArrayType, /*initializer*/ undefined); parameters.push(restParameter); } @@ -108257,7 +113019,7 @@ var ts; function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { return ts.createMethod( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); + /*asteriskToken*/ undefined, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); } function createStubbedMethodBody(preferences) { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), @@ -108266,10 +113028,10 @@ var ts; } function createVisibilityModifier(flags) { if (flags & 4 /* Public */) { - return ts.createToken(114 /* PublicKeyword */); + return ts.createToken(115 /* PublicKeyword */); } else if (flags & 16 /* Protected */) { - return ts.createToken(113 /* ProtectedKeyword */); + return ts.createToken(114 /* ProtectedKeyword */); } return undefined; } @@ -108277,561 +113039,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - var codefix; - (function (codefix) { - var fixId = "inferFromUsage"; - var errorCodes = [ - // Variable declarations - ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, - ]; - codefix.registerCodeFix({ - errorCodes: errorCodes, - getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } - var token = ts.getTokenAtPosition(sourceFile, start); - var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); - var name = declaration && ts.getNameOfDeclaration(declaration); - return !name || changes.length === 0 ? undefined - : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; - }, - fixIds: [fixId], - getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; - var markSeen = ts.nodeSeenTracker(); - return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); - }); - }, - }); - function getDiagnostic(errorCode, token) { - switch (errorCode) { - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return ts.Diagnostics.Infer_parameter_types_from_usage; - default: - return ts.Diagnostics.Infer_type_of_0_from_usage; - } - } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { - return undefined; - } - var parent = token.parent; - switch (errorCode) { - // Variable and Property declarations - case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: - case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); - return parent; - } - return undefined; - case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { - var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); - return symbol.valueDeclaration; - } - return undefined; - } - } - var containingFunction = ts.getContainingFunction(token); - if (containingFunction === undefined) { - return undefined; - } - switch (errorCode) { - // Parameter declarations - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); - return containingFunction; - } - // falls through - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (markSeen(containingFunction)) { - var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); - return param; - } - return undefined; - // Get Accessor declarations - case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: - case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); - return containingFunction; - } - return undefined; - // Set Accessor declarations - case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); - return containingFunction; - } - return undefined; - default: - return ts.Debug.fail(String(errorCode)); - } - } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { - if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); - } - } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - return true; - case 194 /* FunctionExpression */: - return !!declaration.name; - } - return false; - } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return; - } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; - } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); - } - }); - } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { - var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); - if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || - inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); - } - } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); - } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { - var typeIsAccessible = true; - var notAccessible = function () { typeIsAccessible = false; }; - var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { - trackSymbol: function (symbol, declaration, meaning) { - // TODO: GH#18217 - typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; - }, - reportInaccessibleThisError: notAccessible, - reportPrivateInBaseOfClassExpression: notAccessible, - reportInaccessibleUniqueSymbolError: notAccessible, - }); - return typeIsAccessible ? res : undefined; - } - function getReferences(token, program, cancellationToken) { - // Position shouldn't matter since token is not a SourceFile. - return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; - }); - } - function inferTypeForVariableFromUsage(token, program, cancellationToken) { - return InferFromReference.inferTypeFromReferences(getReferences(token, program, cancellationToken), program.getTypeChecker(), cancellationToken); - } - function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { - switch (containingFunction.kind) { - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - var isConstructor = containingFunction.kind === 155 /* Constructor */; - var searchToken = isConstructor ? - ts.findChildOfKind(containingFunction, 123 /* ConstructorKeyword */, sourceFile) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); - } - } - } - var InferFromReference; - (function (InferFromReference) { - function inferTypeFromReferences(references, checker, cancellationToken) { - var usageContext = {}; - for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { - var reference = references_1[_i]; - cancellationToken.throwIfCancellationRequested(); - inferTypeFromContext(reference, checker, usageContext); - } - return getTypeFromUsageContext(usageContext, checker); - } - InferFromReference.inferTypeFromReferences = inferTypeFromReferences; - function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { - if (references.length === 0) { - return undefined; - } - if (!declaration.parameters) { - return undefined; - } - var usageContext = {}; - for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { - var reference = references_2[_i]; - cancellationToken.throwIfCancellationRequested(); - inferTypeFromContext(reference, checker, usageContext); - } - var isConstructor = declaration.kind === 155 /* Constructor */; - var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; - return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { - var types = []; - var isRest = ts.isRestParameter(parameter); - for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { - var callContext = callContexts_1[_i]; - if (callContext.argumentTypes.length <= parameterIndex) { - continue; - } - if (isRest) { - for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); - } - } - else { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); - } - } - if (!types.length) { - return undefined; - } - var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; - }); - } - InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; - function inferTypeFromContext(node, checker, usageContext) { - while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { - node = node.parent; - } - switch (node.parent.kind) { - case 201 /* PostfixUnaryExpression */: - usageContext.isNumber = true; - break; - case 200 /* PrefixUnaryExpression */: - inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); - break; - case 202 /* BinaryExpression */: - inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); - break; - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); - break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: - if (node.parent.expression === node) { - inferTypeFromCallExpressionContext(node.parent, checker, usageContext); - } - else { - inferTypeFromContextualType(node, checker, usageContext); - } - break; - case 187 /* PropertyAccessExpression */: - inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); - break; - case 188 /* ElementAccessExpression */: - inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); - break; - case 235 /* VariableDeclaration */: { - var _a = node.parent, name = _a.name, initializer = _a.initializer; - if (node === name) { - if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. - addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); - } - break; - } - } - // falls through - default: - return inferTypeFromContextualType(node, checker, usageContext); - } - } - function inferTypeFromContextualType(node, checker, usageContext) { - if (ts.isExpressionNode(node)) { - addCandidateType(usageContext, checker.getContextualType(node)); - } - } - function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { - switch (node.operator) { - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - usageContext.isNumber = true; - break; - case 37 /* PlusToken */: - usageContext.isNumberOrString = true; - break; - // case SyntaxKind.ExclamationToken: - // no inferences here; - } - } - function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { - switch (parent.operatorToken.kind) { - // ExponentiationOperator - case 40 /* AsteriskAsteriskToken */: - // MultiplicativeOperator - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - // ShiftOperator - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - // BitwiseOperator - case 48 /* AmpersandToken */: - case 49 /* BarToken */: - case 50 /* CaretToken */: - // CompoundAssignmentOperator - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 69 /* BarEqualsToken */: - case 70 /* CaretEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - // AdditiveOperator - case 38 /* MinusToken */: - // RelationalOperator - case 27 /* LessThanToken */: - case 30 /* LessThanEqualsToken */: - case 29 /* GreaterThanToken */: - case 31 /* GreaterThanEqualsToken */: - var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (operandType.flags & 544 /* EnumLike */) { - addCandidateType(usageContext, operandType); - } - else { - usageContext.isNumber = true; - } - break; - case 59 /* PlusEqualsToken */: - case 37 /* PlusToken */: - var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (otherOperandType.flags & 544 /* EnumLike */) { - addCandidateType(usageContext, otherOperandType); - } - else if (otherOperandType.flags & 168 /* NumberLike */) { - usageContext.isNumber = true; - } - else if (otherOperandType.flags & 68 /* StringLike */) { - usageContext.isString = true; - } - else { - usageContext.isNumberOrString = true; - } - break; - // AssignmentOperators - case 58 /* EqualsToken */: - case 32 /* EqualsEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); - break; - case 92 /* InKeyword */: - if (node === parent.left) { - usageContext.isString = true; - } - break; - // LogicalOperator - case 54 /* BarBarToken */: - if (node === parent.left && - (node.parent.parent.kind === 235 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { - // var x = x || {}; - // TODO: use getFalsyflagsOfType - addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); - } - break; - case 53 /* AmpersandAmpersandToken */: - case 26 /* CommaToken */: - case 93 /* InstanceOfKeyword */: - // nothing to infer here - break; - } - } - function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { - addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); - } - function inferTypeFromCallExpressionContext(parent, checker, usageContext) { - var callContext = { - argumentTypes: [], - returnType: {} - }; - if (parent.arguments) { - for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); - } - } - inferTypeFromContext(parent, checker, callContext.returnType); - if (parent.kind === 189 /* CallExpression */) { - (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); - } - else { - (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); - } - } - function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { - var name = ts.escapeLeadingUnderscores(parent.name.text); - if (!usageContext.properties) { - usageContext.properties = ts.createUnderscoreEscapedMap(); - } - var propertyUsageContext = usageContext.properties.get(name) || {}; - inferTypeFromContext(parent, checker, propertyUsageContext); - usageContext.properties.set(name, propertyUsageContext); - } - function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { - if (node === parent.argumentExpression) { - usageContext.isNumberOrString = true; - return; - } - else { - var indexType = checker.getTypeAtLocation(parent.argumentExpression); - var indexUsageContext = {}; - inferTypeFromContext(parent, checker, indexUsageContext); - if (indexType.flags & 168 /* NumberLike */) { - usageContext.numberIndexContext = indexUsageContext; - } - else { - usageContext.stringIndexContext = indexUsageContext; - } - } - } - function getTypeFromUsageContext(usageContext, checker) { - if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { - return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); - } - else if (usageContext.isNumber) { - return checker.getNumberType(); - } - else if (usageContext.isString) { - return checker.getStringType(); - } - else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); - } - else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { - var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 - var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); - return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); - } - else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { - return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); - } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { - var members_6 = ts.createUnderscoreEscapedMap(); - var callSignatures = []; - var constructSignatures = []; - var stringIndexInfo = void 0; - var numberIndexInfo = void 0; - if (usageContext.properties) { - usageContext.properties.forEach(function (context, name) { - var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); - members_6.set(name, symbol); - }); - } - if (usageContext.callContexts) { - for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { - var callContext = _a[_i]; - callSignatures.push(getSignatureFromCallContext(callContext, checker)); - } - } - if (usageContext.constructContexts) { - for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { - var constructContext = _c[_b]; - constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); - } - } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } - if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 - } - else { - return undefined; - } - } - function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { - var types = []; - if (callContexts) { - for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { - var callContext = callContexts_2[_i]; - if (callContext.argumentTypes.length > parameterIndex) { - if (isRestParameter) { - types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); - } - else { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); - } - } - } - } - if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRestParameter ? checker.createArrayType(type) : type; - } - return undefined; - } - function getSignatureFromCallContext(callContext, checker) { - var parameters = []; - for (var i = 0; i < callContext.argumentTypes.length; i++) { - var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); - symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); - parameters.push(symbol); - } - var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); - // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - } - function addCandidateType(context, type) { - if (type && !(type.flags & 1 /* Any */) && !(type.flags & 32768 /* Never */)) { - (context.candidateTypes || (context.candidateTypes = [])).push(type); - } - } - function hasCallContext(usageContext) { - return !!usageContext && !!usageContext.callContexts; - } - })(InferFromReference || (InferFromReference = {})); - })(codefix = ts.codefix || (ts.codefix = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var codefix; (function (codefix) { @@ -108864,7 +113071,7 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 189 /* CallExpression */ : 190 /* NewExpression */; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 191 /* CallExpression */ : 192 /* NewExpression */; var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); if (!node) { return []; @@ -108975,7 +113182,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { - var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(52 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, propertyDeclaration) { @@ -108983,7 +113190,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { - var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + var undefinedTypeNode = ts.createKeywordTypeNode(141 /* UndefinedKeyword */); var type = propertyDeclaration.type; // TODO: GH#18217 var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); @@ -109004,8 +113211,8 @@ var ts; return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 } function getDefaultValueFromType(checker, type) { - if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + if (type.flags & 512 /* BooleanLiteral */) { + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109029,6 +113236,234 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, 0 /* ExportEquals */); + } + ts.generateTypesForModule = generateTypesForModule; + function generateTypesForGlobal(name, globalValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, 3 /* Global */); + } + ts.generateTypesForGlobal = generateTypesForGlobal; + function generateTypesForModuleOrGlobal(name, globalValue, formatSettings, outputKind) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, globalValue), formatSettings, outputKind); + } + /* @internal */ + function valueInfoToDeclarationFileText(valueInfo, formatSettings, outputKind) { + if (outputKind === void 0) { outputKind = 0 /* ExportEquals */; } + return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + OutputKind[OutputKind["Global"] = 3] = "Global"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(85 /* ExportKeyword */), ts.createModifier(80 /* DefaultKeyword */)] + : kind === 3 /* Global */ || kind === 0 /* ExportEquals */ ? [ts.createModifier(125 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(85 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members, hasNontrivialPrototype = info.hasNontrivialPrototype; + if (!hasNontrivialPrototype) { + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var protoOrInstanceMembers = ts.createMap(); + if (typeof fnAst === "object") + getConstructorFunctionInstanceProperties(fnAst, protoOrInstanceMembers); + for (var _i = 0, prototypeMembers_1 = prototypeMembers; _i < prototypeMembers_1.length; _i++) { + var p = prototypeMembers_1[_i]; + // ignore non-functions on the prototype + if (p.kind === 2 /* FunctionOrClass */) { + var m = tryGetMethod(p); + if (m) { + protoOrInstanceMembers.set(p.name, m); + } + } + } + var classStaticMembers = protoOrInstanceMembers.size !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(116 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(116 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + break; + default: + ts.Debug.assertNever(info); + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), ts.arrayFrom(protoOrInstanceMembers.values()))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + function toPropertyName(name) { + return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name); + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst, members) { + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { + var name_6 = node.left.name.text; + if (!ts.isJsPrivate(name_6)) { + ts.getOrUpdate(members, name_6, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_6, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + } + } + }); + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 200 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(106 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -109125,8 +113560,8 @@ var ts; }); function getImportTypeNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 91 /* ImportKeyword */); - ts.Debug.assert(token.parent.kind === 181 /* ImportType */); + ts.Debug.assert(token.kind === 92 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 183 /* ImportType */); return token.parent; } function doChange(changes, sourceFile, importType) { @@ -109178,7 +113613,7 @@ var ts; var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); var parameter = ts.first(indexSignature.parameters); var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); - var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(133 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ mappedIntersectionType ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); @@ -109198,7 +113633,7 @@ var ts; getAvailableActions: function (context) { var info = getInfo(context); if (!info) - return undefined; + return ts.emptyArray; var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; @@ -109225,16 +113660,16 @@ var ts; return undefined; } switch (exportNode.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: { var node = exportNode; return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { var vs = exportNode; // Must be `export const x = something;`. if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { @@ -109257,17 +113692,17 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 79 /* DefaultKeyword */))); + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 80 /* DefaultKeyword */))); } else { - var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* ExportKeyword */)); + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 85 /* ExportKeyword */)); switch (exportNode.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(79 /* DefaultKeyword */)); + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(80 /* DefaultKeyword */)); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { // We checked in `getInfo` that an initializer exists. @@ -109275,9 +113710,9 @@ var ts; break; } // falls through - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // `export type T = number;` -> `type T = number; export default T;` changes.deleteModifier(exportingSourceFile, exportKeyword); changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); @@ -109304,18 +113739,18 @@ var ts; function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { var parent = ref.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // `a.default` --> `a.foo` changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: { + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: { var spec = parent; // `default as foo` --> `foo`, `default as bar` --> `foo as bar` changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); break; } - case 248 /* ImportClause */: { + case 250 /* ImportClause */: { var clause = parent; ts.Debug.assert(clause.name === ref); var spec = makeImportSpecifier(exportName, ref.text); @@ -109324,7 +113759,7 @@ var ts; // `import foo from "./a";` --> `import { foo } from "./a";` changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); } - else if (namedBindings.kind === 249 /* NamespaceImport */) { + else if (namedBindings.kind === 251 /* NamespaceImport */) { // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; @@ -109345,36 +113780,33 @@ var ts; function changeNamedToDefaultImport(importingSourceFile, ref, changes) { var parent = ref.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // `a.foo` --> `a.default` changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: { - var spec = parent; - if (spec.kind === 251 /* ImportSpecifier */) { - // `import { foo } from "./a";` --> `import foo from "./a";` - // `import { foo as bar } from "./a";` --> `import bar from "./a";` - var defaultImport = ts.createIdentifier(spec.name.text); - if (spec.parent.elements.length === 1) { - changes.replaceNode(importingSourceFile, spec.parent, defaultImport); - } - else { - changes.delete(importingSourceFile, spec); - changes.insertNodeBefore(importingSourceFile, spec.parent, defaultImport); - } + case 253 /* ImportSpecifier */: { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(parent.name.text); + if (parent.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent.parent, defaultImport); } else { - // `export { foo } from "./a";` --> `export { default as foo } from "./a";` - // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` - // `export { foo as default } from "./a";` --> `export { default } from "./a";` - // (Because `export foo from "./a";` isn't valid syntax.) - changes.replaceNode(importingSourceFile, spec, makeExportSpecifier("default", spec.name.text)); + changes.delete(importingSourceFile, parent); + changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport); } break; } + case 257 /* ExportSpecifier */: { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text)); + break; + } default: - ts.Debug.failBadSyntaxKind(parent); + ts.Debug.assertNever(parent); } } function makeImportSpecifier(propertyName, name) { @@ -109397,9 +113829,9 @@ var ts; getAvailableActions: function (context) { var i = getImportToConvert(context); if (!i) - return undefined; - var description = i.kind === 249 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; - var actionName = i.kind === 249 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return ts.emptyArray; + var description = i.kind === 251 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 251 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; }, getEditsForAction: function (context, actionName) { @@ -109421,7 +113853,7 @@ var ts; } function doChange(sourceFile, program, changes, toConvert) { var checker = program.getTypeChecker(); - if (toConvert.kind === 249 /* NamespaceImport */) { + if (toConvert.kind === 251 /* NamespaceImport */) { doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { @@ -109481,7 +113913,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_21 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +113932,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_21(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -109529,12 +113961,12 @@ var ts; var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { - return undefined; + return ts.emptyArray; } var extractions = getPossibleExtractions(targetRange, context); if (extractions === undefined) { // No extractions possible - return undefined; + return ts.emptyArray; } var functionActions = []; var usedFunctionNames = ts.createMap(); @@ -109590,7 +114022,7 @@ var ts; actions: constantActions }); } - return infos.length ? infos : undefined; + return infos.length ? infos : ts.emptyArray; } extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ @@ -109764,20 +114196,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 152 /* PropertyDeclaration */) { + if (current.kind === 154 /* PropertyDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 149 /* Parameter */) { + else if (current.kind === 151 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 155 /* Constructor */) { + if (ctorOrMethod.kind === 157 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 154 /* MethodDeclaration */) { + else if (current.kind === 156 /* MethodDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -109820,7 +114252,7 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 235 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 237 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! @@ -109832,13 +114264,13 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 189 /* CallExpression */) { + if (node.parent.kind === 191 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { @@ -109853,8 +114285,8 @@ var ts; } if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); @@ -109866,20 +114298,20 @@ var ts; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 220 /* IfStatement */: + case 222 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 216 /* Block */: - if (node.parent && node.parent.kind === 233 /* TryStatement */ && node.parent.finallyBlock === node) { + case 218 /* Block */: + if (node.parent && node.parent.kind === 235 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 269 /* CaseClause */: + case 271 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -109891,11 +114323,11 @@ var ts; break; } switch (node.kind) { - case 176 /* ThisType */: - case 99 /* ThisKeyword */: + case 178 /* ThisType */: + case 100 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -109903,8 +114335,8 @@ var ts; seenLabels.pop(); break; } - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: { var label = node.label; if (label) { @@ -109914,20 +114346,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 227 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -109981,7 +114413,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 149 /* Parameter */) { + if (current.kind === 151 /* Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -109992,7 +114424,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 277 /* SourceFile */) { + if (current.kind === 279 /* SourceFile */) { return scopes; } } @@ -110082,32 +114514,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: return "constructor"; - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : "anonymous function"; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return "arrow function"; - case 154 /* MethodDeclaration */: - return "method '" + scope.name.getText(); - case 156 /* GetAccessor */: + case 156 /* MethodDeclaration */: + return "method '" + scope.name.getText() + "'"; + case 158 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: throw ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 238 /* ClassDeclaration */ + return scope.kind === 240 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 243 /* ModuleBlock */ + return scope.kind === 245 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -110126,7 +114558,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110173,20 +114605,20 @@ var ts; var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files - var modifiers = isJS ? [] : [ts.createToken(112 /* PrivateKeyword */)]; + var modifiers = isJS ? [] : [ts.createToken(113 /* PrivateKeyword */)]; if (range.facts & RangeFacts.InStaticRegion) { - modifiers.push(ts.createToken(115 /* StaticKeyword */)); + modifiers.push(ts.createToken(116 /* StaticKeyword */)); } if (range.facts & RangeFacts.IsAsyncFunction) { - modifiers.push(ts.createToken(120 /* AsyncKeyword */)); + modifiers.push(ts.createToken(121 /* AsyncKeyword */)); } newFunction = ts.createMethod( - /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { newFunction = ts.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(121 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; @@ -110203,7 +114635,7 @@ var ts; var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference callArguments); if (range.facts & RangeFacts.IsGenerator) { - call = ts.createYield(ts.createToken(39 /* AsteriskToken */), call); + call = ts.createYield(ts.createToken(40 /* AsteriskToken */), call); } if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); @@ -110327,9 +114759,9 @@ var ts; while (ts.isParenthesizedTypeNode(withoutParens)) { withoutParens = withoutParens.type; } - return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 140 /* UndefinedKeyword */; }) + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 141 /* UndefinedKeyword */; }) ? clone - : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(140 /* UndefinedKeyword */)]); + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(141 /* UndefinedKeyword */)]); } } /** @@ -110342,7 +114774,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110352,11 +114784,11 @@ var ts; if (ts.isClassLike(scope)) { ts.Debug.assert(!isJS); // See CannotExtractToJSClass var modifiers = []; - modifiers.push(ts.createToken(112 /* PrivateKeyword */)); + modifiers.push(ts.createToken(113 /* PrivateKeyword */)); if (rangeFacts & RangeFacts.InStaticRegion) { - modifiers.push(ts.createToken(115 /* StaticKeyword */)); + modifiers.push(ts.createToken(116 /* StaticKeyword */)); } - modifiers.push(ts.createToken(132 /* ReadonlyKeyword */)); + modifiers.push(ts.createToken(133 /* ReadonlyKeyword */)); var newVariable = ts.createProperty( /*decorators*/ undefined, modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); @@ -110385,7 +114817,7 @@ var ts; var localReference = ts.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 219 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 221 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.createVariableStatement( @@ -110404,7 +114836,7 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 219 /* ExpressionStatement */) { + if (node.parent.kind === 221 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. changeTracker.delete(context.file, node.parent); } @@ -110491,7 +114923,7 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 228 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + if (!ignoreReturns && node.kind === 230 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { @@ -110661,7 +115093,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { + else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -110669,14 +115101,14 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 237 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 239 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +115164,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_22 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +115204,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_22(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -110985,30 +115417,30 @@ var ts; function isExtractableExpression(node) { var parent = node.parent; switch (parent.kind) { - case 276 /* EnumMember */: + case 278 /* EnumMember */: return false; } switch (node.kind) { - case 9 /* StringLiteral */: - return parent.kind !== 247 /* ImportDeclaration */ && - parent.kind !== 251 /* ImportSpecifier */; - case 206 /* SpreadElement */: - case 182 /* ObjectBindingPattern */: - case 184 /* BindingElement */: + case 10 /* StringLiteral */: + return parent.kind !== 249 /* ImportDeclaration */ && + parent.kind !== 253 /* ImportSpecifier */; + case 208 /* SpreadElement */: + case 184 /* ObjectBindingPattern */: + case 186 /* BindingElement */: return false; - case 71 /* Identifier */: - return parent.kind !== 184 /* BindingElement */ && - parent.kind !== 251 /* ImportSpecifier */ && - parent.kind !== 255 /* ExportSpecifier */; + case 72 /* Identifier */: + return parent.kind !== 186 /* BindingElement */ && + parent.kind !== 253 /* ImportSpecifier */ && + parent.kind !== 257 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 216 /* Block */: - case 277 /* SourceFile */: - case 243 /* ModuleBlock */: - case 269 /* CaseClause */: + case 218 /* Block */: + case 279 /* SourceFile */: + case 245 /* ModuleBlock */: + case 271 /* CaseClause */: return true; default: return false; @@ -111029,7 +115461,7 @@ var ts; refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!getConvertibleFieldAtPosition(context)) - return undefined; + return ts.emptyArray; return [{ name: actionName, description: actionDescription, @@ -111046,7 +115478,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111057,10 +115489,10 @@ var ts; var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; var accessorModifiers = isInClassLike ? !modifierFlags || modifierFlags & 8 /* Private */ - ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) + ? getModifiers(isJS, isStatic, 115 /* PublicKeyword */) : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined; - var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined; + var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 113 /* PrivateKeyword */) : undefined; updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); ts.suppressLeadingAndTrailingTrivia(getAccessor); @@ -111069,7 +115501,7 @@ var ts; // readonly modifier only existed in classLikeDeclaration var constructor = ts.getFirstConstructorWithBody(container); if (constructor) { - updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); } } else { @@ -111098,7 +115530,7 @@ var ts; return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); } function getModifiers(isJS, isStatic, accessModifier) { - var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined); + var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(116 /* StaticKeyword */) : undefined); return modifiers && ts.createNodeArray(modifiers); } function startsWithUnderscore(name) { @@ -111121,8 +115553,8 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), - container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent, - originalName: declaration.name, + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name.text, declaration: declaration, fieldName: fieldName, accessorName: accessorName, @@ -111173,22 +115605,23 @@ var ts; ? changeTracker.insertNodeAfterComma(file, declaration, accessor) : changeTracker.insertNodeAfter(file, declaration, accessor); } - function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) { + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { if (!constructor.body) return; - var file = context.file, program = context.program, cancellationToken = context.cancellationToken; - var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; - }); - ts.forEach(referenceEntries, function (entry) { - var parent = entry.parent; - var accessorName = ts.createIdentifier(fieldName.text); - var node = ts.isBinaryExpression(parent) - ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken) - : ts.isPropertyAccessExpression(parent) - ? ts.updatePropertyAccess(parent, parent.expression, accessorName) - : ts.Debug.fail("Unexpected write access token"); - changeTracker.replaceNode(file, parent, node); + constructor.body.forEachChild(function recur(node) { + if (ts.isElementAccessExpression(node) && + node.expression.kind === 100 /* ThisKeyword */ && + ts.isStringLiteral(node.argumentExpression) && + node.argumentExpression.text === originalName && + ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName)); + } + if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName)); + } + if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(recur); + } }); } })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); @@ -111203,7 +115636,7 @@ var ts; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) - return undefined; + return ts.emptyArray; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; }, @@ -111265,11 +115698,11 @@ var ts; } function isPureImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return true; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return !ts.hasModifier(node, 1 /* Export */); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; @@ -111322,10 +115755,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_23 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_24 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,22 +115780,22 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_24(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_23(sourceFile); } } function getNamespaceLikeImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 249 /* NamespaceImport */ ? + case 249 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 251 /* NamespaceImport */ ? node.importClause.namedBindings.name : undefined; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node.name; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: return ts.Debug.assertNever(node); @@ -111393,20 +115826,20 @@ var ts; var newNamespaceId = ts.createIdentifier(newNamespaceName); var newModuleString = ts.createLiteral(newModuleSpecifier); switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); default: return ts.Debug.assertNever(node); } } function moduleSpecifierFromImport(i) { - return (i.kind === 247 /* ImportDeclaration */ ? i.moduleSpecifier - : i.kind === 246 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + return (i.kind === 249 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 248 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]); } function forEachImportInStatement(statement, cb) { @@ -111476,15 +115909,15 @@ var ts; } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { switch (importDecl.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); break; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: if (isUnused(importDecl.name)) { changes.delete(sourceFile, importDecl); } break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: @@ -111497,7 +115930,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 251 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -111509,7 +115942,7 @@ var ts; if (namedBindingsUnused) { changes.delete(sourceFile, namedBindings); } - else if (namedBindings.kind === 250 /* NamedImports */) { + else if (namedBindings.kind === 252 /* NamedImports */) { for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { var element = _b[_i]; if (isUnused(element.name)) @@ -111522,14 +115955,14 @@ var ts; function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { var name = varDecl.name; switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: if (isUnused(name)) { changes.delete(sourceFile, name); } break; - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: break; - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } @@ -111634,13 +116067,13 @@ var ts; // Below should all be utilities function isInImport(decl) { switch (decl.kind) { - case 246 /* ImportEqualsDeclaration */: - case 251 /* ImportSpecifier */: - case 248 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: return true; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return isVariableDeclarationInImport(decl); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); default: return false; @@ -111652,7 +116085,7 @@ var ts; } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 247 /* ImportDeclaration */: { + case 249 /* ImportDeclaration */: { var clause = i.importClause; if (!clause) return undefined; @@ -111662,9 +116095,9 @@ var ts; ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) : undefined; } - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return keep(i.name) ? i : undefined; - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { var name = filterBindingName(i.name, keep); return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } @@ -111673,7 +116106,7 @@ var ts; } } function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings.kind === 251 /* NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : undefined; } else { @@ -111683,11 +116116,11 @@ var ts; } function filterBindingName(name, keep) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return keep(name) ? name : undefined; - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return name; - case 182 /* ObjectBindingPattern */: { + case 184 /* ObjectBindingPattern */: { // We can't handle nested destructurings or property names well here, so just copy them all. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; @@ -111744,13 +116177,13 @@ var ts; } function isNonVariableTopLevelDeclaration(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return true; default: return false; @@ -111758,29 +116191,47 @@ var ts; } function forEachTopLevelDeclaration(statement, cb) { switch (statement.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return cb(statement); - case 217 /* VariableStatement */: - return ts.forEach(statement.declarationList.declarations, cb); - case 219 /* ExpressionStatement */: { + case 219 /* VariableStatement */: + return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); + case 221 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } } } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 72 /* Identifier */: + return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); + default: + return ts.Debug.assertNever(name); + } + } function nameOfTopLevelDeclaration(d) { - return d.kind === 219 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + return ts.isExpressionStatement(d) ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); } function getTopLevelDeclarationStatement(d) { - return ts.isVariableDeclaration(d) ? d.parent.parent : d; + switch (d.kind) { + case 237 /* VariableDeclaration */: + return d.parent.parent; + case 186 /* BindingElement */: + return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); + default: + return d; + } } function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { if (isExported(sourceFile, decl, useEs6Exports)) @@ -111807,25 +116258,25 @@ var ts; return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); } function addEs6Export(d) { - var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers); + var modifiers = ts.concatenate([ts.createModifier(85 /* ExportKeyword */)], d.modifiers); switch (d.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.updateVariableStatement(d, modifiers, d.declarationList); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(d); @@ -111836,18 +116287,18 @@ var ts; } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: return [decl.name.text]; // TODO: GH#18217 - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.emptyArray; - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(decl); @@ -111855,7 +116306,7 @@ var ts; } /** Creates `exports.x = x;` */ function createExportAssignment(name) { - return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name))); + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 59 /* EqualsToken */, ts.createIdentifier(name))); } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); @@ -111877,7 +116328,7 @@ var ts; var file = context.file, startPosition = context.startPosition; var info = getConvertibleArrowFunctionAtPosition(file, startPosition); if (!info) - return undefined; + return ts.emptyArray; return [{ name: refactorName, description: refactorDescription, @@ -111919,7 +116370,7 @@ var ts; return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); } function getConvertibleArrowFunctionAtPosition(file, startPosition) { var node = ts.getTokenAtPosition(file, startPosition); @@ -111955,7 +116406,7 @@ var ts; ts.servicesVersion = "0.8"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : - kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : + kind === 72 /* Identifier */ ? new IdentifierObject(72 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; node.flags = parent.flags & 12679168 /* ContextFlags */; @@ -112028,8 +116479,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 303 /* LastJSDocNode */; }); - return child.kind < 146 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; }); + return child.kind < 148 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -112040,7 +116491,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 146 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 148 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -112086,7 +116537,7 @@ var ts; var token = ts.scanner.scan(); var textPos = ts.scanner.getTextPos(); if (textPos <= end) { - if (token === 71 /* Identifier */) { + if (token === 72 /* Identifier */) { ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); } nodes.push(createNode(token, pos, textPos, parent)); @@ -112098,7 +116549,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(304 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -112230,7 +116681,7 @@ var ts; }); return IdentifierObject; }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 71 /* Identifier */; + IdentifierObject.prototype.kind = 72 /* Identifier */; var TypeObject = /** @class */ (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -112276,25 +116727,25 @@ var ts; return this.checker.getDefaultFromTypeParameter(this); }; TypeObject.prototype.isUnion = function () { - return !!(this.flags & 262144 /* Union */); + return !!(this.flags & 1048576 /* Union */); }; TypeObject.prototype.isIntersection = function () { - return !!(this.flags & 524288 /* Intersection */); + return !!(this.flags & 2097152 /* Intersection */); }; TypeObject.prototype.isUnionOrIntersection = function () { - return !!(this.flags & 786432 /* UnionOrIntersection */); + return !!(this.flags & 3145728 /* UnionOrIntersection */); }; TypeObject.prototype.isLiteral = function () { - return !!(this.flags & 192 /* StringOrNumberLiteral */); + return !!(this.flags & 384 /* StringOrNumberLiteral */); }; TypeObject.prototype.isStringLiteral = function () { - return !!(this.flags & 64 /* StringLiteral */); + return !!(this.flags & 128 /* StringLiteral */); }; TypeObject.prototype.isNumberLiteral = function () { - return !!(this.flags & 128 /* NumberLiteral */); + return !!(this.flags & 256 /* NumberLiteral */); }; TypeObject.prototype.isTypeParameter = function () { - return !!(this.flags & 65536 /* TypeParameter */); + return !!(this.flags & 262144 /* TypeParameter */); }; TypeObject.prototype.isClassOrInterface = function () { return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */); @@ -112344,8 +116795,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112431,10 +116882,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -112454,31 +116905,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 166 /* TypeLiteral */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 168 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 149 /* Parameter */: + case 151 /* Parameter */: // Only consider parameter properties if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // falls through - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: { + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -112489,19 +116940,19 @@ var ts; } } // falls through - case 276 /* EnumMember */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: addDeclaration(node); break; - case 253 /* ExportDeclaration */: + case 255 /* 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 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -112513,7 +116964,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -112522,8 +116973,8 @@ var ts; } } break; - case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112835,7 +117286,7 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; }); + var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -112865,8 +117316,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +117355,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112911,11 +117367,11 @@ var ts; compilerHost.trace = function (message) { return host.trace(message); }; } if (host.resolveModuleNames) { - compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }; + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }; } if (host.resolveTypeReferenceDirectives) { - compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile) { - return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile); + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile, redirectedReference); }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); @@ -112924,7 +117380,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -112949,7 +117405,7 @@ var ts; // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -113039,7 +117495,7 @@ var ts; // 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); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +117538,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113106,15 +117562,15 @@ var ts; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { - case 71 /* Identifier */: - return !ts.isLabelName(node); - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + return !ts.isLabelName(node) && !ts.isTagName(node); + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` return !ts.isInComment(sourceFile, position); - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 97 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 98 /* SuperKeyword */: return true; default: return false; @@ -113152,7 +117608,7 @@ var ts; var normalizedFileName = ts.normalizePath(fileName); ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); synchronizeHostData(); - var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); }); + var sourceFilesToSearch = filesToSearch.map(getValidSourceFile); var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } @@ -113160,29 +117616,27 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position); - if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { + if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113223,16 +117677,16 @@ var ts; return undefined; } switch (node.kind) { - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: - case 9 /* StringLiteral */: - case 86 /* FalseKeyword */: - case 101 /* TrueKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 71 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + case 10 /* StringLiteral */: + case 87 /* FalseKeyword */: + case 102 /* TrueKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 72 /* Identifier */: break; // Cant create the text span default: @@ -113248,7 +117702,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 === 242 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 244 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -113310,10 +117764,10 @@ var ts; return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken); } var braceMatching = ts.createMapFromTemplate((_a = {}, - _a[17 /* OpenBraceToken */] = 18 /* CloseBraceToken */, - _a[19 /* OpenParenToken */] = 20 /* CloseParenToken */, - _a[21 /* OpenBracketToken */] = 22 /* CloseBracketToken */, - _a[29 /* GreaterThanToken */] = 27 /* LessThanToken */, + _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */, + _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */, + _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */, + _a[30 /* GreaterThanToken */] = 28 /* LessThanToken */, _a)); braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); function getBraceMatchingAtPosition(fileName, position) { @@ -113389,19 +117843,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -113441,7 +117907,7 @@ var ts; var token = ts.findPrecedingToken(position, sourceFile); if (!token) return undefined; - var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent + var element = token.kind === 30 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent : ts.isJsxText(token) ? token.parent : undefined; if (element && isUnclosedTag(element)) { return { newText: "" }; @@ -113679,7 +118145,7 @@ var ts; function initializeNameTable(sourceFile) { var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); sourceFile.forEachChild(function walk(node) { - if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { + if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { var text = ts.getEscapedTextOfIdentifierOrLiteral(node); nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } @@ -113700,7 +118166,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 257 /* ExternalModuleReference */ || + node.parent.kind === 259 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -113715,15 +118181,15 @@ var ts; ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; function getContainingObjectLiteralElementWorker(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 147 /* ComputedPropertyName */) { + if (node.parent.kind === 149 /* ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 186 /* ObjectLiteralExpression */ || node.parent.parent.kind === 266 /* JsxAttributes */) && + (node.parent.parent.kind === 188 /* ObjectLiteralExpression */ || node.parent.parent.kind === 268 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -113765,7 +118231,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 188 /* ElementAccessExpression */ && + node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -113845,144 +118311,144 @@ var ts; if (node) { var parent = node.parent; switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 235 /* VariableDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return spanInVariableDeclaration(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return spanInParameterDeclaration(node); - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return spanInBlock(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return spanInBlock(node.block); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 221 /* DoStatement */: + case 223 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 234 /* DebuggerStatement */: + case 236 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 220 /* IfStatement */: + case 222 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return spanInForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 233 /* TryStatement */: + case 235 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 184 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 186 /* BindingElement */: // span on complete node return textSpan(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 150 /* Decorator */: + case 152 /* Decorator */: return spanInNodeArray(parent.decorators); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return undefined; // Tokens: - case 25 /* SemicolonToken */: + case 26 /* SemicolonToken */: case 1 /* EndOfFileToken */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return spanInPreviousNode(node); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return spanInOpenBraceToken(node); - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: return spanInCloseBraceToken(node); - case 22 /* CloseBracketToken */: + case 23 /* CloseBracketToken */: return spanInCloseBracketToken(node); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return spanInOpenParenToken(node); - case 20 /* CloseParenToken */: + case 21 /* CloseParenToken */: return spanInCloseParenToken(node); - case 56 /* ColonToken */: + case 57 /* ColonToken */: return spanInColonToken(node); - case 29 /* GreaterThanToken */: - case 27 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 28 /* LessThanToken */: return spanInGreaterThanOrLessThanToken(node); // Keywords: - case 106 /* WhileKeyword */: + case 107 /* WhileKeyword */: return spanInWhileKeyword(node); - case 82 /* ElseKeyword */: - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 83 /* ElseKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return spanInNextNode(node); - case 145 /* OfKeyword */: + case 147 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -113994,14 +118460,14 @@ var ts; // 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 === 71 /* Identifier */ || - node.kind === 206 /* SpreadElement */ || - node.kind === 273 /* PropertyAssignment */ || - node.kind === 274 /* ShorthandPropertyAssignment */) && + if ((node.kind === 72 /* Identifier */ || + node.kind === 208 /* SpreadElement */ || + node.kind === 275 /* PropertyAssignment */ || + node.kind === 276 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 202 /* BinaryExpression */) { + if (node.kind === 204 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -114010,35 +118476,35 @@ var ts; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); } - if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + if (operatorToken.kind === 59 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.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 (operatorToken.kind === 26 /* CommaToken */) { + if (operatorToken.kind === 27 /* CommaToken */) { return spanInNode(left); } } if (ts.isExpressionNode(node)) { switch (parent.kind) { - case 221 /* DoStatement */: + case 223 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 150 /* Decorator */: + case 152 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: return textSpan(node); - case 202 /* BinaryExpression */: - if (node.parent.operatorToken.kind === 26 /* CommaToken */) { + case 204 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 27 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -114047,21 +118513,21 @@ var ts; } } switch (node.parent.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -114069,7 +118535,7 @@ var ts; } break; } - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -114099,7 +118565,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 224 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 226 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } var parent = variableDeclaration.parent; @@ -114111,7 +118577,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - parent.parent.kind === 225 /* ForOfStatement */) { + parent.parent.kind === 227 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -114152,7 +118618,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 238 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */); + (functionDeclaration.parent.kind === 240 /* ClassDeclaration */ && functionDeclaration.kind !== 157 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -114175,26 +118641,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // falls through // Set on parent if on same line otherwise on first statement - case 222 /* WhileStatement */: - case 220 /* IfStatement */: - case 224 /* ForInStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 226 /* 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 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 227 /* 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(forLikeStatement) { - if (forLikeStatement.initializer.kind === 236 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 238 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -114219,21 +118685,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 184 /* BindingElement */) { + if (bindingPattern.parent.kind === 186 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 183 /* ArrayBindingPattern */ && node.kind !== 182 /* ObjectBindingPattern */); - var elements = node.kind === 185 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 185 /* ArrayBindingPattern */ && node.kind !== 184 /* ObjectBindingPattern */); + var elements = node.kind === 187 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -114241,18 +118707,18 @@ var ts; // 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 === 202 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 204 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -114260,25 +118726,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 241 /* EnumDeclaration */: - case 238 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 272 /* CatchClause */: + case 274 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -114286,7 +118752,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 182 /* ObjectBindingPattern */: + case 184 /* 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); @@ -114302,7 +118768,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 183 /* ArrayBindingPattern */: + case 185 /* 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); @@ -114317,12 +118783,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 221 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 189 /* CallExpression */ || - node.parent.kind === 190 /* NewExpression */) { + if (node.parent.kind === 223 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 191 /* CallExpression */ || + node.parent.kind === 192 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 193 /* ParenthesizedExpression */) { + if (node.parent.kind === 195 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -114331,21 +118797,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 193 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 195 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -114355,20 +118821,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 273 /* PropertyAssignment */ || - node.parent.kind === 149 /* Parameter */) { + node.parent.kind === 275 /* PropertyAssignment */ || + node.parent.kind === 151 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 192 /* TypeAssertionExpression */) { + if (node.parent.kind === 194 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 221 /* DoStatement */) { + if (node.parent.kind === 223 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -114376,7 +118842,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 225 /* ForOfStatement */) { + if (node.parent.kind === 227 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -114474,7 +118940,7 @@ var ts; var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; // TODO: GH#18217 + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -114484,7 +118950,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); }; } } @@ -114593,9 +119059,15 @@ var ts; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } + else { + this.directoryExists = undefined; // TODO: GH#18217 + } if ("realpath" in this.shimHost) { this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 } + else { + this.realpath = undefined; // TODO: GH#18217 + } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 887e98b6f5d..cad17f4992f 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ const version: string; } @@ -27,6 +27,9 @@ declare namespace ts { interface MapLike { [index: string]: T; } + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } interface SortedArray extends Array { " __sortedArrayBrand": any; } @@ -69,7 +72,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -81,337 +85,339 @@ declare namespace ts { ShebangTrivia = 6, ConflictMarkerTrivia = 7, NumericLiteral = 8, - StringLiteral = 9, - JsxText = 10, - JsxTextAllWhiteSpaces = 11, - RegularExpressionLiteral = 12, - NoSubstitutionTemplateLiteral = 13, - TemplateHead = 14, - TemplateMiddle = 15, - TemplateTail = 16, - OpenBraceToken = 17, - CloseBraceToken = 18, - OpenParenToken = 19, - CloseParenToken = 20, - OpenBracketToken = 21, - CloseBracketToken = 22, - DotToken = 23, - DotDotDotToken = 24, - SemicolonToken = 25, - CommaToken = 26, - LessThanToken = 27, - LessThanSlashToken = 28, - GreaterThanToken = 29, - LessThanEqualsToken = 30, - GreaterThanEqualsToken = 31, - EqualsEqualsToken = 32, - ExclamationEqualsToken = 33, - EqualsEqualsEqualsToken = 34, - ExclamationEqualsEqualsToken = 35, - EqualsGreaterThanToken = 36, - PlusToken = 37, - MinusToken = 38, - AsteriskToken = 39, - AsteriskAsteriskToken = 40, - SlashToken = 41, - PercentToken = 42, - PlusPlusToken = 43, - MinusMinusToken = 44, - LessThanLessThanToken = 45, - GreaterThanGreaterThanToken = 46, - GreaterThanGreaterThanGreaterThanToken = 47, - AmpersandToken = 48, - BarToken = 49, - CaretToken = 50, - ExclamationToken = 51, - TildeToken = 52, - AmpersandAmpersandToken = 53, - BarBarToken = 54, - QuestionToken = 55, - ColonToken = 56, - AtToken = 57, - EqualsToken = 58, - PlusEqualsToken = 59, - MinusEqualsToken = 60, - AsteriskEqualsToken = 61, - AsteriskAsteriskEqualsToken = 62, - SlashEqualsToken = 63, - PercentEqualsToken = 64, - LessThanLessThanEqualsToken = 65, - GreaterThanGreaterThanEqualsToken = 66, - GreaterThanGreaterThanGreaterThanEqualsToken = 67, - AmpersandEqualsToken = 68, - BarEqualsToken = 69, - CaretEqualsToken = 70, - Identifier = 71, - BreakKeyword = 72, - CaseKeyword = 73, - CatchKeyword = 74, - ClassKeyword = 75, - ConstKeyword = 76, - ContinueKeyword = 77, - DebuggerKeyword = 78, - DefaultKeyword = 79, - DeleteKeyword = 80, - DoKeyword = 81, - ElseKeyword = 82, - EnumKeyword = 83, - ExportKeyword = 84, - ExtendsKeyword = 85, - FalseKeyword = 86, - FinallyKeyword = 87, - ForKeyword = 88, - FunctionKeyword = 89, - IfKeyword = 90, - ImportKeyword = 91, - InKeyword = 92, - InstanceOfKeyword = 93, - NewKeyword = 94, - NullKeyword = 95, - ReturnKeyword = 96, - SuperKeyword = 97, - SwitchKeyword = 98, - ThisKeyword = 99, - ThrowKeyword = 100, - TrueKeyword = 101, - TryKeyword = 102, - TypeOfKeyword = 103, - VarKeyword = 104, - VoidKeyword = 105, - WhileKeyword = 106, - WithKeyword = 107, - ImplementsKeyword = 108, - InterfaceKeyword = 109, - LetKeyword = 110, - PackageKeyword = 111, - PrivateKeyword = 112, - ProtectedKeyword = 113, - PublicKeyword = 114, - StaticKeyword = 115, - YieldKeyword = 116, - AbstractKeyword = 117, - AsKeyword = 118, - AnyKeyword = 119, - AsyncKeyword = 120, - AwaitKeyword = 121, - BooleanKeyword = 122, - ConstructorKeyword = 123, - DeclareKeyword = 124, - GetKeyword = 125, - InferKeyword = 126, - IsKeyword = 127, - KeyOfKeyword = 128, - ModuleKeyword = 129, - NamespaceKeyword = 130, - NeverKeyword = 131, - ReadonlyKeyword = 132, - RequireKeyword = 133, - NumberKeyword = 134, - ObjectKeyword = 135, - SetKeyword = 136, - StringKeyword = 137, - SymbolKeyword = 138, - TypeKeyword = 139, - UndefinedKeyword = 140, - UniqueKeyword = 141, - UnknownKeyword = 142, - FromKeyword = 143, - GlobalKeyword = 144, - OfKeyword = 145, - QualifiedName = 146, - ComputedPropertyName = 147, - TypeParameter = 148, - Parameter = 149, - Decorator = 150, - PropertySignature = 151, - PropertyDeclaration = 152, - MethodSignature = 153, - MethodDeclaration = 154, - Constructor = 155, - GetAccessor = 156, - SetAccessor = 157, - CallSignature = 158, - ConstructSignature = 159, - IndexSignature = 160, - TypePredicate = 161, - TypeReference = 162, - FunctionType = 163, - ConstructorType = 164, - TypeQuery = 165, - TypeLiteral = 166, - ArrayType = 167, - TupleType = 168, - OptionalType = 169, - RestType = 170, - UnionType = 171, - IntersectionType = 172, - ConditionalType = 173, - InferType = 174, - ParenthesizedType = 175, - ThisType = 176, - TypeOperator = 177, - IndexedAccessType = 178, - MappedType = 179, - LiteralType = 180, - ImportType = 181, - ObjectBindingPattern = 182, - ArrayBindingPattern = 183, - BindingElement = 184, - ArrayLiteralExpression = 185, - ObjectLiteralExpression = 186, - PropertyAccessExpression = 187, - ElementAccessExpression = 188, - CallExpression = 189, - NewExpression = 190, - TaggedTemplateExpression = 191, - TypeAssertionExpression = 192, - ParenthesizedExpression = 193, - FunctionExpression = 194, - ArrowFunction = 195, - DeleteExpression = 196, - TypeOfExpression = 197, - VoidExpression = 198, - AwaitExpression = 199, - PrefixUnaryExpression = 200, - PostfixUnaryExpression = 201, - BinaryExpression = 202, - ConditionalExpression = 203, - TemplateExpression = 204, - YieldExpression = 205, - SpreadElement = 206, - ClassExpression = 207, - OmittedExpression = 208, - ExpressionWithTypeArguments = 209, - AsExpression = 210, - NonNullExpression = 211, - MetaProperty = 212, - SyntheticExpression = 213, - TemplateSpan = 214, - SemicolonClassElement = 215, - Block = 216, - VariableStatement = 217, - EmptyStatement = 218, - ExpressionStatement = 219, - IfStatement = 220, - DoStatement = 221, - WhileStatement = 222, - ForStatement = 223, - ForInStatement = 224, - ForOfStatement = 225, - ContinueStatement = 226, - BreakStatement = 227, - ReturnStatement = 228, - WithStatement = 229, - SwitchStatement = 230, - LabeledStatement = 231, - ThrowStatement = 232, - TryStatement = 233, - DebuggerStatement = 234, - VariableDeclaration = 235, - VariableDeclarationList = 236, - FunctionDeclaration = 237, - ClassDeclaration = 238, - InterfaceDeclaration = 239, - TypeAliasDeclaration = 240, - EnumDeclaration = 241, - ModuleDeclaration = 242, - ModuleBlock = 243, - CaseBlock = 244, - NamespaceExportDeclaration = 245, - ImportEqualsDeclaration = 246, - ImportDeclaration = 247, - ImportClause = 248, - NamespaceImport = 249, - NamedImports = 250, - ImportSpecifier = 251, - ExportAssignment = 252, - ExportDeclaration = 253, - NamedExports = 254, - ExportSpecifier = 255, - MissingDeclaration = 256, - ExternalModuleReference = 257, - JsxElement = 258, - JsxSelfClosingElement = 259, - JsxOpeningElement = 260, - JsxClosingElement = 261, - JsxFragment = 262, - JsxOpeningFragment = 263, - JsxClosingFragment = 264, - JsxAttribute = 265, - JsxAttributes = 266, - JsxSpreadAttribute = 267, - JsxExpression = 268, - CaseClause = 269, - DefaultClause = 270, - HeritageClause = 271, - CatchClause = 272, - PropertyAssignment = 273, - ShorthandPropertyAssignment = 274, - SpreadAssignment = 275, - EnumMember = 276, - SourceFile = 277, - Bundle = 278, - UnparsedSource = 279, - InputFiles = 280, - JSDocTypeExpression = 281, - JSDocAllType = 282, - JSDocUnknownType = 283, - JSDocNullableType = 284, - JSDocNonNullableType = 285, - JSDocOptionalType = 286, - JSDocFunctionType = 287, - JSDocVariadicType = 288, - JSDocComment = 289, - JSDocTypeLiteral = 290, - JSDocSignature = 291, - JSDocTag = 292, - JSDocAugmentsTag = 293, - JSDocClassTag = 294, - JSDocCallbackTag = 295, - JSDocEnumTag = 296, - JSDocParameterTag = 297, - JSDocReturnTag = 298, - JSDocThisTag = 299, - JSDocTypeTag = 300, - JSDocTemplateTag = 301, - JSDocTypedefTag = 302, - JSDocPropertyTag = 303, - SyntaxList = 304, - NotEmittedStatement = 305, - PartiallyEmittedExpression = 306, - CommaListExpression = 307, - MergeDeclarationMarker = 308, - EndOfDeclarationMarker = 309, - Count = 310, - FirstAssignment = 58, - LastAssignment = 70, - FirstCompoundAssignment = 59, - LastCompoundAssignment = 70, - FirstReservedWord = 72, - LastReservedWord = 107, - FirstKeyword = 72, - LastKeyword = 145, - FirstFutureReservedWord = 108, - LastFutureReservedWord = 116, - FirstTypeNode = 161, - LastTypeNode = 181, - FirstPunctuation = 17, - LastPunctuation = 70, + BigIntLiteral = 9, + StringLiteral = 10, + JsxText = 11, + JsxTextAllWhiteSpaces = 12, + RegularExpressionLiteral = 13, + NoSubstitutionTemplateLiteral = 14, + TemplateHead = 15, + TemplateMiddle = 16, + TemplateTail = 17, + OpenBraceToken = 18, + CloseBraceToken = 19, + OpenParenToken = 20, + CloseParenToken = 21, + OpenBracketToken = 22, + CloseBracketToken = 23, + DotToken = 24, + DotDotDotToken = 25, + SemicolonToken = 26, + CommaToken = 27, + LessThanToken = 28, + LessThanSlashToken = 29, + GreaterThanToken = 30, + LessThanEqualsToken = 31, + GreaterThanEqualsToken = 32, + EqualsEqualsToken = 33, + ExclamationEqualsToken = 34, + EqualsEqualsEqualsToken = 35, + ExclamationEqualsEqualsToken = 36, + EqualsGreaterThanToken = 37, + PlusToken = 38, + MinusToken = 39, + AsteriskToken = 40, + AsteriskAsteriskToken = 41, + SlashToken = 42, + PercentToken = 43, + PlusPlusToken = 44, + MinusMinusToken = 45, + LessThanLessThanToken = 46, + GreaterThanGreaterThanToken = 47, + GreaterThanGreaterThanGreaterThanToken = 48, + AmpersandToken = 49, + BarToken = 50, + CaretToken = 51, + ExclamationToken = 52, + TildeToken = 53, + AmpersandAmpersandToken = 54, + BarBarToken = 55, + QuestionToken = 56, + ColonToken = 57, + AtToken = 58, + EqualsToken = 59, + PlusEqualsToken = 60, + MinusEqualsToken = 61, + AsteriskEqualsToken = 62, + AsteriskAsteriskEqualsToken = 63, + SlashEqualsToken = 64, + PercentEqualsToken = 65, + LessThanLessThanEqualsToken = 66, + GreaterThanGreaterThanEqualsToken = 67, + GreaterThanGreaterThanGreaterThanEqualsToken = 68, + AmpersandEqualsToken = 69, + BarEqualsToken = 70, + CaretEqualsToken = 71, + Identifier = 72, + BreakKeyword = 73, + CaseKeyword = 74, + CatchKeyword = 75, + ClassKeyword = 76, + ConstKeyword = 77, + ContinueKeyword = 78, + DebuggerKeyword = 79, + DefaultKeyword = 80, + DeleteKeyword = 81, + DoKeyword = 82, + ElseKeyword = 83, + EnumKeyword = 84, + ExportKeyword = 85, + ExtendsKeyword = 86, + FalseKeyword = 87, + FinallyKeyword = 88, + ForKeyword = 89, + FunctionKeyword = 90, + IfKeyword = 91, + ImportKeyword = 92, + InKeyword = 93, + InstanceOfKeyword = 94, + NewKeyword = 95, + NullKeyword = 96, + ReturnKeyword = 97, + SuperKeyword = 98, + SwitchKeyword = 99, + ThisKeyword = 100, + ThrowKeyword = 101, + TrueKeyword = 102, + TryKeyword = 103, + TypeOfKeyword = 104, + VarKeyword = 105, + VoidKeyword = 106, + WhileKeyword = 107, + WithKeyword = 108, + ImplementsKeyword = 109, + InterfaceKeyword = 110, + LetKeyword = 111, + PackageKeyword = 112, + PrivateKeyword = 113, + ProtectedKeyword = 114, + PublicKeyword = 115, + StaticKeyword = 116, + YieldKeyword = 117, + AbstractKeyword = 118, + AsKeyword = 119, + AnyKeyword = 120, + AsyncKeyword = 121, + AwaitKeyword = 122, + BooleanKeyword = 123, + ConstructorKeyword = 124, + DeclareKeyword = 125, + GetKeyword = 126, + InferKeyword = 127, + IsKeyword = 128, + KeyOfKeyword = 129, + ModuleKeyword = 130, + NamespaceKeyword = 131, + NeverKeyword = 132, + ReadonlyKeyword = 133, + RequireKeyword = 134, + NumberKeyword = 135, + ObjectKeyword = 136, + SetKeyword = 137, + StringKeyword = 138, + SymbolKeyword = 139, + TypeKeyword = 140, + UndefinedKeyword = 141, + UniqueKeyword = 142, + UnknownKeyword = 143, + FromKeyword = 144, + GlobalKeyword = 145, + BigIntKeyword = 146, + OfKeyword = 147, + QualifiedName = 148, + ComputedPropertyName = 149, + TypeParameter = 150, + Parameter = 151, + Decorator = 152, + PropertySignature = 153, + PropertyDeclaration = 154, + MethodSignature = 155, + MethodDeclaration = 156, + Constructor = 157, + GetAccessor = 158, + SetAccessor = 159, + CallSignature = 160, + ConstructSignature = 161, + IndexSignature = 162, + TypePredicate = 163, + TypeReference = 164, + FunctionType = 165, + ConstructorType = 166, + TypeQuery = 167, + TypeLiteral = 168, + ArrayType = 169, + TupleType = 170, + OptionalType = 171, + RestType = 172, + UnionType = 173, + IntersectionType = 174, + ConditionalType = 175, + InferType = 176, + ParenthesizedType = 177, + ThisType = 178, + TypeOperator = 179, + IndexedAccessType = 180, + MappedType = 181, + LiteralType = 182, + ImportType = 183, + ObjectBindingPattern = 184, + ArrayBindingPattern = 185, + BindingElement = 186, + ArrayLiteralExpression = 187, + ObjectLiteralExpression = 188, + PropertyAccessExpression = 189, + ElementAccessExpression = 190, + CallExpression = 191, + NewExpression = 192, + TaggedTemplateExpression = 193, + TypeAssertionExpression = 194, + ParenthesizedExpression = 195, + FunctionExpression = 196, + ArrowFunction = 197, + DeleteExpression = 198, + TypeOfExpression = 199, + VoidExpression = 200, + AwaitExpression = 201, + PrefixUnaryExpression = 202, + PostfixUnaryExpression = 203, + BinaryExpression = 204, + ConditionalExpression = 205, + TemplateExpression = 206, + YieldExpression = 207, + SpreadElement = 208, + ClassExpression = 209, + OmittedExpression = 210, + ExpressionWithTypeArguments = 211, + AsExpression = 212, + NonNullExpression = 213, + MetaProperty = 214, + SyntheticExpression = 215, + TemplateSpan = 216, + SemicolonClassElement = 217, + Block = 218, + VariableStatement = 219, + EmptyStatement = 220, + ExpressionStatement = 221, + IfStatement = 222, + DoStatement = 223, + WhileStatement = 224, + ForStatement = 225, + ForInStatement = 226, + ForOfStatement = 227, + ContinueStatement = 228, + BreakStatement = 229, + ReturnStatement = 230, + WithStatement = 231, + SwitchStatement = 232, + LabeledStatement = 233, + ThrowStatement = 234, + TryStatement = 235, + DebuggerStatement = 236, + VariableDeclaration = 237, + VariableDeclarationList = 238, + FunctionDeclaration = 239, + ClassDeclaration = 240, + InterfaceDeclaration = 241, + TypeAliasDeclaration = 242, + EnumDeclaration = 243, + ModuleDeclaration = 244, + ModuleBlock = 245, + CaseBlock = 246, + NamespaceExportDeclaration = 247, + ImportEqualsDeclaration = 248, + ImportDeclaration = 249, + ImportClause = 250, + NamespaceImport = 251, + NamedImports = 252, + ImportSpecifier = 253, + ExportAssignment = 254, + ExportDeclaration = 255, + NamedExports = 256, + ExportSpecifier = 257, + MissingDeclaration = 258, + ExternalModuleReference = 259, + JsxElement = 260, + JsxSelfClosingElement = 261, + JsxOpeningElement = 262, + JsxClosingElement = 263, + JsxFragment = 264, + JsxOpeningFragment = 265, + JsxClosingFragment = 266, + JsxAttribute = 267, + JsxAttributes = 268, + JsxSpreadAttribute = 269, + JsxExpression = 270, + CaseClause = 271, + DefaultClause = 272, + HeritageClause = 273, + CatchClause = 274, + PropertyAssignment = 275, + ShorthandPropertyAssignment = 276, + SpreadAssignment = 277, + EnumMember = 278, + SourceFile = 279, + Bundle = 280, + UnparsedSource = 281, + InputFiles = 282, + JSDocTypeExpression = 283, + JSDocAllType = 284, + JSDocUnknownType = 285, + JSDocNullableType = 286, + JSDocNonNullableType = 287, + JSDocOptionalType = 288, + JSDocFunctionType = 289, + JSDocVariadicType = 290, + JSDocComment = 291, + JSDocTypeLiteral = 292, + JSDocSignature = 293, + JSDocTag = 294, + JSDocAugmentsTag = 295, + JSDocClassTag = 296, + JSDocCallbackTag = 297, + JSDocEnumTag = 298, + JSDocParameterTag = 299, + JSDocReturnTag = 300, + JSDocThisTag = 301, + JSDocTypeTag = 302, + JSDocTemplateTag = 303, + JSDocTypedefTag = 304, + JSDocPropertyTag = 305, + SyntaxList = 306, + NotEmittedStatement = 307, + PartiallyEmittedExpression = 308, + CommaListExpression = 309, + MergeDeclarationMarker = 310, + EndOfDeclarationMarker = 311, + Count = 312, + FirstAssignment = 59, + LastAssignment = 71, + FirstCompoundAssignment = 60, + LastCompoundAssignment = 71, + FirstReservedWord = 73, + LastReservedWord = 108, + FirstKeyword = 73, + LastKeyword = 147, + FirstFutureReservedWord = 109, + LastFutureReservedWord = 117, + FirstTypeNode = 163, + LastTypeNode = 183, + FirstPunctuation = 18, + LastPunctuation = 71, FirstToken = 0, - LastToken = 145, + LastToken = 147, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, - LastLiteralToken = 13, - FirstTemplateToken = 13, - LastTemplateToken = 16, - FirstBinaryOperator = 27, - LastBinaryOperator = 70, - FirstNode = 146, - FirstJSDocNode = 281, - LastJSDocNode = 303, - FirstJSDocTagNode = 292, - LastJSDocTagNode = 303 + LastLiteralToken = 14, + FirstTemplateToken = 14, + LastTemplateToken = 17, + FirstBinaryOperator = 28, + LastBinaryOperator = 71, + FirstNode = 148, + FirstJSDocNode = 283, + LastJSDocNode = 305, + FirstJSDocTagNode = 294, + LastJSDocTagNode = 305 } enum NodeFlags { None = 0, @@ -498,7 +504,6 @@ declare namespace ts { type AsteriskToken = Token; type EqualsGreaterThanToken = Token; type EndOfFileToken = Token & JSDocContainer; - type AtToken = Token; type ReadonlyToken = Token; type AwaitKeywordToken = Token; type PlusToken = Token; @@ -525,7 +530,7 @@ declare namespace ts { } type EntityName = Identifier | QualifiedName; type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; - type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; + type DeclarationName = Identifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; } @@ -536,6 +541,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +638,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +675,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -720,7 +728,7 @@ declare namespace ts { _typeNodeBrand: any; } interface KeywordTypeNode extends TypeNode { - kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; + kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; } interface ImportTypeNode extends NodeWithTypeArguments { kind: SyntaxKind.ImportType; @@ -992,6 +1000,9 @@ declare namespace ts { interface NumericLiteral extends LiteralExpression { kind: SyntaxKind.NumericLiteral; } + interface BigIntLiteral extends LiteralExpression { + kind: SyntaxKind.BigIntLiteral; + } interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; parent: TemplateExpression; @@ -1079,7 +1090,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1539,7 +1550,6 @@ declare namespace ts { } interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; - atToken: AtToken; tagName: Identifier; comment?: string; } @@ -1569,7 +1579,7 @@ declare namespace ts { } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; - constraint: TypeNode | undefined; + constraint: JSDocTypeExpression | undefined; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { @@ -1751,13 +1761,14 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. */ fileExists(path: string): boolean; readFile(path: string): string | undefined; + trace?(s: string): void; } /** * Branded string for keeping track of when we've turned an ambiguous path @@ -1808,11 +1819,13 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): ReadonlyArray | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; sourceFile: SourceFile; + references?: ReadonlyArray; } interface CustomTransformers { /** Custom transformers to evaluate before built-in .js transformations. */ @@ -1836,17 +1849,6 @@ declare namespace ts { /** .ts file (index into sources array) associated with this span */ sourceIndex: number; } - interface SourceMapData { - sourceMapFilePath: string; - jsSourceMappingURL: string; - sourceMapFile: string; - sourceMapSourceRoot: string; - sourceMapSources: string[]; - sourceMapSourcesContent?: (string | null)[]; - inputSourceFileNames: string[]; - sourceMapNames?: string[]; - sourceMapMappings: string; - } /** Return code used by getEmitOutput function to indicate status of the function */ enum ExitStatus { Success = 0, @@ -1918,7 +1920,7 @@ declare namespace ts { typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; + getRootSymbols(symbol: Symbol): ReadonlyArray; getContextualType(node: Expression): Type | undefined; /** * returns unknownSignature in the case of an error. @@ -1936,7 +1938,6 @@ declare namespace ts { /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; @@ -1975,7 +1976,8 @@ declare namespace ts { AllowEmptyTuple = 524288, AllowUniqueESSymbolType = 1048576, AllowEmptyIndexInfoType = 2097152, - IgnoreErrors = 3112960, + AllowNodeModulesRelativePaths = 67108864, + IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, @@ -2056,32 +2058,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2155,44 +2157,47 @@ declare namespace ts { Number = 8, Boolean = 16, Enum = 32, - StringLiteral = 64, - NumberLiteral = 128, - BooleanLiteral = 256, - EnumLiteral = 512, - ESSymbol = 1024, - UniqueESSymbol = 2048, - Void = 4096, - Undefined = 8192, - Null = 16384, - Never = 32768, - TypeParameter = 65536, - Object = 131072, - Union = 262144, - Intersection = 524288, - Index = 1048576, - IndexedAccess = 2097152, - Conditional = 4194304, - Substitution = 8388608, - NonPrimitive = 16777216, - Literal = 448, - Unit = 27072, - StringOrNumberLiteral = 192, - PossiblyFalsy = 29148, - StringLike = 68, - NumberLike = 168, - BooleanLike = 272, - EnumLike = 544, - ESSymbolLike = 3072, - VoidLike = 12288, - UnionOrIntersection = 786432, - StructuredType = 917504, - TypeVariable = 2162688, - InstantiableNonPrimitive = 14745600, - InstantiablePrimitive = 1048576, - Instantiable = 15794176, - StructuredOrInstantiable = 16711680, - Narrowable = 33492479, - NotUnionOrUnit = 16909315 + BigInt = 64, + StringLiteral = 128, + NumberLiteral = 256, + BooleanLiteral = 512, + EnumLiteral = 1024, + BigIntLiteral = 2048, + ESSymbol = 4096, + UniqueESSymbol = 8192, + Void = 16384, + Undefined = 32768, + Null = 65536, + Never = 131072, + TypeParameter = 262144, + Object = 524288, + Union = 1048576, + Intersection = 2097152, + Index = 4194304, + IndexedAccess = 8388608, + Conditional = 16777216, + Substitution = 33554432, + NonPrimitive = 67108864, + Literal = 2944, + Unit = 109440, + StringOrNumberLiteral = 384, + PossiblyFalsy = 117724, + StringLike = 132, + NumberLike = 296, + BigIntLike = 2112, + BooleanLike = 528, + EnumLike = 1056, + ESSymbolLike = 12288, + VoidLike = 49152, + UnionOrIntersection = 3145728, + StructuredType = 3670016, + TypeVariable = 8650752, + InstantiableNonPrimitive = 58982400, + InstantiablePrimitive = 4194304, + Instantiable = 63176704, + StructuredOrInstantiable = 66846720, + Narrowable = 133970943, + NotUnionOrUnit = 67637251 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2203,7 +2208,7 @@ declare namespace ts { aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { - value: string | number; + value: string | number | PseudoBigInt; freshType: LiteralType; regularType: LiteralType; } @@ -2216,6 +2221,9 @@ declare namespace ts { interface NumberLiteralType extends LiteralType { value: number; } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } interface EnumType extends Type { } enum ObjectFlags { @@ -2234,6 +2242,7 @@ declare namespace ts { JsxAttributes = 4096, MarkerType = 8192, JSLiteral = 16384, + FreshLiteral = 32768, ClassOrInterface = 3 } interface ObjectType extends Type { @@ -2490,6 +2499,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2591,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2601,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2673,6 +2674,8 @@ declare namespace ts { primary: boolean; resolvedFileName: string | undefined; packageId?: PackageId; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; @@ -2691,16 +2694,13 @@ declare namespace ts { useCaseSensitiveFileNames(): boolean; getNewLine(): string; readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -2753,7 +2753,8 @@ declare namespace ts { Expression = 1, IdentifierName = 2, MappedTypeParameter = 3, - Unspecified = 4 + Unspecified = 4, + EmbeddedStatement = 5 } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2946,60 +2947,77 @@ declare namespace ts { BarDelimited = 4, AmpersandDelimited = 8, CommaDelimited = 16, - DelimitersMask = 28, - AllowTrailingComma = 32, - Indented = 64, - SpaceBetweenBraces = 128, - SpaceBetweenSiblings = 256, - Braces = 512, - Parenthesis = 1024, - AngleBrackets = 2048, - SquareBrackets = 4096, - BracketsMask = 7680, - OptionalIfUndefined = 8192, - OptionalIfEmpty = 16384, - Optional = 24576, - PreferNewLine = 32768, - NoTrailingNewLine = 65536, - NoInterveningComments = 131072, - NoSpaceIfEmpty = 262144, - SingleElement = 524288, - Modifiers = 131328, - HeritageClauses = 256, - SingleLineTypeLiteralMembers = 384, - MultiLineTypeLiteralMembers = 16449, - TupleTypeElements = 272, - UnionTypeConstituents = 260, - IntersectionTypeConstituents = 264, - ObjectBindingPatternElements = 262576, - ArrayBindingPatternElements = 262448, - ObjectLiteralExpressionProperties = 263122, - ArrayLiteralExpressionElements = 4466, - CommaListElements = 272, - CallExpressionArguments = 1296, - NewExpressionArguments = 9488, - TemplateExpressionSpans = 131072, - SingleLineBlockStatements = 384, - MultiLineBlockStatements = 65, - VariableDeclarationList = 272, - SingleLineFunctionBodyStatements = 384, + AsteriskDelimited = 32, + DelimitersMask = 60, + AllowTrailingComma = 64, + Indented = 128, + SpaceBetweenBraces = 256, + SpaceBetweenSiblings = 512, + Braces = 1024, + Parenthesis = 2048, + AngleBrackets = 4096, + SquareBrackets = 8192, + BracketsMask = 15360, + OptionalIfUndefined = 16384, + OptionalIfEmpty = 32768, + Optional = 49152, + PreferNewLine = 65536, + NoTrailingNewLine = 131072, + NoInterveningComments = 262144, + NoSpaceIfEmpty = 524288, + SingleElement = 1048576, + Modifiers = 262656, + HeritageClauses = 512, + SingleLineTypeLiteralMembers = 768, + MultiLineTypeLiteralMembers = 32897, + TupleTypeElements = 528, + UnionTypeConstituents = 516, + IntersectionTypeConstituents = 520, + ObjectBindingPatternElements = 525136, + ArrayBindingPatternElements = 524880, + ObjectLiteralExpressionProperties = 526226, + ArrayLiteralExpressionElements = 8914, + CommaListElements = 528, + CallExpressionArguments = 2576, + NewExpressionArguments = 18960, + TemplateExpressionSpans = 262144, + SingleLineBlockStatements = 768, + MultiLineBlockStatements = 129, + VariableDeclarationList = 528, + SingleLineFunctionBodyStatements = 768, MultiLineFunctionBodyStatements = 1, ClassHeritageClauses = 0, - ClassMembers = 65, - InterfaceMembers = 65, - EnumMembers = 81, - CaseBlockClauses = 65, - NamedImportsOrExportsElements = 262576, - JsxElementOrFragmentChildren = 131072, - JsxElementAttributes = 131328, - CaseOrDefaultClauseStatements = 81985, - HeritageClauseTypes = 272, - SourceFileStatements = 65537, - Decorators = 24577, - TypeArguments = 26896, - TypeParameters = 26896, - Parameters = 1296, - IndexSignatureParameters = 4432 + ClassMembers = 129, + InterfaceMembers = 129, + EnumMembers = 145, + CaseBlockClauses = 129, + NamedImportsOrExportsElements = 525136, + JsxElementOrFragmentChildren = 262144, + JsxElementAttributes = 262656, + CaseOrDefaultClauseStatements = 163969, + HeritageClauseTypes = 528, + SourceFileStatements = 131073, + Decorators = 49153, + TypeArguments = 53776, + TypeParameters = 53776, + Parameters = 2576, + IndexSignatureParameters = 8848, + JSDocComment = 33 + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } + /** Represents a bigint literal value without requiring bigint support */ + interface PseudoBigInt { + negative: boolean; + base10Value: string; } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; @@ -3114,10 +3132,9 @@ declare namespace ts { function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } -/** Non-internal stuff goes here */ declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray; } declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; @@ -3209,17 +3226,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -3273,6 +3300,7 @@ declare namespace ts { } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; + function isBigIntLiteral(node: Node): node is BigIntLiteral; function isStringLiteral(node: Node): node is StringLiteral; function isJsxText(node: Node): node is JsxText; function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; @@ -3450,6 +3478,7 @@ declare namespace ts { type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail; function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; + function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier; function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; function isModifier(node: Node): node is Modifier; function isEntityName(node: Node): node is EntityName; @@ -3592,7 +3621,7 @@ declare namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -3607,14 +3636,14 @@ declare namespace ts { * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string): Map; + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ interface NonRelativeModuleNameResolutionCache { - getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; + getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; @@ -3622,18 +3651,19 @@ declare namespace ts { } function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; } declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; - function createLiteral(value: number): NumericLiteral; + function createLiteral(value: number | PseudoBigInt): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; - function createLiteral(value: string | number | boolean): PrimaryExpression; + function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; + function createBigIntLiteral(value: string): BigIntLiteral; function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; function createIdentifier(text: string): Identifier; @@ -4134,7 +4164,7 @@ declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; interface FormatDiagnosticsHost { getCurrentDirectory(): string; getCanonicalFileName(fileName: string): string; @@ -4171,14 +4201,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4334,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4358,17 +4400,9 @@ declare namespace ts { /** If provided is used to get the environment variable */ getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } /** * Host to create watch with root files and options @@ -4378,6 +4412,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4448,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,193 +4459,17 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; type EventInitializationFailed = "event::initializationFailed"; - interface SortedReadonlyArray extends ReadonlyArray { - " __sortedArrayBrand": any; - } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4807,9 +4667,9 @@ declare namespace ts { realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. @@ -4817,15 +4677,11 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; + writeFile?(fileName: string, content: string): void; } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; - } + type WithMetadata = T & { + metadata?: unknown; + }; interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; @@ -4843,7 +4699,7 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; @@ -4851,16 +4707,16 @@ declare namespace ts { getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getNavigationTree(fileName: string): NavigationTree; @@ -4882,9 +4738,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5012,7 +4868,7 @@ declare namespace ts { message: string; position: number; } - class TextChange { + interface TextChange { span: TextSpan; newText: string; } @@ -5046,9 +4902,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5114,6 +4977,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5191,24 +5056,25 @@ declare namespace ts { insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter?: boolean; - insertSpaceAfterSemicolonInForStatements?: boolean; - insertSpaceBeforeAndAfterBinaryOperators?: boolean; - insertSpaceAfterConstructor?: boolean; - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - insertSpaceAfterTypeAssertion?: boolean; - insertSpaceBeforeFunctionParenthesis?: boolean; - placeOpenBraceOnNewLineForFunctions?: boolean; - placeOpenBraceOnNewLineForControlBlocks?: boolean; - insertSpaceBeforeTypeAnnotation?: boolean; - indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + readonly insertSpaceAfterCommaDelimiter?: boolean; + readonly insertSpaceAfterSemicolonInForStatements?: boolean; + readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; + readonly insertSpaceAfterConstructor?: boolean; + readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + readonly insertSpaceAfterTypeAssertion?: boolean; + readonly insertSpaceBeforeFunctionParenthesis?: boolean; + readonly placeOpenBraceOnNewLineForFunctions?: boolean; + readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; + readonly insertSpaceBeforeTypeAnnotation?: boolean; + readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } + function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; @@ -5266,15 +5132,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; @@ -5392,8 +5267,9 @@ declare namespace ts { Whitespace = 4, Identifier = 5, NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8 + BigIntLiteral = 7, + StringLiteral = 8, + RegExpLiteral = 9 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -5505,13 +5381,20 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional" + optionalModifier = "optional", + dtsModifier = ".d.ts", + tsModifier = ".ts", + tsxModifier = ".tsx", + jsModifier = ".js", + jsxModifier = ".jsx", + jsonModifier = ".json" } enum ClassificationTypeNames { comment = "comment", identifier = "identifier", keyword = "keyword", numericLiteral = "number", + bigintLiteral = "bigint", operator = "operator", stringLiteral = "string", whiteSpace = "whitespace", @@ -5556,7 +5439,8 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24 + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 } } declare namespace ts { @@ -5648,6 +5532,10 @@ declare namespace ts { function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; } +declare namespace ts { + function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string; + function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string; +} declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 78365f95075..25e193cff42 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -62,7 +62,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -73,7 +73,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -88,6 +88,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -477,10 +478,33 @@ var ts; return result; } ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ function flatMap(array, mapfn) { var result; if (array) { - result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { for (var i = 0; i < array.length; i++) { var v = mapfn(array[i], i); if (v) { @@ -495,7 +519,7 @@ var ts; } return result; } - ts.flatMap = flatMap; + ts.flatMapToMutable = flatMapToMutable; function flatMapIterator(iter, mapfn) { var first = iter.next(); if (first.done) { @@ -716,19 +740,25 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) - return []; + return ts.emptyArray; var last = array[0]; var deduplicated = [last]; for (var i = 1; i < array.length; i++) { @@ -759,7 +789,7 @@ var ts; } ts.insertSorted = insertSorted; function sortAndDeduplicate(array, comparer, equalityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); } ts.sortAndDeduplicate = sortAndDeduplicate; function arrayIsEqualTo(array1, array2, equalityComparer) { @@ -771,7 +801,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -912,7 +942,7 @@ var ts; * Returns a new sorted array. */ function sort(array, comparer) { - return array.slice().sort(comparer); + return (array.length === 0 ? array : array.slice().sort(comparer)); } ts.sort = sort; function arrayIterator(array) { @@ -1018,12 +1048,25 @@ var ts; * @param offset An offset into `array` at which to start the search. */ function binarySearch(array, value, keySelector, keyComparer, offset) { - if (!array || array.length === 0) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { return -1; } var low = offset || 0; var high = array.length - 1; - var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); var midKey = keySelector(array[middle]); @@ -1040,7 +1083,7 @@ var ts; } return ~low; } - ts.binarySearch = binarySearch; + ts.binarySearchKey = binarySearchKey; function reduceLeft(array, f, initial, start, count) { if (array && array.length > 0) { var size = array.length; @@ -1148,7 +1191,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1311,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1432,7 +1479,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1935,6 +1984,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -1954,6 +2007,33 @@ var ts; var counts; var marks; var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; /** * Marks a performance event. * @@ -2029,6 +2109,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2048,368 +2488,370 @@ var ts; SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; // Literals SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; - SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; - SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; // Pseudo-literals - SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; + SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail"; // Punctuation - SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken"; // Assignments - SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken"; // Identifiers - SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; + SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier"; // Reserved words - SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword"; // Strict mode reserved words - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword"; // Contextual keywords - SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; - SyntaxKind[SyntaxKind["InferKeyword"] = 126] = "InferKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 127] = "IsKeyword"; - SyntaxKind[SyntaxKind["KeyOfKeyword"] = 128] = "KeyOfKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 129] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 130] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 131] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 132] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 133] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 134] = "NumberKeyword"; - SyntaxKind[SyntaxKind["ObjectKeyword"] = 135] = "ObjectKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 136] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 137] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 138] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword"; - SyntaxKind[SyntaxKind["UnknownKeyword"] = 142] = "UnknownKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 143] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 144] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 145] = "OfKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 146] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 147] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 148] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 149] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 150] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 151] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 152] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 153] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 154] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 155] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 156] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 157] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 158] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 159] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 160] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 161] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 162] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 163] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 164] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 165] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 166] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 167] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 168] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 169] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 170] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 171] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 172] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 173] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 174] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 175] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 176] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 177] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 178] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 179] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 180] = "LiteralType"; - SyntaxKind[SyntaxKind["ImportType"] = 181] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 182] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 183] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 184] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 185] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 186] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 187] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 188] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 189] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 190] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 191] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 192] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 193] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 194] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 195] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 196] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 197] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 198] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 199] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 200] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 201] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 202] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 203] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 204] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 205] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 206] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 207] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 208] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 209] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 210] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 211] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 212] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 213] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 214] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 215] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 216] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 217] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 218] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 219] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 220] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 221] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 222] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 223] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 224] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 225] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 226] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 227] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 228] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 229] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 230] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 231] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 232] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 233] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 234] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 235] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 236] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 237] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 238] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 239] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 240] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 241] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 242] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 243] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 244] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 245] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 246] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 247] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 248] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 249] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 250] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 251] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 252] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 253] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 254] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 255] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 256] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 218] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 257] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 258] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 259] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 260] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 261] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 262] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 263] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 264] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 265] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 266] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 267] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 268] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 269] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 270] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 271] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 272] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 273] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 274] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 275] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 276] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 277] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 278] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 279] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 280] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 281] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 282] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 283] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 284] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 285] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 286] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 287] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 288] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 289] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 290] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 291] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 292] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 310] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; // Markers - SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 145] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 161] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 181] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 145] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode"; - /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -2609,7 +3051,10 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; + // Errors (cont.) + NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors"; // State NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; @@ -2665,6 +3110,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2696,14 +3143,15 @@ var ts; // of a type, such as the global `Promise` type in lib.d.ts). TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; // with call signatures. - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var SymbolFlags; (function (SymbolFlags) { @@ -2734,38 +3182,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2840,14 +3288,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2857,29 +3306,27 @@ var ts; TypeFlags[TypeFlags["Number"] = 8] = "Number"; TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 64] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 128] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 256] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 512] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 1024] = "ESSymbol"; - TypeFlags[TypeFlags["UniqueESSymbol"] = 2048] = "UniqueESSymbol"; - TypeFlags[TypeFlags["Void"] = 4096] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 8192] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 16384] = "Null"; - TypeFlags[TypeFlags["Never"] = 32768] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 65536] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 131072] = "Object"; - TypeFlags[TypeFlags["Union"] = 262144] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 524288] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 1048576] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 2097152] = "IndexedAccess"; - TypeFlags[TypeFlags["Conditional"] = 4194304] = "Conditional"; - TypeFlags[TypeFlags["Substitution"] = 8388608] = "Substitution"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; - /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; - /* @internal */ - TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes"; + TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt"; + TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 16384] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 65536] = "Null"; + TypeFlags[TypeFlags["Never"] = 131072] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 524288] = "Object"; + TypeFlags[TypeFlags["Union"] = 1048576] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 4194304] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; /* @internal */ TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ @@ -2889,40 +3336,41 @@ var ts; /* @internal */ TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 24576] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 448] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 27072] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 192] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 2944] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 2240] = "StringOrNumberLiteralOrUnique"; + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 29120] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 29148] = "PossiblyFalsy"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 16839967] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 32764] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 68] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 168] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 272] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 544] = "EnumLike"; - TypeFlags[TypeFlags["ESSymbolLike"] = 3072] = "ESSymbolLike"; - TypeFlags[TypeFlags["VoidLike"] = 12288] = "VoidLike"; + TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike"; + TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; /* @internal */ - TypeFlags[TypeFlags["DisjointDomains"] = 16809468] = "DisjointDomains"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 786432] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 917504] = "StructuredType"; - TypeFlags[TypeFlags["TypeVariable"] = 2162688] = "TypeVariable"; - TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 14745600] = "InstantiableNonPrimitive"; - TypeFlags[TypeFlags["InstantiablePrimitive"] = 1048576] = "InstantiablePrimitive"; - TypeFlags[TypeFlags["Instantiable"] = 15794176] = "Instantiable"; - TypeFlags[TypeFlags["StructuredOrInstantiable"] = 16711680] = "StructuredOrInstantiable"; + TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion"; + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ @@ -2957,6 +3405,7 @@ var ts; ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -2968,6 +3417,13 @@ var ts; Variance[Variance["Bivariant"] = 3] = "Bivariant"; Variance[Variance["Independent"] = 4] = "Independent"; })(Variance = ts.Variance || (ts.Variance = {})); + /* @internal */ + var JsxReferenceKind; + (function (JsxReferenceKind) { + JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component"; + JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function"; + JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed"; + })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {})); var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; @@ -2993,9 +3449,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3469,31 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue"; + // Object.defineProperty(exports || module.exports, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports"; + // Object.defineProperty(Foo.prototype, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3266,25 +3730,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3303,25 +3763,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3401,6 +3860,7 @@ var ts; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; + EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); var ListFormat; (function (ListFormat) { @@ -3415,64 +3875,66 @@ var ts; ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma"; // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + ListFormat[ListFormat["Indented"] = 128] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings"; // Brackets/Braces - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + ListFormat[ListFormat["Braces"] = 1024] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 49152] = "Optional"; // Other - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; + ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters"; + ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment"; })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); /* @internal */ var PragmaKindFlags; @@ -3565,20 +4027,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3796,17 +4244,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4127,11 +4579,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4742,7 +5195,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5234,11 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4793,7 +5251,7 @@ var ts; An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), - An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), @@ -4837,14 +5295,14 @@ var ts; Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), @@ -4900,7 +5358,7 @@ var ts; Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), - A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), @@ -4983,7 +5441,7 @@ var ts; _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), - Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), @@ -5014,7 +5472,7 @@ var ts; Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), @@ -5024,7 +5482,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5509,15 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5609,15 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5731,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5827,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5925,18 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5967,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5488,6 +5977,7 @@ var ts; _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), @@ -5515,6 +6005,15 @@ var ts; If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5545,6 +6044,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5609,6 +6109,7 @@ var ts; Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -5673,150 +6174,108 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { - return token >= 71 /* Identifier */; + return token >= 72 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; /* @internal */ function tokenIsIdentifierOrKeywordOrGreaterThan(token) { - return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 118 /* AbstractKeyword */, + any: 120 /* AnyKeyword */, + as: 119 /* AsKeyword */, + bigint: 146 /* BigIntKeyword */, + boolean: 123 /* BooleanKeyword */, + break: 73 /* BreakKeyword */, + case: 74 /* CaseKeyword */, + catch: 75 /* CatchKeyword */, + class: 76 /* ClassKeyword */, + continue: 78 /* ContinueKeyword */, + const: 77 /* ConstKeyword */ + }, + _a["" + "constructor"] = 124 /* ConstructorKeyword */, + _a.debugger = 79 /* DebuggerKeyword */, + _a.declare = 125 /* DeclareKeyword */, + _a.default = 80 /* DefaultKeyword */, + _a.delete = 81 /* DeleteKeyword */, + _a.do = 82 /* DoKeyword */, + _a.else = 83 /* ElseKeyword */, + _a.enum = 84 /* EnumKeyword */, + _a.export = 85 /* ExportKeyword */, + _a.extends = 86 /* ExtendsKeyword */, + _a.false = 87 /* FalseKeyword */, + _a.finally = 88 /* FinallyKeyword */, + _a.for = 89 /* ForKeyword */, + _a.from = 144 /* FromKeyword */, + _a.function = 90 /* FunctionKeyword */, + _a.get = 126 /* GetKeyword */, + _a.if = 91 /* IfKeyword */, + _a.implements = 109 /* ImplementsKeyword */, + _a.import = 92 /* ImportKeyword */, + _a.in = 93 /* InKeyword */, + _a.infer = 127 /* InferKeyword */, + _a.instanceof = 94 /* InstanceOfKeyword */, + _a.interface = 110 /* InterfaceKeyword */, + _a.is = 128 /* IsKeyword */, + _a.keyof = 129 /* KeyOfKeyword */, + _a.let = 111 /* LetKeyword */, + _a.module = 130 /* ModuleKeyword */, + _a.namespace = 131 /* NamespaceKeyword */, + _a.never = 132 /* NeverKeyword */, + _a.new = 95 /* NewKeyword */, + _a.null = 96 /* NullKeyword */, + _a.number = 135 /* NumberKeyword */, + _a.object = 136 /* ObjectKeyword */, + _a.package = 112 /* PackageKeyword */, + _a.private = 113 /* PrivateKeyword */, + _a.protected = 114 /* ProtectedKeyword */, + _a.public = 115 /* PublicKeyword */, + _a.readonly = 133 /* ReadonlyKeyword */, + _a.require = 134 /* RequireKeyword */, + _a.global = 145 /* GlobalKeyword */, + _a.return = 97 /* ReturnKeyword */, + _a.set = 137 /* SetKeyword */, + _a.static = 116 /* StaticKeyword */, + _a.string = 138 /* StringKeyword */, + _a.super = 98 /* SuperKeyword */, + _a.switch = 99 /* SwitchKeyword */, + _a.symbol = 139 /* SymbolKeyword */, + _a.this = 100 /* ThisKeyword */, + _a.throw = 101 /* ThrowKeyword */, + _a.true = 102 /* TrueKeyword */, + _a.try = 103 /* TryKeyword */, + _a.type = 140 /* TypeKeyword */, + _a.typeof = 104 /* TypeOfKeyword */, + _a.undefined = 141 /* UndefinedKeyword */, + _a.unique = 142 /* UniqueKeyword */, + _a.unknown = 143 /* UnknownKeyword */, + _a.var = 105 /* VarKeyword */, + _a.void = 106 /* VoidKeyword */, + _a.while = 107 /* WhileKeyword */, + _a.with = 108 /* WithKeyword */, + _a.yield = 117 /* YieldKeyword */, + _a.async = 121 /* AsyncKeyword */, + _a.await = 122 /* AwaitKeyword */, + _a.of = 147 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, ">": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -5951,11 +6410,28 @@ var ts; } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { - ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } } var res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } if (line < lineStarts.length - 1) { ts.Debug.assert(res < lineStarts[line + 1]); } @@ -6394,6 +6870,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6404,8 +6881,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, - isIdentifier: function () { return token === 71 /* Identifier */ || token > 107 /* LastReservedWord */; }, - isReservedWord: function () { return token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */; }, + isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; }, isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, @@ -6423,6 +6900,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6498,18 +6976,29 @@ var ts; end = pos; } } + var result; if (tokenFlags & 512 /* ContainsSeparator */) { - var result = mainFragment; + result = mainFragment; if (decimalFragment) { result += "." + decimalFragment; } if (scientificFragment) { result += scientificFragment; } - return "" + +result; } else { - return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + return { + type: 8 /* NumericLiteral */, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type: type, value: tokenValue }; } } function scanOctalDigits() { @@ -6524,21 +7013,21 @@ var ts; * returning -1 if the given number is unavailable. */ function scanExactNumberOfHexDigits(count, canHaveSeparators) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; } /** * Scans as many hexadecimal digits as are available in the text, - * returning -1 if the given number of digits was unavailable. + * returning "" if the given number of digits was unavailable. */ function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { - var digits = 0; - var value = 0; + var valueChars = []; var allowSeparator = false; var isPreviousTokenSeparator = false; - while (digits < minCount || scanAsManyAsPossible) { + while (valueChars.length < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); if (canHaveSeparators && ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; @@ -6556,29 +7045,24 @@ var ts; continue; } allowSeparator = canHaveSeparators; - if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { - value = value * 16 + ch - 48 /* _0 */; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase } - else if (ch >= 65 /* A */ && ch <= 70 /* F */) { - value = value * 16 + ch - 65 /* A */ + 10; - } - else if (ch >= 97 /* a */ && ch <= 102 /* f */) { - value = value * 16 + ch - 97 /* a */ + 10; - } - else { + else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) || + (ch >= 97 /* a */ && ch <= 102 /* f */))) { break; } + valueChars.push(ch); pos++; - digits++; isPreviousTokenSeparator = false; } - if (digits < minCount) { - value = -1; + if (valueChars.length < minCount) { + valueChars = []; } if (text.charCodeAt(pos - 1) === 95 /* _ */) { error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } - return value; + return String.fromCharCode.apply(String, valueChars); } function scanString(jsxAttributeString) { if (jsxAttributeString === void 0) { jsxAttributeString = false; } @@ -6630,7 +7114,7 @@ var ts; contents += text.substring(start, pos); tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; break; } var currChar = text.charCodeAt(pos); @@ -6638,14 +7122,14 @@ var ts; if (currChar === 96 /* backtick */) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; break; } // '${' if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 14 /* TemplateHead */ : 15 /* TemplateMiddle */; + resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */; break; } // Escape character @@ -6738,7 +7222,8 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; var isInvalidExtendedEscape = false; // Validate the value of the digit if (escapedValue < 0) { @@ -6820,20 +7305,18 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } - return token = 71 /* Identifier */; + return token = 72 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); - var value = 0; + var value = ""; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. - var numberOfDigits = 0; var separatorAllowed = false; var isPreviousTokenSeparator = false; while (true) { @@ -6855,29 +7338,45 @@ var ts; continue; } separatorAllowed = true; - var valueOfCh = ch - 48 /* _0 */; - if (!isDigit(ch) || valueOfCh >= base) { + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { break; } - value = value * base + valueOfCh; + value += text[pos]; pos++; - numberOfDigits++; isPreviousTokenSeparator = false; } - // Invalid binaryIntegerLiteral or octalIntegerLiteral - if (numberOfDigits === 0) { - return -1; - } if (text.charCodeAt(pos - 1) === 95 /* _ */) { // Literal ends with underscore - not allowed error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); - return value; } return value; } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110 /* n */) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9 /* BigIntLiteral */; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + var numericValue = tokenFlags & 128 /* BinarySpecifier */ + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & 256 /* OctalSpecifier */ + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return 8 /* NumericLiteral */; + } + } function scan() { + var _a; startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7415,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6929,82 +7446,87 @@ var ts; case 33 /* exclamation */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 35 /* ExclamationEqualsEqualsToken */; + return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */; } - return pos += 2, token = 33 /* ExclamationEqualsToken */; + return pos += 2, token = 34 /* ExclamationEqualsToken */; } pos++; - return token = 51 /* ExclamationToken */; + return token = 52 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); - return token = 9 /* StringLiteral */; + return token = 10 /* StringLiteral */; case 96 /* backtick */: return token = scanTemplateAndSetTokenValue(); case 37 /* percent */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 64 /* PercentEqualsToken */; + return pos += 2, token = 65 /* PercentEqualsToken */; } pos++; - return token = 42 /* PercentToken */; + return token = 43 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { - return pos += 2, token = 53 /* AmpersandAmpersandToken */; + return pos += 2, token = 54 /* AmpersandAmpersandToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 68 /* AmpersandEqualsToken */; + return pos += 2, token = 69 /* AmpersandEqualsToken */; } pos++; - return token = 48 /* AmpersandToken */; + return token = 49 /* AmpersandToken */; case 40 /* openParen */: pos++; - return token = 19 /* OpenParenToken */; + return token = 20 /* OpenParenToken */; case 41 /* closeParen */: pos++; - return token = 20 /* CloseParenToken */; + return token = 21 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 61 /* AsteriskEqualsToken */; + return pos += 2, token = 62 /* AsteriskEqualsToken */; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 62 /* AsteriskAsteriskEqualsToken */; + return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */; } - return pos += 2, token = 40 /* AsteriskAsteriskToken */; + return pos += 2, token = 41 /* AsteriskAsteriskToken */; } pos++; - return token = 39 /* AsteriskToken */; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } + return token = 40 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { - return pos += 2, token = 43 /* PlusPlusToken */; + return pos += 2, token = 44 /* PlusPlusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 59 /* PlusEqualsToken */; + return pos += 2, token = 60 /* PlusEqualsToken */; } pos++; - return token = 37 /* PlusToken */; + return token = 38 /* PlusToken */; case 44 /* comma */: pos++; - return token = 26 /* CommaToken */; + return token = 27 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { - return pos += 2, token = 44 /* MinusMinusToken */; + return pos += 2, token = 45 /* MinusMinusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 60 /* MinusEqualsToken */; + return pos += 2, token = 61 /* MinusEqualsToken */; } pos++; - return token = 38 /* MinusToken */; + return token = 39 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber(); + tokenValue = scanNumber().value; return token = 8 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { - return pos += 3, token = 24 /* DotDotDotToken */; + return pos += 3, token = 25 /* DotDotDotToken */; } pos++; - return token = 23 /* DotToken */; + return token = 24 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -7055,43 +7577,43 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 63 /* SlashEqualsToken */; + return pos += 2, token = 64 /* SlashEqualsToken */; } pos++; - return token = 41 /* SlashToken */; + return token = 42 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); - if (value < 0) { + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { error(ts.Diagnostics.Hexadecimal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0x" + tokenValue; tokenFlags |= 64 /* HexSpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 2); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { error(ts.Diagnostics.Binary_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0b" + tokenValue; tokenFlags |= 128 /* BinarySpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 8); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { error(ts.Diagnostics.Octal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0o" + tokenValue; tokenFlags |= 256 /* OctalSpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } // Try to parse as an octal if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { @@ -7112,14 +7634,14 @@ var ts; case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - tokenValue = scanNumber(); - return token = 8 /* NumericLiteral */; + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; case 58 /* colon */: pos++; - return token = 56 /* ColonToken */; + return token = 57 /* ColonToken */; case 59 /* semicolon */: pos++; - return token = 25 /* SemicolonToken */; + return token = 26 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7132,20 +7654,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 65 /* LessThanLessThanEqualsToken */; + return pos += 3, token = 66 /* LessThanLessThanEqualsToken */; } - return pos += 2, token = 45 /* LessThanLessThanToken */; + return pos += 2, token = 46 /* LessThanLessThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 30 /* LessThanEqualsToken */; + return pos += 2, token = 31 /* LessThanEqualsToken */; } if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */) { - return pos += 2, token = 28 /* LessThanSlashToken */; + return pos += 2, token = 29 /* LessThanSlashToken */; } pos++; - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7158,15 +7680,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 34 /* EqualsEqualsEqualsToken */; + return pos += 3, token = 35 /* EqualsEqualsEqualsToken */; } - return pos += 2, token = 32 /* EqualsEqualsToken */; + return pos += 2, token = 33 /* EqualsEqualsToken */; } if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { - return pos += 2, token = 36 /* EqualsGreaterThanToken */; + return pos += 2, token = 37 /* EqualsGreaterThanToken */; } pos++; - return token = 58 /* EqualsToken */; + return token = 59 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7178,25 +7700,25 @@ var ts; } } pos++; - return token = 29 /* GreaterThanToken */; + return token = 30 /* GreaterThanToken */; case 63 /* question */: pos++; - return token = 55 /* QuestionToken */; + return token = 56 /* QuestionToken */; case 91 /* openBracket */: pos++; - return token = 21 /* OpenBracketToken */; + return token = 22 /* OpenBracketToken */; case 93 /* closeBracket */: pos++; - return token = 22 /* CloseBracketToken */; + return token = 23 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 70 /* CaretEqualsToken */; + return pos += 2, token = 71 /* CaretEqualsToken */; } pos++; - return token = 50 /* CaretToken */; + return token = 51 /* CaretToken */; case 123 /* openBrace */: pos++; - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; case 124 /* bar */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7208,22 +7730,22 @@ var ts; } } if (text.charCodeAt(pos + 1) === 124 /* bar */) { - return pos += 2, token = 54 /* BarBarToken */; + return pos += 2, token = 55 /* BarBarToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 69 /* BarEqualsToken */; + return pos += 2, token = 70 /* BarEqualsToken */; } pos++; - return token = 49 /* BarToken */; + return token = 50 /* BarToken */; case 125 /* closeBrace */: pos++; - return token = 18 /* CloseBraceToken */; + return token = 19 /* CloseBraceToken */; case 126 /* tilde */: pos++; - return token = 52 /* TildeToken */; + return token = 53 /* TildeToken */; case 64 /* at */: pos++; - return token = 57 /* AtToken */; + return token = 58 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -7261,29 +7783,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 29 /* GreaterThanToken */) { + if (token === 30 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } - return pos += 2, token = 47 /* GreaterThanGreaterThanGreaterThanToken */; + return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 66 /* GreaterThanGreaterThanEqualsToken */; + return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */; } pos++; - return token = 46 /* GreaterThanGreaterThanToken */; + return token = 47 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { pos++; - return token = 31 /* GreaterThanEqualsToken */; + return token = 32 /* GreaterThanEqualsToken */; } } return token; } function reScanSlashToken() { - if (token === 41 /* SlashToken */ || token === 63 /* SlashEqualsToken */) { + if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -7328,7 +7850,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12 /* RegularExpressionLiteral */; + token = 13 /* RegularExpressionLiteral */; } return token; } @@ -7336,7 +7858,7 @@ var ts; * Unconditionally back up and scan a template expression portion. */ function reScanTemplateToken() { - ts.Debug.assert(token === 18 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -7353,14 +7875,14 @@ var ts; if (char === 60 /* lessThan */) { if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; - return token = 28 /* LessThanSlashToken */; + return token = 29 /* LessThanSlashToken */; } pos++; - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; } if (char === 123 /* openBrace */) { pos++; - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; } // First non-whitespace character on this line. var firstNonWhitespace = 0; @@ -7392,7 +7914,7 @@ var ts; } pos++; } - return firstNonWhitespace === -1 ? 11 /* JsxTextAllWhiteSpaces */ : 10 /* JsxText */; + return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -7418,7 +7940,7 @@ var ts; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(/*jsxAttributeString*/ true); - return token = 9 /* StringLiteral */; + return token = 10 /* StringLiteral */; default: // If this scans anything other than `{`, it's a parse error. return scan(); @@ -7442,43 +7964,43 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - return token = 57 /* AtToken */; + return token = 58 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - return token = 39 /* AsteriskToken */; + return token = 40 /* AsteriskToken */; case 123 /* openBrace */: - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; case 125 /* closeBrace */: - return token = 18 /* CloseBraceToken */; + return token = 19 /* CloseBraceToken */; case 91 /* openBracket */: - return token = 21 /* OpenBracketToken */; + return token = 22 /* OpenBracketToken */; case 93 /* closeBracket */: - return token = 22 /* CloseBracketToken */; + return token = 23 /* CloseBracketToken */; case 60 /* lessThan */: - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; case 61 /* equals */: - return token = 58 /* EqualsToken */; + return token = 59 /* EqualsToken */; case 44 /* comma */: - return token = 26 /* CommaToken */; + return token = 27 /* CommaToken */; case 46 /* dot */: - return token = 23 /* DotToken */; + return token = 24 /* DotToken */; case 96 /* backtick */: while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { pos++; } tokenValue = text.substring(tokenPos + 1, pos); pos++; - return token = 13 /* NoSubstitutionTemplateLiteral */; + return token = 14 /* NoSubstitutionTemplateLiteral */; } if (isIdentifierStart(ch, 6 /* Latest */)) { while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7555,10 +8077,12 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); -/** Non-internal stuff goes here */ var ts; (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -7575,7 +8099,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7622,7 +8145,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -7631,7 +8153,9 @@ var ts; writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, - writeSymbol: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, getTextPos: function () { return str.length; }, getLine: function () { return 0; }, getColumn: function () { return 0; }, @@ -7657,22 +8181,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8288,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -7837,7 +8354,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 277 /* SourceFile */) { + while (node && node.kind !== 279 /* SourceFile */) { node = node.parent; } return node; @@ -7845,11 +8362,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 216 /* Block */: - case 244 /* CaseBlock */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return true; } return false; @@ -7983,7 +8500,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8001,12 +8518,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,35 +8558,37 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) || + ts.isBigIntLiteral(node))) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (node.singleQuote) { return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; } else { return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; } - case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return "`" + escapeText(node.text, 96 /* backtick */) + "`"; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: // tslint:disable-next-line no-invalid-template-strings return "`" + escapeText(node.text, 96 /* backtick */) + "${"; - case 15 /* TemplateMiddle */: + case 16 /* TemplateMiddle */: // tslint:disable-next-line no-invalid-template-strings return "}" + escapeText(node.text, 96 /* backtick */) + "${"; - case 16 /* TemplateTail */: + case 17 /* TemplateTail */: return "}" + escapeText(node.text, 96 /* backtick */) + "`"; case 8 /* NumericLiteral */: - case 12 /* RegularExpressionLiteral */: + case 9 /* BigIntLiteral */: + case 13 /* RegularExpressionLiteral */: return node.text; } return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -8084,15 +8611,15 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 235 /* VariableDeclaration */ && node.parent.kind === 272 /* CatchClause */; + return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { - return ts.isModuleDeclaration(node) && node.name.kind === 9 /* StringLiteral */; + return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */; } ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { @@ -8116,11 +8643,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 242 /* ModuleDeclaration */ && (!node.body); + return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 277 /* SourceFile */ || - node.kind === 242 /* ModuleDeclaration */ || + return node.kind === 279 /* SourceFile */ || + node.kind === 244 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -8137,9 +8664,9 @@ var ts; // - 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 switch (node.parent.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.isExternalModule(node.parent); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; @@ -8155,22 +8682,22 @@ var ts; ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 277 /* SourceFile */: - case 244 /* CaseBlock */: - case 272 /* CatchClause */: - case 242 /* ModuleDeclaration */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 274 /* CatchClause */: + case 244 /* ModuleDeclaration */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; - case 216 /* Block */: + case 218 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -8180,9 +8707,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: - case 291 /* JSDocSignature */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 293 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -8192,25 +8719,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 287 /* JSDocFunctionType */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; default: ts.assertType(node); @@ -8220,8 +8747,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: return true; default: return false; @@ -8230,15 +8757,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 217 /* VariableStatement */: - case 238 /* ClassDeclaration */: - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 219 /* VariableStatement */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: return true; default: return false; @@ -8268,12 +8795,13 @@ var ts; ts.getNameFromIndexInfo = getNameFromIndexInfo; function getTextOfPropertyName(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return name.escapedText; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: return ts.Debug.assertNever(name); @@ -8282,11 +8810,11 @@ var ts; ts.getTextOfPropertyName = getTextOfPropertyName; function entityNameToString(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); default: throw ts.Debug.assertNever(name); @@ -8331,7 +8859,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 216 /* Block */) { + if (node.body && node.body.kind === 218 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -8345,7 +8873,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* 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 @@ -8354,25 +8882,25 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 240 /* TypeAliasDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: errorNode = node.name; break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -8408,6 +8936,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8417,11 +8949,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 189 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; + return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 189 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { @@ -8429,20 +8961,20 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 219 /* ExpressionStatement */ - && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 221 /* ExpressionStatement */ + && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return node.kind !== 10 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 149 /* Parameter */ || - node.kind === 148 /* TypeParameter */ || - node.kind === 194 /* FunctionExpression */ || - node.kind === 195 /* ArrowFunction */ || - node.kind === 193 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 151 /* Parameter */ || + node.kind === 150 /* TypeParameter */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 197 /* ArrowFunction */ || + node.kind === 195 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -8458,46 +8990,48 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 181 /* LastTypeNode */) { + if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) { return true; } switch (node.kind) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 134 /* NumberKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 140 /* UndefinedKeyword */: - case 131 /* NeverKeyword */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: return true; - case 105 /* VoidKeyword */: - return node.parent.kind !== 198 /* VoidExpression */; - case 209 /* ExpressionWithTypeArguments */: + case 106 /* VoidKeyword */: + return node.parent.kind !== 200 /* VoidExpression */; + case 211 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 148 /* TypeParameter */: - return node.parent.kind === 179 /* MappedType */ || node.parent.kind === 174 /* InferType */; + case 150 /* TypeParameter */: + return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container - case 71 /* Identifier */: + case 72 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 189 /* 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 === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 187 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 146 /* QualifiedName */: - case 187 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: { + case 148 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + case 100 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 165 /* TypeQuery */) { + if (parent.kind === 167 /* TypeQuery */) { return false; } - if (parent.kind === 181 /* ImportType */) { + if (parent.kind === 183 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -8506,40 +9040,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 181 /* LastTypeNode */) { + if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return node === parent.constraint; - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return node === parent.constraint; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 149 /* Parameter */: - case 235 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: return node === parent.type; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return node === parent.type; - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return node === parent.type; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return node === parent.type; - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -8564,23 +9098,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitor(node); - case 244 /* CaseBlock */: - case 216 /* Block */: - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 229 /* WithStatement */: - case 230 /* SwitchStatement */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 231 /* LabeledStatement */: - case 233 /* TryStatement */: - case 272 /* CatchClause */: + case 246 /* CaseBlock */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -8590,26 +9124,26 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 241 /* EnumDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* 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. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 147 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 149 /* 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(node.name.expression); @@ -8632,10 +9166,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 167 /* ArrayType */) { + if (node && node.kind === 169 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 162 /* TypeReference */) { + else if (node && node.kind === 164 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -8645,12 +9179,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 166 /* TypeLiteral */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 168 /* TypeLiteral */: return node.members; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return node.properties; } } @@ -8658,14 +9192,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 184 /* BindingElement */: - case 276 /* EnumMember */: - case 149 /* Parameter */: - case 273 /* PropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 274 /* ShorthandPropertyAssignment */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 278 /* EnumMember */: + case 151 /* Parameter */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 276 /* ShorthandPropertyAssignment */: + case 237 /* VariableDeclaration */: return true; } } @@ -8677,8 +9211,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 236 /* VariableDeclarationList */ - && node.parent.parent.kind === 217 /* VariableStatement */; + return node.parent.kind === 238 /* VariableDeclarationList */ + && node.parent.parent.kind === 219 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -8689,13 +9223,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return true; } return false; @@ -8706,7 +9240,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 231 /* LabeledStatement */) { + if (node.statement.kind !== 233 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -8714,17 +9248,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 216 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 186 /* ObjectLiteralExpression */; + return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 154 /* MethodDeclaration */ && - (node.parent.kind === 186 /* ObjectLiteralExpression */ || - node.parent.kind === 207 /* ClassExpression */); + return node.kind === 156 /* MethodDeclaration */ && + (node.parent.kind === 188 /* ObjectLiteralExpression */ || + node.parent.kind === 209 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -8737,7 +9271,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 273 /* PropertyAssignment */) { + if (property.kind === 275 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -8774,14 +9308,14 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 277 /* SourceFile */); + ts.Debug.assert(node.kind !== 279 /* SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* 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 @@ -8796,9 +9330,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8809,26 +9343,26 @@ var ts; node = node.parent; } break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 242 /* ModuleDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 241 /* EnumDeclaration */: - case 277 /* SourceFile */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 244 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 243 /* EnumDeclaration */: + case 279 /* SourceFile */: return node; } } @@ -8838,9 +9372,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return container; } } @@ -8862,27 +9396,27 @@ var ts; return node; } switch (node.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: node = node.parent; break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return node; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8898,14 +9432,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 194 /* FunctionExpression */ || func.kind === 195 /* ArrowFunction */) { + if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 193 /* ParenthesizedExpression */) { + while (parent.kind === 195 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 189 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -8916,8 +9450,8 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) - && node.expression.kind === 97 /* SuperKeyword */; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 98 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; /** @@ -8925,20 +9459,20 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) - && node.expression.kind === 99 /* ThisKeyword */; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 100 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; - case 71 /* Identifier */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 148 /* QualifiedName */: return node; } return undefined; @@ -8946,10 +9480,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return node.tag; - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -8958,25 +9492,25 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: // classes are valid targets return true; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 238 /* ClassDeclaration */; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: + return parent.kind === 240 /* ClassDeclaration */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 238 /* ClassDeclaration */; - case 149 /* Parameter */: + && parent.kind === 240 /* ClassDeclaration */; + case 151 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 155 /* Constructor */ - || parent.kind === 154 /* MethodDeclaration */ - || parent.kind === 157 /* SetAccessor */) - && grandparent.kind === 238 /* ClassDeclaration */; + && (parent.kind === 157 /* Constructor */ + || parent.kind === 156 /* MethodDeclaration */ + || parent.kind === 159 /* SetAccessor */) + && grandparent.kind === 240 /* ClassDeclaration */; } return false; } @@ -8992,10 +9526,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 154 /* MethodDeclaration */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 159 /* SetAccessor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -9004,9 +9538,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 260 /* JsxOpeningElement */ || - parent.kind === 259 /* JsxSelfClosingElement */ || - parent.kind === 261 /* JsxClosingElement */) { + if (parent.kind === 262 /* JsxOpeningElement */ || + parent.kind === 261 /* JsxSelfClosingElement */ || + parent.kind === 263 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -9014,56 +9548,57 @@ var ts; ts.isJSXTagName = isJSXTagName; function isExpressionNode(node) { switch (node.kind) { - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 12 /* RegularExpressionLiteral */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 191 /* TaggedTemplateExpression */: - case 210 /* AsExpression */: - case 192 /* TypeAssertionExpression */: - case 211 /* NonNullExpression */: - case 193 /* ParenthesizedExpression */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: - case 195 /* ArrowFunction */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: - case 202 /* BinaryExpression */: - case 203 /* ConditionalExpression */: - case 206 /* SpreadElement */: - case 204 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 208 /* OmittedExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 205 /* YieldExpression */: - case 199 /* AwaitExpression */: - case 212 /* MetaProperty */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 13 /* RegularExpressionLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 212 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 208 /* SpreadElement */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 210 /* OmittedExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 207 /* YieldExpression */: + case 201 /* AwaitExpression */: + case 214 /* MetaProperty */: return true; - case 146 /* QualifiedName */: - while (node.parent.kind === 146 /* QualifiedName */) { + case 148 /* QualifiedName */: + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node); - case 71 /* Identifier */: - if (node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node)) { + return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node); + case 72 /* Identifier */: + if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 99 /* ThisKeyword */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: return isInExpressionContext(node); default: return false; @@ -9073,49 +9608,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 276 /* EnumMember */: - case 273 /* PropertyAssignment */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 186 /* BindingElement */: return parent.initializer === node; - case 219 /* ExpressionStatement */: - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 228 /* ReturnStatement */: - case 229 /* WithStatement */: - case 230 /* SwitchStatement */: - case 269 /* CaseClause */: - case 232 /* ThrowStatement */: + case 221 /* ExpressionStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 230 /* ReturnStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 234 /* ThrowStatement */: return parent.expression === node; - case 223 /* ForStatement */: + case 225 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 236 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 236 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) || forInStatement.expression === node; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return node === parent.expression; - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return node === parent.expression; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return node === parent.expression; - case 150 /* Decorator */: - case 268 /* JsxExpression */: - case 267 /* JsxSpreadAttribute */: - case 275 /* SpreadAssignment */: + case 152 /* Decorator */: + case 270 /* JsxExpression */: + case 269 /* JsxSpreadAttribute */: + case 277 /* SpreadAssignment */: return true; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -9123,7 +9658,7 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */; + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -9132,21 +9667,21 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9160,15 +9695,15 @@ var ts; ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && - (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */); + (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { - if (callExpression.kind !== 189 /* CallExpression */) { + if (callExpression.kind !== 191 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 /* Identifier */ || expression.escapedText !== "require") { + if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") { return false; } if (args.length !== 1) { @@ -9186,29 +9721,29 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; decl = node.parent; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.right === node) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) { name = node.parent.left; decl = name; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54 /* BarBarToken */) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) { if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { name = node.parent.parent.name; decl = node.parent.parent; } - else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.parent.right === node.parent) { + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) { name = node.parent.parent.left; decl = name; } @@ -9216,42 +9751,55 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && - ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; } return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { - if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,47 +9808,47 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 194 /* FunctionExpression */ || - initializer.kind === 207 /* ClassExpression */ || - initializer.kind === 195 /* ArrowFunction */) { + if (initializer.kind === 196 /* FunctionExpression */ || + initializer.kind === 209 /* ClassExpression */ || + initializer.kind === 197 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : - ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { - var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; - if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) { return parent.left; } } @@ -9308,7 +9856,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9323,7 +9871,7 @@ var ts; return name.escapedText === initializer.escapedText; } if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { - return (initializer.expression.kind === 99 /* ThisKeyword */ || + return (initializer.expression.kind === 100 /* ThisKeyword */ || ts.isIdentifier(initializer.expression) && (initializer.expression.escapedText === "window" || initializer.expression.escapedText === "self" || @@ -9352,13 +9900,36 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { - if (expr.operatorToken.kind !== 58 /* EqualsToken */ || + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 59 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } @@ -9367,13 +9938,13 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { - if (lhs.expression.kind === 99 /* ThisKeyword */) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + else if (isModuleExportsPropertyAccessExpression(lhs)) { // module.exports = expr return 2 /* ModuleExports */; } @@ -9398,7 +9969,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,12 +9978,12 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && - expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; @@ -9421,7 +9992,7 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { @@ -9430,14 +10001,14 @@ var ts; ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return node.parent; - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return node.parent.parent; - case 189 /* CallExpression */: - return node.parent; - case 180 /* LiteralType */: + case 191 /* CallExpression */: + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; + case 182 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -9447,12 +10018,12 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return node.moduleSpecifier; - case 246 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 257 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 181 /* ImportType */: + case 248 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 183 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; default: return ts.Debug.assertNever(node); @@ -9461,11 +10032,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return undefined; default: return ts.Debug.assertNever(node); @@ -9473,19 +10044,19 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 247 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 149 /* Parameter */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 274 /* ShorthandPropertyAssignment */: - case 273 /* PropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 151 /* Parameter */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 276 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -9493,14 +10064,13 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 287 /* JSDocFunctionType */ && - node.parameters.length > 0 && - node.parameters[0].name && - node.parameters[0].name.escapedText === "new"; + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -9510,27 +10080,27 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 /* EqualsToken */ + node.expression.operatorToken.kind === 59 /* EqualsToken */ ? node.expression.right : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 /* BarBarToken */ + node.expression.right.operatorToken.kind === 55 /* BarBarToken */ ? node.expression.right.right : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return node.initializer; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return node.initializer; } } @@ -9540,7 +10110,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 242 /* ModuleDeclaration */ + node.body.kind === 244 /* ModuleDeclaration */ ? node.body : undefined; } @@ -9555,10 +10125,14 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.addRange(result, node.jsDoc); } - if (node.kind === 149 /* Parameter */) { + if (node.kind === 151 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 150 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9566,11 +10140,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 273 /* PropertyAssignment */ || - parent.kind === 152 /* PropertyDeclaration */ || - parent.kind === 219 /* ExpressionStatement */ && node.kind === 187 /* PropertyAccessExpression */ || + if (parent.kind === 275 /* PropertyAssignment */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ || getNestedModuleDeclaration(parent) || - ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */) { + ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) { return parent; } // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. @@ -9581,7 +10155,7 @@ var ts; // var x = function(name) { return name.length; } else if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node || - ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */)) { + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) { return parent.parent; } else if (parent.parent && parent.parent.parent && @@ -9604,7 +10178,7 @@ var ts; if (!decl) { return undefined; } - var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; @@ -9639,7 +10213,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 288 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9652,31 +10226,31 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? - binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; - return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 193 /* ParenthesizedExpression */: - case 185 /* ArrayLiteralExpression */: - case 206 /* SpreadElement */: - case 211 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 187 /* ArrayLiteralExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: node = parent; break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -9703,22 +10277,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 216 /* Block */: - case 217 /* VariableStatement */: - case 229 /* WithStatement */: - case 220 /* IfStatement */: - case 230 /* SwitchStatement */: - case 244 /* CaseBlock */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 231 /* LabeledStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 233 /* TryStatement */: - case 272 /* CatchClause */: + case 218 /* Block */: + case 219 /* VariableStatement */: + case 231 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: return true; } return false; @@ -9735,27 +10309,33 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 175 /* ParenthesizedType */); + return walkUp(node, 177 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 193 /* ParenthesizedExpression */); + return walkUp(node, 195 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function skipParentheses(node) { - while (node.kind === 193 /* ParenthesizedExpression */) { + while (node.kind === 195 /* ParenthesizedExpression */) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { + if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 196 /* DeleteExpression */; + return node && node.kind === 198 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -9773,35 +10353,39 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 72 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { - return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 147 /* ComputedPropertyName */ && + return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 149 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -9809,32 +10393,32 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 276 /* EnumMember */: - case 273 /* PropertyAssignment */: - case 187 /* PropertyAccessExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 189 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: // Name on right hand side of dot in a type query or type reference if (parent.right === node) { - while (parent.kind === 146 /* QualifiedName */) { + while (parent.kind === 148 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 165 /* TypeQuery */ || parent.kind === 162 /* TypeReference */; + return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */; } return false; - case 184 /* BindingElement */: - case 251 /* ImportSpecifier */: + case 186 /* BindingElement */: + case 253 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 255 /* ExportSpecifier */: - case 265 /* JsxAttribute */: + case 257 /* ExportSpecifier */: + case 267 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -9849,15 +10433,16 @@ var ts; // export { x as } from ... // export = // export default + // module.exports = function isAliasSymbolDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ || - node.kind === 245 /* NamespaceExportDeclaration */ || - node.kind === 248 /* ImportClause */ && !!node.name || - node.kind === 249 /* NamespaceImport */ || - node.kind === 251 /* ImportSpecifier */ || - node.kind === 255 /* ExportSpecifier */ || - node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + return node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + node.kind === 250 /* ImportClause */ && !!node.name || + node.kind === 251 /* NamespaceImport */ || + node.kind === 253 /* ImportSpecifier */ || + node.kind === 257 /* ExportSpecifier */ || + node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10451,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -9877,12 +10462,12 @@ var ts; } ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; function getClassExtendsHeritageElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; @@ -9894,7 +10479,7 @@ var ts; } ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -9928,11 +10513,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 72 /* FirstKeyword */ <= token && token <= 145 /* LastKeyword */; + return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 117 /* FirstContextualKeyword */ <= token && token <= 145 /* LastContextualKeyword */; + return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -9944,6 +10529,11 @@ var ts; return token !== undefined && isNonContextualKeyword(token); } ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; function isTrivia(token) { return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; } @@ -9962,14 +10552,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (hasModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -9983,10 +10573,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256 /* Async */); @@ -10011,7 +10601,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 147 /* ComputedPropertyName */ && + return name.kind === 149 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -10027,12 +10617,12 @@ var ts; ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return name.escapedText; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); @@ -10048,9 +10638,9 @@ var ts; ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: return true; default: @@ -10059,11 +10649,11 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? ts.idText(node) : node.text; + return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -10078,7 +10668,7 @@ var ts; * Includes the word "Symbol" with unicode escapes */ function isESSymbolIdentifier(node) { - return node.kind === 71 /* Identifier */ && node.escapedText === "Symbol"; + return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { @@ -10087,11 +10677,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 149 /* Parameter */; + return root.kind === 151 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 184 /* BindingElement */) { + while (node.kind === 186 /* BindingElement */) { node = node.parent.parent; } return node; @@ -10099,15 +10689,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 155 /* Constructor */ - || kind === 194 /* FunctionExpression */ - || kind === 237 /* FunctionDeclaration */ - || kind === 195 /* ArrowFunction */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 242 /* ModuleDeclaration */ - || kind === 277 /* SourceFile */; + return kind === 157 /* Constructor */ + || kind === 196 /* FunctionExpression */ + || kind === 239 /* FunctionDeclaration */ + || kind === 197 /* ArrowFunction */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 244 /* ModuleDeclaration */ + || kind === 279 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -10126,38 +10716,38 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 190 /* NewExpression */: + case 192 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 200 /* PrefixUnaryExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 199 /* AwaitExpression */: - case 203 /* ConditionalExpression */: - case 205 /* YieldExpression */: + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: return 1 /* Right */; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (operator) { - case 40 /* AsteriskAsteriskToken */: - case 58 /* EqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 69 /* BarEqualsToken */: + case 41 /* AsteriskAsteriskToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: return 1 /* Right */; } } @@ -10166,15 +10756,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 202 /* BinaryExpression */) { + if (expression.kind === 204 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 200 /* PrefixUnaryExpression */ || expression.kind === 201 /* PostfixUnaryExpression */) { + else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -10184,116 +10774,116 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return 0; - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return 1; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return 2; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return 4; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (operatorKind) { - case 26 /* CommaToken */: + case 27 /* CommaToken */: return 0; - case 58 /* EqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 69 /* BarEqualsToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: return 3; default: return getBinaryOperatorPrecedence(operatorKind); } - case 200 /* PrefixUnaryExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 199 /* AwaitExpression */: + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: return 16; - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return 17; - case 189 /* CallExpression */: + case 191 /* CallExpression */: return 18; - case 190 /* NewExpression */: + case 192 /* NewExpression */: return hasArguments ? 19 : 18; - case 191 /* TaggedTemplateExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 193 /* TaggedTemplateExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return 19; - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 71 /* Identifier */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 72 /* Identifier */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 207 /* ClassExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 193 /* ParenthesizedExpression */: - case 208 /* OmittedExpression */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 195 /* ParenthesizedExpression */: + case 210 /* OmittedExpression */: return 20; default: return -1; } } ts.getOperatorPrecedence = getOperatorPrecedence; - /* @internal */ function getBinaryOperatorPrecedence(kind) { switch (kind) { - case 54 /* BarBarToken */: + case 55 /* BarBarToken */: return 5; - case 53 /* AmpersandAmpersandToken */: + case 54 /* AmpersandAmpersandToken */: return 6; - case 49 /* BarToken */: + case 50 /* BarToken */: return 7; - case 50 /* CaretToken */: + case 51 /* CaretToken */: return 8; - case 48 /* AmpersandToken */: + case 49 /* AmpersandToken */: return 9; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: return 10; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: return 11; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return 12; - case 37 /* PlusToken */: - case 38 /* MinusToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: return 13; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: return 14; - case 40 /* AsteriskAsteriskToken */: + case 41 /* AsteriskAsteriskToken */: return 15; } // -1 is lower than all other precedences. Returning it will cause binary expression @@ -10361,7 +10951,7 @@ var ts; if (fileName) { return fileDiagnostics.get(fileName) || []; } - var fileDiags = ts.flatMap(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); if (!nonFileDiagnostics.length) { return fileDiags; } @@ -10419,7 +11009,7 @@ var ts; } function isIntrinsicJsxName(name) { var ch = name.charCodeAt(0); - return (ch >= 97 /* a */ && ch <= 122 /* z */) || name.indexOf("-") > -1; + return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-"); } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -10502,16 +11092,10 @@ var ts; lineStart = true; } } - function writeTextOfNode(text, node) { - var s = getTextOfNodeFromSourceText(text, node); - write(s); - updateLineCountAndPosFor(s); - } reset(); return { write: write, rawWrite: rawWrite, - writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, increaseIndent: function () { indent++; }, @@ -10534,10 +11118,77 @@ var ts; writePunctuation: write, writeSpace: write, writeStringLiteral: write, - writeSymbol: write + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write }; } ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; function getResolvedExternalModuleName(host, file, referenceFile) { return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } @@ -10600,7 +11251,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10614,7 +11265,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10673,11 +11324,11 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { - return id.originalKeywordKind === 99 /* ThisKeyword */; + return id.originalKeywordKind === 100 /* ThisKeyword */; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { @@ -10688,10 +11339,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 156 /* GetAccessor */) { + if (accessor.kind === 158 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 157 /* SetAccessor */) { + else if (accessor.kind === 159 /* SetAccessor */) { setAccessor = accessor; } else { @@ -10711,10 +11362,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 156 /* GetAccessor */ && !getAccessor) { + if (member.kind === 158 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 157 /* SetAccessor */ && !setAccessor) { + if (member.kind === 159 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -10735,7 +11386,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11402,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -10760,7 +11411,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 289 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -10794,13 +11445,13 @@ var ts; function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { if (comments && comments.length > 0) { if (leadingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } var emitInterveningSeparator = false; for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { var comment = comments_1[_i]; if (emitInterveningSeparator) { - writer.write(" "); + writer.writeSpace(" "); emitInterveningSeparator = false; } writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); @@ -10812,7 +11463,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -10930,7 +11581,7 @@ var ts; } else { // Single line comment of style //.... - writer.write(text.substring(commentPos, commentEnd)); + writer.writeComment(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; @@ -10939,14 +11590,14 @@ var ts; var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { // trimmed forward and ending spaces text - writer.write(currentLineText); + writer.writeComment(currentLineText); if (end !== commentEnd) { writer.writeLine(); } } else { // Empty string - make sure we write empty line - writer.writeLiteral(newLine); + writer.rawWrite(newLine); } } function calculateIndent(text, pos, end) { @@ -11000,7 +11651,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4 /* NestedNamespace */ || (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace)) { + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* Export */; } return flags; @@ -11008,44 +11659,49 @@ var ts; ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { - case 115 /* StaticKeyword */: return 32 /* Static */; - case 114 /* PublicKeyword */: return 4 /* Public */; - case 113 /* ProtectedKeyword */: return 16 /* Protected */; - case 112 /* PrivateKeyword */: return 8 /* Private */; - case 117 /* AbstractKeyword */: return 128 /* Abstract */; - case 84 /* ExportKeyword */: return 1 /* Export */; - case 124 /* DeclareKeyword */: return 2 /* Ambient */; - case 76 /* ConstKeyword */: return 2048 /* Const */; - case 79 /* DefaultKeyword */: return 512 /* Default */; - case 120 /* AsyncKeyword */: return 256 /* Async */; - case 132 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 116 /* StaticKeyword */: return 32 /* Static */; + case 115 /* PublicKeyword */: return 4 /* Public */; + case 114 /* ProtectedKeyword */: return 16 /* Protected */; + case 113 /* PrivateKeyword */: return 8 /* Private */; + case 118 /* AbstractKeyword */: return 128 /* Abstract */; + case 85 /* ExportKeyword */: return 1 /* Export */; + case 125 /* DeclareKeyword */: return 2 /* Ambient */; + case 77 /* ConstKeyword */: return 2048 /* Const */; + case 80 /* DefaultKeyword */: return 512 /* Default */; + case 121 /* AsyncKeyword */: return 256 /* Async */; + case 133 /* ReadonlyKeyword */: return 64 /* Readonly */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 54 /* BarBarToken */ - || token === 53 /* AmpersandAmpersandToken */ - || token === 51 /* ExclamationToken */; + return token === 55 /* BarBarToken */ + || token === 54 /* AmpersandAmpersandToken */ + || token === 52 /* ExclamationToken */; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 58 /* FirstAssignment */ && token <= 70 /* LastAssignment */; + return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment - ? node.operatorToken.kind === 58 /* EqualsToken */ + ? node.operatorToken.kind === 59 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) && ts.isLeftHandSideExpression(node.left); } @@ -11053,8 +11709,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 186 /* ObjectLiteralExpression */ - || kind === 185 /* ArrayLiteralExpression */; + return kind === 188 /* ObjectLiteralExpression */ + || kind === 187 /* ArrayLiteralExpression */; } return false; } @@ -11063,17 +11719,8 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; function isPropertyAccessEntityNameExpression(node) { @@ -11085,17 +11732,17 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 186 /* ObjectLiteralExpression */ && + return expression.kind === 188 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 185 /* ArrayLiteralExpression */ && + return expression.kind === 187 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -11107,10 +11754,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * 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. @@ -11249,6 +11896,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +12008,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11436,8 +12107,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -11514,23 +12185,47 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 201 /* PostfixUnaryExpression */: - case 200 /* PrefixUnaryExpression */: + case 195 /* ParenthesizedExpression */: + return accessKind(parent); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: var operator = parent.operator; - return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 202 /* BinaryExpression */: + return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 204 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? - operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 275 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 187 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11621,7 +12316,7 @@ var ts; } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { - return type.flags & 131072 /* Object */ ? type.objectFlags : 0; + return type.flags & 524288 /* Object */ ? type.objectFlags : 0; } ts.getObjectFlags = getObjectFlags; function typeHasCallOrConstructSignatures(type, checker) { @@ -11672,6 +12367,31 @@ var ts; return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) + || kind === 120 /* AnyKeyword */ + || kind === 143 /* UnknownKeyword */ + || kind === 135 /* NumberKeyword */ + || kind === 146 /* BigIntKeyword */ + || kind === 136 /* ObjectKeyword */ + || kind === 123 /* BooleanKeyword */ + || kind === 138 /* StringKeyword */ + || kind === 139 /* SymbolKeyword */ + || kind === 100 /* ThisKeyword */ + || kind === 106 /* VoidKeyword */ + || kind === 141 /* UndefinedKeyword */ + || kind === 96 /* NullKeyword */ + || kind === 132 /* NeverKeyword */ + || kind === 211 /* ExpressionWithTypeArguments */ + || kind === 284 /* JSDocAllType */ + || kind === 285 /* JSDocUnknownType */ + || kind === 286 /* JSDocNullableType */ + || kind === 287 /* JSDocNonNullableType */ + || kind === 288 /* JSDocOptionalType */ + || kind === 289 /* JSDocFunctionType */ + || kind === 290 /* JSDocVariadicType */; + } + ts.isTypeNodeKind = isTypeNodeKind; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11756,13 +12476,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -11899,9 +12612,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 148 /* TypeParameter */) { + if (d && d.kind === 150 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 239 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) { return current; } } @@ -11909,7 +12622,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 155 /* Constructor */; + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11939,14 +12652,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 235 /* VariableDeclaration */) { + if (node.kind === 237 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 236 /* VariableDeclarationList */) { + if (node && node.kind === 238 /* VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 217 /* VariableStatement */) { + if (node && node.kind === 219 /* VariableStatement */) { flags |= getFlags(node); } return flags; @@ -12090,38 +12803,34 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; - case 219 /* ExpressionStatement */: + break; + case 221 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return expr.name; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; - case 193 /* ParenthesizedExpression */: { + break; + case 195 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 231 /* LabeledStatement */: { + case 233 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12140,31 +12849,36 @@ var ts; /** @internal */ function getNonAssignedNameOfDeclaration(declaration) { switch (declaration.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return declaration; - case 303 /* JSDocPropertyTag */: - case 297 /* JSDocParameterTag */: { + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 146 /* QualifiedName */) { + if (name.kind === 148 /* QualifiedName */) { return name.right; } break; } - case 202 /* BinaryExpression */: { + case 191 /* CallExpression */: + case 204 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: case 3 /* PrototypeProperty */: return expr.left.name; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr.arguments[1]; default: return undefined; } } - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 252 /* ExportAssignment */: { + case 254 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } @@ -12198,15 +12912,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12940,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12350,10 +13080,23 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -12371,684 +13114,688 @@ var ts; return node.kind === 8 /* NumericLiteral */; } ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9 /* BigIntLiteral */; + } + ts.isBigIntLiteral = isBigIntLiteral; function isStringLiteral(node) { - return node.kind === 9 /* StringLiteral */; + return node.kind === 10 /* StringLiteral */; } ts.isStringLiteral = isStringLiteral; function isJsxText(node) { - return node.kind === 10 /* JsxText */; + return node.kind === 11 /* JsxText */; } ts.isJsxText = isJsxText; function isRegularExpressionLiteral(node) { - return node.kind === 12 /* RegularExpressionLiteral */; + return node.kind === 13 /* RegularExpressionLiteral */; } ts.isRegularExpressionLiteral = isRegularExpressionLiteral; function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13 /* NoSubstitutionTemplateLiteral */; + return node.kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; // Pseudo-literals function isTemplateHead(node) { - return node.kind === 14 /* TemplateHead */; + return node.kind === 15 /* TemplateHead */; } ts.isTemplateHead = isTemplateHead; function isTemplateMiddle(node) { - return node.kind === 15 /* TemplateMiddle */; + return node.kind === 16 /* TemplateMiddle */; } ts.isTemplateMiddle = isTemplateMiddle; function isTemplateTail(node) { - return node.kind === 16 /* TemplateTail */; + return node.kind === 17 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; function isIdentifier(node) { - return node.kind === 71 /* Identifier */; + return node.kind === 72 /* Identifier */; } ts.isIdentifier = isIdentifier; // Names function isQualifiedName(node) { - return node.kind === 146 /* QualifiedName */; + return node.kind === 148 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 147 /* ComputedPropertyName */; + return node.kind === 149 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 148 /* TypeParameter */; + return node.kind === 150 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 149 /* Parameter */; + return node.kind === 151 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 150 /* Decorator */; + return node.kind === 152 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 151 /* PropertySignature */; + return node.kind === 153 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 152 /* PropertyDeclaration */; + return node.kind === 154 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 153 /* MethodSignature */; + return node.kind === 155 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 154 /* MethodDeclaration */; + return node.kind === 156 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 155 /* Constructor */; + return node.kind === 157 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 156 /* GetAccessor */; + return node.kind === 158 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 157 /* SetAccessor */; + return node.kind === 159 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 158 /* CallSignature */; + return node.kind === 160 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 159 /* ConstructSignature */; + return node.kind === 161 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 160 /* IndexSignature */; + return node.kind === 162 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 157 /* SetAccessor */ || node.kind === 156 /* GetAccessor */; + return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 161 /* TypePredicate */; + return node.kind === 163 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 162 /* TypeReference */; + return node.kind === 164 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 163 /* FunctionType */; + return node.kind === 165 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 164 /* ConstructorType */; + return node.kind === 166 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 165 /* TypeQuery */; + return node.kind === 167 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 166 /* TypeLiteral */; + return node.kind === 168 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 167 /* ArrayType */; + return node.kind === 169 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 168 /* TupleType */; + return node.kind === 170 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 171 /* UnionType */; + return node.kind === 173 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 172 /* IntersectionType */; + return node.kind === 174 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 173 /* ConditionalType */; + return node.kind === 175 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 174 /* InferType */; + return node.kind === 176 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 175 /* ParenthesizedType */; + return node.kind === 177 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 176 /* ThisType */; + return node.kind === 178 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 177 /* TypeOperator */; + return node.kind === 179 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 178 /* IndexedAccessType */; + return node.kind === 180 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 179 /* MappedType */; + return node.kind === 181 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 180 /* LiteralType */; + return node.kind === 182 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 181 /* ImportType */; + return node.kind === 183 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 182 /* ObjectBindingPattern */; + return node.kind === 184 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 183 /* ArrayBindingPattern */; + return node.kind === 185 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 184 /* BindingElement */; + return node.kind === 186 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 185 /* ArrayLiteralExpression */; + return node.kind === 187 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 186 /* ObjectLiteralExpression */; + return node.kind === 188 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 187 /* PropertyAccessExpression */; + return node.kind === 189 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 188 /* ElementAccessExpression */; + return node.kind === 190 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 189 /* CallExpression */; + return node.kind === 191 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 190 /* NewExpression */; + return node.kind === 192 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 191 /* TaggedTemplateExpression */; + return node.kind === 193 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 192 /* TypeAssertionExpression */; + return node.kind === 194 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 193 /* ParenthesizedExpression */; + return node.kind === 195 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 306 /* PartiallyEmittedExpression */) { + while (node.kind === 308 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 194 /* FunctionExpression */; + return node.kind === 196 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 195 /* ArrowFunction */; + return node.kind === 197 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 196 /* DeleteExpression */; + return node.kind === 198 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 197 /* TypeOfExpression */; + return node.kind === 199 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 198 /* VoidExpression */; + return node.kind === 200 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 199 /* AwaitExpression */; + return node.kind === 201 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 200 /* PrefixUnaryExpression */; + return node.kind === 202 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 201 /* PostfixUnaryExpression */; + return node.kind === 203 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 202 /* BinaryExpression */; + return node.kind === 204 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 203 /* ConditionalExpression */; + return node.kind === 205 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 204 /* TemplateExpression */; + return node.kind === 206 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 205 /* YieldExpression */; + return node.kind === 207 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 206 /* SpreadElement */; + return node.kind === 208 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 207 /* ClassExpression */; + return node.kind === 209 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 208 /* OmittedExpression */; + return node.kind === 210 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */; + return node.kind === 211 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 210 /* AsExpression */; + return node.kind === 212 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 211 /* NonNullExpression */; + return node.kind === 213 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 212 /* MetaProperty */; + return node.kind === 214 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; // Misc function isTemplateSpan(node) { - return node.kind === 214 /* TemplateSpan */; + return node.kind === 216 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 215 /* SemicolonClassElement */; + return node.kind === 217 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Block function isBlock(node) { - return node.kind === 216 /* Block */; + return node.kind === 218 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 217 /* VariableStatement */; + return node.kind === 219 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 218 /* EmptyStatement */; + return node.kind === 220 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 219 /* ExpressionStatement */; + return node.kind === 221 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 220 /* IfStatement */; + return node.kind === 222 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 221 /* DoStatement */; + return node.kind === 223 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 222 /* WhileStatement */; + return node.kind === 224 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 223 /* ForStatement */; + return node.kind === 225 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 224 /* ForInStatement */; + return node.kind === 226 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 225 /* ForOfStatement */; + return node.kind === 227 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 226 /* ContinueStatement */; + return node.kind === 228 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 227 /* BreakStatement */; + return node.kind === 229 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isBreakOrContinueStatement(node) { - return node.kind === 227 /* BreakStatement */ || node.kind === 226 /* ContinueStatement */; + return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 228 /* ReturnStatement */; + return node.kind === 230 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 229 /* WithStatement */; + return node.kind === 231 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 230 /* SwitchStatement */; + return node.kind === 232 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 231 /* LabeledStatement */; + return node.kind === 233 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 232 /* ThrowStatement */; + return node.kind === 234 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 233 /* TryStatement */; + return node.kind === 235 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 234 /* DebuggerStatement */; + return node.kind === 236 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 235 /* VariableDeclaration */; + return node.kind === 237 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 236 /* VariableDeclarationList */; + return node.kind === 238 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 237 /* FunctionDeclaration */; + return node.kind === 239 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 238 /* ClassDeclaration */; + return node.kind === 240 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 239 /* InterfaceDeclaration */; + return node.kind === 241 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 240 /* TypeAliasDeclaration */; + return node.kind === 242 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 241 /* EnumDeclaration */; + return node.kind === 243 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */; + return node.kind === 244 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 243 /* ModuleBlock */; + return node.kind === 245 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 244 /* CaseBlock */; + return node.kind === 246 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 245 /* NamespaceExportDeclaration */; + return node.kind === 247 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */; + return node.kind === 248 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 247 /* ImportDeclaration */; + return node.kind === 249 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 248 /* ImportClause */; + return node.kind === 250 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 249 /* NamespaceImport */; + return node.kind === 251 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 250 /* NamedImports */; + return node.kind === 252 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 251 /* ImportSpecifier */; + return node.kind === 253 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 252 /* ExportAssignment */; + return node.kind === 254 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 253 /* ExportDeclaration */; + return node.kind === 255 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 254 /* NamedExports */; + return node.kind === 256 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 255 /* ExportSpecifier */; + return node.kind === 257 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 256 /* MissingDeclaration */; + return node.kind === 258 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; // Module References function isExternalModuleReference(node) { - return node.kind === 257 /* ExternalModuleReference */; + return node.kind === 259 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 258 /* JsxElement */; + return node.kind === 260 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 259 /* JsxSelfClosingElement */; + return node.kind === 261 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 260 /* JsxOpeningElement */; + return node.kind === 262 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 261 /* JsxClosingElement */; + return node.kind === 263 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 262 /* JsxFragment */; + return node.kind === 264 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 263 /* JsxOpeningFragment */; + return node.kind === 265 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 264 /* JsxClosingFragment */; + return node.kind === 266 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 265 /* JsxAttribute */; + return node.kind === 267 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 266 /* JsxAttributes */; + return node.kind === 268 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 267 /* JsxSpreadAttribute */; + return node.kind === 269 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 268 /* JsxExpression */; + return node.kind === 270 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 269 /* CaseClause */; + return node.kind === 271 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 270 /* DefaultClause */; + return node.kind === 272 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 271 /* HeritageClause */; + return node.kind === 273 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 272 /* CatchClause */; + return node.kind === 274 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 273 /* PropertyAssignment */; + return node.kind === 275 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 274 /* ShorthandPropertyAssignment */; + return node.kind === 276 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 275 /* SpreadAssignment */; + return node.kind === 277 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 276 /* EnumMember */; + return node.kind === 278 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 277 /* SourceFile */; + return node.kind === 279 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 278 /* Bundle */; + return node.kind === 280 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 279 /* UnparsedSource */; + return node.kind === 281 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 281 /* JSDocTypeExpression */; + return node.kind === 283 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 282 /* JSDocAllType */; + return node.kind === 284 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 283 /* JSDocUnknownType */; + return node.kind === 285 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 284 /* JSDocNullableType */; + return node.kind === 286 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 285 /* JSDocNonNullableType */; + return node.kind === 287 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 286 /* JSDocOptionalType */; + return node.kind === 288 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 287 /* JSDocFunctionType */; + return node.kind === 289 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 288 /* JSDocVariadicType */; + return node.kind === 290 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 289 /* JSDocComment */; + return node.kind === 291 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 293 /* JSDocAugmentsTag */; + return node.kind === 295 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 294 /* JSDocClassTag */; + return node.kind === 296 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocEnumTag(node) { - return node.kind === 296 /* JSDocEnumTag */; + return node.kind === 298 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 299 /* JSDocThisTag */; + return node.kind === 301 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 297 /* JSDocParameterTag */; + return node.kind === 299 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 298 /* JSDocReturnTag */; + return node.kind === 300 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 300 /* JSDocTypeTag */; + return node.kind === 302 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 301 /* JSDocTemplateTag */; + return node.kind === 303 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 302 /* JSDocTypedefTag */; + return node.kind === 304 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 303 /* JSDocPropertyTag */; + return node.kind === 305 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */; + return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 290 /* JSDocTypeLiteral */; + return node.kind === 292 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocCallbackTag(node) { - return node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 297 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocSignature(node) { - return node.kind === 291 /* JSDocSignature */; + return node.kind === 293 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); @@ -13059,7 +13806,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 304 /* SyntaxList */; + return n.kind === 306 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13069,7 +13816,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 146 /* FirstNode */; + return kind >= 148 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13078,7 +13825,7 @@ var ts; * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 145 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */; } ts.isToken = isToken; // Node Arrays @@ -13090,7 +13837,7 @@ var ts; // Literals /* @internal */ function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */; + return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */; } ts.isLiteralKind = isLiteralKind; function isLiteralExpression(node) { @@ -13100,7 +13847,7 @@ var ts; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { - return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; + return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isTemplateLiteralToken(node) { @@ -13109,12 +13856,16 @@ var ts; ts.isTemplateLiteralToken = isTemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node) { var kind = node.kind; - return kind === 15 /* TemplateMiddle */ - || kind === 16 /* TemplateTail */; + return kind === 16 /* TemplateMiddle */ + || kind === 17 /* TemplateTail */; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isStringTextContainingNode(node) { - return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -13127,17 +13878,17 @@ var ts; /* @internal */ function isModifierKind(token) { switch (token) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 79 /* DefaultKeyword */: - case 84 /* ExportKeyword */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 115 /* StaticKeyword */: + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 80 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 116 /* StaticKeyword */: return true; } return false; @@ -13150,7 +13901,7 @@ var ts; ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */; + return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -13159,23 +13910,23 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 146 /* QualifiedName */ - || kind === 71 /* Identifier */; + return kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 9 /* StringLiteral */ + return kind === 72 /* Identifier */ + || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 147 /* ComputedPropertyName */; + || kind === 149 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 182 /* ObjectBindingPattern */ - || kind === 183 /* ArrayBindingPattern */; + return kind === 72 /* Identifier */ + || kind === 184 /* ObjectBindingPattern */ + || kind === 185 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -13190,13 +13941,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; default: return false; @@ -13205,14 +13956,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 163 /* FunctionType */: - case 287 /* JSDocFunctionType */: - case 164 /* ConstructorType */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 166 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -13227,29 +13978,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 155 /* Constructor */ - || kind === 152 /* PropertyDeclaration */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 160 /* IndexSignature */ - || kind === 215 /* SemicolonClassElement */; + return kind === 157 /* Constructor */ + || kind === 154 /* PropertyDeclaration */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 162 /* IndexSignature */ + || kind === 217 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */); + return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */); + return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return true; default: return false; @@ -13259,11 +14010,11 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 159 /* ConstructSignature */ - || kind === 158 /* CallSignature */ - || kind === 151 /* PropertySignature */ - || kind === 153 /* MethodSignature */ - || kind === 160 /* IndexSignature */; + return kind === 161 /* ConstructSignature */ + || kind === 160 /* CallSignature */ + || kind === 153 /* PropertySignature */ + || kind === 155 /* MethodSignature */ + || kind === 162 /* IndexSignature */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -13272,51 +14023,28 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 273 /* PropertyAssignment */ - || kind === 274 /* ShorthandPropertyAssignment */ - || kind === 275 /* SpreadAssignment */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 275 /* PropertyAssignment */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 277 /* SpreadAssignment */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type - function isTypeNodeKind(kind) { - return (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) - || kind === 119 /* AnyKeyword */ - || kind === 142 /* UnknownKeyword */ - || kind === 134 /* NumberKeyword */ - || kind === 135 /* ObjectKeyword */ - || kind === 122 /* BooleanKeyword */ - || kind === 137 /* StringKeyword */ - || kind === 138 /* SymbolKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 105 /* VoidKeyword */ - || kind === 140 /* UndefinedKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 131 /* NeverKeyword */ - || kind === 209 /* ExpressionWithTypeArguments */ - || kind === 282 /* JSDocAllType */ - || kind === 283 /* JSDocUnknownType */ - || kind === 284 /* JSDocNullableType */ - || kind === 285 /* JSDocNonNullableType */ - || kind === 286 /* JSDocOptionalType */ - || kind === 287 /* JSDocFunctionType */ - || kind === 288 /* JSDocVariadicType */; - } /** * Node test that determines whether a node is a valid type node. * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* * of a TypeNode. */ function isTypeNode(node) { - return isTypeNodeKind(node.kind); + return ts.isTypeNodeKind(node.kind); } ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return true; } return false; @@ -13327,8 +14055,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 183 /* ArrayBindingPattern */ - || kind === 182 /* ObjectBindingPattern */; + return kind === 185 /* ArrayBindingPattern */ + || kind === 184 /* ObjectBindingPattern */; } return false; } @@ -13336,15 +14064,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 185 /* ArrayLiteralExpression */ - || kind === 186 /* ObjectLiteralExpression */; + return kind === 187 /* ArrayLiteralExpression */ + || kind === 188 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 184 /* BindingElement */ - || kind === 208 /* OmittedExpression */; + return kind === 186 /* BindingElement */ + || kind === 210 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -13353,9 +14081,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: return true; } return false; @@ -13376,8 +14104,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 182 /* ObjectBindingPattern */: - case 186 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: return true; } return false; @@ -13389,8 +14117,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: return true; } return false; @@ -13399,26 +14127,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 187 /* PropertyAccessExpression */ - || kind === 146 /* QualifiedName */ - || kind === 181 /* ImportType */; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */ + || kind === 183 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 187 /* PropertyAccessExpression */ - || kind === 146 /* QualifiedName */; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 191 /* TaggedTemplateExpression */: - case 150 /* Decorator */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 152 /* Decorator */: return true; default: return false; @@ -13426,13 +14154,13 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 189 /* CallExpression */ || node.kind === 190 /* NewExpression */; + return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 204 /* TemplateExpression */ - || kind === 13 /* NoSubstitutionTemplateLiteral */; + return kind === 206 /* TemplateExpression */ + || kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; /* @internal */ @@ -13442,33 +14170,34 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - case 190 /* NewExpression */: - case 189 /* CallExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 191 /* TaggedTemplateExpression */: - case 185 /* ArrayLiteralExpression */: - case 193 /* ParenthesizedExpression */: - case 186 /* ObjectLiteralExpression */: - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: - case 71 /* Identifier */: - case 12 /* RegularExpressionLiteral */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 192 /* NewExpression */: + case 191 /* CallExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 193 /* TaggedTemplateExpression */: + case 187 /* ArrayLiteralExpression */: + case 195 /* ParenthesizedExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 72 /* Identifier */: + case 13 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 101 /* TrueKeyword */: - case 97 /* SuperKeyword */: - case 211 /* NonNullExpression */: - case 212 /* MetaProperty */: - case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 102 /* TrueKeyword */: + case 98 /* SuperKeyword */: + case 213 /* NonNullExpression */: + case 214 /* MetaProperty */: + case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: return false; @@ -13481,13 +14210,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 199 /* AwaitExpression */: - case 192 /* TypeAssertionExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 194 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13496,11 +14225,11 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return true; - case 200 /* PrefixUnaryExpression */: - return expr.operator === 43 /* PlusPlusToken */ || - expr.operator === 44 /* MinusMinusToken */; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 44 /* PlusPlusToken */ || + expr.operator === 45 /* MinusMinusToken */; default: return false; } @@ -13517,15 +14246,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 203 /* ConditionalExpression */: - case 205 /* YieldExpression */: - case 195 /* ArrowFunction */: - case 202 /* BinaryExpression */: - case 206 /* SpreadElement */: - case 210 /* AsExpression */: - case 208 /* OmittedExpression */: - case 307 /* CommaListExpression */: - case 306 /* PartiallyEmittedExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + case 197 /* ArrowFunction */: + case 204 /* BinaryExpression */: + case 208 /* SpreadElement */: + case 212 /* AsExpression */: + case 210 /* OmittedExpression */: + case 309 /* CommaListExpression */: + case 308 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13533,18 +14262,18 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 192 /* TypeAssertionExpression */ - || kind === 210 /* AsExpression */; + return kind === 194 /* TypeAssertionExpression */ + || kind === 212 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 306 /* PartiallyEmittedExpression */; + return node.kind === 308 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 305 /* NotEmittedStatement */; + return node.kind === 307 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13555,13 +14284,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return true; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13569,7 +14298,7 @@ var ts; ts.isIterationStatement = isIterationStatement; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 224 /* ForInStatement */ || node.kind === 225 /* ForOfStatement */; + return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13593,113 +14322,113 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 243 /* ModuleBlock */ - || kind === 242 /* ModuleDeclaration */ - || kind === 71 /* Identifier */; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */ + || kind === 72 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 243 /* ModuleBlock */ - || kind === 242 /* ModuleDeclaration */; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 242 /* ModuleDeclaration */; + return kind === 72 /* Identifier */ + || kind === 244 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 250 /* NamedImports */ - || kind === 249 /* NamespaceImport */; + return kind === 252 /* NamedImports */ + || kind === 251 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */ || node.kind === 241 /* EnumDeclaration */; + return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 195 /* ArrowFunction */ - || kind === 184 /* BindingElement */ - || kind === 238 /* ClassDeclaration */ - || kind === 207 /* ClassExpression */ - || kind === 155 /* Constructor */ - || kind === 241 /* EnumDeclaration */ - || kind === 276 /* EnumMember */ - || kind === 255 /* ExportSpecifier */ - || kind === 237 /* FunctionDeclaration */ - || kind === 194 /* FunctionExpression */ - || kind === 156 /* GetAccessor */ - || kind === 248 /* ImportClause */ - || kind === 246 /* ImportEqualsDeclaration */ - || kind === 251 /* ImportSpecifier */ - || kind === 239 /* InterfaceDeclaration */ - || kind === 265 /* JsxAttribute */ - || kind === 154 /* MethodDeclaration */ - || kind === 153 /* MethodSignature */ - || kind === 242 /* ModuleDeclaration */ - || kind === 245 /* NamespaceExportDeclaration */ - || kind === 249 /* NamespaceImport */ - || kind === 149 /* Parameter */ - || kind === 273 /* PropertyAssignment */ - || kind === 152 /* PropertyDeclaration */ - || kind === 151 /* PropertySignature */ - || kind === 157 /* SetAccessor */ - || kind === 274 /* ShorthandPropertyAssignment */ - || kind === 240 /* TypeAliasDeclaration */ - || kind === 148 /* TypeParameter */ - || kind === 235 /* VariableDeclaration */ - || kind === 302 /* JSDocTypedefTag */ - || kind === 295 /* JSDocCallbackTag */ - || kind === 303 /* JSDocPropertyTag */; + return kind === 197 /* ArrowFunction */ + || kind === 186 /* BindingElement */ + || kind === 240 /* ClassDeclaration */ + || kind === 209 /* ClassExpression */ + || kind === 157 /* Constructor */ + || kind === 243 /* EnumDeclaration */ + || kind === 278 /* EnumMember */ + || kind === 257 /* ExportSpecifier */ + || kind === 239 /* FunctionDeclaration */ + || kind === 196 /* FunctionExpression */ + || kind === 158 /* GetAccessor */ + || kind === 250 /* ImportClause */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 253 /* ImportSpecifier */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 267 /* JsxAttribute */ + || kind === 156 /* MethodDeclaration */ + || kind === 155 /* MethodSignature */ + || kind === 244 /* ModuleDeclaration */ + || kind === 247 /* NamespaceExportDeclaration */ + || kind === 251 /* NamespaceImport */ + || kind === 151 /* Parameter */ + || kind === 275 /* PropertyAssignment */ + || kind === 154 /* PropertyDeclaration */ + || kind === 153 /* PropertySignature */ + || kind === 159 /* SetAccessor */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 150 /* TypeParameter */ + || kind === 237 /* VariableDeclaration */ + || kind === 304 /* JSDocTypedefTag */ + || kind === 297 /* JSDocCallbackTag */ + || kind === 305 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 237 /* FunctionDeclaration */ - || kind === 256 /* MissingDeclaration */ - || kind === 238 /* ClassDeclaration */ - || kind === 239 /* InterfaceDeclaration */ - || kind === 240 /* TypeAliasDeclaration */ - || kind === 241 /* EnumDeclaration */ - || kind === 242 /* ModuleDeclaration */ - || kind === 247 /* ImportDeclaration */ - || kind === 246 /* ImportEqualsDeclaration */ - || kind === 253 /* ExportDeclaration */ - || kind === 252 /* ExportAssignment */ - || kind === 245 /* NamespaceExportDeclaration */; + return kind === 239 /* FunctionDeclaration */ + || kind === 258 /* MissingDeclaration */ + || kind === 240 /* ClassDeclaration */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 243 /* EnumDeclaration */ + || kind === 244 /* ModuleDeclaration */ + || kind === 249 /* ImportDeclaration */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 255 /* ExportDeclaration */ + || kind === 254 /* ExportAssignment */ + || kind === 247 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 227 /* BreakStatement */ - || kind === 226 /* ContinueStatement */ - || kind === 234 /* DebuggerStatement */ - || kind === 221 /* DoStatement */ - || kind === 219 /* ExpressionStatement */ - || kind === 218 /* EmptyStatement */ - || kind === 224 /* ForInStatement */ - || kind === 225 /* ForOfStatement */ - || kind === 223 /* ForStatement */ - || kind === 220 /* IfStatement */ - || kind === 231 /* LabeledStatement */ - || kind === 228 /* ReturnStatement */ - || kind === 230 /* SwitchStatement */ - || kind === 232 /* ThrowStatement */ - || kind === 233 /* TryStatement */ - || kind === 217 /* VariableStatement */ - || kind === 222 /* WhileStatement */ - || kind === 229 /* WithStatement */ - || kind === 305 /* NotEmittedStatement */ - || kind === 309 /* EndOfDeclarationMarker */ - || kind === 308 /* MergeDeclarationMarker */; + return kind === 229 /* BreakStatement */ + || kind === 228 /* ContinueStatement */ + || kind === 236 /* DebuggerStatement */ + || kind === 223 /* DoStatement */ + || kind === 221 /* ExpressionStatement */ + || kind === 220 /* EmptyStatement */ + || kind === 226 /* ForInStatement */ + || kind === 227 /* ForOfStatement */ + || kind === 225 /* ForStatement */ + || kind === 222 /* IfStatement */ + || kind === 233 /* LabeledStatement */ + || kind === 230 /* ReturnStatement */ + || kind === 232 /* SwitchStatement */ + || kind === 234 /* ThrowStatement */ + || kind === 235 /* TryStatement */ + || kind === 219 /* VariableStatement */ + || kind === 224 /* WhileStatement */ + || kind === 231 /* WithStatement */ + || kind === 307 /* NotEmittedStatement */ + || kind === 311 /* EndOfDeclarationMarker */ + || kind === 310 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + if (node.kind === 150 /* TypeParameter */) { + return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -13726,10 +14455,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 216 /* Block */) + if (node.kind !== 218 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 233 /* TryStatement */ || node.parent.kind === 272 /* CatchClause */) { + if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) { return false; } } @@ -13739,81 +14468,81 @@ var ts; /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 257 /* ExternalModuleReference */ - || kind === 146 /* QualifiedName */ - || kind === 71 /* Identifier */; + return kind === 259 /* ExternalModuleReference */ + || kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; } ts.isModuleReference = isModuleReference; // JSX /* @internal */ function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 99 /* ThisKeyword */ - || kind === 71 /* Identifier */ - || kind === 187 /* PropertyAccessExpression */; + return kind === 100 /* ThisKeyword */ + || kind === 72 /* Identifier */ + || kind === 189 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 258 /* JsxElement */ - || kind === 268 /* JsxExpression */ - || kind === 259 /* JsxSelfClosingElement */ - || kind === 10 /* JsxText */ - || kind === 262 /* JsxFragment */; + return kind === 260 /* JsxElement */ + || kind === 270 /* JsxExpression */ + || kind === 261 /* JsxSelfClosingElement */ + || kind === 11 /* JsxText */ + || kind === 264 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 265 /* JsxAttribute */ - || kind === 267 /* JsxSpreadAttribute */; + return kind === 267 /* JsxAttribute */ + || kind === 269 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 268 /* JsxExpression */; + return kind === 10 /* StringLiteral */ + || kind === 270 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 260 /* JsxOpeningElement */ - || kind === 259 /* JsxSelfClosingElement */; + return kind === 262 /* JsxOpeningElement */ + || kind === 261 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 269 /* CaseClause */ - || kind === 270 /* DefaultClause */; + return kind === 271 /* CaseClause */ + || kind === 272 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */; + return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 289 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */; + return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 157 /* SetAccessor */; + return node.kind === 159 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 156 /* GetAccessor */; + return node.kind === 158 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -13843,12 +14572,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 162 /* TypeReference */ || node.kind === 209 /* ExpressionWithTypeArguments */; + return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13877,15 +14606,14 @@ var ts; } ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { - return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; + return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isStringLiteralLike = isStringLiteralLike; })(ts || (ts = {})); /* @internal */ (function (ts) { - /** @internal */ function isNamedImportsOrExports(node) { - return node.kind === 250 /* NamedImports */ || node.kind === 254 /* NamedExports */; + return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function Symbol(flags, name) { @@ -13930,10 +14658,9 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - /* @internal */ function formatStringFromArgs(text, args, baseIndex) { if (baseIndex === void 0) { baseIndex = 0; } - return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); }); + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; function getLocaleSpecificMessage(message) { @@ -13962,7 +14689,6 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; - /* @internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -13987,7 +14713,6 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; - /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -14024,14 +14749,12 @@ var ts; function getDiagnosticFilePath(diagnostic) { return diagnostic.file ? diagnostic.file.path : undefined; } - /* @internal */ function compareDiagnostics(d1, d2) { return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || 0 /* EqualTo */; } ts.compareDiagnostics = compareDiagnostics; - /* @internal */ function compareDiagnosticsSkipRelatedInformation(d1, d2) { return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || ts.compareValues(d1.start, d2.start) || @@ -14092,6 +14815,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14843,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14856,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14323,7 +15058,6 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; - /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -14401,8 +15135,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15356,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14684,6 +15423,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14910,36 +15650,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15067,14 +15828,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +16006,98 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: // 0b or 0B + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: // 0o or 0O + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + var nIndex = stringValue.length - 1; + // Skip leading 0s + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + // Omit leading "0b", "0o", or "0x", and trailing "n" + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + var digit = digitChar <= 57 /* _9 */ + ? digitChar - 48 /* _0 */ + : 10 + digitChar - + (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; })(ts || (ts = {})); var ts; (function (ts) { @@ -15264,10 +16117,10 @@ var ts; var SourceFileConstructor; // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 277 /* SourceFile */) { + if (kind === 279 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 71 /* Identifier */) { + else if (kind === 72 /* Identifier */) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } else if (!ts.isNodeKind(kind)) { @@ -15316,28 +16169,29 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 145 /* LastToken */) { + if (!node || node.kind <= 147 /* LastToken */) { return; } switch (node.kind) { - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -15345,7 +16199,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -15353,405 +16207,399 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 168 /* TupleType */: + case 170 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 174 /* InferType */: + case 176 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 181 /* ImportType */: + case 183 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 175 /* ParenthesizedType */: - case 177 /* TypeOperator */: + case 177 /* ParenthesizedType */: + case 179 /* TypeOperator */: return visitNode(cbNode, node.type); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 179 /* MappedType */: + case 181 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return visitNode(cbNode, node.literal); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 210 /* AsExpression */: + case 212 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return visitNode(cbNode, node.name); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 277 /* SourceFile */: + case 279 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: return visitNode(cbNode, node.label); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 269 /* CaseClause */: + case 271 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 150 /* Decorator */: + case 152 /* Decorator */: return visitNode(cbNode, node.expression); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 276 /* EnumMember */: + case 278 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 250 /* NamedImports */: - case 254 /* NamedExports */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 169 /* OptionalType */: - case 170 /* RestType */: - case 281 /* JSDocTypeExpression */: - case 285 /* JSDocNonNullableType */: - case 284 /* JSDocNullableType */: - case 286 /* JSDocOptionalType */: - case 288 /* JSDocVariadicType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 283 /* JSDocTypeExpression */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 288 /* JSDocOptionalType */: + case 290 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 289 /* JSDocComment */: + case 291 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: - if (node.isNameFirst) { - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression); - } - else { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - } - case 298 /* JSDocReturnTag */: - return visitNode(cbNode, node.typeExpression); - case 300 /* JSDocTypeTag */: - return visitNode(cbNode, node.typeExpression); - case 293 /* JSDocAugmentsTag */: - return visitNode(cbNode, node.class); - case 301 /* JSDocTemplateTag */: - return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302 /* JSDocTypedefTag */: - if (node.typeExpression && - node.typeExpression.kind === 281 /* JSDocTypeExpression */) { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName); - } - else { - return visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - } - case 295 /* JSDocCallbackTag */: - return visitNode(cbNode, node.fullName) || + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303 /* JSDocTemplateTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304 /* JSDocTypedefTag */: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 /* JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297 /* JSDocCallbackTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299 /* JSDocThisTag */: - return visitNode(cbNode, node.typeExpression); - case 296 /* JSDocEnumTag */: - return visitNode(cbNode, node.typeExpression); - case 291 /* JSDocSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - ts.forEach(node.typeParameters, cbNode) || + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293 /* JSDocSignature */: + return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290 /* JSDocTypeLiteral */: - if (node.jsDocPropertyTags) { - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); - } - } - return; - case 306 /* PartiallyEmittedExpression */: + case 292 /* JSDocTypeLiteral */: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294 /* JSDocTag */: + case 296 /* JSDocClassTag */: + return visitNode(cbNode, node.tagName); + case 308 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15761,7 +16609,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16778,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -15965,18 +16817,18 @@ var ts; sourceFile.endOfFileToken = parseTokenNode(); } else { - var statement = createNode(219 /* ExpressionStatement */); + var statement = createNode(221 /* ExpressionStatement */); switch (token()) { - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: statement.expression = parseArrayLiteralExpression(); break; - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: statement.expression = parseTokenNode(); break; - case 38 /* MinusToken */: - if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) { + case 39 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) { statement.expression = parsePrefixUnaryExpression(); } else { @@ -15984,8 +16836,8 @@ var ts; } break; case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) { + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) { statement.expression = parseLiteralNode(); break; } @@ -16121,7 +16973,7 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // 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(277 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -16326,20 +17178,20 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token() === 71 /* Identifier */) { + if (token() === 72 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token() === 116 /* YieldKeyword */ && inYieldContext()) { + if (token() === 117 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) { + if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token() > 107 /* LastReservedWord */; + return token() > 108 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -16382,29 +17234,29 @@ var ts; } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token() === 25 /* SemicolonToken */) { + if (token() === 26 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 25 /* SemicolonToken */) { + if (token() === 26 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } return true; } else { - return parseExpected(25 /* SemicolonToken */); + return parseExpected(26 /* SemicolonToken */); } } function createNode(kind, pos) { nodeCount++; var p = pos >= 0 ? pos : scanner.getStartPos(); return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : - kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } function createNodeWithJSDoc(kind, pos) { @@ -16446,7 +17298,7 @@ var ts; parseErrorAtCurrentToken(diagnosticMessage, arg0); } var result = createNode(kind); - if (kind === 71 /* Identifier */) { + if (kind === 72 /* Identifier */) { result.escapedText = ""; } else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { @@ -16467,9 +17319,9 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(71 /* Identifier */); + var node = createNode(72 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 71 /* Identifier */) { + if (token() !== 72 /* Identifier */) { node.originalKeywordKind = token(); } node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); @@ -16478,7 +17330,7 @@ var ts; } // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; - return createMissingNode(71 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -16488,16 +17340,16 @@ var ts; } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || + token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { var node = parseLiteralNode(); node.text = internIdentifier(node.text); return node; } - if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -16509,13 +17361,13 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(147 /* ComputedPropertyName */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(149 /* ComputedPropertyName */); + parseExpected(22 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker // will error if it sees a comma expression. node.expression = allowInAnd(parseExpression); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function parseContextualModifier(t) { @@ -16530,20 +17382,20 @@ var ts; } function nextTokenCanFollowModifier() { switch (token()) { - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; - case 84 /* ExportKeyword */: + return nextToken() === 84 /* EnumKeyword */; + case 85 /* ExportKeyword */: nextToken(); - if (token() === 79 /* DefaultKeyword */) { + if (token() === 80 /* DefaultKeyword */) { return lookAhead(nextTokenCanFollowDefaultKeyword); } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - case 79 /* DefaultKeyword */: + return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + case 80 /* DefaultKeyword */: return nextTokenCanFollowDefaultKeyword(); - case 115 /* StaticKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: + case 116 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: nextToken(); return canFollowModifier(); default: @@ -16554,18 +17406,18 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 21 /* OpenBracketToken */ - || token() === 17 /* OpenBraceToken */ - || token() === 39 /* AsteriskToken */ - || token() === 24 /* DotDotDotToken */ + return token() === 22 /* OpenBracketToken */ + || token() === 18 /* OpenBraceToken */ + || token() === 40 /* AsteriskToken */ + || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenCanFollowDefaultKeyword() { nextToken(); - return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ || - token() === 109 /* InterfaceKeyword */ || - (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ || + token() === 110 /* InterfaceKeyword */ || + (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -16583,9 +17435,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -16593,21 +17445,29 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 22 /* OpenBracketToken */: + case 40 /* AsteriskToken */: + case 25 /* DotDotDotToken */: + case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` // That way we won't consume the body of a class in its heritage clause. - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -16622,37 +17482,39 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); + return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern(); case 19 /* TypeParameters */: return isIdentifier(); case 15 /* ArrayLiteralMembers */: - if (token() === 26 /* CommaToken */) { - return true; + switch (token()) { + case 27 /* CommaToken */: + case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; } // falls through case 11 /* ArgumentExpressions */: - return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(/*isJSDocParameter*/ false); case 17 /* JSDocParameters */: return isStartOfParameter(/*isJSDocParameter*/ true); case 20 /* TypeArguments */: case 21 /* TupleElementTypes */: - return token() === 26 /* CommaToken */ || isStartOfType(); + return token() === 27 /* CommaToken */ || isStartOfType(); case 22 /* HeritageClauses */: return isHeritageClause(); case 23 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; } return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17 /* OpenBraceToken */); - if (nextToken() === 18 /* CloseBraceToken */) { + ts.Debug.assert(token() === 18 /* OpenBraceToken */); + if (nextToken() === 19 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // @@ -16661,7 +17523,7 @@ var ts; // extends {} extends // extends {} implements var next = nextToken(); - return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */; + return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */; } return true; } @@ -16678,8 +17540,8 @@ var ts; return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 /* ImplementsKeyword */ || - token() === 85 /* ExtendsKeyword */) { + if (token() === 109 /* ImplementsKeyword */ || + token() === 86 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -16707,37 +17569,37 @@ var ts; case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: case 23 /* ImportOrExportSpecifiers */: - return token() === 18 /* CloseBraceToken */; + return token() === 19 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); case 19 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; + return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: case 21 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token() === 22 /* CloseBracketToken */; + return token() === 23 /* CloseBracketToken */; case 17 /* JSDocParameters */: case 16 /* Parameters */: case 18 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 20 /* TypeArguments */: // All other tokens should cause the type-argument to terminate except comma token - return token() !== 26 /* CommaToken */; + return token() !== 27 /* CommaToken */; case 22 /* HeritageClauses */: - return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; + return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; + return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */; case 14 /* JsxChildren */: - return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash); default: return false; } @@ -16757,7 +17619,7 @@ var ts; // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -16927,20 +17789,20 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 155 /* Constructor */: - case 160 /* IndexSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 152 /* PropertyDeclaration */: - case 215 /* SemicolonClassElement */: + case 157 /* Constructor */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 217 /* SemicolonClassElement */: return true; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ && - methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */; + var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */; return !nameIsConstructor; } } @@ -16949,8 +17811,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: return true; } } @@ -16959,58 +17821,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 217 /* VariableStatement */: - case 216 /* Block */: - case 220 /* IfStatement */: - case 219 /* ExpressionStatement */: - case 232 /* ThrowStatement */: - case 228 /* ReturnStatement */: - case 230 /* SwitchStatement */: - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 218 /* EmptyStatement */: - case 233 /* TryStatement */: - case 231 /* LabeledStatement */: - case 221 /* DoStatement */: - case 234 /* DebuggerStatement */: - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: - case 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 219 /* VariableStatement */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 221 /* ExpressionStatement */: + case 234 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 232 /* SwitchStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 220 /* EmptyStatement */: + case 235 /* TryStatement */: + case 233 /* LabeledStatement */: + case 223 /* DoStatement */: + case 236 /* DebuggerStatement */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 276 /* EnumMember */; + return node.kind === 278 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 151 /* PropertySignature */: - case 158 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 153 /* PropertySignature */: + case 160 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 235 /* VariableDeclaration */) { + if (node.kind !== 237 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -17031,7 +17893,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 149 /* Parameter */) { + if (node.kind !== 151 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -17088,7 +17950,7 @@ var ts; var startPos = scanner.getStartPos(); list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(26 /* CommaToken */)) { + if (parseOptional(27 /* CommaToken */)) { // No need to check for a zero length node since we know we parsed a comma continue; } @@ -17098,13 +17960,13 @@ var ts; } // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. - parseExpected(26 /* CommaToken */); + parseExpected(27 /* CommaToken */); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // 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 (considerSemicolonAsDelimiter && token() === 25 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } if (startPos === scanner.getStartPos()) { @@ -17155,8 +18017,8 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); - while (parseOptional(23 /* DotToken */)) { - if (token() === 27 /* LessThanToken */) { + while (parseOptional(24 /* DotToken */)) { + if (token() === 28 /* LessThanToken */) { // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting entity.jsdocDotPos = dotPos; break; @@ -17167,7 +18029,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(146 /* QualifiedName */, entity.pos); + var node = createNode(148 /* QualifiedName */, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -17198,33 +18060,33 @@ 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(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(204 /* TemplateExpression */); + var template = createNode(206 /* TemplateExpression */); template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); var list = []; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */); + } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { - var span = createNode(214 /* TemplateSpan */); + var span = createNode(216 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 18 /* CloseBraceToken */) { + if (token() === 19 /* CloseBraceToken */) { reScanTemplateToken(); literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(16 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */)); + literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */)); } span.literal = literal; return finishNode(span); @@ -17234,18 +18096,17 @@ var ts; } function parseTemplateHead() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); return fragment; } function parseTemplateMiddleOrTemplateTail() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind"); + ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind"); return fragment; } function parseLiteralLikeNode(kind) { var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = text; + node.text = scanner.getTokenValue(); if (scanner.hasExtendedUnicodeEscape()) { node.hasExtendedUnicodeEscape = true; } @@ -17267,24 +18128,24 @@ var ts; } // TYPES function parseTypeReference() { - var node = createNode(162 /* TypeReference */); + var node = createNode(164 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + if (!scanner.hasPrecedingLineBreak() && token() === 28 /* LessThanToken */) { + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */); } return finishNode(node); } // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return ts.nodeIsMissing(node.typeName); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: { + case 165 /* FunctionType */: + case 166 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -17292,20 +18153,20 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(161 /* TypePredicate */, lhs.pos); + var node = createNode(163 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(176 /* ThisType */); + var node = createNode(178 /* ThisType */); nextToken(); return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(282 /* JSDocAllType */); + var result = createNode(284 /* JSDocAllType */); if (postFixEquals) { - return createPostfixType(286 /* JSDocOptionalType */, result); + return createPostfixType(288 /* JSDocOptionalType */, result); } else { nextToken(); @@ -17313,7 +18174,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(285 /* JSDocNonNullableType */); + var result = createNode(287 /* JSDocNonNullableType */); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -17331,64 +18192,66 @@ var ts; // Foo // Foo(?= // (?| - if (token() === 26 /* CommaToken */ || - token() === 18 /* CloseBraceToken */ || - token() === 20 /* CloseParenToken */ || - token() === 29 /* GreaterThanToken */ || - token() === 58 /* EqualsToken */ || - token() === 49 /* BarToken */) { - var result = createNode(283 /* JSDocUnknownType */, pos); + if (token() === 27 /* CommaToken */ || + token() === 19 /* CloseBraceToken */ || + token() === 21 /* CloseParenToken */ || + token() === 30 /* GreaterThanToken */ || + token() === 59 /* EqualsToken */ || + token() === 50 /* BarToken */) { + var result = createNode(285 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(284 /* JSDocNullableType */, pos); + var result = createNode(286 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(287 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); nextToken(); - fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); } - var node = createNode(162 /* TypeReference */); + var node = createNode(164 /* TypeReference */); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(149 /* Parameter */); - if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { + var parameter = createNode(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) { parameter.name = parseIdentifierName(); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); } parameter.type = parseJSDocType(); return finishNode(parameter); } function parseJSDocType() { - var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { - var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); + var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } - if (token() === 58 /* EqualsToken */) { - return createPostfixType(286 /* JSDocOptionalType */, type); + if (token() === 59 /* EqualsToken */) { + return createPostfixType(288 /* JSDocOptionalType */, type); } return type; } function parseTypeQuery() { - var node = createNode(165 /* TypeQuery */); - parseExpected(103 /* TypeOfKeyword */); + var node = createNode(167 /* TypeQuery */); + parseExpected(104 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(148 /* TypeParameter */); + var node = createNode(150 /* TypeParameter */); node.name = parseIdentifier(); - if (parseOptional(85 /* ExtendsKeyword */)) { + if (parseOptional(86 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the // user writes a constraint that is an expression and not an actual type, then parse // it out as an expression (so we can recover well), but report that a type is needed @@ -17407,39 +18270,39 @@ var ts; node.expression = parseUnaryExpressionOrHigher(); } } - if (parseOptional(58 /* EqualsToken */)) { + if (parseOptional(59 /* EqualsToken */)) { node.default = parseType(); } return finishNode(node); } function parseTypeParameters() { - if (token() === 27 /* LessThanToken */) { - return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + if (token() === 28 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */); } } function parseParameterType() { - if (parseOptional(56 /* ColonToken */)) { + if (parseOptional(57 /* ColonToken */)) { return parseType(); } return undefined; } function isStartOfParameter(isJSDocParameter) { - return token() === 24 /* DotDotDotToken */ || + return token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 /* AtToken */ || + token() === 58 /* AtToken */ || isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseParameter() { - var node = createNodeWithJSDoc(149 /* Parameter */); - if (token() === 99 /* ThisKeyword */) { + var node = createNodeWithJSDoc(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); @@ -17454,7 +18317,7 @@ var ts; // to avoid this we'll advance cursor to the next token. nextToken(); } - node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.questionToken = parseOptionalToken(56 /* QuestionToken */); node.type = parseParameterType(); node.initializer = parseInitializer(); return finishNode(node); @@ -17476,16 +18339,16 @@ var ts; return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { - if (returnToken === 36 /* EqualsGreaterThanToken */) { + if (returnToken === 37 /* EqualsGreaterThanToken */) { parseExpected(returnToken); return true; } - else if (parseOptional(56 /* ColonToken */)) { + else if (parseOptional(57 /* ColonToken */)) { return true; } - else if (isType && token() === 36 /* EqualsGreaterThanToken */) { + else if (isType && token() === 37 /* EqualsGreaterThanToken */) { // This is easy to get backward, especially in type contexts, so parse the type anyway - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); nextToken(); return true; } @@ -17506,7 +18369,7 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (!parseExpected(19 /* OpenParenToken */)) { + if (!parseExpected(20 /* OpenParenToken */)) { signature.parameters = createMissingList(); return false; } @@ -17519,12 +18382,12 @@ var ts; parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - return parseExpected(20 /* CloseParenToken */); + return parseExpected(21 /* CloseParenToken */); } function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. // First check if it was a comma. If so, we're done with the member. - if (parseOptional(26 /* CommaToken */)) { + if (parseOptional(27 /* CommaToken */)) { return; } // Didn't have a comma. We must have a (possible ASI) semicolon. @@ -17532,15 +18395,15 @@ var ts; } function parseSignatureMember(kind) { var node = createNodeWithJSDoc(kind); - if (kind === 159 /* ConstructSignature */) { - parseExpected(94 /* NewKeyword */); + if (kind === 161 /* ConstructSignature */) { + parseExpected(95 /* NewKeyword */); } - fillSignature(56 /* ColonToken */, 4 /* Type */, node); + fillSignature(57 /* ColonToken */, 4 /* Type */, node); parseTypeMemberSemicolon(); return finishNode(node); } function isIndexSignature() { - return token() === 21 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { // The only allowed sequence is: @@ -17560,7 +18423,7 @@ var ts; // [] // nextToken(); - if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) { + if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) { return true; } if (ts.isModifierKind(token())) { @@ -17579,39 +18442,39 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token() !== 55 /* QuestionToken */) { + if (token() !== 56 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; + return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(node) { - node.kind = 160 /* IndexSignature */; - node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.kind = 162 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(node) { node.name = parsePropertyName(); - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - node.kind = 153 /* MethodSignature */; + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + node.kind = 155 /* MethodSignature */; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] - fillSignature(56 /* ColonToken */, 4 /* Type */, node); + fillSignature(57 /* ColonToken */, 4 /* Type */, node); } else { - node.kind = 151 /* PropertySignature */; + node.kind = 153 /* PropertySignature */; node.type = parseTypeAnnotation(); - if (token() === 58 /* EqualsToken */) { + if (token() === 59 /* 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. @@ -17623,7 +18486,7 @@ var ts; } function isTypeMemberStart() { // Return true if we have the start of a signature member - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return true; } var idToken = false; @@ -17633,7 +18496,7 @@ var ts; nextToken(); } // Index signatures and computed property names are type members - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers @@ -17644,21 +18507,21 @@ var ts; // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token() === 19 /* OpenParenToken */ || - token() === 27 /* LessThanToken */ || - token() === 55 /* QuestionToken */ || - token() === 56 /* ColonToken */ || - token() === 26 /* CommaToken */ || + return token() === 20 /* OpenParenToken */ || + token() === 28 /* LessThanToken */ || + token() === 56 /* QuestionToken */ || + token() === 57 /* ColonToken */ || + token() === 27 /* CommaToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(158 /* CallSignature */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseSignatureMember(160 /* CallSignature */); } - if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(159 /* ConstructSignature */); + if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161 /* ConstructSignature */); } var node = createNodeWithJSDoc(0 /* Unknown */); node.modifiers = parseModifiers(); @@ -17669,30 +18532,30 @@ var ts; } function nextTokenIsOpenParenOrLessThan() { nextToken(); - return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; + return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */; } function nextTokenIsDot() { - return nextToken() === 23 /* DotToken */; + return nextToken() === 24 /* DotToken */; } function nextTokenIsOpenParenOrLessThanOrDot() { switch (nextToken()) { - case 19 /* OpenParenToken */: - case 27 /* LessThanToken */: - case 23 /* DotToken */: + case 20 /* OpenParenToken */: + case 28 /* LessThanToken */: + case 24 /* DotToken */: return true; } return false; } function parseTypeLiteral() { - var node = createNode(166 /* TypeLiteral */); + var node = createNode(168 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { members = parseList(4 /* TypeMembers */, parseTypeMember); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { members = createMissingList(); @@ -17701,89 +18564,89 @@ var ts; } function isStartOfMappedType() { nextToken(); - if (token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { - return nextToken() === 132 /* ReadonlyKeyword */; + if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + return nextToken() === 133 /* ReadonlyKeyword */; } - if (token() === 132 /* ReadonlyKeyword */) { + if (token() === 133 /* ReadonlyKeyword */) { nextToken(); } - return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; + return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */; } function parseMappedTypeParameter() { - var node = createNode(148 /* TypeParameter */); + var node = createNode(150 /* TypeParameter */); node.name = parseIdentifier(); - parseExpected(92 /* InKeyword */); + parseExpected(93 /* InKeyword */); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(179 /* MappedType */); - parseExpected(17 /* OpenBraceToken */); - if (token() === 132 /* ReadonlyKeyword */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { + var node = createNode(181 /* MappedType */); + parseExpected(18 /* OpenBraceToken */); + if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { node.readonlyToken = parseTokenNode(); - if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) { - parseExpectedToken(132 /* ReadonlyKeyword */); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + parseExpectedToken(133 /* ReadonlyKeyword */); } } - parseExpected(21 /* OpenBracketToken */); + parseExpected(22 /* OpenBracketToken */); node.typeParameter = parseMappedTypeParameter(); - parseExpected(22 /* CloseBracketToken */); - if (token() === 55 /* QuestionToken */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { + parseExpected(23 /* CloseBracketToken */); + if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { node.questionToken = parseTokenNode(); - if (node.questionToken.kind !== 55 /* QuestionToken */) { - parseExpectedToken(55 /* QuestionToken */); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + parseExpectedToken(56 /* QuestionToken */); } } node.type = parseTypeAnnotation(); parseSemicolon(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseTupleElementType() { var pos = getNodePos(); - if (parseOptional(24 /* DotDotDotToken */)) { - var node = createNode(170 /* RestType */, pos); + if (parseOptional(25 /* DotDotDotToken */)) { + var node = createNode(172 /* RestType */, pos); node.type = parseType(); return finishNode(node); } var type = parseType(); - if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 284 /* JSDocNullableType */ && type.pos === type.type.pos) { - type.kind = 169 /* OptionalType */; + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 171 /* OptionalType */; } return type; } function parseTupleType() { - var node = createNode(168 /* TupleType */); - node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + var node = createNode(170 /* TupleType */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(175 /* ParenthesizedType */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(177 /* ParenthesizedType */); + parseExpected(20 /* OpenParenToken */); node.type = parseType(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseFunctionOrConstructorType() { var pos = getNodePos(); - var kind = parseOptional(94 /* NewKeyword */) ? 164 /* ConstructorType */ : 163 /* FunctionType */; + var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */; var node = createNodeWithJSDoc(kind, pos); - fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 23 /* DotToken */ ? undefined : node; + return token() === 24 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(180 /* LiteralType */); + var node = createNode(182 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(200 /* PrefixUnaryExpression */); - unaryMinusExpression.operator = 38 /* MinusToken */; + unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 39 /* MinusToken */; nextToken(); } - var expression = token() === 101 /* TrueKeyword */ || token() === 86 /* FalseKeyword */ + var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */ ? parseTokenNode() : parseLiteralLikeNode(token()); if (negative) { @@ -17796,79 +18659,82 @@ var ts; } function isStartOfTypeOfImportType() { nextToken(); - return token() === 91 /* ImportKeyword */; + return token() === 92 /* ImportKeyword */; } function parseImportType() { sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; - var node = createNode(181 /* ImportType */); - if (parseOptional(103 /* TypeOfKeyword */)) { + var node = createNode(183 /* ImportType */); + if (parseOptional(104 /* TypeOfKeyword */)) { node.isTypeOf = true; } - parseExpected(91 /* ImportKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(92 /* ImportKeyword */); + parseExpected(20 /* OpenParenToken */); node.argument = parseType(); - parseExpected(20 /* CloseParenToken */); - if (parseOptional(23 /* DotToken */)) { + parseExpected(21 /* CloseParenToken */); + if (parseOptional(24 /* DotToken */)) { node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); } node.typeArguments = tryParseTypeArguments(); return finishNode(node); } - function nextTokenIsNumericLiteral() { - return nextToken() === 8 /* NumericLiteral */; + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */; } function parseNonArrayType() { switch (token()) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 138 /* SymbolKeyword */: - case 122 /* BooleanKeyword */: - case 140 /* UndefinedKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 139 /* SymbolKeyword */: + case 123 /* BooleanKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: return parseJSDocAllType(/*postfixEquals*/ false); - case 61 /* AsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: return parseJSDocAllType(/*postfixEquals*/ true); - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseJSDocFunctionType(); - case 51 /* ExclamationToken */: + case 52 /* ExclamationToken */: return parseJSDocNonNullableType(); - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return parseLiteralTypeNode(); - case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); - case 105 /* VoidKeyword */: - case 95 /* NullKeyword */: + case 39 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 106 /* VoidKeyword */: + case 96 /* NullKeyword */: return parseTokenNode(); - case 99 /* ThisKeyword */: { + case 100 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 103 /* TypeOfKeyword */: + case 104 /* TypeOfKeyword */: return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: return parseTupleType(); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return parseParenthesizedType(); - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return parseImportType(); default: return parseTypeReference(); @@ -17876,42 +18742,44 @@ var ts; } function isStartOfType(inStartOfParameter) { switch (token()) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 141 /* UniqueKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 103 /* TypeOfKeyword */: - case 131 /* NeverKeyword */: - case 17 /* OpenBraceToken */: - case 21 /* OpenBracketToken */: - case 27 /* LessThanToken */: - case 49 /* BarToken */: - case 48 /* AmpersandToken */: - case 94 /* NewKeyword */: - case 9 /* StringLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 142 /* UniqueKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 104 /* TypeOfKeyword */: + case 132 /* NeverKeyword */: + case 18 /* OpenBraceToken */: + case 22 /* OpenBracketToken */: + case 28 /* LessThanToken */: + case 50 /* BarToken */: + case 49 /* AmpersandToken */: + case 95 /* NewKeyword */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 135 /* ObjectKeyword */: - case 39 /* AsteriskToken */: - case 55 /* QuestionToken */: - case 51 /* ExclamationToken */: - case 24 /* DotDotDotToken */: - case 126 /* InferKeyword */: - case 91 /* ImportKeyword */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 136 /* ObjectKeyword */: + case 40 /* AsteriskToken */: + case 56 /* QuestionToken */: + case 52 /* ExclamationToken */: + case 25 /* DotDotDotToken */: + case 127 /* InferKeyword */: + case 92 /* ImportKeyword */: return true; - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return !inStartOfParameter; - case 38 /* MinusToken */: - return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); - case 19 /* OpenParenToken */: + case 39 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); @@ -17921,35 +18789,35 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 51 /* ExclamationToken */: - type = createPostfixType(285 /* JSDocNonNullableType */, type); + case 52 /* ExclamationToken */: + type = createPostfixType(287 /* JSDocNonNullableType */, type); break; - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createPostfixType(284 /* JSDocNullableType */, type); + type = createPostfixType(286 /* JSDocNullableType */, type); break; - case 21 /* OpenBracketToken */: - parseExpected(21 /* OpenBracketToken */); + case 22 /* OpenBracketToken */: + parseExpected(22 /* OpenBracketToken */); if (isStartOfType()) { - var node = createNode(178 /* IndexedAccessType */, type.pos); + var node = createNode(180 /* IndexedAccessType */, type.pos); node.objectType = type; node.indexType = parseType(); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); type = finishNode(node); } else { - var node = createNode(167 /* ArrayType */, type.pos); + var node = createNode(169 /* ArrayType */, type.pos); node.elementType = type; - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); type = finishNode(node); } break; @@ -17966,16 +18834,16 @@ var ts; return finishNode(postfix); } function parseTypeOperator(operator) { - var node = createNode(177 /* TypeOperator */); + var node = createNode(179 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseInferType() { - var node = createNode(174 /* InferType */); - parseExpected(126 /* InferKeyword */); - var typeParameter = createNode(148 /* TypeParameter */); + var node = createNode(176 /* InferType */); + parseExpected(127 /* InferKeyword */); + var typeParameter = createNode(150 /* TypeParameter */); typeParameter.name = parseIdentifier(); node.typeParameter = finishNode(typeParameter); return finishNode(node); @@ -17983,10 +18851,10 @@ var ts; function parseTypeOperatorOrHigher() { var operator = token(); switch (operator) { - case 128 /* KeyOfKeyword */: - case 141 /* UniqueKeyword */: + case 129 /* KeyOfKeyword */: + case 142 /* UniqueKeyword */: return parseTypeOperator(operator); - case 126 /* InferKeyword */: + case 127 /* InferKeyword */: return parseInferType(); } return parsePostfixTypeOrHigher(); @@ -18006,27 +18874,27 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(172 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(171 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */); } function isStartOfFunctionType() { - if (token() === 27 /* LessThanToken */) { + if (token() === 28 /* LessThanToken */) { return true; } - return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token() === 99 /* ThisKeyword */) { + if (isIdentifier() || token() === 100 /* ThisKeyword */) { nextToken(); return true; } - if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) { + if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -18036,7 +18904,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -18044,17 +18912,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || - token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || + token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token() === 20 /* CloseParenToken */) { + if (token() === 21 /* CloseParenToken */) { nextToken(); - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -18066,7 +18934,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(161 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -18077,7 +18945,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -18088,49 +18956,50 @@ var ts; return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) { + if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) { return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); - if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { - var node = createNode(173 /* ConditionalType */, type.pos); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) { + var node = createNode(175 /* ConditionalType */, type.pos); node.checkType = type; // The type following 'extends' is not permitted to be another conditional type node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); - parseExpected(55 /* QuestionToken */); + parseExpected(56 /* QuestionToken */); node.trueType = parseTypeWorker(); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.falseType = parseTypeWorker(); return finishNode(node); } return type; } function parseTypeAnnotation() { - return parseOptional(56 /* ColonToken */) ? parseType() : undefined; + return parseOptional(57 /* ColonToken */) ? parseType() : undefined; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { switch (token()) { - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 19 /* OpenParenToken */: - case 21 /* OpenBracketToken */: - case 17 /* OpenBraceToken */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 94 /* NewKeyword */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 71 /* Identifier */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 20 /* OpenParenToken */: + case 22 /* OpenBracketToken */: + case 18 /* OpenBraceToken */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 95 /* NewKeyword */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 72 /* Identifier */: return true; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); default: return isIdentifier(); @@ -18141,18 +19010,18 @@ var ts; return true; } switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 27 /* LessThanToken */: - case 121 /* AwaitKeyword */: - case 116 /* YieldKeyword */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 28 /* LessThanToken */: + case 122 /* AwaitKeyword */: + case 117 /* YieldKeyword */: // Yield/await always starts an expression. Either it is an identifier (in which case // it is definitely an expression). Or it's a keyword (either because we're in // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. @@ -18170,10 +19039,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 17 /* OpenBraceToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && - token() !== 57 /* AtToken */ && + return token() !== 18 /* OpenBraceToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + token() !== 58 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -18187,7 +19056,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) { + while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -18196,7 +19065,7 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(58 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { // AssignmentExpression[in,yield]: @@ -18241,7 +19110,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -18257,7 +19126,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 116 /* YieldKeyword */) { + if (token() === 117 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -18286,15 +19155,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(205 /* YieldExpression */); + var node = createNode(207 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 39 /* AsteriskToken */ || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + (token() === 40 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -18305,20 +19174,20 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(195 /* ArrowFunction */, asyncModifier.pos); + node = createNode(197 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(195 /* ArrowFunction */, identifier.pos); + node = createNode(197 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(149 /* Parameter */, identifier.pos); + var parameter = createNode(151 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); - node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -18343,8 +19212,8 @@ var ts; // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */); - arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return finishNode(arrowFunction); @@ -18354,10 +19223,10 @@ var ts; // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -18367,28 +19236,28 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) { + if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) { return 0 /* False */; } } var first = token(); var second = nextToken(); - if (first === 19 /* OpenParenToken */) { - if (second === 20 /* CloseParenToken */) { + if (first === 20 /* OpenParenToken */) { + if (second === 21 /* CloseParenToken */) { // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. var third = nextToken(); switch (third) { - case 36 /* EqualsGreaterThanToken */: - case 56 /* ColonToken */: - case 17 /* OpenBraceToken */: + case 37 /* EqualsGreaterThanToken */: + case 57 /* ColonToken */: + case 18 /* OpenBraceToken */: return 1 /* True */; default: return 0 /* False */; @@ -18400,42 +19269,42 @@ var ts; // ({ x }) => { } // ([ x ]) // ({ x }) - if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) { + if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) { return 2 /* Unknown */; } // Simple case: "(..." // This is an arrow function with a rest parameter. - if (second === 24 /* DotDotDotToken */) { + if (second === 25 /* DotDotDotToken */) { return 1 /* True */; } // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. - if (ts.isModifierKind(second) && second !== 120 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { return 1 /* True */; } // If we had "(" followed by something that's not an identifier, // then this definitely doesn't look like a lambda. "this" is not // valid, but we want to parse it and then give a semantic error. - if (!isIdentifier() && second !== 99 /* ThisKeyword */) { + if (!isIdentifier() && second !== 100 /* ThisKeyword */) { return 0 /* False */; } switch (nextToken()) { - case 56 /* ColonToken */: + case 57 /* ColonToken */: // If we have something like "(a:", then we must have a // type-annotated parameter in an arrow function expression. return 1 /* True */; - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: nextToken(); // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 58 /* EqualsToken */ || token() === 20 /* CloseParenToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) { return 1 /* True */; } // Otherwise it is definitely not a lambda. return 0 /* False */; - case 26 /* CommaToken */: - case 58 /* EqualsToken */: - case 20 /* CloseParenToken */: + case 27 /* CommaToken */: + case 59 /* EqualsToken */: + case 21 /* CloseParenToken */: // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function return 2 /* Unknown */; } @@ -18443,7 +19312,7 @@ var ts; return 0 /* False */; } else { - ts.Debug.assert(first === 27 /* LessThanToken */); + ts.Debug.assert(first === 28 /* LessThanToken */); // If we have "<" not followed by an identifier, // then this definitely is not an arrow function. if (!isIdentifier()) { @@ -18453,17 +19322,17 @@ var ts; if (sourceFile.languageVariant === 1 /* JSX */) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 85 /* ExtendsKeyword */) { + if (third === 86 /* ExtendsKeyword */) { var fourth = nextToken(); switch (fourth) { - case 58 /* EqualsToken */: - case 29 /* GreaterThanToken */: + case 59 /* EqualsToken */: + case 30 /* GreaterThanToken */: return false; default: return true; } } - else if (third === 26 /* CommaToken */) { + else if (third === 27 /* CommaToken */) { return true; } return false; @@ -18482,7 +19351,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); @@ -18495,23 +19364,23 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { return 1 /* True */; } } return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNodeWithJSDoc(195 /* ArrowFunction */); + var node = createNodeWithJSDoc(197 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. @@ -18521,7 +19390,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) { + if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) { return undefined; } // Parsing a signature isn't enough. @@ -18532,19 +19401,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { + if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); } - if (token() !== 25 /* SemicolonToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && + if (token() !== 26 /* SemicolonToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -18569,20 +19438,20 @@ var ts; } function parseConditionalExpressionRest(leftOperand) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - var questionToken = parseOptionalToken(55 /* QuestionToken */); + var questionToken = parseOptionalToken(56 /* QuestionToken */); if (!questionToken) { return leftOperand; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(203 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(205 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56 /* ColonToken */); + node.colonToken = parseExpectedToken(57 /* ColonToken */); node.whenFalse = ts.nodeIsPresent(node.colonToken) ? parseAssignmentExpressionOrHigher() - : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -18590,7 +19459,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 145 /* OfKeyword */; + return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -18619,16 +19488,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 92 /* InKeyword */ && inDisallowInContext()) { + if (token() === 93 /* InKeyword */ && inDisallowInContext()) { break; } - if (token() === 118 /* AsKeyword */) { + if (token() === 119 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -18649,51 +19518,51 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 92 /* InKeyword */) { + if (inDisallowInContext() && token() === 93 /* InKeyword */) { return false; } return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(202 /* BinaryExpression */, left.pos); + var node = createNode(204 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(210 /* AsExpression */, left.pos); + var node = createNode(212 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(200 /* PrefixUnaryExpression */); + var node = createNode(202 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(196 /* DeleteExpression */); + var node = createNode(198 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(197 /* TypeOfExpression */); + var node = createNode(199 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(198 /* VoidExpression */); + var node = createNode(200 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 121 /* AwaitKeyword */) { + if (token() === 122 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -18703,7 +19572,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(199 /* AwaitExpression */); + var node = createNode(201 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -18727,7 +19596,7 @@ var ts; */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? + return token() === 41 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } @@ -18744,10 +19613,10 @@ var ts; */ var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40 /* AsteriskAsteriskToken */) { + if (token() === 41 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 192 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) { parseErrorAt(pos, end, 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 { @@ -18772,23 +19641,23 @@ var ts; */ function parseSimpleUnaryExpression() { switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: return parsePrefixUnaryExpression(); - case 80 /* DeleteKeyword */: + case 81 /* DeleteKeyword */: return parseDeleteExpression(); - case 103 /* TypeOfKeyword */: + case 104 /* TypeOfKeyword */: return parseTypeOfExpression(); - case 105 /* VoidKeyword */: + case 106 /* VoidKeyword */: return parseVoidExpression(); - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // This is modified UnaryExpression grammar in TypeScript // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); - case 121 /* AwaitKeyword */: + case 122 /* AwaitKeyword */: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -18811,16 +19680,16 @@ var ts; // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 121 /* AwaitKeyword */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 122 /* AwaitKeyword */: return false; - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression if (sourceFile.languageVariant !== 1 /* JSX */) { return false; @@ -18843,21 +19712,21 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseUpdateExpression() { - if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(200 /* PrefixUnaryExpression */); + if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) { + var node = createNode(202 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(201 /* PostfixUnaryExpression */, expression.pos); + if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -18898,7 +19767,7 @@ var ts; // 3)we have a MemberExpression which either completes the LeftHandSideExpression, // or starts the beginning of the first four CallExpression productions. var expression; - if (token() === 91 /* ImportKeyword */) { + if (token() === 92 /* ImportKeyword */) { if (lookAhead(nextTokenIsOpenParenOrLessThan)) { // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" // For example: @@ -18913,8 +19782,8 @@ var ts; var fullStart = scanner.getStartPos(); nextToken(); // advance past the 'import' nextToken(); // advance past the dot - var node = createNode(212 /* MetaProperty */, fullStart); - node.keywordToken = 91 /* ImportKeyword */; + var node = createNode(214 /* MetaProperty */, fullStart); + node.keywordToken = 92 /* ImportKeyword */; node.name = parseIdentifierName(); expression = finishNode(node); sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; @@ -18924,7 +19793,7 @@ var ts; } } else { - expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); } // Now, we *may* be complete. However, we might have consumed the start of a // CallExpression. As such, we need to consume the rest of it here to be complete. @@ -18983,22 +19852,22 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) { + if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(187 /* PropertyAccessExpression */, expression.pos); + var node = createNode(189 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - parseExpectedToken(23 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 260 /* JsxOpeningElement */) { - var node = createNode(258 /* JsxElement */, opening.pos); + if (opening.kind === 262 /* JsxOpeningElement */) { + var node = createNode(260 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -19007,15 +19876,15 @@ var ts; } result = finishNode(node); } - else if (opening.kind === 263 /* JsxOpeningFragment */) { - var node = createNode(262 /* JsxFragment */, opening.pos); + else if (opening.kind === 265 /* JsxOpeningFragment */) { + var node = createNode(264 /* JsxFragment */, opening.pos); node.openingFragment = opening; node.children = parseJsxChildren(node.openingFragment); node.closingFragment = parseJsxClosingFragment(inExpressionContext); result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 259 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -19026,15 +19895,15 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token() === 27 /* LessThanToken */) { + if (inExpressionContext && token() === 28 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(202 /* BinaryExpression */, result.pos); + var badNode = createNode(204 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -19042,8 +19911,8 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10 /* JsxText */); - node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; + var node = createNode(11 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; currentToken = scanner.scanJsxToken(); return finishNode(node); } @@ -19059,15 +19928,15 @@ var ts; parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); } return undefined; - case 28 /* LessThanSlashToken */: + case 29 /* LessThanSlashToken */: case 7 /* ConflictMarkerTrivia */: return undefined; - case 10 /* JsxText */: - case 11 /* JsxTextAllWhiteSpaces */: + case 11 /* JsxText */: + case 12 /* JsxTextAllWhiteSpaces */: return parseJsxText(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); default: return ts.Debug.assertNever(token); @@ -19088,16 +19957,16 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(266 /* JsxAttributes */); + var jsxAttributes = createNode(268 /* JsxAttributes */); jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(27 /* LessThanToken */); - if (token() === 29 /* GreaterThanToken */) { + parseExpected(28 /* LessThanToken */); + if (token() === 30 /* GreaterThanToken */) { // See below for explanation of scanJsxText - var node_1 = createNode(263 /* JsxOpeningFragment */, fullStart); + var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart); scanJsxText(); return finishNode(node_1); } @@ -19105,23 +19974,23 @@ var ts; var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; - if (token() === 29 /* GreaterThanToken */) { + if (token() === 30 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(260 /* JsxOpeningElement */, fullStart); + node = createNode(262 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { - parseExpected(41 /* SlashToken */); + parseExpected(42 /* SlashToken */); if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(259 /* JsxSelfClosingElement */, fullStart); + node = createNode(261 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.typeArguments = typeArguments; @@ -19135,10 +20004,10 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token() === 99 /* ThisKeyword */ ? + var expression = token() === 100 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); + while (parseOptional(24 /* DotToken */)) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -19146,33 +20015,33 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(268 /* JsxExpression */); - if (!parseExpected(17 /* OpenBraceToken */)) { + var node = createNode(270 /* JsxExpression */); + if (!parseExpected(18 /* OpenBraceToken */)) { return undefined; } - if (token() !== 18 /* CloseBraceToken */) { - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + if (token() !== 19 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { - parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(265 /* JsxAttribute */); + var node = createNode(267 /* JsxAttribute */); node.name = parseIdentifierName(); - if (token() === 58 /* EqualsToken */) { + if (token() === 59 /* EqualsToken */) { switch (scanJsxAttributeValue()) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: node.initializer = parseLiteralNode(); break; default: @@ -19183,72 +20052,72 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(267 /* JsxSpreadAttribute */); - parseExpected(17 /* OpenBraceToken */); - parseExpected(24 /* DotDotDotToken */); + var node = createNode(269 /* JsxSpreadAttribute */); + parseExpected(18 /* OpenBraceToken */); + parseExpected(25 /* DotDotDotToken */); node.expression = parseExpression(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(261 /* JsxClosingElement */); - parseExpected(28 /* LessThanSlashToken */); + var node = createNode(263 /* JsxClosingElement */); + parseExpected(29 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxClosingFragment(inExpressionContext) { - var node = createNode(264 /* JsxClosingFragment */); - parseExpected(28 /* LessThanSlashToken */); + var node = createNode(266 /* JsxClosingFragment */); + parseExpected(29 /* LessThanSlashToken */); if (ts.tokenIsIdentifierOrKeyword(token())) { parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(192 /* TypeAssertionExpression */); - parseExpected(27 /* LessThanToken */); + var node = createNode(194 /* TypeAssertionExpression */); + parseExpected(28 /* LessThanToken */); node.type = parseType(); - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(23 /* DotToken */); + var dotToken = parseOptionalToken(24 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; } - if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(211 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName - if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(188 /* ElementAccessExpression */, expression.pos); + if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) { + var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; - if (token() === 22 /* CloseBracketToken */) { - indexedAccess.argumentExpression = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + if (token() === 23 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); } else { var argument = allowInAnd(parseExpression); @@ -19257,7 +20126,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } @@ -19269,13 +20138,13 @@ var ts; } } function isTemplateStartOfTaggedTemplate() { - return token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */; + return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */; } function parseTaggedTemplateRest(tag, typeArguments) { - var tagExpression = createNode(191 /* TaggedTemplateExpression */, tag.pos); + var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos); tagExpression.tag = tag; tagExpression.typeArguments = typeArguments; - tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); return finishNode(tagExpression); @@ -19283,7 +20152,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 27 /* LessThanToken */) { + if (token() === 28 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -19296,15 +20165,15 @@ var ts; expression = parseTaggedTemplateRest(expression, typeArguments); continue; } - var callExpr = createNode(189 /* CallExpression */, expression.pos); + var callExpr = createNode(191 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(189 /* CallExpression */, expression.pos); + else if (token() === 20 /* OpenParenToken */) { + var callExpr = createNode(191 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -19314,17 +20183,17 @@ var ts; } } function parseArgumentList() { - parseExpected(19 /* OpenParenToken */); + parseExpected(20 /* OpenParenToken */); var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(27 /* LessThanToken */)) { + if (!parseOptional(28 /* LessThanToken */)) { return undefined; } var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); - if (!parseExpected(29 /* GreaterThanToken */)) { + if (!parseExpected(30 /* GreaterThanToken */)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } @@ -19336,34 +20205,34 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 19 /* OpenParenToken */: // foo( - case 13 /* NoSubstitutionTemplateLiteral */: // foo `...` - case 14 /* TemplateHead */: // foo `...${100}...` + case 20 /* OpenParenToken */: // foo( + case 14 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 15 /* TemplateHead */: // foo `...${100}...` // these are the only tokens can legally follow a type argument // list. So we definitely want to treat them as type arg lists. - case 23 /* DotToken */: // foo. - case 20 /* CloseParenToken */: // foo) - case 22 /* CloseBracketToken */: // foo] - case 56 /* ColonToken */: // foo: - case 25 /* SemicolonToken */: // foo; - case 55 /* QuestionToken */: // foo? - case 32 /* EqualsEqualsToken */: // foo == - case 34 /* EqualsEqualsEqualsToken */: // foo === - case 33 /* ExclamationEqualsToken */: // foo != - case 35 /* ExclamationEqualsEqualsToken */: // foo !== - case 53 /* AmpersandAmpersandToken */: // foo && - case 54 /* BarBarToken */: // foo || - case 50 /* CaretToken */: // foo ^ - case 48 /* AmpersandToken */: // foo & - case 49 /* BarToken */: // foo | - case 18 /* CloseBraceToken */: // foo } + case 24 /* DotToken */: // foo. + case 21 /* CloseParenToken */: // foo) + case 23 /* CloseBracketToken */: // foo] + case 57 /* ColonToken */: // foo: + case 26 /* SemicolonToken */: // foo; + case 56 /* QuestionToken */: // foo? + case 33 /* EqualsEqualsToken */: // foo == + case 35 /* EqualsEqualsEqualsToken */: // foo === + case 34 /* ExclamationEqualsToken */: // foo != + case 36 /* ExclamationEqualsEqualsToken */: // foo !== + case 54 /* AmpersandAmpersandToken */: // foo && + case 55 /* BarBarToken */: // foo || + case 51 /* CaretToken */: // foo ^ + case 49 /* AmpersandToken */: // foo & + case 50 /* BarToken */: // foo | + case 19 /* CloseBraceToken */: // foo } case 1 /* EndOfFileToken */: // foo // these cases can't legally follow a type arg list. However, they're not legal // expressions either. The user is probably in the middle of a generic type. So // treat it as such. return true; - case 26 /* CommaToken */: // foo, - case 17 /* OpenBraceToken */: // foo { + case 27 /* CommaToken */: // foo, + case 18 /* OpenBraceToken */: // foo { // We don't want to treat these as type arguments. Otherwise we'll parse this // as an invocation expression. Instead, we want to parse out the expression // in isolation from the type arguments. @@ -19375,22 +20244,23 @@ var ts; function parsePrimaryExpression() { switch (token()) { case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return parseLiteralNode(); - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return parseTokenNode(); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return parseParenthesizedExpression(); - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: return parseArrayLiteralExpression(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseObjectLiteralExpression(); - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. // If we encounter `async [no LineTerminator here] function` then this is an async // function; otherwise, its an identifier. @@ -19398,75 +20268,76 @@ var ts; break; } return parseFunctionExpression(); - case 75 /* ClassKeyword */: + case 76 /* ClassKeyword */: return parseClassExpression(); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseFunctionExpression(); - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: return parseNewExpressionOrNewDotTarget(); - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) { return parseLiteralNode(); } break; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNodeWithJSDoc(193 /* ParenthesizedExpression */); - parseExpected(19 /* OpenParenToken */); + var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(206 /* SpreadElement */); - parseExpected(24 /* DotDotDotToken */); + var node = createNode(208 /* SpreadElement */); + parseExpected(25 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(208 /* OmittedExpression */) : + return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(185 /* ArrayLiteralExpression */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(187 /* ArrayLiteralExpression */); + parseExpected(22 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function parseObjectLiteralElement() { var node = createNodeWithJSDoc(0 /* Unknown */); - if (parseOptionalToken(24 /* DotDotDotToken */)) { - node.kind = 275 /* SpreadAssignment */; + if (parseOptionalToken(25 /* DotDotDotToken */)) { + node.kind = 277 /* SpreadAssignment */; node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* GetAccessor */); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); } - if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 157 /* SetAccessor */); + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); } - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } // check if it is short-hand property assignment or normal property assignment @@ -19474,30 +20345,30 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */); if (isShorthandPropertyAssignment) { - node.kind = 274 /* ShorthandPropertyAssignment */; - var equalsToken = parseOptionalToken(58 /* EqualsToken */); + node.kind = 276 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(59 /* EqualsToken */); if (equalsToken) { node.equalsToken = equalsToken; node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } } else { - node.kind = 273 /* PropertyAssignment */; - parseExpected(56 /* ColonToken */); + node.kind = 275 /* PropertyAssignment */; + parseExpected(57 /* ColonToken */); node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(186 /* ObjectLiteralExpression */); - parseExpected(17 /* OpenBraceToken */); + var node = createNode(188 /* ObjectLiteralExpression */); + parseExpected(18 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseFunctionExpression() { @@ -19510,10 +20381,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNodeWithJSDoc(194 /* FunctionExpression */); + var node = createNodeWithJSDoc(196 /* FunctionExpression */); node.modifiers = parseModifiers(); - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; node.name = @@ -19521,7 +20392,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlock(isGenerator | isAsync); if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -19533,10 +20404,10 @@ var ts; } function parseNewExpressionOrNewDotTarget() { var fullStart = scanner.getStartPos(); - parseExpected(94 /* NewKeyword */); - if (parseOptional(23 /* DotToken */)) { - var node_2 = createNode(212 /* MetaProperty */, fullStart); - node_2.keywordToken = 94 /* NewKeyword */; + parseExpected(95 /* NewKeyword */); + if (parseOptional(24 /* DotToken */)) { + var node_2 = createNode(214 /* MetaProperty */, fullStart); + node_2.keywordToken = 95 /* NewKeyword */; node_2.name = parseIdentifierName(); return finishNode(node_2); } @@ -19552,23 +20423,23 @@ var ts; } break; } - var node = createNode(190 /* NewExpression */, fullStart); + var node = createNode(192 /* NewExpression */, fullStart); node.expression = expression; node.typeArguments = typeArguments; - if (node.typeArguments || token() === 19 /* OpenParenToken */) { + if (node.typeArguments || token() === 20 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(216 /* Block */); - if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(218 /* Block */); + if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -19595,52 +20466,52 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(218 /* EmptyStatement */); - parseExpected(25 /* SemicolonToken */); + var node = createNode(220 /* EmptyStatement */); + parseExpected(26 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(220 /* IfStatement */); - parseExpected(90 /* IfKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(222 /* IfStatement */); + parseExpected(91 /* IfKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined; + node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(221 /* DoStatement */); - parseExpected(81 /* DoKeyword */); + var node = createNode(223 /* DoStatement */); + parseExpected(82 /* DoKeyword */); node.statement = parseStatement(); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. - parseOptional(25 /* SemicolonToken */); + parseOptional(26 /* SemicolonToken */); return finishNode(node); } function parseWhileStatement() { - var node = createNode(222 /* WhileStatement */); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(224 /* WhileStatement */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(88 /* ForKeyword */); - var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(89 /* ForKeyword */); + var awaitToken = parseOptionalToken(122 /* AwaitKeyword */); + parseExpected(20 /* OpenParenToken */); var initializer; - if (token() !== 25 /* SemicolonToken */) { - if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { + if (token() !== 26 /* SemicolonToken */) { + if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -19648,33 +20519,33 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(145 /* OfKeyword */) : parseOptional(145 /* OfKeyword */)) { - var forOfStatement = createNode(225 /* ForOfStatement */, pos); + if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) { + var forOfStatement = createNode(227 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } - else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(224 /* ForInStatement */, pos); + else if (parseOptional(93 /* InKeyword */)) { + var forInStatement = createNode(226 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(223 /* ForStatement */, pos); + var forStatement = createNode(225 /* ForStatement */, pos); forStatement.initializer = initializer; - parseExpected(25 /* SemicolonToken */); - if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { + parseExpected(26 /* SemicolonToken */); + if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(25 /* SemicolonToken */); - if (token() !== 20 /* CloseParenToken */) { + parseExpected(26 /* SemicolonToken */); + if (token() !== 21 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -19682,7 +20553,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 227 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -19690,8 +20561,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(228 /* ReturnStatement */); - parseExpected(96 /* ReturnKeyword */); + var node = createNode(230 /* ReturnStatement */); + parseExpected(97 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -19699,42 +20570,42 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(229 /* WithStatement */); - parseExpected(107 /* WithKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(231 /* WithStatement */); + parseExpected(108 /* WithKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(269 /* CaseClause */); - parseExpected(73 /* CaseKeyword */); + var node = createNode(271 /* CaseClause */); + parseExpected(74 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(270 /* DefaultClause */); - parseExpected(79 /* DefaultKeyword */); - parseExpected(56 /* ColonToken */); + var node = createNode(272 /* DefaultClause */); + parseExpected(80 /* DefaultKeyword */); + parseExpected(57 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(230 /* SwitchStatement */); - parseExpected(98 /* SwitchKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(232 /* SwitchStatement */); + parseExpected(99 /* SwitchKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(244 /* CaseBlock */); - parseExpected(17 /* OpenBraceToken */); + parseExpected(21 /* CloseParenToken */); + var caseBlock = createNode(246 /* CaseBlock */); + parseExpected(18 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); node.caseBlock = finishNode(caseBlock); return finishNode(node); } @@ -19746,32 +20617,32 @@ 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(232 /* ThrowStatement */); - parseExpected(100 /* ThrowKeyword */); + var node = createNode(234 /* ThrowStatement */); + parseExpected(101 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(233 /* TryStatement */); - parseExpected(102 /* TryKeyword */); + var node = createNode(235 /* TryStatement */); + parseExpected(103 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token() === 87 /* FinallyKeyword */) { - parseExpected(87 /* FinallyKeyword */); + if (!node.catchClause || token() === 88 /* FinallyKeyword */) { + parseExpected(88 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(272 /* CatchClause */); - parseExpected(74 /* CatchKeyword */); - if (parseOptional(19 /* OpenParenToken */)) { + var result = createNode(274 /* CatchClause */); + parseExpected(75 /* CatchKeyword */); + if (parseOptional(20 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); } else { // Keep shape of node to avoid degrading performance. @@ -19781,8 +20652,8 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(234 /* DebuggerStatement */); - parseExpected(78 /* DebuggerKeyword */); + var node = createNode(236 /* DebuggerStatement */); + parseExpected(79 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); } @@ -19792,13 +20663,13 @@ var ts; // a colon. var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); - if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - node.kind = 231 /* LabeledStatement */; + if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) { + node.kind = 233 /* LabeledStatement */; node.label = expression; node.statement = parseStatement(); } else { - node.kind = 219 /* ExpressionStatement */; + node.kind = 221 /* ExpressionStatement */; node.expression = expression; parseSemicolon(); } @@ -19810,25 +20681,25 @@ var ts; } function nextTokenIsClassKeywordOnSameLine() { nextToken(); - return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: return true; // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; // however, an identifier cannot be followed by another identifier on the same line. This is what we @@ -19851,41 +20722,41 @@ var ts; // I {} // // could be legal, it would add complexity for very little gain. - case 109 /* InterfaceKeyword */: - case 139 /* TypeKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 132 /* ReadonlyKeyword */: + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: nextToken(); // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 144 /* GlobalKeyword */: + case 145 /* GlobalKeyword */: nextToken(); - return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; - case 91 /* ImportKeyword */: + return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */; + case 92 /* ImportKeyword */: nextToken(); - return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); - case 84 /* ExportKeyword */: + return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 85 /* ExportKeyword */: nextToken(); - if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ || - token() === 118 /* AsKeyword */) { + if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ || + token() === 119 /* AsKeyword */) { return true; } continue; - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: nextToken(); continue; default: @@ -19898,50 +20769,50 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 57 /* AtToken */: - case 25 /* SemicolonToken */: - case 17 /* OpenBraceToken */: - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 90 /* IfKeyword */: - case 81 /* DoKeyword */: - case 106 /* WhileKeyword */: - case 88 /* ForKeyword */: - case 77 /* ContinueKeyword */: - case 72 /* BreakKeyword */: - case 96 /* ReturnKeyword */: - case 107 /* WithKeyword */: - case 98 /* SwitchKeyword */: - case 100 /* ThrowKeyword */: - case 102 /* TryKeyword */: - case 78 /* DebuggerKeyword */: + case 58 /* AtToken */: + case 26 /* SemicolonToken */: + case 18 /* OpenBraceToken */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 91 /* IfKeyword */: + case 82 /* DoKeyword */: + case 107 /* WhileKeyword */: + case 89 /* ForKeyword */: + case 78 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 97 /* ReturnKeyword */: + case 108 /* WithKeyword */: + case 99 /* SwitchKeyword */: + case 101 /* ThrowKeyword */: + case 103 /* TryKeyword */: + case 79 /* DebuggerKeyword */: // 'catch' and 'finally' do not actually indicate that the code is part of a statement, // however, we say they are here so that we may gracefully parse them and error later. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return true; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); - case 76 /* ConstKeyword */: - case 84 /* ExportKeyword */: + case 77 /* ConstKeyword */: + case 85 /* ExportKeyword */: return isStartOfDeclaration(); - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 109 /* InterfaceKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: - case 139 /* TypeKeyword */: - case 144 /* GlobalKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 110 /* InterfaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 140 /* TypeKeyword */: + case 145 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 116 /* StaticKeyword */: + case 133 /* 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); @@ -19951,7 +20822,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */; + return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -19960,67 +20831,67 @@ var ts; } function parseStatement() { switch (token()) { - case 25 /* SemicolonToken */: + case 26 /* SemicolonToken */: return parseEmptyStatement(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); - case 104 /* VarKeyword */: - return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); - case 110 /* LetKeyword */: + case 105 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + case 111 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); } break; - case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(createNodeWithJSDoc(237 /* FunctionDeclaration */)); - case 75 /* ClassKeyword */: - return parseClassDeclaration(createNodeWithJSDoc(238 /* ClassDeclaration */)); - case 90 /* IfKeyword */: + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */)); + case 76 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */)); + case 91 /* IfKeyword */: return parseIfStatement(); - case 81 /* DoKeyword */: + case 82 /* DoKeyword */: return parseDoStatement(); - case 106 /* WhileKeyword */: + case 107 /* WhileKeyword */: return parseWhileStatement(); - case 88 /* ForKeyword */: + case 89 /* ForKeyword */: return parseForOrForInOrForOfStatement(); - case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(226 /* ContinueStatement */); - case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(227 /* BreakStatement */); - case 96 /* ReturnKeyword */: + case 78 /* ContinueKeyword */: + return parseBreakOrContinueStatement(228 /* ContinueStatement */); + case 73 /* BreakKeyword */: + return parseBreakOrContinueStatement(229 /* BreakStatement */); + case 97 /* ReturnKeyword */: return parseReturnStatement(); - case 107 /* WithKeyword */: + case 108 /* WithKeyword */: return parseWithStatement(); - case 98 /* SwitchKeyword */: + case 99 /* SwitchKeyword */: return parseSwitchStatement(); - case 100 /* ThrowKeyword */: + case 101 /* ThrowKeyword */: return parseThrowStatement(); - case 102 /* TryKeyword */: + case 103 /* TryKeyword */: // Include 'catch' and 'finally' for error recovery. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return parseTryStatement(); - case 78 /* DebuggerKeyword */: + case 79 /* DebuggerKeyword */: return parseDebuggerStatement(); - case 57 /* AtToken */: + case 58 /* AtToken */: return parseDeclaration(); - case 120 /* AsyncKeyword */: - case 109 /* InterfaceKeyword */: - case 139 /* TypeKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 83 /* EnumKeyword */: - case 84 /* ExportKeyword */: - case 91 /* ImportKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: - case 144 /* GlobalKeyword */: + case 121 /* AsyncKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 84 /* EnumKeyword */: + case 85 /* ExportKeyword */: + case 92 /* ImportKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 118 /* AbstractKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + case 145 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -20029,7 +20900,7 @@ var ts; return parseExpressionOrLabeledStatement(); } function isDeclareModifier(modifier) { - return modifier.kind === 124 /* DeclareKeyword */; + return modifier.kind === 125 /* DeclareKeyword */; } function parseDeclaration() { var node = createNodeWithJSDoc(0 /* Unknown */); @@ -20048,33 +20919,33 @@ var ts; } function parseDeclarationWorker(node) { switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: return parseVariableStatement(node); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseFunctionDeclaration(node); - case 75 /* ClassKeyword */: + case 76 /* ClassKeyword */: return parseClassDeclaration(node); - case 109 /* InterfaceKeyword */: + case 110 /* InterfaceKeyword */: return parseInterfaceDeclaration(node); - case 139 /* TypeKeyword */: + case 140 /* TypeKeyword */: return parseTypeAliasDeclaration(node); - case 83 /* EnumKeyword */: + case 84 /* EnumKeyword */: return parseEnumDeclaration(node); - case 144 /* GlobalKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: + case 145 /* GlobalKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: return parseModuleDeclaration(node); - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return parseImportDeclarationOrImportEqualsDeclaration(node); - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: nextToken(); switch (token()) { - case 79 /* DefaultKeyword */: - case 58 /* EqualsToken */: + case 80 /* DefaultKeyword */: + case 59 /* EqualsToken */: return parseExportAssignment(node); - case 118 /* AsKeyword */: + case 119 /* AsKeyword */: return parseNamespaceExportDeclaration(node); default: return parseExportDeclaration(node); @@ -20083,7 +20954,7 @@ var ts; if (node.decorators || node.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 missing = createMissingNode(256 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; @@ -20094,10 +20965,10 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) { + if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -20105,25 +20976,25 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token() === 26 /* CommaToken */) { - return createNode(208 /* OmittedExpression */); + if (token() === 27 /* CommaToken */) { + return createNode(210 /* OmittedExpression */); } - var node = createNode(184 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(184 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56 /* ColonToken */) { + if (tokenIsIdentifier && token() !== 57 /* ColonToken */) { node.name = propertyName; } else { - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -20131,27 +21002,27 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(182 /* ObjectBindingPattern */); - parseExpected(17 /* OpenBraceToken */); + var node = createNode(184 /* ObjectBindingPattern */); + parseExpected(18 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(183 /* ArrayBindingPattern */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(185 /* ArrayBindingPattern */); + parseExpected(22 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier(); + return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -20160,10 +21031,10 @@ var ts; return parseVariableDeclaration(/*allowExclamation*/ true); } function parseVariableDeclaration(allowExclamation) { - var node = createNode(235 /* VariableDeclaration */); + var node = createNode(237 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); - if (allowExclamation && node.name.kind === 71 /* Identifier */ && - token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (allowExclamation && node.name.kind === 72 /* Identifier */ && + token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -20173,14 +21044,14 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(236 /* VariableDeclarationList */); + var node = createNode(238 /* VariableDeclarationList */); switch (token()) { - case 104 /* VarKeyword */: + case 105 /* VarKeyword */: break; - case 110 /* LetKeyword */: + case 111 /* LetKeyword */: node.flags |= 1 /* Let */; break; - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: node.flags |= 2 /* Const */; break; default: @@ -20196,7 +21067,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() === 145 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -20208,44 +21079,44 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; + return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */; } function parseVariableStatement(node) { - node.kind = 217 /* VariableStatement */; + node.kind = 219 /* VariableStatement */; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return finishNode(node); } function parseFunctionDeclaration(node) { - node.kind = 237 /* FunctionDeclaration */; - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.kind = 239 /* FunctionDeclaration */; + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); return finishNode(node); } function parseConstructorDeclaration(node) { - node.kind = 155 /* Constructor */; - parseExpected(123 /* ConstructorKeyword */); - fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.kind = 157 /* Constructor */; + parseExpected(124 /* ConstructorKeyword */); + fillSignature(57 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); return finishNode(node); } function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { - node.kind = 154 /* MethodDeclaration */; + node.kind = 156 /* MethodDeclaration */; node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); return finishNode(node); } function parsePropertyDeclaration(node) { - node.kind = 152 /* PropertyDeclaration */; - if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.kind = 154 /* PropertyDeclaration */; + if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -20265,12 +21136,12 @@ var ts; return finishNode(node); } function parsePropertyOrMethodDeclaration(node) { - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } return parsePropertyDeclaration(node); @@ -20278,13 +21149,13 @@ var ts; function parseAccessorDeclaration(node, kind) { node.kind = kind; node.name = parsePropertyName(); - fillSignature(56 /* ColonToken */, 0 /* None */, node); + fillSignature(57 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */); return finishNode(node); } function isClassMemberStart() { var idToken; - if (token() === 57 /* AtToken */) { + if (token() === 58 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. @@ -20301,7 +21172,7 @@ var ts; } nextToken(); } - if (token() === 39 /* AsteriskToken */) { + if (token() === 40 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. @@ -20311,24 +21182,24 @@ var ts; nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... if (idToken !== undefined) { // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!ts.isKeyword(idToken) || idToken === 136 /* SetKeyword */ || idToken === 125 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. switch (token()) { - case 19 /* OpenParenToken */: // Method declaration - case 27 /* LessThanToken */: // Generic Method declaration - case 51 /* ExclamationToken */: // Non-null assertion on property name - case 56 /* ColonToken */: // Type Annotation for declaration - case 58 /* EqualsToken */: // Initializer for declaration - case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. + case 20 /* OpenParenToken */: // Method declaration + case 28 /* LessThanToken */: // Generic Method declaration + case 52 /* ExclamationToken */: // Non-null assertion on property name + case 57 /* ColonToken */: // Type Annotation for declaration + case 59 /* EqualsToken */: // Initializer for declaration + case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. return true; default: // Covers @@ -20346,10 +21217,10 @@ var ts; var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(57 /* AtToken */)) { + if (!parseOptional(58 /* AtToken */)) { break; } - var decorator = createNode(150 /* Decorator */, decoratorStart); + var decorator = createNode(152 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -20369,7 +21240,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) { + if (token() === 77 /* 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)) { @@ -20388,7 +21259,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -20398,21 +21269,21 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 25 /* SemicolonToken */) { - var result = createNode(215 /* SemicolonClassElement */); + if (token() === 26 /* SemicolonToken */) { + var result = createNode(217 /* SemicolonClassElement */); nextToken(); return finishNode(result); } var node = createNodeWithJSDoc(0 /* Unknown */); node.decorators = parseDecorators(); node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* GetAccessor */); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); } - if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 157 /* SetAccessor */); + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); } - if (token() === 123 /* ConstructorKeyword */) { + if (token() === 124 /* ConstructorKeyword */) { return parseConstructorDeclaration(node); } if (isIndexSignature()) { @@ -20421,37 +21292,37 @@ var ts; // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || + token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || - token() === 39 /* AsteriskToken */ || - token() === 21 /* OpenBracketToken */) { + token() === 40 /* AsteriskToken */ || + token() === 22 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(node); } if (node.decorators || node.modifiers) { // treat this as a property declaration with a missing name. - node.name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 207 /* ClassExpression */); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */); } function parseClassDeclaration(node) { - return parseClassDeclarationOrExpression(node, 238 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(node, kind) { node.kind = kind; - parseExpected(75 /* ClassKeyword */); + parseExpected(76 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } node.members = parseClassMembers(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -20469,7 +21340,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses() { // ClassTail[Yield,Await] : (Modified) See 14.5 @@ -20481,33 +21352,33 @@ var ts; } function parseHeritageClause() { var tok = token(); - ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. - var node = createNode(271 /* HeritageClause */); + ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(273 /* HeritageClause */); node.token = tok; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); } function parseExpressionWithTypeArguments() { - var node = createNode(209 /* ExpressionWithTypeArguments */); + var node = createNode(211 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); node.typeArguments = tryParseTypeArguments(); return finishNode(node); } function tryParseTypeArguments() { - return token() === 27 /* LessThanToken */ - ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + return token() === 28 /* LessThanToken */ + ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */) : undefined; } function isHeritageClause() { - return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(node) { - node.kind = 239 /* InterfaceDeclaration */; - parseExpected(109 /* InterfaceKeyword */); + node.kind = 241 /* InterfaceDeclaration */; + parseExpected(110 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); @@ -20515,11 +21386,11 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(node) { - node.kind = 240 /* TypeAliasDeclaration */; - parseExpected(139 /* TypeKeyword */); + node.kind = 242 /* TypeAliasDeclaration */; + parseExpected(140 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(58 /* EqualsToken */); + parseExpected(59 /* EqualsToken */); node.type = parseType(); parseSemicolon(); return finishNode(node); @@ -20529,18 +21400,18 @@ 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 = createNodeWithJSDoc(276 /* EnumMember */); + var node = createNodeWithJSDoc(278 /* EnumMember */); node.name = parsePropertyName(); node.initializer = allowInAnd(parseInitializer); return finishNode(node); } function parseEnumDeclaration(node) { - node.kind = 241 /* EnumDeclaration */; - parseExpected(83 /* EnumKeyword */); + node.kind = 243 /* EnumDeclaration */; + parseExpected(84 /* EnumKeyword */); node.name = parseIdentifier(); - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -20548,10 +21419,10 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(243 /* ModuleBlock */); - if (parseExpected(17 /* OpenBraceToken */)) { + var node = createNode(245 /* ModuleBlock */); + if (parseExpected(18 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -20559,20 +21430,20 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(node, flags) { - node.kind = 242 /* ModuleDeclaration */; + node.kind = 244 /* ModuleDeclaration */; // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(23 /* DotToken */) + node.body = parseOptional(24 /* DotToken */) ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(node) { - node.kind = 242 /* ModuleDeclaration */; - if (token() === 144 /* GlobalKeyword */) { + node.kind = 244 /* ModuleDeclaration */; + if (token() === 145 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -20581,7 +21452,7 @@ var ts; node.name = parseLiteralNode(); node.name.text = internIdentifier(node.name.text); } - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -20591,68 +21462,68 @@ var ts; } function parseModuleDeclaration(node) { var flags = 0; - if (token() === 144 /* GlobalKeyword */) { + if (token() === 145 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(node); } - else if (parseOptional(130 /* NamespaceKeyword */)) { + else if (parseOptional(131 /* NamespaceKeyword */)) { flags |= 16 /* Namespace */; } else { - parseExpected(129 /* ModuleKeyword */); - if (token() === 9 /* StringLiteral */) { + parseExpected(130 /* ModuleKeyword */); + if (token() === 10 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(node); } } return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { - return token() === 133 /* RequireKeyword */ && + return token() === 134 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 19 /* OpenParenToken */; + return nextToken() === 20 /* OpenParenToken */; } function nextTokenIsSlash() { - return nextToken() === 41 /* SlashToken */; + return nextToken() === 42 /* SlashToken */; } function parseNamespaceExportDeclaration(node) { - node.kind = 245 /* NamespaceExportDeclaration */; - parseExpected(118 /* AsKeyword */); - parseExpected(130 /* NamespaceKeyword */); + node.kind = 247 /* NamespaceExportDeclaration */; + parseExpected(119 /* AsKeyword */); + parseExpected(131 /* NamespaceKeyword */); node.name = parseIdentifier(); parseSemicolon(); return finishNode(node); } function parseImportDeclarationOrImportEqualsDeclaration(node) { - parseExpected(91 /* ImportKeyword */); + parseExpected(92 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 143 /* FromKeyword */) { + if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) { return parseImportEqualsDeclaration(node, identifier); } } // Import statement - node.kind = 247 /* ImportDeclaration */; + node.kind = 249 /* ImportDeclaration */; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || // import id - token() === 39 /* AsteriskToken */ || // import * - token() === 17 /* OpenBraceToken */) { // import { + token() === 40 /* AsteriskToken */ || // import * + token() === 18 /* OpenBraceToken */) { // import { node.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(143 /* FromKeyword */); + parseExpected(144 /* FromKeyword */); } node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(node); } function parseImportEqualsDeclaration(node, identifier) { - node.kind = 246 /* ImportEqualsDeclaration */; + node.kind = 248 /* ImportEqualsDeclaration */; node.name = identifier; - parseExpected(58 /* EqualsToken */); + parseExpected(59 /* EqualsToken */); node.moduleReference = parseModuleReference(); parseSemicolon(); return finishNode(node); @@ -20664,7 +21535,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(248 /* ImportClause */, fullStart); + var importClause = createNode(250 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -20673,8 +21544,8 @@ var ts; // If there was no default import or if there is comma token after default import // parse namespace or named imports if (!importClause.name || - parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(250 /* NamedImports */); + parseOptional(27 /* CommaToken */)) { + importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */); } return finishNode(importClause); } @@ -20684,15 +21555,15 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(257 /* ExternalModuleReference */); - parseExpected(133 /* RequireKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(259 /* ExternalModuleReference */); + parseExpected(134 /* RequireKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = parseModuleSpecifier(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9 /* StringLiteral */) { + if (token() === 10 /* StringLiteral */) { var result = parseLiteralNode(); result.text = internIdentifier(result.text); return result; @@ -20707,9 +21578,9 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(249 /* NamespaceImport */); - parseExpected(39 /* AsteriskToken */); - parseExpected(118 /* AsKeyword */); + var namespaceImport = createNode(251 /* NamespaceImport */); + parseExpected(40 /* AsteriskToken */); + parseExpected(119 /* AsKeyword */); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } @@ -20722,14 +21593,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(255 /* ExportSpecifier */); + return parseImportOrExportSpecifier(257 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(251 /* ImportSpecifier */); + return parseImportOrExportSpecifier(253 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -20743,9 +21614,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 118 /* AsKeyword */) { + if (token() === 119 /* AsKeyword */) { node.propertyName = identifierName; - parseExpected(118 /* AsKeyword */); + parseExpected(119 /* AsKeyword */); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -20754,24 +21625,24 @@ var ts; else { node.name = identifierName; } - if (kind === 251 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(node) { - node.kind = 253 /* ExportDeclaration */; - if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(143 /* FromKeyword */); + node.kind = 255 /* ExportDeclaration */; + if (parseOptional(40 /* AsteriskToken */)) { + parseExpected(144 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(254 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(256 /* 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() === 143 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(143 /* FromKeyword */); + if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(144 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -20779,12 +21650,12 @@ var ts; return finishNode(node); } function parseExportAssignment(node) { - node.kind = 252 /* ExportAssignment */; - if (parseOptional(58 /* EqualsToken */)) { + node.kind = 254 /* ExportAssignment */; + if (parseOptional(59 /* EqualsToken */)) { node.isExportEquals = true; } else { - parseExpected(79 /* DefaultKeyword */); + parseExpected(80 /* DefaultKeyword */); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -20799,10 +21670,10 @@ var ts; } function isAnExternalModuleIndicatorNode(node) { return ts.hasModifier(node, 1 /* Export */) - || node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */ - || node.kind === 247 /* ImportDeclaration */ - || node.kind === 252 /* ExportAssignment */ - || node.kind === 253 /* ExportDeclaration */ + || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */ + || node.kind === 249 /* ImportDeclaration */ + || node.kind === 254 /* ExportAssignment */ + || node.kind === 255 /* ExportDeclaration */ ? node : undefined; } @@ -20815,7 +21686,7 @@ var ts; return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); } function isImportMeta(node) { - return ts.isMetaProperty(node) && node.keywordToken === 91 /* ImportKeyword */ && node.name.escapedText === "meta"; + return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta"; } var ParsingContext; (function (ParsingContext) { @@ -20866,11 +21737,11 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); - var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); + var result = createNode(283 /* JSDocTypeExpression */); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } fixupParentReferences(result); return finishNode(result); @@ -20958,7 +21829,7 @@ var ts; } loop: while (true) { switch (token()) { - case 57 /* AtToken */: + case 58 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingWhitespace(comments); addTag(parseTag(indent)); @@ -20978,7 +21849,7 @@ var ts; state = 0 /* BeginningOfLine */; indent = 0; break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: var asterisk = scanner.getTokenText(); if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { // If we've already seen an asterisk, then we can no longer parse a tag on this line @@ -20991,13 +21862,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21012,7 +21876,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21034,7 +21900,7 @@ var ts; } } function createJSDocComment() { - var result = createNode(289 /* JSDocComment */, start); + var result = createNode(291 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -21068,61 +21934,60 @@ var ts; } } var precedingLineBreak = scanner.hasPrecedingLineBreak(); - while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { if (token() === 4 /* NewLineTrivia */) { precedingLineBreak = true; } - else if (token() === 39 /* AsteriskToken */) { + else if (token() === 40 /* AsteriskToken */) { precedingLineBreak = false; } nextJSDocToken(); } } function parseTag(indent) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getTokenPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": case "extends": - tag = parseAugmentsTag(atToken, tagName); + tag = parseAugmentsTag(start, tagName); break; case "class": case "constructor": - tag = parseClassTag(atToken, tagName); + tag = parseClassTag(start, tagName); break; case "this": - tag = parseThisTag(atToken, tagName); + tag = parseThisTag(start, tagName); break; case "enum": - tag = parseEnumTag(atToken, tagName); + tag = parseEnumTag(start, tagName); break; case "arg": case "argument": case "param": - return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent); + return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent); case "return": case "returns": - tag = parseReturnTag(atToken, tagName); + tag = parseReturnTag(start, tagName); break; case "template": - tag = parseTemplateTag(atToken, tagName); + tag = parseTemplateTag(start, tagName); break; case "type": - tag = parseTypeTag(atToken, tagName); + tag = parseTypeTag(start, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName, indent); + tag = parseTypedefTag(start, tagName, indent); break; case "callback": - tag = parseCallbackTag(atToken, tagName, indent); + tag = parseCallbackTag(start, tagName, indent); break; default: - tag = parseUnknownTag(atToken, tagName); + tag = parseUnknownTag(start, tagName); break; } if (!tag.comment) { @@ -21152,7 +22017,7 @@ var ts; } indent = 0; break; - case 57 /* AtToken */: + case 58 /* AtToken */: scanner.setTextPos(scanner.getTextPos() - 1); // falls through case 1 /* EndOfFileToken */: @@ -21171,9 +22036,9 @@ var ts; indent += whitespace.length; } break; - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: state = 2 /* SavingComments */; - if (lookAhead(function () { return nextJSDocToken() === 57 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { pushComment(scanner.getTokenText()); nextJSDocToken(); pushComment(scanner.getTokenText()); @@ -21181,7 +22046,7 @@ var ts; } pushComment(scanner.getTokenText()); break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; @@ -21201,9 +22066,8 @@ var ts; removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } - function parseUnknownTag(atToken, tagName) { - var result = createNode(292 /* JSDocTag */, atToken.pos); - result.atToken = atToken; + function parseUnknownTag(start, tagName) { + var result = createNode(294 /* JSDocTag */, start); result.tagName = tagName; return finishNode(result); } @@ -21222,37 +22086,37 @@ var ts; } function tryParseTypeExpression() { skipWhitespaceOrAsterisk(); - return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; + return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { - if (token() === 13 /* NoSubstitutionTemplateLiteral */) { + if (token() === 14 /* NoSubstitutionTemplateLiteral */) { // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; } // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' - var isBracketed = parseOptional(21 /* OpenBracketToken */); + var isBracketed = parseOptional(22 /* OpenBracketToken */); var name = parseJSDocEntityName(); if (isBracketed) { skipWhitespace(); // May have an optional default, e.g. '[foo = 42]' - if (parseOptionalToken(58 /* EqualsToken */)) { + if (parseOptionalToken(59 /* EqualsToken */)) { parseExpression(); } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); } return { name: name, isBracketed: isBracketed }; } function isObjectOrObjectArrayTypeReference(node) { switch (node.kind) { - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return true; - case 167 /* ArrayType */: + case 169 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; } } - function parseParameterOrPropertyTag(atToken, tagName, target, indent) { + function parseParameterOrPropertyTag(start, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -21262,17 +22126,14 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(303 /* JSDocPropertyTag */, atToken.pos) : - createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + createNode(305 /* JSDocPropertyTag */, start) : + createNode(299 /* JSDocParameterTag */, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; } - result.atToken = atToken; result.tagName = tagName; result.typeExpression = typeExpression; result.name = name; @@ -21281,22 +22142,22 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 167 /* ArrayType */) { + if (typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -21304,81 +22165,74 @@ var ts; } } } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) { + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(298 /* JSDocReturnTag */, atToken.pos); - result.atToken = atToken; + var result = createNode(300 /* JSDocReturnTag */, start); result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) { + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(300 /* JSDocTypeTag */, atToken.pos); - result.atToken = atToken; + var result = createNode(302 /* JSDocTypeTag */, start); result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } - function parseAugmentsTag(atToken, tagName) { - var result = createNode(293 /* JSDocAugmentsTag */, atToken.pos); - result.atToken = atToken; + function parseAugmentsTag(start, tagName) { + var result = createNode(295 /* JSDocAugmentsTag */, start); result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } function parseExpressionWithTypeArgumentsForAugments() { - var usedBrace = parseOptional(17 /* OpenBraceToken */); - var node = createNode(209 /* ExpressionWithTypeArguments */); + var usedBrace = parseOptional(18 /* OpenBraceToken */); + var node = createNode(211 /* ExpressionWithTypeArguments */); node.expression = parsePropertyAccessEntityNameExpression(); node.typeArguments = tryParseTypeArguments(); var res = finishNode(node); if (usedBrace) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } return res; } function parsePropertyAccessEntityNameExpression() { var node = parseJSDocIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var prop = createNode(187 /* PropertyAccessExpression */, node.pos); + while (parseOptional(24 /* DotToken */)) { + var prop = createNode(189 /* PropertyAccessExpression */, node.pos); prop.expression = node; prop.name = parseJSDocIdentifierName(); node = finishNode(prop); } return node; } - function parseClassTag(atToken, tagName) { - var tag = createNode(294 /* JSDocClassTag */, atToken.pos); - tag.atToken = atToken; + function parseClassTag(start, tagName) { + var tag = createNode(296 /* JSDocClassTag */, start); tag.tagName = tagName; return finishNode(tag); } - function parseThisTag(atToken, tagName) { - var tag = createNode(299 /* JSDocThisTag */, atToken.pos); - tag.atToken = atToken; + function parseThisTag(start, tagName) { + var tag = createNode(301 /* JSDocThisTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseEnumTag(atToken, tagName) { - var tag = createNode(296 /* JSDocEnumTag */, atToken.pos); - tag.atToken = atToken; + function parseEnumTag(start, tagName) { + var tag = createNode(298 /* JSDocEnumTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseTypedefTag(atToken, tagName, indent) { + function parseTypedefTag(start, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); - typedefTag.atToken = atToken; + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304 /* JSDocTypedefTag */, start); typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); @@ -21390,12 +22244,11 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); } - if (child.kind === 300 /* JSDocTypeTag */) { + if (child.kind === 302 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -21408,7 +22261,7 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 167 /* ArrayType */) { + if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? @@ -21426,8 +22279,8 @@ var ts; return undefined; } var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(242 /* ModuleDeclaration */, pos); + if (parseOptional(24 /* DotToken */)) { + var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos); if (nested) { jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } @@ -21440,25 +22293,23 @@ var ts; } return typeNameOrNamespaceName; } - function parseCallbackTag(atToken, tagName, indent) { - var callbackTag = createNode(295 /* JSDocCallbackTag */, atToken.pos); - callbackTag.atToken = atToken; + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297 /* JSDocCallbackTag */, start); callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); skipWhitespace(); callbackTag.comment = parseTagComments(indent); var child; - var start = scanner.getStartPos(); - var jsdocSignature = createNode(291 /* JSDocSignature */, start); + var jsdocSignature = createNode(293 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { - if (parseOptionalJsdoc(57 /* AtToken */)) { + if (parseOptionalJsdoc(58 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 298 /* JSDocReturnTag */) { + if (tag && tag.kind === 300 /* JSDocReturnTag */) { return tag; } } @@ -21492,18 +22343,18 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { - case 57 /* AtToken */: + case 58 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); - if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -21516,13 +22367,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 71 /* Identifier */: + case 72 /* Identifier */: canParseTag = false; break; case 1 /* EndOfFileToken */: @@ -21530,17 +22381,16 @@ var ts; } } } - function tryParseChildTag(target) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */); - atToken.end = scanner.getTextPos(); + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getStartPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); skipWhitespace(); var t; switch (tagName.escapedText) { case "type": - return target === 1 /* Property */ && parseTypeTag(atToken, tagName); + return target === 1 /* Property */ && parseTypeTag(start, tagName); case "prop": case "property": t = 1 /* Property */; @@ -21556,28 +22406,25 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(start, tagName, target, indent); } - function parseTemplateTag(atToken, tagName) { + function parseTemplateTag(start, tagName) { // the template tag looks like '@template {Constraint} T,U,V' var constraint; - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { constraint = parseJSDocTypeExpression(); } var typeParameters = []; var typeParametersPos = getNodePos(); do { skipWhitespace(); - var typeParameter = createNode(148 /* TypeParameter */); + var typeParameter = createNode(150 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); finishNode(typeParameter); skipWhitespace(); typeParameters.push(typeParameter); - } while (parseOptionalJsdoc(26 /* CommaToken */)); - var result = createNode(301 /* JSDocTemplateTag */, atToken.pos); - result.atToken = atToken; + } while (parseOptionalJsdoc(27 /* CommaToken */)); + var result = createNode(303 /* JSDocTemplateTag */, start); result.tagName = tagName; result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -21596,16 +22443,16 @@ var ts; } function parseJSDocEntityName() { var entity = parseJSDocIdentifierName(); - if (parseOptional(21 /* OpenBracketToken */)) { - parseExpected(22 /* CloseBracketToken */); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> // but it's not worth it to enforce that restriction. } - while (parseOptional(23 /* DotToken */)) { + while (parseOptional(24 /* DotToken */)) { var name = parseJSDocIdentifierName(); - if (parseOptional(21 /* OpenBracketToken */)) { - parseExpected(22 /* CloseBracketToken */); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); } entity = createQualifiedName(entity, name); } @@ -21613,11 +22460,11 @@ var ts; } function parseJSDocIdentifierName(message) { if (!ts.tokenIsIdentifierOrKeyword(token())) { - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(71 /* Identifier */, pos); + var result = createNode(72 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); @@ -21743,9 +22590,9 @@ var ts; } function shouldCheckNode(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 71 /* Identifier */: + case 72 /* Identifier */: return true; } return false; @@ -22323,10 +23170,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 71 /* Identifier */) { + if (lhs.kind === 72 /* Identifier */) { return lhs.escapedText === rhs.escapedText; } - if (lhs.kind === 99 /* ThisKeyword */) { + if (lhs.kind === 100 /* ThisKeyword */) { return true; } // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only @@ -22383,7 +23230,8 @@ var ts; ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.symbol", "lib.esnext.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], - ["esnext.intl", "lib.esnext.intl.d.ts"] + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -22399,8 +23247,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +23261,61 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22455,26 +23357,11 @@ var ts; description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date }, { - name: "pretty", + name: "showConfig", type: "boolean", - showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental - }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, // Basic { @@ -22490,6 +23377,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23397,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23410,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23418,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23436,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23546,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23555,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23564,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23590,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23599,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23633,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23646,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23654,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23664,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23680,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23692,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23703,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22862,42 +23776,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h }, - { - name: "diagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_diagnostic_information - }, - { - name: "extendedDiagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_verbose_diagnostic_information - }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23840,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23860,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23906,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23914,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23942,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23970,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +24061,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +24111,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +24131,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +24139,7 @@ var ts; 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)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +24175,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +24218,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +24243,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23432,6 +24398,9 @@ var ts; } var result = ts.parseJsonText(configFileName, configFileText); var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; @@ -23571,7 +24540,7 @@ var ts; var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 273 /* PropertyAssignment */) { + if (element.kind !== 275 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -23619,20 +24588,24 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { - case 101 /* TrueKeyword */: + case 102 /* TrueKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return true; - case 86 /* FalseKeyword */: + case 87 /* FalseKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return false; - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for return null; // tslint:disable-line:no-null-keyword - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } @@ -23649,13 +24622,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 200 /* PrefixUnaryExpression */: - if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + case 202 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return -Number(valueExpression.operand.text); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -23672,7 +24645,7 @@ var ts; return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); } - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -23712,6 +24685,115 @@ var ts; } return false; } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return false; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + } + return function (path) { return includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return !excludeRe.test(path); }; + } + return function (_) { return false; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } /** * Generate tsconfig configuration when running command line "--init" * @param options commandlineOptions to be generated into tsconfig.json @@ -23722,62 +24804,6 @@ var ts; var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - // There is a typeMap associated with this command-line option so use it to map value back to its name - return ts.forEachEntry(customTypeMap, function (mapValue, key) { - if (mapValue === value) { - return key; - } - }); - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_3 = function (name) { - if (ts.hasProperty(options, name)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - return "continue"; - } - var value = options[name]; - var optionDefinition = optionsNameMap.get(name.toLowerCase()); - if (optionDefinition) { - var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap_1) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result.set(name, value); - } - else { - if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); - } - } - } - } - }; - for (var name in options) { - _loop_3(name); - } - return result; - } function getDefaultValueForOption(option) { switch (option.type) { case "number": @@ -23926,7 +24952,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24970,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23980,19 +25021,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +25040,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +25053,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24110,11 +25165,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24142,26 +25192,30 @@ var ts; } function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { - errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return undefined; - } - var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return undefined; + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } } + return extendedConfigPath; } - return extendedConfigPath; + // If the path isn't a rooted or relative path, resolve like a module + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +25223,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25437,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24408,10 +25462,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24421,9 +25480,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24431,7 +25506,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24442,16 +25517,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24584,7 +25659,7 @@ var ts; } } /** - * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. * Also converts enum values back to strings. */ /* @internal */ @@ -24640,6 +25715,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24649,14 +25730,15 @@ var ts; Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; Extensions[Extensions["Json"] = 2] = "Json"; - Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */ + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25747,97 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24748,9 +25879,13 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24769,8 +25904,10 @@ var ts; trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24779,13 +25916,12 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - if (!options.preserveSymlinks) { - resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); - } + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -24794,14 +25930,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } - return ts.forEach(typeRoots, function (typeRoot) { + return ts.firstDefined(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,8 +25953,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - var resolvedFile = resolvedTypeScriptOnly(result && result.value); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + var resolvedFile = resolvedTypeScriptOnly(result); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -24856,14 +26000,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -24874,29 +26022,56 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); } ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + /*@internal*/ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName) { + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); - var perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = ts.createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); } - function getOrCreateCacheForModuleName(nonRelativeModuleName) { + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); - var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); } - return perModuleNameCache; + return result; } function createPerModuleNameCache() { var directoryPathMap = ts.createMap(); @@ -24971,13 +26146,19 @@ var ts; return perFolderCache && perFolderCache.get(moduleName); } ts.resolveModuleNameFromCache = resolveModuleNameFromCache; - function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } var containingDirectory = ts.getDirectoryPath(containingFile); - var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { @@ -24999,10 +26180,10 @@ var ts; } switch (moduleResolution) { case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; default: return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); @@ -25011,7 +26192,7 @@ var ts; perFolderCache.set(moduleName, result); if (!ts.isExternalModuleNameRelative(moduleName)) { // put result in per-module name cache - cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); } } } @@ -25086,15 +26267,28 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +26326,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +26345,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,95 +26356,72 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!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); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; - function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? - tryResolve(Extensions.JavaScript) : - (tryResolve(Extensions.TypeScript) || - tryResolve(Extensions.JavaScript) || - (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); if (result && result.value) { var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +26435,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +26452,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,10 +26483,15 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; /** * This will be called on the successfully resolved path from `loadModuleFromFile`. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) @@ -25352,52 +26529,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @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; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - if (extensions === Extensions.Json) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25407,16 +26578,17 @@ var ts; return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.TSConfig: case Extensions.Json: return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26602,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26640,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,51 +26652,72 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { - // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25542,6 +26729,7 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TSConfig: case Extensions.Json: return extension === ".json" /* Json */; case Extensions.TypeScript: @@ -25550,87 +26738,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26868,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,68 +26881,69 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } - function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } if (!ts.isExternalModuleNameRelative(moduleName)) { - var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26958,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25758,24 +26989,24 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: if (!(ts.hasModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. other uninstantiated module declarations. - case 243 /* ModuleBlock */: { + case 245 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateWorker(n); @@ -25797,9 +27028,9 @@ var ts; }); return state_1; } - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return getModuleInstanceState(node); - case 71 /* Identifier */: + case 72 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should // be considered the same as type alias if (node.isInJSDocNamespace) { @@ -25944,19 +27175,23 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + 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.kind === 252 /* ExportAssignment */) { + if (node.kind === 254 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -25965,7 +27200,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -25977,36 +27212,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: return "__constructor" /* Constructor */; - case 163 /* FunctionType */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: + case 165 /* FunctionType */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: return "__call" /* Call */; - case 164 /* ConstructorType */: - case 159 /* ConstructSignature */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: return "__new" /* New */; - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return "__index" /* Index */; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 149 /* Parameter */: + case 151 /* 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 === 287 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -26075,7 +27310,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26103,7 +27339,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; } @@ -26130,7 +27366,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 255 /* ExportSpecifier */ || (node.kind === 246 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -26153,12 +27389,12 @@ var ts; // 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.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26197,7 +27433,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 195 /* ArrowFunction */) { + if (node.kind !== 197 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -26229,7 +27465,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property intialization checks. - currentReturnTarget = isIIFE || node.kind === 155 /* Constructor */ ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; @@ -26242,13 +27478,13 @@ var ts; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { node.flags |= emitFlags; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 155 /* Constructor */) { + if (node.kind === 157 /* Constructor */) { node.returnFlowNode = currentFlow; } } @@ -26291,8 +27527,8 @@ var ts; } } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -26321,81 +27557,82 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: bindWhileStatement(node); break; - case 221 /* DoStatement */: + case 223 /* DoStatement */: bindDoStatement(node); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: bindForStatement(node); break; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: bindIfStatement(node); break; - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: bindTryStatement(node); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: bindSwitchStatement(node); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: bindCaseBlock(node); break; - case 269 /* CaseClause */: + case 271 /* CaseClause */: bindCaseClause(node); break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: bindLabeledStatement(node); break; - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: bindCallExpressionFlow(node); break; - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 277 /* SourceFile */: { + case 279 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; default: @@ -26406,24 +27643,26 @@ var ts; } function isNarrowingExpression(expr) { switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return isNarrowableReference(expr); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return hasNarrowableArgument(expr); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 200 /* PrefixUnaryExpression */: - return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 202 /* PrefixUnaryExpression */: + return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 199 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || + return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && @@ -26438,7 +27677,7 @@ var ts; } } } - if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26452,32 +27691,32 @@ var ts; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return isNarrowableReference(expr.left); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); - case 92 /* InKeyword */: + case 93 /* InKeyword */: return isNarrowableInOperands(expr.left, expr.right); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return isNarrowableOperand(expr.right); } } @@ -26512,8 +27751,8 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -26551,34 +27790,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 220 /* IfStatement */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: return parent.expression === node; - case 223 /* ForStatement */: - case 203 /* ConditionalExpression */: + case 225 /* ForStatement */: + case 205 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 193 /* ParenthesizedExpression */) { + if (node.kind === 195 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 200 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 202 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 54 /* BarBarToken */); + return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 55 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 193 /* ParenthesizedExpression */ || - node.parent.kind === 200 /* PrefixUnaryExpression */ && - node.parent.operator === 51 /* ExclamationToken */) { + while (node.parent.kind === 195 /* ParenthesizedExpression */ || + node.parent.kind === 202 /* PrefixUnaryExpression */ && + node.parent.operator === 52 /* ExclamationToken */) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -26619,7 +27858,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 231 /* LabeledStatement */ + var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */ ? ts.lastOrUndefined(activeLabels) : undefined; // if do statement is wrapped in labeled statement then target labels for break/continue with or without @@ -26653,13 +27892,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 225 /* ForOfStatement */) { + if (node.kind === 227 /* ForOfStatement */) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 236 /* VariableDeclarationList */) { + if (node.initializer.kind !== 238 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -26681,7 +27920,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 228 /* ReturnStatement */) { + if (node.kind === 230 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -26701,7 +27940,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 227 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -26797,7 +28036,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 270 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; @@ -26821,7 +28060,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -26865,14 +28103,14 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } - if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { + if (!node.statement || node.statement.kind !== 223 /* DoStatement */) { // do statement sets current flow inside bindDoStatement addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -26883,10 +28121,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 185 /* ArrayLiteralExpression */) { + else if (node.kind === 187 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 206 /* SpreadElement */) { + if (e.kind === 208 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -26894,16 +28132,16 @@ var ts; } } } - else if (node.kind === 186 /* ObjectLiteralExpression */) { + else if (node.kind === 188 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 273 /* PropertyAssignment */) { + if (p.kind === 275 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 274 /* ShorthandPropertyAssignment */) { + else if (p.kind === 276 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 275 /* SpreadAssignment */) { + else if (p.kind === 277 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -26911,7 +28149,7 @@ var ts; } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -26922,7 +28160,7 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51 /* ExclamationToken */) { + if (node.operator === 52 /* ExclamationToken */) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; @@ -26932,20 +28170,20 @@ var ts; } else { bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -26959,7 +28197,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 188 /* ElementAccessExpression */) { + if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -26970,7 +28208,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -27008,6 +28246,7 @@ var ts; } } function bindJSDocTypeAlias(node) { + node.tagName.parent = node; if (node.fullName) { setParentPointers(node, node.fullName); } @@ -27017,10 +28256,10 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 193 /* ParenthesizedExpression */) { + while (expr.kind === 195 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 194 /* FunctionExpression */ || expr.kind === 195 /* ArrowFunction */) { + if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -27028,7 +28267,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -27037,54 +28276,54 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 186 /* ObjectLiteralExpression */: - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 266 /* JsxAttributes */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 268 /* JsxAttributes */: return 1 /* IsContainer */; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 179 /* MappedType */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: - case 287 /* JSDocFunctionType */: - case 163 /* FunctionType */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 164 /* ConstructorType */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 289 /* JSDocFunctionType */: + case 165 /* FunctionType */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 166 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 272 /* CatchClause */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 244 /* CaseBlock */: + case 274 /* CatchClause */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 246 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 216 /* Block */: + case 218 /* 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 @@ -27117,45 +28356,45 @@ var ts; // 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 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 277 /* SourceFile */: + case 279 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 186 /* ObjectLiteralExpression */: - case 239 /* InterfaceDeclaration */: - case 266 /* JsxAttributes */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 188 /* ObjectLiteralExpression */: + case 241 /* InterfaceDeclaration */: + case 268 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 291 /* JSDocSignature */: - case 160 /* IndexSignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 287 /* JSDocFunctionType */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 240 /* TypeAliasDeclaration */: - case 179 /* MappedType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 293 /* JSDocSignature */: + case 162 /* IndexSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 289 /* JSDocFunctionType */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -27176,11 +28415,11 @@ var ts; : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 277 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 277 /* SourceFile */ || body.kind === 243 /* ModuleBlock */)) { + var body = node.kind === 279 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 253 /* ExportDeclaration */ || stat.kind === 252 /* ExportAssignment */) { + if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { return true; } } @@ -27208,7 +28447,7 @@ var ts; } else { var pattern = void 0; - if (node.name.kind === 9 /* StringLiteral */) { + if (node.name.kind === 10 /* StringLiteral */) { var text = node.name.text; if (ts.hasZeroOrOneAsteriskCharacter(text)) { pattern = ts.tryParsePattern(text); @@ -27217,7 +28456,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +28476,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27264,7 +28503,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) { continue; } var identifier = prop.name; @@ -27276,7 +28515,7 @@ var ts; // 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 === 273 /* PropertyAssignment */ || prop.kind === 274 /* ShorthandPropertyAssignment */ || prop.kind === 154 /* MethodDeclaration */ + var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -27308,10 +28547,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -27325,9 +28564,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27345,9 +28581,9 @@ var ts; currentFlow = { flags: 2 /* Start */ }; parent = typeAlias; bind(typeAlias.typeExpression); - if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { + if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27363,8 +28599,8 @@ var ts; // check for reserved words used as identifiers in strict mode code. function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && + node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 117 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && !(node.flags & 4194304 /* Ambient */)) { // Report error only if there are no parse errors in file @@ -27400,7 +28636,7 @@ var ts; } function checkStrictModeDeleteExpression(node) { // Grammar checking - if (inStrictMode && node.expression.kind === 71 /* Identifier */) { + if (inStrictMode && node.expression.kind === 72 /* 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); @@ -27411,7 +28647,7 @@ var ts; return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71 /* Identifier */) { + if (name && name.kind === 72 /* 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 @@ -27452,8 +28688,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 277 /* SourceFile */ && - blockScopeContainer.kind !== 242 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 279 /* SourceFile */ && + blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -27479,7 +28715,7 @@ var ts; function checkStrictModePrefixUnaryExpression(node) { // Grammar checking if (inStrictMode) { - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -27548,7 +28784,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 145 /* LastToken */) { + if (node.kind > 147 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -27572,7 +28808,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27610,7 +28846,7 @@ var ts; function bindWorker(node) { switch (node.kind) { /* Strict mode checks */ - case 71 /* Identifier */: + case 72 /* Identifier */: // for typedef type names with namespaces, bind the new jsdoc type symbol here // because it requires all containing namespaces to be in effect, namely the // current "blockScopeContainer" needs to be set to its immediate namespace parent. @@ -27619,32 +28855,32 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through - case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 274 /* ShorthandPropertyAssignment */)) { + case 100 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; - case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27668,142 +28904,155 @@ var ts; // Nothing to do break; default: - ts.Debug.fail("Unknown special property assignment kind"); + ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return checkStrictModeCatchClause(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return checkStrictModeWithStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 176 /* ThisType */: + case 178 /* ThisType */: seenThisKeyword = true; return; - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: break; // Binding the children will handle everything - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return bindTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return bindParameter(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return bindPropertyWorker(node); - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 276 /* EnumMember */: + case 278 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); - case 237 /* FunctionDeclaration */: + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); + case 239 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); - case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); - case 163 /* FunctionType */: - case 287 /* JSDocFunctionType */: - case 291 /* JSDocSignature */: - case 164 /* ConstructorType */: + case 158 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); + case 159 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + case 166 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 179 /* MappedType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 181 /* MappedType */: return bindAnonymousTypeWorker(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return bindFunctionExpression(node); - case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + case 191 /* CallExpression */: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; // Nothing to do + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); - case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - case 241 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); + case 242 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + case 243 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return bindJsxAttributes(node); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return bindImportClause(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return bindExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return bindExportAssignment(node); - case 277 /* SourceFile */: + case 279 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 216 /* Block */: + case 218 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 297 /* JSDocParameterTag */: - if (node.parent.kind === 291 /* JSDocSignature */) { + case 299 /* JSDocParameterTag */: + if (node.parent.kind === 293 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 290 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { break; } // falls through - case 303 /* JSDocPropertyTag */: + case 305 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -27835,37 +29084,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27892,6 +29139,21 @@ var ts; } return true; } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } function bindExportsPropertyAssignment(node) { // When we create a property via 'exports.foo = bar', the 'exports.foo' property access // expression is the declaration @@ -27901,7 +29163,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27928,17 +29190,17 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. - if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) { var l = thisContainer.parent.left; if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); @@ -27951,18 +29213,18 @@ var ts; declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } break; - case 155 /* Constructor */: - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: // this.foo assignment in a source file // Do not bind. It would be nice to support this someday though. break; @@ -27971,10 +29233,10 @@ var ts; } } function bindSpecialPropertyDeclaration(node) { - if (node.expression.kind === 99 /* ThisKeyword */) { + if (node.expression.kind === 100 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 277 /* SourceFile */) { + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -27988,7 +29250,11 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28005,11 +29271,17 @@ var ts; classPrototype.parent = lhs; bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } function bindSpecialPropertyAssignment(node) { var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28033,42 +29305,48 @@ var ts; node.expression.parent = node; bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); } - function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) - : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; - namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ + : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,11 +29355,14 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -28090,7 +29371,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28132,7 +29413,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 238 /* ClassDeclaration */) { + if (node.kind === 240 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); } else { @@ -28174,8 +29455,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,15 +29471,15 @@ var ts; // 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 */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } function bindParameter(node) { - if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -28207,7 +29491,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +29509,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,26 +29550,26 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 174 /* InferType */) { + else if (node.parent.kind === 176 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28300,13 +29584,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 218 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) || // report error on class declarations - node.kind === 238 /* ClassDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,24 +29626,23 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return true; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.hasModifier(s, 2048 /* Const */); default: return false; } } - /* @internal */ function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || @@ -28382,6 +29663,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28393,58 +29677,58 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return computeNewExpression(node, subtreeFlags); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); - case 149 /* Parameter */: + case 151 /* Parameter */: return computeParameter(node, subtreeFlags); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return computeCatchClause(node, subtreeFlags); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 155 /* Constructor */: + case 157 /* Constructor */: return computeConstructor(node, subtreeFlags); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return computePropertyDeclaration(node, subtreeFlags); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return computeMethod(node, subtreeFlags); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -28457,61 +29741,61 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } - if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + if (expression.kind === 92 /* ImportKeyword */) { + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 186 /* ObjectLiteralExpression */) { + if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ESNext if they contain rest transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 185 /* ArrayLiteralExpression */) { + else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ - || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { + else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ + || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28522,25 +29806,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28550,8 +29834,8 @@ 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 (expressionKind === 210 /* AsExpression */ - || expressionKind === 192 /* TypeAssertionExpression */) { + if (expressionKind === 212 /* AsExpression */ + || expressionKind === 194 /* TypeAssertionExpression */) { transformFlags |= 3 /* AssertTypeScript */; } // If the expression of a ParenthesizedExpression is a destructuring assignment, @@ -28575,44 +29859,44 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 85 /* ExtendsKeyword */: + case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; - case 108 /* ImplementsKeyword */: + case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; @@ -28621,7 +29905,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28632,7 +29916,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28644,7 +29928,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28654,11 +29938,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28674,7 +29958,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28685,7 +29969,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28699,11 +29983,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28711,10 +29995,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28726,7 +30010,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28739,13 +30023,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28758,7 +30042,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28774,13 +30058,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28790,7 +30074,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28807,26 +30091,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28834,18 +30120,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28853,7 +30141,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28864,22 +30152,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28888,7 +30176,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28899,7 +30187,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28908,78 +30196,78 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { - case 120 /* AsyncKeyword */: - case 199 /* AwaitExpression */: + case 121 /* AsyncKeyword */: + case 201 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 306 /* PartiallyEmittedExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; break; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 211 /* NonNullExpression */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 213 /* NonNullExpression */: + case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: - case 10 /* JsxText */: - case 261 /* JsxClosingElement */: - case 262 /* JsxFragment */: - case 263 /* JsxOpeningFragment */: - case 264 /* JsxClosingFragment */: - case 265 /* JsxAttribute */: - case 266 /* JsxAttributes */: - case 267 /* JsxSpreadAttribute */: - case 268 /* JsxExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 11 /* JsxText */: + case 263 /* JsxClosingElement */: + case 264 /* JsxFragment */: + case 265 /* JsxOpeningFragment */: + case 266 /* JsxClosingFragment */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 270 /* JsxExpression */: // These nodes are Jsx syntax. transformFlags |= 4 /* AssertJsx */; break; - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 204 /* TemplateExpression */: - case 191 /* TaggedTemplateExpression */: - case 274 /* ShorthandPropertyAssignment */: - case 115 /* StaticKeyword */: - case 212 /* MetaProperty */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + case 276 /* ShorthandPropertyAssignment */: + case 116 /* StaticKeyword */: + case 214 /* MetaProperty */: // These nodes are ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { transformFlags |= 192 /* AssertES2015 */; } @@ -28989,65 +30277,69 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } break; - case 225 /* ForOfStatement */: + case 9 /* BigIntLiteral */: + transformFlags |= 8 /* AssertESNext */; + break; + case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { transformFlags |= 8 /* AssertESNext */; } transformFlags |= 192 /* AssertES2015 */; break; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 148 /* TypeParameter */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 161 /* TypePredicate */: - case 162 /* TypeReference */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 165 /* TypeQuery */: - case 166 /* TypeLiteral */: - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 169 /* OptionalType */: - case 170 /* RestType */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 173 /* ConditionalType */: - case 174 /* InferType */: - case 175 /* ParenthesizedType */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 176 /* ThisType */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 180 /* LiteralType */: - case 245 /* NamespaceExportDeclaration */: + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 163 /* TypePredicate */: + case 164 /* TypeReference */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 167 /* TypeQuery */: + case 168 /* TypeLiteral */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 176 /* InferType */: + case 177 /* ParenthesizedType */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = 3 /* AssertTypeScript */; excludeFlags = -3 /* TypeExcludes */; break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29056,93 +30348,93 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + case 208 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; - case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + case 277 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; - case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + case 184 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; - case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + case 185 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; - case 150 /* Decorator */: + case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; - case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + case 188 /* ObjectLiteralExpression */: + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; } break; - case 185 /* ArrayLiteralExpression */: - case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + case 187 /* ArrayLiteralExpression */: + case 192 /* NewExpression */: + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } break; - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + case 279 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29155,71 +30447,71 @@ var ts; * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather * than calling this function. */ - /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) { + if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { return -3 /* TypeExcludes */; } switch (kind) { - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; - case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; - case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; - case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; - case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 137 /* StringKeyword */: - case 135 /* ObjectKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 148 /* TypeParameter */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 187 /* ArrayLiteralExpression */: + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + case 244 /* ModuleDeclaration */: + return 647001409 /* ModuleExcludes */; + case 151 /* Parameter */: + return 637535553 /* ParameterExcludes */; + case 197 /* ArrowFunction */: + return 653604161 /* ArrowFunctionExcludes */; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return 653620545 /* FunctionExcludes */; + case 238 /* VariableDeclarationList */: + return 639894849 /* VariableDeclarationListExcludes */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 638121281 /* ClassExcludes */; + case 157 /* Constructor */: + return 653616449 /* ConstructorExcludes */; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return 653616449 /* MethodOrAccessorExcludes */; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 138 /* StringKeyword */: + case 136 /* ObjectKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; - case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; - case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 306 /* PartiallyEmittedExpression */: - case 193 /* ParenthesizedExpression */: - case 97 /* SuperKeyword */: + case 188 /* ObjectLiteralExpression */: + return 638358849 /* ObjectLiteralExcludes */; + case 274 /* CatchClause */: + return 637797697 /* CatchClauseExcludes */; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return 637666625 /* BindingPatternExcludes */; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + case 195 /* ParenthesizedExpression */: + case 98 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29277,7 +30569,7 @@ var ts; if (shouldBail) return; // Visit the type's related types, if any - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var objectType = type; var objectFlags = objectType.objectFlags; if (objectFlags & 4 /* Reference */) { @@ -29293,16 +30585,16 @@ var ts; visitObjectType(objectType); } } - if (type.flags & 65536 /* TypeParameter */) { + if (type.flags & 262144 /* TypeParameter */) { visitTypeParameter(type); } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { visitUnionOrIntersectionType(type); } - if (type.flags & 1048576 /* Index */) { + if (type.flags & 4194304 /* Index */) { visitIndexType(type); } - if (type.flags & 2097152 /* IndexedAccess */) { + if (type.flags & 8388608 /* IndexedAccess */) { visitIndexedAccessType(type); } } @@ -29391,7 +30683,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 165 /* TypeQuery */) { + if (d.type && d.type.kind === 167 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -29434,6 +30726,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30758,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29463,10 +30768,12 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); @@ -29625,27 +30932,13 @@ var ts; var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); return parsed ? isImplementationOfOverload(parsed) : undefined; }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return ts.Debug.fail(); - links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); - } - return links.immediateTarget; - }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { - var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isParameter); @@ -29669,15 +30962,17 @@ var ts; getNumberType: function () { return numberType; }, createPromiseType: createPromiseType, createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, getESSymbolType: function () { return esSymbolType; }, getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -29685,7 +30980,7 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, - getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, @@ -29739,7 +31034,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29762,24 +31058,43 @@ var ts; var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); - var undefinedType = createIntrinsicType(8192 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(8192 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(16384 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(16384 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); - var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); - var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); - var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(4096 /* Void */, "void"); - var neverType = createIntrinsicType(32768 /* Never */, "never"); - var silentNeverType = createIntrinsicType(32768 /* Never */, "never"); - var implicitNeverType = createIntrinsicType(32768 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -29792,18 +31107,18 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(65536 /* TypeParameter */); - var markerSubType = createType(65536 /* TypeParameter */); + var markerSuperType = createType(262144 /* TypeParameter */); + var markerSubType = createType(262144 /* TypeParameter */); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(65536 /* TypeParameter */); + var markerOtherType = createType(262144 /* TypeParameter */); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29815,6 +31130,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +31150,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +31162,9 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29852,6 +31172,7 @@ var ts; var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -29877,84 +31198,99 @@ var ts; TypeFacts[TypeFacts["None"] = 0] = "None"; TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; - TypeFacts[TypeFacts["TypeofEQBoolean"] = 4] = "TypeofEQBoolean"; - TypeFacts[TypeFacts["TypeofEQSymbol"] = 8] = "TypeofEQSymbol"; - TypeFacts[TypeFacts["TypeofEQObject"] = 16] = "TypeofEQObject"; - TypeFacts[TypeFacts["TypeofEQFunction"] = 32] = "TypeofEQFunction"; - TypeFacts[TypeFacts["TypeofEQHostObject"] = 64] = "TypeofEQHostObject"; - TypeFacts[TypeFacts["TypeofNEString"] = 128] = "TypeofNEString"; - TypeFacts[TypeFacts["TypeofNENumber"] = 256] = "TypeofNENumber"; - TypeFacts[TypeFacts["TypeofNEBoolean"] = 512] = "TypeofNEBoolean"; - TypeFacts[TypeFacts["TypeofNESymbol"] = 1024] = "TypeofNESymbol"; - TypeFacts[TypeFacts["TypeofNEObject"] = 2048] = "TypeofNEObject"; - TypeFacts[TypeFacts["TypeofNEFunction"] = 4096] = "TypeofNEFunction"; - TypeFacts[TypeFacts["TypeofNEHostObject"] = 8192] = "TypeofNEHostObject"; - TypeFacts[TypeFacts["EQUndefined"] = 16384] = "EQUndefined"; - TypeFacts[TypeFacts["EQNull"] = 32768] = "EQNull"; - TypeFacts[TypeFacts["EQUndefinedOrNull"] = 65536] = "EQUndefinedOrNull"; - TypeFacts[TypeFacts["NEUndefined"] = 131072] = "NEUndefined"; - TypeFacts[TypeFacts["NENull"] = 262144] = "NENull"; - TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; - TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; - TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["All"] = 4194303] = "All"; + TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; + TypeFacts[TypeFacts["All"] = 16777215] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. - TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; - TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; - TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; - TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; - TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; - TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; - TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; - TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; - TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; - TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; - TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; - TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; - TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; - TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; - TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; - TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; - TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; - TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; - TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; - TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; - TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; - TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; - TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; - TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; - TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; - TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts"; + TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts"; + TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, number: 2 /* TypeofEQNumber */, - boolean: 4 /* TypeofEQBoolean */, - symbol: 8 /* TypeofEQSymbol */, - undefined: 16384 /* EQUndefined */, - object: 16 /* TypeofEQObject */, - function: 32 /* TypeofEQFunction */ + bigint: 4 /* TypeofEQBigInt */, + boolean: 8 /* TypeofEQBoolean */, + symbol: 16 /* TypeofEQSymbol */, + undefined: 65536 /* EQUndefined */, + object: 32 /* TypeofEQObject */, + function: 64 /* TypeofEQFunction */ }); var typeofNEFacts = ts.createMapFromTemplate({ - string: 128 /* TypeofNEString */, - number: 256 /* TypeofNENumber */, - boolean: 512 /* TypeofNEBoolean */, - symbol: 1024 /* TypeofNESymbol */, - undefined: 131072 /* NEUndefined */, - object: 2048 /* TypeofNEObject */, - function: 4096 /* TypeofNEFunction */ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ }); var typeofTypesByName = ts.createMapFromTemplate({ string: stringType, number: numberType, + bigint: bigintType, boolean: booleanType, symbol: esSymbolType, undefined: undefinedType @@ -29975,6 +31311,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +31448,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,10 +31509,14 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { - target = cloneSymbol(target); + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); } // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { @@ -30184,8 +31526,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30204,55 +31547,56 @@ var ts; else if (target.flags & 1024 /* NamespaceModule */) { error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } - else { + else { // error var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30268,7 +31612,8 @@ var ts; } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { - target.set(id, target.has(id) ? mergeSymbol(target.get(id), sourceSymbol) : sourceSymbol); + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); }); } function mergeModuleAugmentation(moduleName) { @@ -30330,7 +31675,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { - return node.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -30360,8 +31705,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30388,17 +31733,17 @@ var ts; } if (declaration.pos <= usage.pos) { // declaration is before usage - if (declaration.kind === 184 /* BindingElement */) { + if (declaration.kind === 186 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 184 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 235 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage); } - else if (declaration.kind === 235 /* VariableDeclaration */) { + else if (declaration.kind === 237 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -30417,12 +31762,12 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 252 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -30430,9 +31775,9 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 217 /* VariableStatement */: - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 219 /* VariableStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -30453,16 +31798,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 152 /* PropertyDeclaration */ && + current.parent.kind === 154 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 154 /* MethodDeclaration */) { + if (declaration.kind === 156 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -30504,27 +31849,35 @@ var ts; // - 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 & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 149 /* Parameter */ || - lastLocation.kind === 148 /* TypeParameter */ + lastLocation.kind === 151 /* Parameter */ || + lastLocation.kind === 150 /* TypeParameter */ // local types not visible outside the function body : false; } - if (meaning & 67216319 /* 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 === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (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 === 151 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } - else if (location.kind === 173 /* ConditionalType */) { + else if (location.kind === 175 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -30538,14 +31891,14 @@ var ts; } } switch (location.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -30569,7 +31922,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 255 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) { break; } } @@ -30583,13 +31936,13 @@ var ts; } } break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* 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 @@ -30599,17 +31952,20 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } } } break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30624,7 +31980,7 @@ var ts; } break loop; } - if (location.kind === 207 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -30632,11 +31988,11 @@ var ts; } } break; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. - if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { + if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30652,29 +32008,29 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -30687,7 +32043,7 @@ var ts; } } break; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -30696,7 +32052,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 === 149 /* Parameter */) { + if (location.parent && location.parent.kind === 151 /* Parameter */) { location = location.parent; } // @@ -30709,8 +32065,8 @@ var ts; location = location.parent; } break; - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); break; @@ -30724,13 +32080,13 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { result.isReferenced |= meaning; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30739,7 +32095,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,16 +32150,15 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -30812,12 +32167,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: // For `namespace N { N; }` + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -30829,7 +32184,7 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 148 /* TypeParameter */) { + if (decl.kind === 150 /* TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 @@ -30884,10 +32239,10 @@ var ts; */ function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -30897,9 +32252,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +32273,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30951,7 +32309,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30968,6 +32326,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -30983,13 +32344,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node; - case 248 /* ImportClause */: + case 250 /* ImportClause */: return node.parent; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return node.parent.parent; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -30999,7 +32360,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -31037,7 +32398,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +32452,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31147,7 +32508,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31181,7 +32542,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31191,20 +32552,20 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 252 /* ExportAssignment */: - case 202 /* BinaryExpression */: + case 257 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 254 /* ExportAssignment */: + case 204 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -31215,10 +32576,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32610,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31265,11 +32626,11 @@ var ts; var node = getDeclarationOfAliasSymbol(symbol); if (!node) return ts.Debug.fail(); - if (node.kind === 252 /* ExportAssignment */) { + if (node.kind === 254 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 255 /* ExportSpecifier */) { + else if (node.kind === 257 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -31287,22 +32648,22 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 146 /* QualifiedName */) { + if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31311,19 +32672,19 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; - if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + if (name.kind === 72 /* Identifier */) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; } } - else if (name.kind === 146 /* QualifiedName */ || name.kind === 187 /* PropertyAccessExpression */) { - var left = name.kind === 146 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 146 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) { + var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -31331,7 +32692,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32727,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32743,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,8 +32765,18 @@ var ts; return symbol && symbol.valueDeclaration; } } - function resolveExternalModuleName(location, moduleReferenceExpression) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); } function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { if (isForAugmentation === void 0) { isForAugmentation = false; } @@ -31421,7 +32804,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32823,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32855,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32863,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,24 +32875,28 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { return exported; } var merged = cloneSymbol(exported); @@ -31530,7 +32917,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 277 /* SourceFile */)) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); return symbol; } @@ -31598,7 +32985,7 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 32764 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -31688,6 +33075,50 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } /** * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` @@ -31696,10 +33127,12 @@ var ts; var container = getParentOfSymbol(symbol); if (container) { var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { - return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope } - return ts.append(additionalContainers, container); + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); } var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); if (!ts.length(candidates)) { @@ -31737,13 +33170,13 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 155 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -31766,7 +33199,7 @@ var ts; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(131072 /* Object */); + var type = createType(524288 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; type.members = undefined; @@ -31821,12 +33254,12 @@ var ts; } } switch (location.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -31837,7 +33270,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +33320,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31923,7 +33359,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -31938,10 +33374,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: continue; default: return false; @@ -31952,11 +33388,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +33430,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32048,10 +33494,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -32098,21 +33544,21 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 165 /* TypeQuery */ || + if (entityName.parent.kind === 167 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 147 /* ComputedPropertyName */) { + entityName.parent.kind === 149 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || - entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ || + entityName.parent.kind === 248 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32125,7 +33571,7 @@ var ts; } function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } - var nodeFlags = 3112960 /* IgnoreErrors */; + var nodeFlags = 70221824 /* IgnoreErrors */; if (flags & 2 /* UseOnlyExternalAliasing */) { nodeFlags |= 128 /* UseOnlyExternalAliasing */; } @@ -32135,6 +33581,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32151,15 +33600,15 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 164 /* ConstructorType */ : 163 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 159 /* ConstructSignature */ : 158 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */; } - var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 return writer; } } @@ -32167,7 +33616,7 @@ var ts; if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -32217,9 +33666,15 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, - visitedSymbols: undefined, + visitedTypes: undefined, + symbolDepth: undefined, inferTypeParameters: undefined, approximateLength: 0 }; @@ -32243,85 +33698,92 @@ var ts; } if (type.flags & 1 /* Any */) { context.approximateLength += 3; - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } if (type.flags & 2 /* Unknown */) { - return ts.createKeywordTypeNode(142 /* UnknownKeyword */); + return ts.createKeywordTypeNode(143 /* UnknownKeyword */); } if (type.flags & 4 /* String */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(137 /* StringKeyword */); + return ts.createKeywordTypeNode(138 /* StringKeyword */); } if (type.flags & 8 /* Number */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(134 /* NumberKeyword */); + return ts.createKeywordTypeNode(135 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146 /* BigIntKeyword */); } if (type.flags & 16 /* Boolean */) { context.approximateLength += 7; - return ts.createKeywordTypeNode(122 /* BooleanKeyword */); + return ts.createKeywordTypeNode(123 /* BooleanKeyword */); } - if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { + if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined)); + return enumLiteralName; } - if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + if (type.flags & 1056 /* EnumLike */) { + return symbolToTypeNode(type.symbol, context, 67897832 /* Type */); } - if (type.flags & 64 /* StringLiteral */) { + if (type.flags & 128 /* StringLiteral */) { context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & 128 /* NumberLiteral */) { + if (type.flags & 256 /* NumberLiteral */) { context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } - if (type.flags & 256 /* BooleanLiteral */) { + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512 /* BooleanLiteral */) { context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 2048 /* UniqueESSymbol */) { + if (type.flags & 8192 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } context.approximateLength += 13; - return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); + return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */)); } - if (type.flags & 4096 /* Void */) { + if (type.flags & 16384 /* Void */) { context.approximateLength += 4; - return ts.createKeywordTypeNode(105 /* VoidKeyword */); + return ts.createKeywordTypeNode(106 /* VoidKeyword */); } - if (type.flags & 8192 /* Undefined */) { + if (type.flags & 32768 /* Undefined */) { context.approximateLength += 9; - return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + return ts.createKeywordTypeNode(141 /* UndefinedKeyword */); } - if (type.flags & 16384 /* Null */) { + if (type.flags & 65536 /* Null */) { context.approximateLength += 4; - return ts.createKeywordTypeNode(95 /* NullKeyword */); + return ts.createKeywordTypeNode(96 /* NullKeyword */); } - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { context.approximateLength += 5; - return ts.createKeywordTypeNode(131 /* NeverKeyword */); + return ts.createKeywordTypeNode(132 /* NeverKeyword */); } - if (type.flags & 1024 /* ESSymbol */) { + if (type.flags & 4096 /* ESSymbol */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(138 /* SymbolKeyword */); + return ts.createKeywordTypeNode(139 /* SymbolKeyword */); } - if (type.flags & 16777216 /* NonPrimitive */) { + if (type.flags & 67108864 /* NonPrimitive */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(135 /* ObjectKeyword */); + return ts.createKeywordTypeNode(136 /* ObjectKeyword */); } - if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { + if (type.flags & 262144 /* TypeParameter */ && type.isThisType) { if (context.flags & 4194304 /* InObjectTypeLiteral */) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; @@ -32335,16 +33797,16 @@ var ts; } var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); return typeReferenceToTypeNode(type); } - if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && - type.flags & 65536 /* TypeParameter */ && + type.flags & 262144 /* TypeParameter */ && ts.length(type.symbol.declarations) && ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && @@ -32355,20 +33817,23 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } - if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { - var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -32379,23 +33844,23 @@ var ts; } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & 1048576 /* Index */) { + if (type.flags & 4194304 /* Index */) { var indexedType = type.type; context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 2097152 /* IndexedAccess */) { + if (type.flags & 8388608 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } - if (type.flags & 4194304 /* Conditional */) { + if (type.flags & 16777216 /* Conditional */) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); var saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; @@ -32406,12 +33871,12 @@ var ts; context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } - if (type.flags & 8388608 /* Substitution */) { + if (type.flags & 33554432 /* Substitution */) { return typeToTypeNodeHelper(type.typeVariable, context); } return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; var appropriateConstraintTypeNode; @@ -32430,43 +33895,52 @@ var ts; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { + var typeId = "" + type.id; var symbol = type.symbol; var id; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects - else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } - else if (context.visitedSymbols && context.visitedSymbols.has(id)) { + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { - context.approximateLength += 3; - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return createElidedInformationPlaceholder(context); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.visitedSymbols) { - context.visitedSymbols = ts.createMap(); + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); } - context.visitedSymbols.set(id, true); + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); var result = createTypeNodeFromObjectType(type); - context.visitedSymbols.delete(id); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); return result; } } @@ -32480,11 +33954,11 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 277 /* SourceFile */ || declaration.parent.kind === 243 /* ModuleBlock */; + return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } @@ -32501,12 +33975,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 163 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 164 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context); return signatureNode; } } @@ -32533,8 +34007,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +34047,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +34060,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32638,17 +34112,22 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 158 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 159 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ? - createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : - resolvedType.stringIndexInfo; - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context)); + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context); + } + typeElements.push(indexSignature); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); @@ -32679,31 +34158,34 @@ var ts; return typeElements.length ? typeElements : undefined; } } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; if (propertySymbol.valueDeclaration) { @@ -32715,10 +34197,16 @@ var ts; } else { var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; } @@ -32769,7 +34257,7 @@ var ts; } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 137 /* StringKeyword */ : 134 /* NumberKeyword */); + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -32782,7 +34270,7 @@ var ts; } context.approximateLength += (name.length + 4); return ts.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { var typeParameters; @@ -32793,7 +34281,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -32812,18 +34300,18 @@ var ts; returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } if (context.flags & 256 /* SuppressAnyReturnType */) { - if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) { returnTypeNode = undefined; } } else if (!returnTypeNode) { - returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */); } context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +34322,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32846,9 +34334,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -32857,16 +34345,16 @@ var ts; var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; - var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - parameterDeclaration.name.kind === 146 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; - var questionToken = isOptional ? ts.createToken(55 /* QuestionToken */) : undefined; + var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); @@ -32875,21 +34363,34 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 184 /* BindingElement */) { + if (clone.kind === 186 /* BindingElement */) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32900,13 +34401,22 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + var parentSpecifiers; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); - if (ts.length(parents)) { - for (var _i = 0, _a = parents; _i < _a.length; _i++) { - var parent = _a[_i]; + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); @@ -32929,6 +34439,24 @@ var ts; } return [symbol]; } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } } } function typeParametersToTypeParameterDeclarations(symbol, context) { @@ -32966,7 +34494,7 @@ var ts; return top; } function getSpecifierForModuleSymbol(symbol, context) { - var file = ts.getDeclarationOfKind(symbol, 277 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -32996,7 +34524,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,12 +34539,20 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); @@ -33103,6 +34646,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33143,7 +34689,7 @@ var ts; if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { - var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); @@ -33156,12 +34702,12 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 24576 /* Nullable */)) { - if (t.flags & (256 /* BooleanLiteral */ | 512 /* EnumLiteral */)) { - var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 262144 /* Union */) { + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) { + var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33171,9 +34717,9 @@ var ts; result.push(t); } } - if (flags & 16384 /* Null */) + if (flags & 65536 /* Null */) result.push(nullType); - if (flags & 8192 /* Undefined */) + if (flags & 32768 /* Undefined */) result.push(undefinedType); return result || types; } @@ -33188,8 +34734,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 175 /* ParenthesizedType */; }); - if (node.kind === 240 /* TypeAliasDeclaration */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; }); + if (node.kind === 242 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -33197,11 +34743,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 243 /* ModuleBlock */ && + node.parent.kind === 245 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); } /** * Gets a human-readable name for a symbol. @@ -33224,27 +34770,30 @@ var ts; var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 235 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 207 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var nameType = symbol.nameType; if (nameType) { - if (nameType.flags & 64 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; } - if (nameType && nameType.flags & 2048 /* UniqueESSymbol */) { + if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; } } @@ -33261,27 +34810,27 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 237 /* FunctionDeclaration */: - case 241 /* EnumDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 243 /* EnumDeclaration */: + case 248 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -33289,53 +34838,53 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 246 /* ImportEqualsDeclaration */ && parent.kind !== 277 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 155 /* Constructor */: - case 159 /* ConstructSignature */: - case 158 /* CallSignature */: - case 160 /* IndexSignature */: - case 149 /* Parameter */: - case 243 /* ModuleBlock */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 166 /* TypeLiteral */: - case 162 /* TypeReference */: - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 175 /* ParenthesizedType */: + case 157 /* Constructor */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 151 /* Parameter */: + case 245 /* ModuleBlock */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 164 /* TypeReference */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 177 /* 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 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: return false; // Type parameters are always visible - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: // Source file and namespace export are always visible - case 277 /* SourceFile */: - case 245 /* NamespaceExportDeclaration */: + case 279 /* SourceFile */: + case 247 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return false; default: return false; @@ -33344,11 +34893,11 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + if (node.parent && node.parent.kind === 254 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + else if (node.parent.kind === 257 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34918,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34967,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33426,6 +34977,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33439,12 +34992,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 235 /* VariableDeclaration */: - case 236 /* VariableDeclarationList */: - case 251 /* ImportSpecifier */: - case 250 /* NamedImports */: - case 249 /* NamespaceImport */: - case 248 /* ImportClause */: + case 237 /* VariableDeclaration */: + case 238 /* VariableDeclarationList */: + case 253 /* ImportSpecifier */: + case 252 /* NamedImports */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: return false; default: return true; @@ -33474,28 +35027,36 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); + return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); - if (source.flags & 32768 /* Never */) { + source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); + if (source.flags & 131072 /* Never */) { return emptyObjectType; } - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } - var members = ts.createSymbolTable(); - var names = ts.createUnderscoreEscapedMap(); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var name = properties_2[_i]; - names.set(ts.getTextOfPropertyName(name), true); + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - if (!names.has(prop.escapedName) + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getNonReadonlySymbol(prop)); + members.set(prop.escapedName, getSpreadSymbol(prop)); } } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); @@ -33519,8 +35080,12 @@ var ts; if (isTypeAny(parentType)) { return parentType; } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } var type; - if (pattern.kind === 182 /* ObjectBindingPattern */) { + if (pattern.kind === 184 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -33538,51 +35103,9 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - var isLate = isLateBindableName(name); - var isWellKnown = ts.isComputedPropertyName(name) && ts.isWellKnownSymbolSyntactically(name.expression); - if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { - var exprType = checkExpression(name.expression); - if (isTypeAssignableToKind(exprType, 3072 /* ESSymbolLike */)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); - } - return anyType; - } - var indexerType = isTypeAssignableToKind(exprType, 168 /* NumberLike */) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); - if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(parentType, 1 /* Number */)) { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType)); - } - } - return indexerType || 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. - var nameType = isLate ? checkComputedPropertyName(name) : undefined; - var text = isLate ? getLateBoundNameFromType(nameType) : - isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : - ts.getTextOfPropertyName(name); - // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation - if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { - parentType = getNonNullableType(parentType); - } - if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType)); - } - return anyType; - } - var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); - type = declaredType && getFlowTypeOfReference(declaration, declaredType) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || - getIndexTypeOfType(parentType, 0 /* String */); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return errorType; - } + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); } } else { @@ -33590,27 +35113,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33618,11 +35141,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { - type = getTypeWithFacts(type, 131072 /* NEUndefined */); + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) { + type = getTypeWithFacts(type, 524288 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33634,11 +35157,11 @@ var ts; } function isNullOrUndefined(node) { var expr = ts.skipParentheses(node); - return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 185 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -33648,11 +35171,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 224 /* ForInStatement */) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (65536 /* TypeParameter */ | 1048576 /* Index */) ? getExtractStringType(indexType) : stringType; + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 225 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* 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, @@ -33670,8 +35193,8 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no @@ -33685,11 +35208,11 @@ var ts; return autoArrayType; } } - if (declaration.kind === 149 /* Parameter */) { + if (declaration.kind === 151 /* 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 === 157 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 156 /* GetAccessor */); + if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -33701,16 +35224,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +35259,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33747,14 +35276,14 @@ var ts; var types; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = ts.isBinaryExpression(declaration) ? declaration : + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +35291,11 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,26 +35303,24 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; } } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(24576 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +35339,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +35353,35 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); - if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + if (type.flags & 524288 /* Object */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33851,9 +35405,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33862,9 +35414,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 155 /* Constructor */ || - thisContainer.kind === 237 /* FunctionDeclaration */ || - (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 157 /* Constructor */ || + thisContainer.kind === 239 /* FunctionDeclaration */ || + (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -33876,8 +35428,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +35437,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33899,8 +35451,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33939,7 +35491,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var hasRestElement = !!(lastElement && lastElement.kind === 184 /* BindingElement */ && lastElement.dotDotDotToken); + var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken); if (elements.length === 0 || elements.length === 1 && hasRestElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -33962,7 +35514,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 182 /* ObjectBindingPattern */ + return pattern.kind === 184 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -33984,7 +35536,7 @@ var ts; reportErrorsFromWidening(declaration, type); } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & 2048 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } return getWidenedType(type); @@ -33992,16 +35544,16 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 149 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -34037,19 +35589,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } - if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + if (declaration.kind === 254 /* ExportAssignment */) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && - (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +35622,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34085,6 +35644,14 @@ var ts; || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } @@ -34095,7 +35662,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 156 /* GetAccessor */) { + if (accessor.kind === 158 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -34122,9 +35689,9 @@ var ts; return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); } function getTypeOfAccessorsWorker(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */); + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34152,14 +35719,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34168,7 +35733,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* 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)); } } @@ -34176,13 +35741,13 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 2162688 /* TypeVariable */ ? baseConstructorType : undefined; + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34208,9 +35773,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 202 /* BinaryExpression */ || - declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + else if (declaration.kind === 204 /* BinaryExpression */ || + declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) { + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35784,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35813,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35822,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34329,7 +35886,7 @@ var ts; var target = getTargetType(type); return target === checkBase || ts.some(getBaseTypes(target), check); } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return ts.some(type.types, check); } return false; @@ -34353,35 +35910,35 @@ var ts; return undefined; } switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 287 /* JSDocFunctionType */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 179 /* MappedType */: - case 173 /* ConditionalType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 181 /* MappedType */: + case 175 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 179 /* MappedType */) { + if (node.kind === 181 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 173 /* ConditionalType */) { + else if (node.kind === 175 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */ || node.kind === 239 /* InterfaceDeclaration */) && + (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } @@ -34389,7 +35946,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, 239 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -34398,9 +35955,9 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 239 /* InterfaceDeclaration */ || - node.kind === 238 /* ClassDeclaration */ || - node.kind === 207 /* ClassExpression */ || + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || + node.kind === 209 /* ClassExpression */ || ts.isTypeAlias(node)) { var declaration = node; result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); @@ -34427,27 +35984,24 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { return true; } - if (type.flags & 2162688 /* TypeVariable */) { + if (type.flags & 8650752 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34473,7 +36027,7 @@ var ts; ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag checkExpression(extended.expression); } - if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */)) { + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -34483,7 +36037,18 @@ var ts; return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } return type.resolvedBaseConstructorType = errorType; } type.resolvedBaseConstructorType = baseConstructorType; @@ -34512,13 +36077,15 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 1 /* Any */))) { + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? 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 @@ -34529,8 +36096,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34547,7 +36114,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { @@ -34577,14 +36144,14 @@ var ts; // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return !!(type.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 524288 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -34603,7 +36170,7 @@ var ts; } } else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -34620,7 +36187,7 @@ var ts; function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 /* InterfaceDeclaration */) { + if (declaration.kind === 241 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -34629,7 +36196,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34661,7 +36228,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536 /* TypeParameter */); + type.thisType = createType(262144 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -34678,7 +36245,7 @@ var ts; return errorType; } var declaration = ts.find(symbol.declarations, function (d) { - return ts.isJSDocTypeAlias(d) || d.kind === 240 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */; }); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. @@ -34702,10 +36269,10 @@ var ts; return links.declaredType; } function isStringConcatExpression(expr) { - if (expr.kind === 9 /* StringLiteral */) { + if (expr.kind === 10 /* StringLiteral */) { return true; } - else if (expr.kind === 202 /* BinaryExpression */) { + else if (expr.kind === 204 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -34716,15 +36283,15 @@ var ts; return !(member.flags & 4194304 /* Ambient */); } switch (expr.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return true; - case 200 /* PrefixUnaryExpression */: - return expr.operator === 38 /* MinusToken */ && + case 202 /* PrefixUnaryExpression */: + return expr.operator === 39 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -34738,10 +36305,10 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241 /* EnumDeclaration */) { + if (declaration.kind === 243 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) { return links.enumKind = 1 /* Literal */; } if (!isLiteralEnumMember(member)) { @@ -34753,7 +36320,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -34765,19 +36332,19 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241 /* EnumDeclaration */) { + if (declaration.kind === 243 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); - if (enumType_1.flags & 262144 /* Union */) { - enumType_1.flags |= 512 /* EnumLiteral */; + if (enumType_1.flags & 1048576 /* Union */) { + enumType_1.flags |= 1024 /* EnumLiteral */; enumType_1.symbol = symbol; } return links.declaredType = enumType_1; @@ -34800,7 +36367,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(65536 /* TypeParameter */); + var type = createType(262144 /* TypeParameter */); type.symbol = symbol; links.declaredType = type; } @@ -34844,22 +36411,23 @@ var ts; */ function isThislessType(node) { switch (node.kind) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 135 /* ObjectKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: - case 180 /* LiteralType */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + case 182 /* LiteralType */: return true; - case 167 /* ArrayType */: + case 169 /* ArrayType */: return isThislessType(node.elementType); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -34885,7 +36453,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 155 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -34901,12 +36469,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -34950,7 +36518,7 @@ var ts; * Indicates whether a type can be used as a late-bound name. */ function isTypeUsableAsLateBoundName(type) { - return !!(type.flags & 2240 /* StringOrNumberLiteralOrUnique */); + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); } /** * Indicates whether a declaration name is definitely late-bindable. @@ -34993,10 +36561,10 @@ var ts; * Gets the symbolic name for a late-bound member from its type. */ function getLateBoundNameFromType(type) { - if (type.flags & 2048 /* UniqueESSymbol */) { + if (type.flags & 8192 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +36584,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35161,7 +36729,7 @@ var ts; return needApparentType ? getApparentType(ref) : ref; } } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } return needApparentType ? getApparentType(type) : type; @@ -35270,7 +36838,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35290,7 +36858,7 @@ var ts; function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { return s; } } @@ -35324,8 +36892,7 @@ var ts; // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional // parameters and may differ in return types. When signatures differ in return types, the resulting return // type is the union of the constituent return types. - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + function getUnionSignatures(signatureLists) { var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { @@ -35371,8 +36938,8 @@ var ts; 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 callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -35407,7 +36974,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35430,7 +36997,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35468,7 +37035,7 @@ var ts; if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 2162688 /* TypeVariable */)) { + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -35484,6 +37051,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35501,7 +37069,7 @@ var ts; var modifiers = getMappedTypeModifiers(type.mappedType); var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; - var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; @@ -35511,6 +37079,7 @@ var ts; inferredProp.nameType = prop.nameType; inferredProp.propertyType = getTypeOfSymbol(prop); inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -35529,12 +37098,12 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateModifiers = getMappedTypeModifiers(type); - var include = keyofStringsOnly ? 64 /* StringLiteral */ : 2240 /* StringOrNumberLiteralOrUnique */; + var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); @@ -35544,11 +37113,9 @@ var ts; } } else { - // First, if the constraint type is a type parameter, obtain the base constraint. Then, - // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 14745600 /* InstantiableNonPrimitive */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 1048576 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); @@ -35560,7 +37127,7 @@ var ts; var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. - if (t.flags & 2240 /* StringOrNumberLiteralOrUnique */) { + if (t.flags & 8576 /* StringOrNumberLiteralOrUnique */) { var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || @@ -35572,7 +37139,7 @@ var ts; // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks // mode, if the underlying property is optional we remove 'undefined' from the type. prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; @@ -35595,7 +37162,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35608,8 +37175,8 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 177 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; + return constraintDeclaration.kind === 179 /* TypeOperator */ && + constraintDeclaration.operator === 129 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { @@ -35625,16 +37192,16 @@ var ts; // the modifiers type is T. Otherwise, the modifiers type is {}. var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 1048576 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } function getMappedTypeModifiers(type) { var declaration = type.declaration; - return (declaration.readonlyToken ? declaration.readonlyToken.kind === 38 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | - (declaration.questionToken ? declaration.questionToken.kind === 38 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); } function getMappedTypeOptionality(type) { var modifiers = getMappedTypeModifiers(type); @@ -35653,7 +37220,7 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { if (type.objectFlags & 4 /* Reference */) { resolveTypeReferenceMembers(type); } @@ -35670,10 +37237,10 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 262144 /* Union */) { + else if (type.flags & 1048576 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -35681,7 +37248,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; @@ -35690,7 +37257,7 @@ var ts; * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -35714,7 +37281,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { break; } } @@ -35724,12 +37291,13 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 786432 /* UnionOrIntersection */ ? + return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { - return obj.properties.some(function (property) { + var list = obj.properties; + return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); @@ -35737,7 +37305,7 @@ var ts; } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 262144 /* Union */)) { + if (!(unionType.flags & 1048576 /* Union */)) { return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); @@ -35756,24 +37324,33 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : - type.flags & 2097152 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : - type.flags & 4194304 /* Conditional */ ? getConstraintOfConditionalType(type) : + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { var rootTrueType = type.root.trueType; - var rootTrueConstraint = rootTrueType.flags & 8388608 /* Substitution */ ? rootTrueType.substitute : rootTrueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); } return type.resolvedDefaultConstraint; @@ -35785,11 +37362,12 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); - if (!(instantiated.flags & 32768 /* Never */)) { + if (!(instantiated.flags & 131072 /* Never */)) { return instantiated; } } @@ -35804,23 +37382,23 @@ var ts; var hasDisjointDomainType = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 15794176 /* Instantiable */) { + if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). var constraint = getConstraintOfType(t); - while (constraint && constraint.flags & (65536 /* TypeParameter */ | 1048576 /* Index */ | 4194304 /* Conditional */)) { + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { constraint = getConstraintOfType(constraint); } if (constraint) { // A constraint that isn't a union type implies that the final type would be a non-union // type as well. Since non-union constraints are of no interest, we can exit here. - if (!(constraint.flags & 262144 /* Union */)) { + if (!(constraint.flags & 1048576 /* Union */)) { return undefined; } constraints = ts.append(constraints, constraint); } } - else if (t.flags & 16809468 /* DisjointDomains */) { + else if (t.flags & 67238908 /* DisjointDomains */) { hasDisjointDomainType = true; } } @@ -35832,7 +37410,7 @@ var ts; // intersection operation to reduce the union constraints. for (var _b = 0, _c = type.types; _b < _c.length; _b++) { var t = _c[_b]; - if (t.flags & 16809468 /* DisjointDomains */) { + if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } } @@ -35842,11 +37420,11 @@ var ts; return undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; + return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -35864,6 +37442,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +37450,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35884,45 +37473,42 @@ var ts; return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { - if (t.flags & 65536 /* TypeParameter */) { + if (t.flags & 262144 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint); } - if (t.flags & 786432 /* UnionOrIntersection */) { + if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 262144 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 524288 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 1048576 /* Index */) { + if (t.flags & 4194304 /* Index */) { return keyofConstraintType; } - if (t.flags & 2097152 /* IndexedAccess */) { + if (t.flags & 8388608 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } - if (t.flags & 4194304 /* Conditional */) { + if (t.flags & 16777216 /* Conditional */) { var constraint = getConstraintOfConditionalType(t); return constraint && getBaseConstraint(constraint); } - if (t.flags & 8388608 /* Substitution */) { + if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,26 +37558,42 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 /* StringLike */ ? globalStringType : + t.flags & 296 /* NumberLike */ ? globalNumberType : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 528 /* BooleanLike */ ? globalBooleanType : + t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : + t.flags & 4194304 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var indexTypes; - var isUnion = containingType.flags & 262144 /* Union */; + var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; @@ -36016,10 +37618,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36104,27 +37706,31 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 917504 /* StructuredType */) { + if (type.flags & 3670016 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -36138,7 +37744,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 917504 /* StructuredType */) { + if (type.flags & 3670016 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -36192,12 +37798,12 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 286 /* JSDocOptionalType */ + node.type && node.type.kind === 288 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -36231,7 +37837,7 @@ var ts; return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -36256,30 +37862,32 @@ var ts; } function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { - if (!typeArguments) { - typeArguments = []; - } - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { - defaultType = anyType; - } - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - typeArguments.length = typeParameters.length; - } + if (!numTypeParameters) { + return []; } - return typeArguments; + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); @@ -36292,7 +37900,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37913,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36315,7 +37923,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 180 /* LiteralType */) { + if (type && type.kind === 182 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter @@ -36329,20 +37937,20 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 156 /* GetAccessor */ || declaration.kind === 157 /* SetAccessor */) && + if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) && !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 155 /* Constructor */ ? + var classType = declaration.kind === 157 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37981,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36396,13 +38004,13 @@ var ts; if (!node) return false; switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node.escapedText === "arguments" && ts.isExpressionNode(node); - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return node.name.kind === 147 /* ComputedPropertyName */ + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node.name.kind === 149 /* ComputedPropertyName */ && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -36460,7 +38068,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36477,7 +38085,7 @@ var ts; function createTypePredicateFromTypePredicateNode(node, func) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71 /* Identifier */) { + if (parameterName.kind === 72 /* Identifier */) { return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); } else { @@ -36487,7 +38095,7 @@ var ts; function getTypePredicateParameterIndex(parameterList, parameter) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { return i; } } @@ -36501,6 +38109,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36526,7 +38135,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 155 /* Constructor */) { + if (declaration.kind === 157 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -36536,12 +38145,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -36556,8 +38165,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +38211,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36615,7 +38228,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 === 155 /* Constructor */ || signature.declaration.kind === 159 /* ConstructSignature */; // TODO: GH#18217 + var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217 var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -36629,7 +38242,7 @@ var ts; return symbol.members.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 134 /* NumberKeyword */ : 137 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -36656,7 +38269,7 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */); return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { @@ -36664,13 +38277,13 @@ var ts; if (typeParameter.symbol) { for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.parent.kind === 174 /* InferType */) { + if (declaration.parent.kind === 176 /* InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. var grandParent = declaration.parent.parent; - if (grandParent.kind === 162 /* TypeReference */) { + if (grandParent.kind === 164 /* TypeReference */) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -36695,7 +38308,7 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter // declaration, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 149 /* Parameter */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } } @@ -36719,7 +38332,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -36792,10 +38405,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36825,7 +38438,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36852,9 +38465,9 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -36880,14 +38493,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +38522,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36904,16 +38531,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -36936,13 +38568,13 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { - var result = createType(8388608 /* Substitution */); + var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 168 /* TupleType */ && node.elementTypes.length === 1; + return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1; } function getImpliedConstraint(typeVariable, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : @@ -36951,9 +38583,9 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 289 /* JSDocComment */) { + while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 173 /* ConditionalType */ && node === parent.trueType) { + if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -36964,7 +38596,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */); + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -37022,23 +38654,23 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getNullableType(type, 16384 /* Null */) : type; + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37065,9 +38697,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: return declaration; } } @@ -37076,7 +38708,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 131072 /* Object */)) { + if (!(type.flags & 524288 /* Object */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } @@ -37087,10 +38719,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37118,6 +38750,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37144,12 +38779,21 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType; + } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -37198,7 +38842,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(65536 /* TypeParameter */); + var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); if (i < maxLength) { var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); property.type = typeParameter; @@ -37220,7 +38864,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536 /* TypeParameter */); + type.thisType = createType(262144 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -37255,8 +38899,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var lastElement = ts.lastOrUndefined(node.elementTypes); - var restElement_1 = lastElement && lastElement.kind === 170 /* RestType */ ? lastElement : undefined; - var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 169 /* OptionalType */ && n !== restElement_1; }) + 1; + var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1; var elementTypes = ts.map(node.elementTypes, function (n) { var type = getTypeFromTypeNode(n); return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; @@ -37265,6 +38909,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37295,16 +38947,17 @@ var ts; var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 27072 /* Unit */ && combined & 27072 /* Unit */) { + if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) { return true; } combined |= t.flags; - if (combined & 24576 /* Nullable */ && combined & (131072 /* Object */ | 16777216 /* NonPrimitive */) || - combined & 16777216 /* NonPrimitive */ && combined & (16809468 /* DisjointDomains */ & ~16777216 /* NonPrimitive */) || - combined & 68 /* StringLike */ && combined & (16809468 /* DisjointDomains */ & ~68 /* StringLike */) || - combined & 168 /* NumberLike */ && combined & (16809468 /* DisjointDomains */ & ~168 /* NumberLike */) || - combined & 3072 /* ESSymbolLike */ && combined & (16809468 /* DisjointDomains */ & ~3072 /* ESSymbolLike */) || - combined & 12288 /* VoidLike */ && combined & (16809468 /* DisjointDomains */ & ~12288 /* VoidLike */)) { + if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) || + combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || + combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || + combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || + combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) || + combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || + combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) { return true; } } @@ -37312,20 +38965,18 @@ var ts; } function addTypeToUnion(typeSet, includes, type) { var flags = type.flags; - if (flags & 262144 /* Union */) { + if (flags & 1048576 /* Union */) { return addTypesToUnion(typeSet, includes, type.types); } // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are // another form of 'never' (in that they have an empty value domain). We could in theory turn // intersections of unit types into 'never' upon construction, but deferring the reduction makes it // easier to reason about their origin. - if (!(flags & 32768 /* Never */ || flags & 524288 /* Intersection */ && isEmptyIntersectionType(type))) { + if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { includes |= flags & ~939524096 /* ConstructionFlags */; - if (flags & 3 /* AnyOrUnknown */) { - if (type === wildcardType) - includes |= 268435456 /* Wildcard */; - } - else if (!strictNullChecks && flags & 24576 /* Nullable */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(flags & 134217728 /* ContainsWideningType */)) includes |= 134217728 /* NonWideningType */; } @@ -37333,10 +38984,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38999,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - 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 isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37373,11 +39012,11 @@ var ts; } function isSetOfLiteralsFromSameEnum(types) { var first = types[0]; - if (first.flags & 512 /* EnumLiteral */) { + if (first.flags & 1024 /* EnumLiteral */) { var firstEnum = getParentOfSymbol(first.symbol); for (var i = 1; i < types.length; i++) { var other = types[i]; - if (!(other.flags & 512 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { return false; } } @@ -37402,10 +39041,11 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || - t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37428,25 +39068,27 @@ var ts; } var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); - if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1 /* Literal */: + if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + neverType; + } } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { - removeRedundantLiteralTypes(typeSet, includes); - } - break; - case 2 /* Subtype */: - removeSubtypes(typeSet); - break; - } - if (typeSet.length === 0) { - return includes & 16384 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : - includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -37483,7 +39125,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -37493,10 +39135,11 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 24576 /* Nullable */); - type = createType(262144 /* Union */ | propagatedFlags | unionOfUnitTypes); + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(1048576 /* Union */ | propagatedFlags); unionTypes.set(id, type); type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; /* Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. @@ -37518,11 +39161,14 @@ var ts; } function addTypeToIntersection(typeSet, includes, type) { var flags = type.flags; - if (flags & 524288 /* Intersection */) { + if (flags & 2097152 /* Intersection */) { return addTypesToIntersection(typeSet, includes, type.types); } - if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { - includes |= 536870912 /* EmptyObject */; + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912 /* EmptyObject */)) { + includes |= 536870912 /* EmptyObject */; + typeSet.push(type); + } } else { includes |= flags & ~939524096 /* ConstructionFlags */; @@ -37530,10 +39176,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +39185,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37553,9 +39196,10 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 4 /* String */ && includes & 64 /* StringLiteral */ || - t.flags & 8 /* Number */ && includes & 128 /* NumberLiteral */ || - t.flags & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */; + var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37568,10 +39212,11 @@ var ts; for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { var u = unionTypes_1[_i]; if (!containsType(u.types, type)) { - var primitive = type.flags & 64 /* StringLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ ? numberType : - type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : - undefined; + var primitive = type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + undefined; if (!primitive || !containsType(u.types, primitive)) { return false; } @@ -37584,13 +39229,16 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; }); + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } var i = index + 1; // Remove all but the first union of primitive types and collect them in // the unionTypes array. while (i < types.length) { var t = types[i]; - if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) { + if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -37619,7 +39267,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */); + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -37635,22 +39283,23 @@ var ts; function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); - if (includes & 32768 /* Never */) { + if (includes & 131072 /* Never */) { return neverType; } if (includes & 1 /* Any */) { return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; } - if (!strictNullChecks && includes & 24576 /* Nullable */) { - return includes & 8192 /* Undefined */ ? undefinedType : nullType; + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 32768 /* Undefined */ ? undefinedType : nullType; } - if (includes & 4 /* String */ && includes & 64 /* StringLiteral */ || - includes & 8 /* Number */ && includes & 128 /* NumberLiteral */ || - includes & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */) { + if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 536870912 /* EmptyObject */ && !(includes & 131072 /* Object */)) { - typeSet.push(emptyObjectType); + if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { return unknownType; @@ -37658,8 +39307,8 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - if (includes & 262144 /* Union */) { - if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) { + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -37667,15 +39316,15 @@ var ts; } // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. - var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 262144 /* Union */) !== 0; }); + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; }); var unionType = typeSet[unionIndex_1]; return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 24576 /* Nullable */); - type = createType(524288 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(2097152 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. @@ -37692,7 +39341,7 @@ var ts; return links.resolvedType; } function createIndexType(type, stringsOnly) { - var result = createType(1048576 /* Index */); + var result = createType(4194304 /* Index */); result.type = type; result.stringsOnly = stringsOnly; return result; @@ -37702,14 +39351,22 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } - function getLiteralTypeFromPropertyName(prop, include) { + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) : - name && name.kind === 147 /* ComputedPropertyName */ && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : - getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); } if (type && type.flags & include) { return type; @@ -37717,8 +39374,8 @@ var ts; } return neverType; } - function getLiteralTypeFromPropertyNames(type, include) { - return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromPropertyName(t, include); })); + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); } function getNonEnumNumberIndexInfo(type) { var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); @@ -37726,16 +39383,16 @@ var ts; } function getIndexType(type, stringsOnly) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } - return type.flags & 262144 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - type.flags & 524288 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : type === wildcardType ? wildcardType : type.flags & 1 /* Any */ ? keyofConstraintType : - stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */) : - getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, 2048 /* UniqueESSymbol */)]) : - getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */ | 2048 /* UniqueESSymbol */)]) : - getLiteralTypeFromPropertyNames(type, 2240 /* StringOrNumberLiteralOrUnique */); + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) : + getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */); } function getExtractStringType(type) { if (keyofStringsOnly) { @@ -37746,17 +39403,17 @@ var ts; } function getIndexTypeOrString(type) { var indexType = getExtractStringType(getIndexType(type)); - return indexType.flags & 32768 /* Never */ ? stringType : indexType; + return indexType.flags & 131072 /* Never */ ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { switch (node.operator) { - case 128 /* KeyOfKeyword */: + case 129 /* KeyOfKeyword */: links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); break; - case 141 /* UniqueKeyword */: - links.resolvedType = node.type.kind === 138 /* SymbolKeyword */ + case 142 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 139 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) : errorType; break; @@ -37765,7 +39422,7 @@ var ts; return links.resolvedType; // TODO: GH#18217 } function createIndexedAccessType(objectType, indexType) { - var type = createType(2097152 /* IndexedAccess */); + var type = createType(8388608 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; return type; @@ -37786,56 +39443,63 @@ var ts; if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { return true; } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { return ts.every(type.types, isJSLiteralType); } - if (type.flags & 524288 /* Intersection */) { + if (type.flags & 2097152 /* Intersection */) { return ts.some(type.types, isJSLiteralType); } - if (type.flags & 15794176 /* Instantiable */) { + if (type.flags & 63176704 /* Instantiable */) { return isJSLiteralType(getResolvedBaseConstraint(type)); } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - undefined; + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } - if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { - if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) { + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { return objectType; } - var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { - var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = getIndexNodeForAccessExpression(accessNode); error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { @@ -37843,7 +39507,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768 /* Never */) { + if (indexType.flags & 131072 /* Never */) { return neverType; } if (isJSLiteralType(objectType)) { @@ -37869,15 +39533,15 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { return anyType; } if (accessNode) { - var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; - if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { @@ -37887,30 +39551,38 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 /* ElementAccessExpression */ + ? accessNode.argumentExpression + : accessNode.kind === 180 /* IndexedAccessType */ + ? accessNode.indexType + : accessNode.kind === 149 /* ComputedPropertyName */ + ? accessNode.expression + : accessNode; } function isGenericObjectType(type) { - return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); } function isGenericIndexType(type) { - return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); - } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); } function getSimplifiedType(type) { - return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 1048576 /* Union */) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // the type itself if no transformation is possible. @@ -37922,37 +39594,20 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); - } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 1048576 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 63176704 /* Instantiable */)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37960,7 +39615,7 @@ var ts; if (isGenericMappedType(objectType)) { return type.simplified = substituteIndexedMappedType(objectType, type); } - if (objectType.flags & 65536 /* TypeParameter */) { + if (objectType.flags & 262144 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); @@ -37973,7 +39628,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -37982,7 +39638,7 @@ var ts; // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 188 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } @@ -37998,19 +39654,30 @@ var ts; // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38018,7 +39685,7 @@ var ts; var objectType = getTypeFromTypeNode(node.objectType); var indexType = getTypeFromTypeNode(node.indexType); var resolved = getIndexedAccessType(objectType, indexType, node); - links.resolvedType = resolved.flags & 2097152 /* IndexedAccess */ && + links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && resolved.objectType === objectType && resolved.indexType === indexType ? getConstrainedTypeVariable(resolved, node) : resolved; @@ -38040,7 +39707,7 @@ var ts; return links.resolvedType; } function getActualTypeVariable(type) { - return type.flags & 8388608 /* Substitution */ ? type.typeVariable : type; + return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); @@ -38051,7 +39718,7 @@ var ts; // If this is a distributive conditional type and the check type is generic we need to defer // resolution of the conditional type such that a later instantiation will properly distribute // over union types. - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 15794176 /* Instantiable */); + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); @@ -38090,7 +39757,7 @@ var ts; } // Return a deferred type for a check that is neither definitely true nor definitely false var erasedCheckType = getActualTypeVariable(checkType); - var result = createType(4194304 /* Conditional */); + var result = createType(16777216 /* Conditional */); result.root = root; result.checkType = erasedCheckType; result.extendsType = extendsType; @@ -38122,7 +39789,7 @@ var ts; return true; } while (node) { - if (node.kind === 173 /* ConditionalType */) { + if (node.kind === 175 /* ConditionalType */) { if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { return true; } @@ -38145,7 +39812,7 @@ var ts; extendsType: getTypeFromTypeNode(node.extendsType), trueType: getTypeFromTypeNode(node.trueType), falseType: getTypeFromTypeNode(node.falseType), - isDistributive: !!(checkType.flags & 65536 /* TypeParameter */), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, @@ -38188,7 +39855,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39885,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39899,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38265,6 +39932,9 @@ var ts; function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } /** * Since the source of spread types are object literals, which are not binary, * this function should be called in a left folding style, with left = previous result of getSpreadType @@ -38277,21 +39947,37 @@ var ts; if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { return unknownType; } - if (left.flags & 32768 /* Never */) { + if (left.flags & 131072 /* Never */) { return right; } - if (right.flags & 32768 /* Never */) { + if (right.flags & 131072 /* Never */) { return left; } - if (left.flags & 262144 /* Union */) { + if (left.flags & 1048576 /* Union */) { return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); } - if (right.flags & 262144 /* Union */) { + if (right.flags & 1048576 /* Union */) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); } - if (right.flags & (272 /* BooleanLike */ | 168 /* NumberLike */ | 68 /* StringLike */ | 544 /* EnumLike */ | 16777216 /* NonPrimitive */ | 1048576 /* Index */)) { + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { return left; } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & 2097152 /* Intersection */) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); var stringIndexInfo; @@ -38311,7 +39997,7 @@ var ts; skippedPrivateMembers.set(rightProp.escapedName, true); } else if (isSpreadableProperty(rightProp)) { - members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { @@ -38326,7 +40012,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); var result = createSymbol(flags, leftProp.escapedName); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -38335,27 +40021,28 @@ var ts; } } else { - members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= typeFlags | 268435456 /* ContainsObjectLiteral */; - spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); + spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */) - ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) - : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable + return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isReadonly && !isSetonlyAccessor) { return prop; } var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); var result = createSymbol(flags, prop.escapedName); - result.type = getTypeOfSymbol(prop); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); result.declarations = prop.declarations; result.nameType = prop.nameType; result.syntheticOrigin = prop; @@ -38374,10 +40061,11 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; + freshType.freshType = freshType; type.freshType = freshType; } return type.freshType; @@ -38385,21 +40073,27 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + return type.flags & 2944 /* Literal */ ? type.regularType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } + function isFreshLiteralType(type) { + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; + } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', // where NNN is the text representation of a numeric literal and SSS are the characters // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where // EEE is a unique id for the containing enum type. - var qualifier = typeof value === "number" ? "#" : "@"; - var key = enumId ? enumId + qualifier + value : qualifier + value; + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); var type = literalTypes.get(key); if (!type) { - var flags = (typeof value === "number" ? 128 /* NumberLiteral */ : 64 /* StringLiteral */) | (enumId ? 512 /* EnumLiteral */ : 0); + var flags = (typeof value === "number" ? 256 /* NumberLiteral */ : + typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) | + (enumId ? 1024 /* EnumLiteral */ : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; } return type; } @@ -38411,7 +40105,7 @@ var ts; return links.resolvedType; } function createUniqueESSymbolType(symbol) { - var type = createType(2048 /* UniqueESSymbol */); + var type = createType(8192 /* UniqueESSymbol */); type.symbol = symbol; return type; } @@ -38426,9 +40120,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 239 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) { if (!ts.hasModifier(container, 32 /* Static */) && - (container.kind !== 155 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -38444,87 +40138,89 @@ var ts; } function getTypeFromTypeNode(node) { switch (node.kind) { - case 119 /* AnyKeyword */: - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: + case 120 /* AnyKeyword */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: return anyType; - case 142 /* UnknownKeyword */: + case 143 /* UnknownKeyword */: return unknownType; - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: return stringType; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: return numberType; - case 122 /* BooleanKeyword */: + case 146 /* BigIntKeyword */: + return bigintType; + case 123 /* BooleanKeyword */: return booleanType; - case 138 /* SymbolKeyword */: + case 139 /* SymbolKeyword */: return esSymbolType; - case 105 /* VoidKeyword */: + case 106 /* VoidKeyword */: return voidType; - case 140 /* UndefinedKeyword */: + case 141 /* UndefinedKeyword */: return undefinedType; - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: return nullType; - case 131 /* NeverKeyword */: + case 132 /* NeverKeyword */: return neverType; - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; - case 176 /* ThisType */: - case 99 /* ThisKeyword */: + case 178 /* ThisType */: + case 100 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return getTypeFromTypeReference(node); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return booleanType; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return getTypeFromOptionalTypeNode(node); - case 171 /* UnionType */: + case 173 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 175 /* ParenthesizedType */: - case 170 /* RestType */: - case 285 /* JSDocNonNullableType */: - case 281 /* JSDocTypeExpression */: + case 177 /* ParenthesizedType */: + case 172 /* RestType */: + case 287 /* JSDocNonNullableType */: + case 283 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 287 /* JSDocFunctionType */: - case 291 /* JSDocSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 174 /* InferType */: + case 176 /* InferType */: return getTypeFromInferTypeNode(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode - case 71 /* Identifier */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 148 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -38591,7 +40287,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38605,10 +40301,10 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function wildcardMapper(type) { - return type.flags & 65536 /* TypeParameter */ ? wildcardType : type; + return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; } function cloneTypeParameter(typeParameter) { - var result = createType(65536 /* TypeParameter */); + var result = createType(262144 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -38654,7 +40350,7 @@ var ts; } function instantiateSymbol(symbol, mapper) { var links = getSymbolLinks(symbol); - if (links.type && !maybeTypeOfKind(links.type, 131072 /* Object */ | 15794176 /* Instantiable */)) { + if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { // If the type of the symbol is already resolved, and if that type could not possibly // be affected by instantiation, simply return the symbol itself. return symbol; @@ -38692,7 +40388,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +40398,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38734,8 +40430,8 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 146 /* QualifiedName */ || - node.parent.kind === 162 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + return !(node.kind === 148 /* QualifiedName */ || + node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks @@ -38743,26 +40439,36 @@ var ts; // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 216 /* Block */ ? "quit" : n === container_3; })) { + if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) { return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { - case 176 /* ThisType */: + case 178 /* ThisType */: return !!tp.isThisType; - case 71 /* Identifier */: + case 72 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return true; } return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +40478,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38812,13 +40522,19 @@ var ts; var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); var modifiers = getMappedTypeModifiers(type); return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38851,61 +40567,77 @@ var ts; if (root.isDistributive) { var checkType_1 = root.checkType; var instantiatedType = mapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & (262144 /* Union */ | 32768 /* Never */)) { + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return mapper(type); + } + if (flags & 524288 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } function getWildcardInstantiation(type) { - return type.flags & (32764 /* Primitive */ | 3 /* AnyOrUnknown */ | 32768 /* Never */) ? type : + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); } function instantiateIndexInfo(info, mapper) { @@ -38914,34 +40646,34 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 202 /* BinaryExpression */: - return node.operatorToken.kind === 54 /* BarBarToken */ && + case 204 /* BinaryExpression */: + return node.operatorToken.kind === 55 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 266 /* JsxAttributes */: - return ts.some(node.properties, isContextSensitive); - case 265 /* JsxAttribute */: { + case 268 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 268 /* JsxExpression */: { + case 270 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -38958,7 +40690,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 195 /* ArrowFunction */) { + if (node.kind !== 197 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -38971,14 +40703,14 @@ var ts; function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. var body = node.body; - return body.kind === 216 /* Block */ ? false : isContextSensitive(body); + return body.kind === 218 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); @@ -38989,7 +40721,7 @@ var ts; return result; } } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -39004,6 +40736,9 @@ var ts; function compareTypesAssignable(source, target) { return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } function isTypeSubtypeOf(source, target) { return isTypeRelatedTo(source, target, subtypeRelation); } @@ -39019,11 +40754,12 @@ var ts; // Note that this check ignores type parameters and only considers the // inheritance hierarchy. function isTypeDerivedFrom(source, target) { - return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : - target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : - source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39049,33 +40785,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { - case 268 /* JsxExpression */: - case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); - case 202 /* BinaryExpression */: + case 270 /* JsxExpression */: + case 195 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: - case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage); } break; - case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); - case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); - case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + case 188 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation); + case 187 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation); + case 268 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target, relation); + case 197 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40885,17 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */) + continue; // Don't elaborate on indexes on generic variables + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40904,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39112,16 +40915,19 @@ var ts; var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; var issuedElaboration = false; if (!targetProp) { - var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40961,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40994,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39208,17 +41019,17 @@ var ts; prop = _a[_i]; if (ts.isSpreadAssignment(prop)) return [3 /*break*/, 7]; - type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), 2240 /* StringOrNumberLiteralOrUnique */); - if (!type || (type.flags & 32768 /* Never */)) { + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 131072 /* Never */)) { return [3 /*break*/, 7]; } _b = prop.kind; switch (_b) { - case 157 /* SetAccessor */: return [3 /*break*/, 2]; - case 156 /* GetAccessor */: return [3 /*break*/, 2]; - case 154 /* MethodDeclaration */: return [3 /*break*/, 2]; - case 274 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 273 /* PropertyAssignment */: return [3 /*break*/, 4]; + case 159 /* SetAccessor */: return [3 /*break*/, 2]; + case 158 /* GetAccessor */: return [3 /*break*/, 2]; + case 156 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 275 /* PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -39239,8 +41050,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,14 +41081,15 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 154 /* MethodDeclaration */ && - kind !== 153 /* MethodSignature */ && kind !== 155 /* Constructor */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ && + kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -39295,11 +41107,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39311,7 +41123,7 @@ var ts; var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && - (getFalsyFlags(sourceType) & 24576 /* Nullable */) === (getFalsyFlags(targetType) & 24576 /* Nullable */); + (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); var related = callbacks ? // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : @@ -39325,13 +41137,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39403,12 +41215,15 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 131072 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 /* NonPrimitive */ ? true : - type.flags & 262144 /* Union */ ? ts.some(type.types, isEmptyObjectType) : - type.flags & 524288 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : + return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 /* NonPrimitive */ ? true : + type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : false; } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type); + } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { if (sourceSymbol === targetSymbol) { return true; @@ -39445,43 +41260,45 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 3 /* AnyOrUnknown */ || s & 32768 /* Never */ || source === wildcardType) + if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType) return true; - if (t & 32768 /* Never */) + if (t & 131072 /* Never */) return false; - if (s & 68 /* StringLike */ && t & 4 /* String */) + if (s & 132 /* StringLike */ && t & 4 /* String */) return true; - if (s & 64 /* StringLiteral */ && s & 512 /* EnumLiteral */ && - t & 64 /* StringLiteral */ && !(t & 512 /* EnumLiteral */) && + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && + t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 168 /* NumberLike */ && t & 8 /* Number */) + if (s & 296 /* NumberLike */ && t & 8 /* Number */) return true; - if (s & 128 /* NumberLiteral */ && s & 512 /* EnumLiteral */ && - t & 128 /* NumberLiteral */ && !(t & 512 /* EnumLiteral */) && + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && + t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 272 /* BooleanLike */ && t & 16 /* Boolean */) + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) return true; - if (s & 3072 /* ESSymbolLike */ && t & 1024 /* ESSymbol */) + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) + return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) return true; if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 512 /* EnumLiteral */ && t & 512 /* EnumLiteral */) { - if (s & 262144 /* Union */ && t & 262144 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 448 /* Literal */ && t & 448 /* Literal */ && + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 8192 /* Undefined */ && (!strictNullChecks || t & (8192 /* Undefined */ | 4096 /* Void */))) + if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */))) return true; - if (s & 16384 /* Null */ && (!strictNullChecks || t & 16384 /* Null */)) + if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */)) return true; - if (s & 131072 /* Object */ && t & 16777216 /* NonPrimitive */) + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) return true; - if (s & 2048 /* UniqueESSymbol */ || t & 2048 /* UniqueESSymbol */) + if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) @@ -39489,30 +41306,30 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (8 /* Number */ | 128 /* NumberLiteral */) && !(s & 512 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 128 /* NumberLiteral */ && t & 512 /* EnumLiteral */)) + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; } return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(target)) { target = target.regularType; } if (source === target || - relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */) { + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */) { + if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) { return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); } return false; @@ -39532,6 +41349,7 @@ var ts; */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -39539,7 +41357,7 @@ var ts; var depth = 0; var expandingFlags = 0 /* None */; var overflow = false; - var isIntersectionConstituent = false; + var suppressNextError = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (overflow) { @@ -39566,15 +41384,27 @@ var ts; } } var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } if (errorOutputContainer) { errorOutputContainer.error = diag; } diagnostics.add(diag); // TODO: GH#18217 } return result !== 0 /* False */; - function reportError(message, arg0, arg1, arg2) { + function reportError(message, arg0, arg1, arg2, arg3) { ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } } function reportRelationError(message, source, target) { var sourceType = typeToString(source); @@ -39607,7 +41437,7 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 786432 /* UnionOrIntersection */)) { + if (!(type.flags & 3145728 /* UnionOrIntersection */)) { return false; } // at this point we know that this is union or intersection type possibly with nullable constituents. @@ -39615,7 +41445,7 @@ var ts; var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 24576 /* Nullable */) { + if (t.flags & 98304 /* Nullable */) { continue; } if (seenNonNullable) { @@ -39631,24 +41461,24 @@ var ts; * * Ternary.Maybe if they are related with assumptions of other relationships, or * * Ternary.False if they are not related. */ - function isRelatedTo(source, target, reportErrors, headMessage) { + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(target)) { target = target.regularType; } - if (source.flags & 8388608 /* Substitution */) { + if (source.flags & 33554432 /* Substitution */) { source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } - if (target.flags & 8388608 /* Substitution */) { + if (target.flags & 33554432 /* Substitution */) { target = target.typeVariable; } - if (source.flags & 2097152 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { source = getSimplifiedType(source); } - if (target.flags & 2097152 /* IndexedAccess */) { + if (target.flags & 8388608 /* IndexedAccess */) { target = getSimplifiedType(target); } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. @@ -39660,10 +41490,10 @@ var ts; // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" // when dealing with generics. // * We also don't deal with primitive source types, since we already halt elaboration below. - if (target.flags & 262144 /* Union */ && source.flags & 131072 /* Object */ && - target.types.length <= 3 && maybeTypeOfKind(target, 24576 /* Nullable */)) { - var nullStrippedTarget = extractTypesOfKind(target, ~24576 /* Nullable */); - if (!(nullStrippedTarget.flags & (262144 /* Union */ | 32768 /* Never */))) { + if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); + if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { target = nullStrippedTarget; } } @@ -39673,11 +41503,12 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (isObjectLiteralType(source) && source.flags & 33554432 /* FreshLiteral */) { - var discriminantType = target.flags & 262144 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) { + var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -39692,14 +41523,11 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && - !hasCommonProperties(source, target)) { + !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); var constructs = getSignaturesOfType(source, 1 /* Construct */); @@ -39715,25 +41543,24 @@ var ts; } var result = 0 /* False */; var saveErrorInfo = errorInfo; - var saveIsIntersectionConstituent = isIntersectionConstituent; - isIntersectionConstituent = false; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); } else { - if (target.flags & 262144 /* Union */) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */) && !(target.flags & 32764 /* Primitive */)); + if (target.flags & 1048576 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); } - else if (target.flags & 524288 /* Intersection */) { - isIntersectionConstituent = true; + else if (target.flags & 2097152 /* Intersection */) { + isIntersectionConstituent = true; // set here to affect the following trio of checks result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 524288 /* Intersection */) { + else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -39749,13 +41576,13 @@ var ts; // breaking the intersection apart. result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } - if (!result && (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - if (!result && source.flags & 524288 /* Intersection */) { + if (!result && source.flags & 2097152 /* Intersection */) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -39765,22 +41592,23 @@ var ts; // we need to check this constraint against a union on the target side. Also, given a type // variable V constrained to 'string | number', 'V & number' has a combined constraint of // 'string & number | number & number' which reduces to just 'number'. - var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 262144 /* Union */)); + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */)); if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 131072 /* Object */ && target.flags & 32764 /* Primitive */) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 131072 /* Object */ && globalObjectType === source) { + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } - else if (ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && target.flags & 524288 /* Intersection */) { + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { var targetTypes = target.types; var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); @@ -39790,6 +41618,10 @@ var ts; return result; } } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } reportRelationError(headMessage, source, target); } return result; @@ -39797,49 +41629,23 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); + if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); } - if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { + if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { @@ -39849,17 +41655,18 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. if (!errorNode) return { value: ts.Debug.fail() }; - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { @@ -39888,13 +41695,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39910,7 +41720,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 262144 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -39923,16 +41733,17 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; } function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { var sourceObjectFlags = ts.getObjectFlags(source); - if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 262144 /* Union */) { + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { return ts.find(unionTarget.types, function (target) { - if (target.flags & 131072 /* Object */) { + if (target.flags & 524288 /* Object */) { var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); if (overlapObjFlags & 4 /* Reference */) { return source.target === target.target; @@ -39950,39 +41761,33 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); - if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } + if (target.flags & 1048576 /* Union */) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; var targetTypes = target.types; for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); + var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); if (!related) { return 0 /* False */; } @@ -39992,7 +41797,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 262144 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -40017,9 +41822,10 @@ var ts; } return result; } - function typeArgumentsRelatedTo(source, target, variances, reportErrors) { - var sources = source.typeArguments || ts.emptyArray; - var targets = target.typeArguments || ts.emptyArray; + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } @@ -40073,7 +41879,7 @@ var ts; // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function recursiveTypeRelatedTo(source, target, reportErrors) { + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { if (overflow) { return 0 /* False */; } @@ -40116,7 +41922,7 @@ var ts; expandingFlags |= 1 /* Source */; if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) expandingFlags |= 2 /* Target */; - var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -40139,13 +41945,57 @@ var ts; function getConstraintForRelation(type) { return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } - function structuredTypeRelatedTo(source, target, reportErrors) { + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288 /* Object */)) { + if (flags & 4194304 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 8388608 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 16777216 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 65536 /* TypeParameter */) { - // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144 /* TypeParameter */) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -40155,9 +42005,9 @@ var ts; } } } - else if (target.flags & 1048576 /* Index */) { + else if (target.flags & 4194304 /* Index */) { // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 1048576 /* Index */) { + if (source.flags & 4194304 /* Index */) { if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } @@ -40168,20 +42018,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } - else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (target.flags & 8388608 /* IndexedAccess */) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40190,23 +42045,24 @@ var ts; var template = getTemplateTypeFromMappedType(target); var modifiers = getMappedTypeModifiers(target); if (!(modifiers & 8 /* ExcludeOptional */)) { - if (template.flags & 2097152 /* IndexedAccess */ && template.objectType === source && + if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source && template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } } - if (source.flags & 2162688 /* TypeVariable */) { - if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + if (source.flags & 8650752 /* TypeVariable */) { + if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { // A type S[K] is related to a type T[J] if S is related to T and K is related to J. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { result &= isRelatedTo(source.indexType, target.indexType, reportErrors); @@ -40217,29 +42073,32 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 65536 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~16777216 /* NonPrimitive */))) { + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { errorInfo = saveErrorInfo; return result; } } - else { - var instantiated = getTypeWithThisArgument(constraint, source); - if (result = isRelatedTo(instantiated, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; } } - else if (source.flags & 1048576 /* Index */) { + else if (source.flags & 4194304 /* Index */) { if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { errorInfo = saveErrorInfo; return result; } } - else if (source.flags & 4194304 /* Conditional */) { - if (target.flags & 4194304 /* Conditional */) { + else if (source.flags & 16777216 /* Conditional */) { + if (target.flags & 16777216 /* Conditional */) { // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, // and Y1 is related to Y2. @@ -40272,13 +42131,33 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); - if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { return result; } // The type arguments did not relate appropriately, but it may be because we have no variance @@ -40305,36 +42184,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +42226,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40373,7 +42242,24 @@ var ts; var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } } return 0 /* False */; } @@ -40420,8 +42306,8 @@ var ts; } } var properties = getPropertiesOfObjectType(target); - for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { - var targetProp = properties_3[_b]; + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { @@ -40491,35 +42377,8 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { + if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -40549,8 +42408,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40647,7 +42506,7 @@ var ts; continue; } // Skip over symbol-named members - if (prop.nameType && prop.nameType.flags & 2048 /* UniqueESSymbol */) { + if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) { continue; } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { @@ -40742,6 +42601,51 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -40749,62 +42653,71 @@ var ts; result.objectFlags |= 8192 /* MarkerType */; return result; } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } // Return an array containing the variance of each type parameter. The variance is effectively // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } function getVariances(type) { if (!strictFunctionTypes) { return ts.emptyArray; } - var typeParameters = type.typeParameters || ts.emptyArray; - var variances = type.variances; - if (!variances) { - if (type === globalArrayType || type === globalReadonlyArrayType) { - // Arrays are known to be covariant, no need to spend time computing this - variances = [1 /* Covariant */]; - } - else { - // The emptyArray singleton is used to signal a recursive invocation. - type.variances = ts.emptyArray; - variances = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - // We first compare instantiations where the type parameter is replaced with - // marker types that have a known subtype relationship. From this we can infer - // invariance, covariance, contravariance or bivariance. - var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); - var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); - var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | - (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); - // If the instantiations appear to be related bivariantly it may be because the - // type parameter is independent (i.e. it isn't witnessed anywhere in the generic - // type). To determine this we compare instantiations where the type parameter is - // replaced with marker types that are known to be unrelated. - if (variance === 3 /* Bivariant */ && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { - variance = 4 /* Independent */; - } - variances.push(variance); - } - } - type.variances = variances; + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return ts.emptyArray; } - return variances; + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } // Return true if the given type reference has a 'void' type argument for a covariant type parameter. // See comment at call in recursiveTypeRelatedTo for when this case matters. function hasCovariantVoidArgument(type, variances) { for (var i = 0; i < variances.length; i++) { - if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 4096 /* Void */) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { return true; } } return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -40897,13 +42810,13 @@ var ts; // levels, but unequal at some level beyond that. function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 131072 /* Object */) { + if (depth >= 5 && type.flags & 524288 /* Object */) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 131072 /* Object */ && t.symbol === symbol) { + if (t.flags & 524288 /* Object */ && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -40958,12 +42871,8 @@ var ts; return true; } // A source signature partially matches a target signature if the target signature has no fewer required - // parameters and no more overall parameters than the source signature (where a signature with a rest - // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = sourceHasRestParameter ? 1 : 0; - var targetRestCount = targetHasRestParameter ? 1 : 0; - if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) { + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { return true; } return false; @@ -41009,7 +42918,7 @@ var ts; for (var i = 0; i < targetLen; i++) { var s = getTypeAtPosition(source, i); var t = getTypeAtPosition(target, i); - var related = compareTypes(s, t); + var related = compareTypes(t, s); if (!related) { return 0 /* False */; } @@ -41030,8 +42939,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41054,9 +42963,9 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 24576 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 24576 /* Nullable */) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) : getUnionType(types, 2 /* Subtype */); } // Return the leftmost type for which no type to the right is a subtype. @@ -41069,11 +42978,14 @@ var ts; function isReadonlyArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 24576 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isEmptyArrayLiteralType(type) { var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; @@ -41083,40 +42995,47 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { - return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); + return !(type.flags & (109440 /* Unit */ | 131072 /* Never */)); } function isUnitType(type) { - return !!(type.flags & 27072 /* Unit */); + return !!(type.flags & 109440 /* Unit */); } function isLiteralType(type) { return type.flags & 16 /* Boolean */ ? true : - type.flags & 262144 /* Union */ ? type.flags & 512 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : + type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 /* StringLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : - type; + return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 512 /* BooleanLiteral */ ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : - type; + return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : + type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : + type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; } function getWidenedUniqueESSymbolType(type) { - return type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : type; } function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { @@ -41135,13 +43054,21 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41150,15 +43077,16 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : - type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : - type.flags & 29148 /* PossiblyFalsy */; + return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 : + type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 : + type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 : + type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 : + type.flags & 117724 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 29120 /* DefinitelyFalsy */); }) : + return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) : type; } function extractDefinitelyFalsyTypes(type) { @@ -41167,10 +43095,13 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : - type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + type.flags & 64 /* BigInt */ ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) || + type.flags & 128 /* StringLiteral */ && type.value === "" || + type.flags & 256 /* NumberLiteral */ && type.value === 0 || + type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : neverType; } /** @@ -41179,15 +43110,15 @@ var ts; * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both */ function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (8192 /* Undefined */ | 16384 /* Null */); + var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */); return missing === 0 ? type : - missing === 8192 /* Undefined */ ? getUnionType([type, undefinedType]) : - missing === 16384 /* Null */ ? getUnionType([type, nullType]) : + missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 65536 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } function getOptionalType(type) { ts.Debug.assert(strictNullChecks); - return type.flags & 8192 /* Undefined */ ? type : getUnionType([type, undefinedType]); + return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { if (!deferredGlobalNonNullableTypeAlias) { @@ -41197,7 +43128,7 @@ var ts; if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); } - return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -41240,7 +43171,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && type.flags & 33554432 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -41250,7 +43181,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; + regularNew.flags = resolved.flags; regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); type.regularType = regularNew; return regularNew; @@ -41338,15 +43269,15 @@ var ts; } function getWidenedTypeWithContext(type, context) { if (type.flags & 402653184 /* RequiresWidening */) { - if (type.flags & 24576 /* Nullable */) { + if (type.flags & 98304 /* Nullable */) { return anyType; } if (isObjectLiteralType(type)) { return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); - var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 24576 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). @@ -41372,7 +43303,7 @@ var ts; function reportWideningErrorsInType(type) { var errorReported = false; if (type.flags & 134217728 /* ContainsWideningType */) { - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } @@ -41408,68 +43339,90 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { - case 202 /* BinaryExpression */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + case 204 /* BinaryExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 149 /* Parameter */: + case 151 /* Parameter */: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - if (!declaration.name) { + case 289 /* JSDocFunctionType */: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; break; - case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + case 181 /* MappedType */: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41518,11 +43471,11 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - return !!(type.flags & 15794176 /* Instantiable */ || + return !!(type.flags & 63176704 /* Instantiable */ || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || - type.flags & 786432 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -41531,13 +43484,13 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || !!(type.flags & 786432 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { - if (!(t.flags & 64 /* StringLiteral */)) { + if (!(t.flags & 128 /* StringLiteral */)) { return; } var name = ts.escapeLeadingUnderscores(t.value); @@ -41558,25 +43511,25 @@ var ts; * property is computed by inferring from the source property type to X for the type * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ - function inferTypeForHomomorphicMappedType(source, target) { - var key = source.id + "," + target.id; + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } reverseMappedCache.set(key, undefined); - var type = createReverseMappedType(source, target); + var type = createReverseMappedType(source, target, constraint); reverseMappedCache.set(key, type); return type; } - function createReverseMappedType(source, target) { + function createReverseMappedType(source, target, constraint) { var properties = getPropertiesOfType(source); if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { return undefined; } // If any property contains context sensitive functions that have been skipped, the source type // is incomplete and we can't infer a meaningful input type. - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var prop = properties_4[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { return undefined; } @@ -41584,13 +43537,13 @@ var ts; // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been // applied to the element type(s). if (isArrayType(source)) { - return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isReadonlyArrayType(source)) { - return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isTupleType(source)) { - var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); @@ -41600,30 +43553,46 @@ var ts; var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; + reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); } - function inferReverseMappedType(sourceType, target) { - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = target.flags & 524288 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; - if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (!sourceProp) { - return targetProp; - } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3 /*break*/, 3]; + return [4 /*yield*/, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; } - } - return undefined; + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -41645,7 +43614,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41671,8 +43642,8 @@ var ts; } return; } - if (source.flags & 262144 /* Union */ && target.flags & 262144 /* Union */ && !(source.flags & 512 /* EnumLiteral */ && target.flags & 512 /* EnumLiteral */) || - source.flags & 524288 /* Intersection */ && target.flags & 524288 /* Intersection */) { + if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) || + source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -41695,7 +43666,7 @@ var ts; (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } - else if (t.flags & (128 /* NumberLiteral */ | 64 /* StringLiteral */)) { + else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) { var b = getBaseTypeOfLiteralType(t); if (typeIdenticalToSomeType(b, target.types)) { (matchingTypes || (matchingTypes = [])).push(t, b); @@ -41710,7 +43681,7 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 2162688 /* TypeVariable */) { + if (target.flags & 8650752 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding @@ -41718,7 +43689,7 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType) { + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -41731,19 +43702,39 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } - if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 63176704 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments @@ -41760,12 +43751,12 @@ var ts; } } } - else if (source.flags & 1048576 /* Index */ && target.flags & 1048576 /* Index */) { + else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { contravariant = !contravariant; inferFromTypes(source.type, target.type); contravariant = !contravariant; } - else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 1048576 /* Index */) { + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; var savePriority = priority; @@ -41774,17 +43765,20 @@ var ts; priority = savePriority; contravariant = !contravariant; } - else if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (source.flags & 4194304 /* Conditional */ && target.flags & 4194304 /* Conditional */) { + else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } - else if (target.flags & 786432 /* UnionOrIntersection */) { + else if (target.flags & 16777216 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -41809,7 +43803,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 262144 /* Union */) { + else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -41818,10 +43812,25 @@ var ts; } } else { - if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } - if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -41831,7 +43840,7 @@ var ts; // an instantiation of the same generic type), we do not explore this target as it would yield // no further inferences. We exclude the static side of classes from this check since it shares // its symbol with the instance side which would lead to false positives. - var isNonConstructorObject = target.flags & 131072 /* Object */ && + var isNonConstructorObject = target.flags & 524288 /* Object */ && !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { @@ -41847,6 +43856,13 @@ var ts; } } } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { @@ -41859,7 +43875,7 @@ var ts; } } function getInferenceInfoForType(type) { - if (type.flags & 2162688 /* TypeVariable */) { + if (type.flags & 8650752 /* TypeVariable */) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -41869,6 +43885,44 @@ var ts; } return undefined; } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* HomomorphicMappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } function inferFromObjectTypes(source, target) { if (isGenericMappedType(source) && isGenericMappedType(target)) { // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer @@ -41878,31 +43932,7 @@ var ts; } if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 1048576 /* Index */) { - // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, - // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source - // type and then make a secondary inference from that type to T. We make a secondary inference - // such that direct inferences to T get priority over inferences to Partial, for example. - var inference = getInferenceInfoForType(constraintType.type); - if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - var savePriority = priority; - priority |= 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; - } - } - return; - } - if (constraintType.flags & 65536 /* TypeParameter */) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. - var savePriority = priority; - priority |= 4 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { return; } } @@ -41915,33 +43945,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +43986,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +44030,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42007,11 +44050,11 @@ var ts; reducedTypes.push(t); } } - return type.flags & 262144 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +44072,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +44085,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +44098,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +44127,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +44156,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42124,7 +44198,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 165 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 146 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the @@ -42133,20 +44207,20 @@ var ts; // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } - if (node.kind === 99 /* ThisKeyword */) { + if (node.kind === 100 /* ThisKeyword */) { return "0"; } - if (node.kind === 187 /* PropertyAccessExpression */) { + if (node.kind === 189 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); return key && key + "." + ts.idText(node.name); } - if (node.kind === 184 /* BindingElement */) { + if (node.kind === 186 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 184 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -42155,14 +44229,14 @@ var ts; } function getBindingElementNameText(element) { var parent = element.parent; - if (parent.kind === 182 /* ObjectBindingPattern */) { + if (parent.kind === 184 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.idText(name); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return name.text; default: @@ -42176,29 +44250,29 @@ var ts; } function isMatchingReference(source, target) { switch (source.kind) { - case 71 /* Identifier */: - return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 235 /* VariableDeclaration */ || target.kind === 184 /* BindingElement */) && + case 72 /* Identifier */: + return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99 /* ThisKeyword */: - return target.kind === 99 /* ThisKeyword */; - case 97 /* SuperKeyword */: - return target.kind === 97 /* SuperKeyword */; - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 100 /* ThisKeyword */: + return target.kind === 100 /* ThisKeyword */; + case 98 /* SuperKeyword */: + return target.kind === 98 /* SuperKeyword */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 184 /* BindingElement */: - if (target.kind !== 187 /* PropertyAccessExpression */) + case 186 /* BindingElement */: + if (target.kind !== 189 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 184 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 235 /* VariableDeclaration */) { + if (source.parent.parent.kind === 237 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; return !!maybeId && isMatchingReference(maybeId, t.expression); } @@ -42211,7 +44285,7 @@ var ts; undefined; } function containsMatchingReference(source, target) { - while (source.kind === 187 /* PropertyAccessExpression */) { + while (source.kind === 189 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -42224,32 +44298,52 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 187 /* PropertyAccessExpression */ && + return target.kind === 189 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71 /* Identifier */) { + if (expr.kind === 72 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 187 /* PropertyAccessExpression */) { + if (expr.kind === 189 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 262144 /* Union */) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; + function isDiscriminantType(type) { + if (type.flags & 1048576 /* Union */) { + if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { + return true; } } return false; } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576 /* Union */); + } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -42276,7 +44370,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -42289,16 +44383,35 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 32768 /* Never */) { + if (assignedType.flags & 131072 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +44419,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42322,55 +44435,66 @@ var ts; function getTypeFacts(type) { var flags = type.flags; if (flags & 4 /* String */) { - return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; } - if (flags & 64 /* StringLiteral */) { + if (flags & 128 /* StringLiteral */) { var isEmpty = type.value === ""; return strictNullChecks ? - isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : + isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; } if (flags & (8 /* Number */ | 32 /* Enum */)) { - return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; } - if (flags & 128 /* NumberLiteral */) { + if (flags & 256 /* NumberLiteral */) { var isZero = type.value === 0; return strictNullChecks ? - isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : - isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; + isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : + isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : + isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; } if (flags & 16 /* Boolean */) { - return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; } - if (flags & 272 /* BooleanLike */) { + if (flags & 528 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 524288 /* Object */) { + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ : + strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } - if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { - return 2457472 /* UndefinedFacts */; + if (flags & (16384 /* Void */ | 32768 /* Undefined */)) { + return 9830144 /* UndefinedFacts */; } - if (flags & 16384 /* Null */) { - return 2340752 /* NullFacts */; + if (flags & 65536 /* Null */) { + return 9363232 /* NullFacts */; } - if (flags & 3072 /* ESSymbolLike */) { - return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; } - if (flags & 16777216 /* NonPrimitive */) { - return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } - if (flags & 15794176 /* Instantiable */) { + if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 786432 /* UnionOrIntersection */) { + if (flags & 3145728 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } - return 4194303 /* All */; + return 16777215 /* All */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -42378,7 +44502,7 @@ var ts; function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); + return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); } return type; } @@ -42390,7 +44514,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42398,15 +44522,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 185 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 273 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 225 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -42423,21 +44547,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return stringType; - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return undefinedType; - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -42445,7 +44569,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 182 /* ObjectBindingPattern */ ? + var type = pattern.kind === 184 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -42463,39 +44587,39 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 224 /* ForInStatement */) { + if (node.parent.parent.kind === 226 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 225 /* ForOfStatement */) { + if (node.parent.parent.kind === 227 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 235 /* VariableDeclaration */ ? + return node.kind === 237 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { - return node.kind === 235 /* VariableDeclaration */ && node.initializer && + return node.kind === 237 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 184 /* BindingElement */ && node.parent.kind === 202 /* BinaryExpression */ && + node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return getReferenceCandidate(node.left); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return getReferenceCandidate(node.right); } } @@ -42503,13 +44627,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 193 /* ParenthesizedExpression */ || - parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + return parent.kind === 195 /* ParenthesizedExpression */ || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 269 /* CaseClause */) { + if (clause.kind === 271 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -42525,14 +44649,31 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271 /* CaseClause */) { + if (clause.expression.kind === 10 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { - return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 262144 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -42541,34 +44682,37 @@ var ts; } return true; } - if (source.flags & 512 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); + return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); } return f(type) ? type : neverType; } function mapType(type, mapper, noReductions) { - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { return type; } - if (!(type.flags & 262144 /* Union */)) { + if (!(type.flags & 1048576 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42591,12 +44735,14 @@ var ts; // typeWithPrimitives have been replaced with occurrences of string literals and numeric // literals in typeWithLiterals, respectively. function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* StringLiteral */) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* NumberLiteral */)) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) { return mapType(typeWithPrimitives, function (t) { - return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 64 /* StringLiteral */) : - t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 128 /* NumberLiteral */) : - t; + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : + t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : + t; }); } return typeWithPrimitives; @@ -42630,9 +44776,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 32768 /* Never */ ? + return elementType.flags & 131072 /* Never */ ? autoArrayType : - createArrayType(elementType.flags & 262144 /* Union */ ? + createArrayType(elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType); } @@ -42648,9 +44794,9 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - if (!(t.flags & 32768 /* Never */)) { + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; } @@ -42672,15 +44818,15 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 187 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || - parent.parent.kind === 189 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 188 /* ElementAccessExpression */ && + var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 202 /* BinaryExpression */ && - parent.parent.operatorToken.kind === 58 /* EqualsToken */ && + parent.parent.kind === 204 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 59 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 168 /* NumberLike */); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -42691,7 +44837,7 @@ var ts; return links.maybeTypePredicate; } function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97 /* SuperKeyword */) { + if (node.expression.kind !== 98 /* SuperKeyword */) { var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); @@ -42713,7 +44859,7 @@ var ts; if (flowAnalysisDisabled) { return errorType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 33492479 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) { return declaredType; } var sharedFlowStart = sharedFlowCount; @@ -42723,14 +44869,14 @@ var ts; // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. - var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent && reference.parent.kind === 211 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 32768 /* Never */) { + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { return declaredType; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42796,9 +44942,9 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.container; if (container && container !== flowContainer && - reference.kind !== 187 /* PropertyAccessExpression */ && - reference.kind !== 188 /* ElementAccessExpression */ && - reference.kind !== 99 /* ThisKeyword */) { + reference.kind !== 189 /* PropertyAccessExpression */ && + reference.kind !== 190 /* ElementAccessExpression */ && + reference.kind !== 100 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -42833,11 +44979,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + if (declaredType.flags & 1048576 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,15 +44992,27 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } + // for (const _ in ref) acts as a nonnull on ref + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } // Assignment doesn't affect reference return undefined; } function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 189 /* CallExpression */ ? + var expr = node.kind === 191 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -42862,15 +45020,16 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -42884,7 +45043,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { return flowType; } // If we have an antecedent type (meaning we're reachable in some way), we first @@ -42901,19 +45060,25 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 32768 /* Never */ ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43027,8 +45192,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 262144 /* Union */) || - expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + if (!(computedType.flags & 1048576 /* Union */) || + expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { return false; } var access = expr; @@ -43049,10 +45214,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); + return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } if (isMatchingReferenceDiscriminant(expr, declaredType)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } if (containsMatchingReferenceDiscriminant(reference, expr)) { return declaredType; @@ -43070,7 +45235,7 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if ((type.flags & (262144 /* Union */ | 131072 /* Object */)) || (type.flags & 65536 /* TypeParameter */ && type.isThisType)) { + if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); } @@ -43078,19 +45243,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -43109,15 +45274,15 @@ var ts; return declaredType; } break; - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 92 /* InKeyword */: + case 93 /* InKeyword */: var target = getReferenceCandidate(expr.right); if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; - case 26 /* CommaToken */: + case 27 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } return type; @@ -43126,28 +45291,28 @@ var ts; if (type.flags & 1 /* Any */) { return type; } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 24576 /* Nullable */) { + if (valueType.flags & 98304 /* Nullable */) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; + var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */; var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - valueType.flags & 16384 /* Null */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : + valueType.flags & 65536 /* Null */ ? + assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : + assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 16909315 /* NotUnionOrUnit */) { + if (type.flags & 67637251 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 32768 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -43159,40 +45324,47 @@ var ts; // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { return declaredType; } return type; } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 15794176 /* Instantiable */) { + if (type.flags & 63176704 /* Instantiable */) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43203,27 +45375,115 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 32768 /* Never */ ? neverType : + var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 /* Any */ ? type : globalFunctionType; + case "object": + return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjusted clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { return declaredType; } return type; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43240,22 +45500,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43263,9 +45513,9 @@ var ts; } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 32768 /* Never */)) { + if (!(assignableType.flags & 131072 /* Never */)) { return assignableType; } } @@ -43305,7 +45555,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 188 /* ElementAccessExpression */ || invokedExpression.kind === 187 /* PropertyAccessExpression */) { + if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -43322,20 +45572,20 @@ var ts; // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 200 /* PrefixUnaryExpression */: - if (expr.operator === 51 /* ExclamationToken */) { + case 202 /* PrefixUnaryExpression */: + if (expr.operator === 52 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -43349,7 +45599,7 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 71 /* Identifier */) { + if (location.kind === 72 /* Identifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } @@ -43370,17 +45620,17 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 243 /* ModuleBlock */ || - node.kind === 277 /* SourceFile */ || - node.kind === 152 /* PropertyDeclaration */; + node.kind === 245 /* ModuleBlock */ || + node.kind === 279 /* SourceFile */ || + node.kind === 154 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43388,13 +45638,13 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 149 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) { symbol.isAssigned = true; } } @@ -43409,21 +45659,21 @@ var ts; /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 149 /* Parameter */ && + declaration.kind === 151 /* Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 8192 /* Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 8192 /* Undefined */); - return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 187 /* PropertyAccessExpression */ || - parent.kind === 189 /* CallExpression */ && parent.expression === node || - parent.kind === 188 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 184 /* BindingElement */ && parent.name === node && !!parent.initializer; + return parent.kind === 189 /* PropertyAccessExpression */ || + parent.kind === 191 /* CallExpression */ && parent.expression === node || + parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { - return type.flags & 14745600 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 24576 /* Nullable */); + return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */); } function getConstraintForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, @@ -43436,7 +45686,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43454,7 +45704,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 195 /* ArrowFunction */) { + if (container.kind === 197 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { @@ -43475,28 +45725,28 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 238 /* ClassDeclaration */ + if (declaration.kind === 240 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); } } - else if (declaration.kind === 207 /* ClassExpression */) { + else if (declaration.kind === 209 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 277 /* SourceFile */) { + while (container.kind !== 279 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43509,12 +45759,17 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } return errorType; } } @@ -43538,7 +45793,7 @@ var ts; // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 149 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -43547,8 +45802,8 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 194 /* FunctionExpression */ || - flowContainer.kind === 195 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ || + flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -43557,9 +45812,9 @@ var ts; // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || - isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || - node.parent.kind === 211 /* NonNullExpression */ || - declaration.kind === 235 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) || + node.parent.kind === 213 /* NonNullExpression */ || + declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 4194304 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -43568,7 +45823,7 @@ var ts; // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (type === autoType || type === autoArrayType) { + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); @@ -43577,7 +45832,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -43587,10 +45842,13 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 272 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -43611,26 +45869,46 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + 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 === 223 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && + if (container.kind === 225 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 193 /* ParenthesizedExpression */) { + while (current.parent.kind === 195 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -43638,9 +45916,9 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 200 /* PrefixUnaryExpression */ || current.parent.kind === 201 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) { var expr = current.parent; - isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; + isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */; } if (!isAssigned) { return false; @@ -43651,7 +45929,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 152 /* PropertyDeclaration */ || container.kind === 155 /* Constructor */) { + if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -43719,37 +45997,37 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 155 /* Constructor */) { + if (container.kind === 157 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 195 /* ArrowFunction */) { + if (container.kind === 197 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } switch (container.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* 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 241 /* EnumDeclaration */: + case 243 /* 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 155 /* Constructor */: + case 157 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: if (ts.hasModifier(container, 32 /* Static */)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -43760,39 +46038,43 @@ var ts; var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ? + var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } } return type || anyType; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,16 +46089,68 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 196 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 156 /* MethodDeclaration */ && + container.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 196 /* FunctionExpression */ && + container.parent.kind === 275 /* PropertyAssignment */ && + container.parent.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === 196 /* FunctionExpression */ && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -43830,15 +46164,15 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 149 /* Parameter */; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 189 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 195 /* ArrowFunction */) { + while (container && container.kind === 197 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -43851,14 +46185,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 147 /* ComputedPropertyName */; }); - if (current && current.kind === 147 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; }); + if (current && current.kind === 149 /* 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 === 186 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -43866,7 +46200,7 @@ var ts; } return errorType; } - if (!isCallExpression && container.kind === 155 /* Constructor */) { + if (!isCallExpression && container.kind === 157 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { @@ -43898,16 +46232,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // 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: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43919,20 +46255,21 @@ var ts; // // 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); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = 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 === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. + if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -43946,7 +46283,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 186 /* ObjectLiteralExpression */) { + if (container.parent.kind === 188 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -43967,7 +46304,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 155 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 157 /* 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 errorType; @@ -43982,7 +46319,7 @@ 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 === 155 /* Constructor */; + return container.kind === 157 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -43990,21 +46327,21 @@ var 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\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) { if (ts.hasModifier(container, 32 /* Static */)) { - return container.kind === 154 /* MethodDeclaration */ || - container.kind === 153 /* MethodSignature */ || - container.kind === 156 /* GetAccessor */ || - container.kind === 157 /* SetAccessor */; + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */; } else { - return container.kind === 154 /* MethodDeclaration */ || - container.kind === 153 /* MethodSignature */ || - container.kind === 156 /* GetAccessor */ || - container.kind === 157 /* SetAccessor */ || - container.kind === 152 /* PropertyDeclaration */ || - container.kind === 151 /* PropertySignature */ || - container.kind === 155 /* Constructor */; + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */ || + container.kind === 154 /* PropertyDeclaration */ || + container.kind === 153 /* PropertySignature */ || + container.kind === 157 /* Constructor */; } } } @@ -44012,10 +46349,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 154 /* MethodDeclaration */ || - func.kind === 156 /* GetAccessor */ || - func.kind === 157 /* SetAccessor */) && func.parent.kind === 186 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 194 /* FunctionExpression */ && func.parent.kind === 273 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 156 /* MethodDeclaration */ || + func.kind === 158 /* GetAccessor */ || + func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -44023,11 +46360,11 @@ var ts; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 524288 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 195 /* ArrowFunction */) { + if (func.kind === 197 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -44039,7 +46376,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44054,7 +46391,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 273 /* PropertyAssignment */) { + if (literal.parent.kind !== 275 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -44068,9 +46405,9 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = func.parent; - if (parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) { var target = parent.left; - if (target.kind === 187 /* PropertyAccessExpression */ || target.kind === 188 /* ElementAccessExpression */) { + if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) { var expression = target.expression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { @@ -44096,7 +46433,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44130,7 +46467,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 149 /* Parameter */) { + if (declaration.kind === 151 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -44142,7 +46479,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 184 /* BindingElement */) { + if (parentDeclaration.kind !== 186 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -44163,9 +46500,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44212,7 +46561,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44220,10 +46569,13 @@ var ts; // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 191 /* TaggedTemplateExpression */) { + if (template.parent.kind === 193 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -44232,26 +46584,33 @@ var ts; var binaryExpression = node.parent; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { - case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; - case 54 /* BarBarToken */: + case 59 /* EqualsToken */: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; - case 53 /* AmpersandAmpersandToken */: - case 26 /* CommaToken */: + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; default: return undefined; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,26 +46628,57 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return ts.Debug.fail("Does not apply"); default: return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - if (t.flags & 917504 /* StructuredType */) { + if (t.flags & 3670016 /* StructuredType */) { var prop = getPropertyOfType(t, name); if (prop) { return getTypeOfSymbol(prop); @@ -44299,6 +46689,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +46698,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44329,8 +46717,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44346,7 +46734,6 @@ var ts; // type of T. function getContextualTypeForElementExpression(arrayContextualType, index) { return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) - || getIndexTypeOfContextualType(arrayContextualType, 1 /* Number */) || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); } // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. @@ -44388,54 +46775,44 @@ var ts; // recursive (and possibly infinite) invocations of getContextualType. function isPossiblyDiscriminantValue(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 71 /* Identifier */: + case 9 /* BigIntLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 72 /* Identifier */: + case 141 /* UndefinedKeyword */: return true; - case 187 /* PropertyAccessExpression */: - case 193 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 195 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 270 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44464,52 +46841,54 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 186 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 195 /* ArrowFunction */: - case 228 /* ReturnStatement */: + case 197 /* ArrowFunction */: + case 230 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 201 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); + case 191 /* CallExpression */: + case 192 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 185 /* ArrayLiteralExpression */: { + case 187 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 214 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 204 /* TemplateExpression */); + case 216 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 193 /* ParenthesizedExpression */: { + case 195 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent); } return undefined; @@ -44519,67 +46898,16 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; } - var valueType = checkExpression(node.tagName); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); + return getContextualTypeForArgumentAtIndex(node, 0); } - function getJsxSignaturesParameterTypes(valueType, isJs, context) { - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (valueType.flags & 4 /* String */) { - return anyType; - } - else if (valueType.flags & 64 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = valueType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - } - return anyType; - } - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(valueType, 1 /* Construct */); - var ctor = true; - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, 0 /* Call */); - ctor = false; - if (signatures.length === 0) { - // We found no signatures at all, which is an error - return errorType; - } - } - var links = getNodeLinks(context); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(valueType); - var cachedResolved = links.resolvedSignatures.get(cacheKey); - if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { - signatures = cachedResolved; - } - else if (!cachedResolved) { - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); - } - return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); @@ -44594,22 +46922,40 @@ var ts; var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } return attributesType; } - function getJsxPropsTypeFromClassType(sig, isJs, context, reportErrors) { + function getJsxPropsTypeFromClassType(sig, context) { var ns = getJsxNamespaceAt(context); var forcedLookupLocation = getJsxElementPropertiesName(ns); var attributesType = forcedLookupLocation === undefined @@ -44622,7 +46968,7 @@ var ts; : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); if (!attributesType) { // There is no property named 'props' on this instance type - if (reportErrors && !!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); } return emptyObjectType; @@ -44640,7 +46986,7 @@ var ts; var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); var hostClassType = getReturnTypeOfSignature(sig); apparentAttributesType = intersectTypes(typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) : intrinsicClassAttribs, apparentAttributesType); } var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); @@ -44676,7 +47022,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 194 /* FunctionExpression */ || node.kind === 195 /* ArrowFunction */; + return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -44695,7 +47041,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -44704,13 +47050,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 262144 /* Union */)) { + if (!(type.flags & 1048576 /* Union */)) { return getContextualCallSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44743,10 +47089,10 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 184 /* BindingElement */ && !!node.initializer) || - (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + return (node.kind === 186 /* BindingElement */ && !!node.initializer) || + (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44755,7 +47101,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elementCount; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 206 /* SpreadElement */) { + if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -44768,7 +47114,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,47 +47123,59 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } - if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { + if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) { hasNonEndingSpreadElement = true; } } if (!hasNonEndingSpreadElement) { - var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206 /* SpreadElement */; + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - 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 (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + 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 (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) { + if (e.kind !== 210 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44826,12 +47184,12 @@ var ts; } function isNumericName(name) { switch (name.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return isNumericComputedName(name); - case 71 /* Identifier */: + case 72 /* Identifier */: return isNumericLiteralName(name.escapedText); case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return isNumericLiteralName(name.text); default: return false; @@ -44840,7 +47198,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAssignableToKind(checkComputedPropertyName(name), 168 /* NumberLike */); + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -44875,8 +47233,8 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (links.resolvedType.flags & 24576 /* Nullable */ || - !isTypeAssignableToKind(links.resolvedType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */) && + if (links.resolvedType.flags & 98304 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -44896,6 +47254,17 @@ var ts; var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + } function checkObjectLiteral(node, checkMode) { var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking @@ -44903,13 +47272,13 @@ var ts; var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 33554432 /* FreshLiteral */; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44919,15 +47288,15 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 147 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 273 /* PropertyAssignment */ || - memberDecl.kind === 274 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 275 /* PropertyAssignment */ || + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : - memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -44938,7 +47307,7 @@ var ts; } } typeFlags |= type.flags; - var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? + var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : @@ -44949,8 +47318,8 @@ 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 === 273 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 274 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -44975,12 +47344,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 275 /* SpreadAssignment */) { + else if (memberDecl.kind === 277 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -44992,7 +47361,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); offset = i + 1; continue; } @@ -45002,10 +47371,10 @@ 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 === 156 /* GetAccessor */ || memberDecl.kind === 157 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (computedNameType && !(computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */)) { + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { if (isTypeAssignableTo(computedNameType, numberType)) { hasComputedNumberProperty = true; @@ -45039,7 +47408,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); } return spread; } @@ -45048,9 +47417,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; - result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); - result.objectFlags |= 128 /* ObjectLiteral */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; + result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -45060,20 +47428,17 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 24576 /* Nullable */)) { - propagatedFlags |= (result.flags & 939524096 /* PropagatingFlags */); - } + propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; return result; } } function isValidSpreadType(type) { - return !!(type.flags & (3 /* AnyOrUnknown */ | 16777216 /* NonPrimitive */) || - getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 131072 /* Object */ && !isGenericMappedType(type) || - type.flags & 786432 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); } function checkJsxSelfClosingElementDeferred(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node, 0 /* Normal */); + checkJsxOpeningLikeElementOrOpeningFragment(node); } function checkJsxSelfClosingElement(node, _checkMode) { checkNodeDeferred(node); @@ -45081,7 +47446,7 @@ var ts; } function checkJsxElementDeferred(node) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, 0 /* Normal */); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -45089,18 +47454,20 @@ var ts; else { checkExpression(node.closingElement.tagName); } + checkJsxChildren(node); } function checkJsxElement(node, _checkMode) { checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } - function checkJsxFragment(node, checkMode) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { error(node, compilerOptions.jsxFactory ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } + checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } /** @@ -45114,7 +47481,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) { - return tagName.kind === 71 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); + return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); } function checkJsxAttribute(node, checkMode) { return node.initializer @@ -45133,16 +47500,19 @@ var ts; function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); - var spread = emptyObjectType; + var spread = emptyJsxObjectType; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45157,9 +47527,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +47537,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,11 +47546,11 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 258 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -45191,32 +47561,35 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); } } if (hasSpreadAnyType) { return anyType; } - if (typeToIntersect && spread !== emptyObjectType) { + if (typeToIntersect && spread !== emptyJsxObjectType) { return getIntersectionType([typeToIntersect, spread]); } - return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable * @param attributesTable a symbol table of attributes property */ function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; - result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; return result; } } @@ -45226,7 +47599,7 @@ var ts; var child = _a[_i]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. - if (child.kind === 10 /* JsxText */) { + if (child.kind === 11 /* JsxText */) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); } @@ -45248,7 +47621,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45289,57 +47662,6 @@ var ts; } return links.resolvedSymbol; } - function instantiateJsxSignatures(node, signatures) { - var instantiatedSignatures = []; - var candidateForTypeArgumentError; - var hasTypeArgumentError = !!node.typeArguments; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); - if (typeArgumentInstantiated) { - hasTypeArgumentError = false; - instantiatedSignatures.push(typeArgumentInstantiated); - } - else { - if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - candidateForTypeArgumentError = signature; - } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - } - else { - instantiatedSignatures.push(signature); - } - } - if (node.typeArguments && hasTypeArgumentError) { - if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); - } - // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine - else if (node.typeArguments.length !== 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); - } - } - return instantiatedSignatures; - } - function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { - if (reportErrors === void 0) { reportErrors = false; } - if (!node.typeArguments) { - return; - } - if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - return; - } - var args = checkTypeArguments(signature, node.typeArguments, reportErrors); - if (!args) { - return; - } - return getSignatureInstantiation(signature, args, isJavascript); - } function getJsxNamespaceAt(location) { var links = location && getNodeLinks(location); if (links && links.jsxNamespace) { @@ -45373,7 +47695,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +47719,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45410,217 +47732,78 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - return undefined; + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; } - if (propsType.flags & 524288 /* Intersection */) { - var propsApparentType = []; - for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { - var t = _a[_i]; - propsApparentType.push(getApparentType(t)); + else if (elementType.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; } - return getIntersectionType(propsApparentType); - } - return getApparentType(propsType); - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return only attributes type of successfully resolved call signature. - * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) - * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); - if (callSignature !== unknownSignature) { - var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); - var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; } } - return undefined; - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return all attributes type of resolved call signature including candidate signatures. - * This function assumes that the caller handled other possible element type of the JSX element. - * This function is a behavior used by language service when looking up completion in JSX element. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - var candidate = candidatesOutArray_1[_i]; - var callReturnType = getReturnTypeOfSignature(candidate); - // TODO: GH#18217: callReturnType should always be defined... - var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - var shouldBeCandidate = true; - for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217 - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - // If we can't find any matching, just return everything. - if (!result) { - result = allMatchingAttributesType; - } - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { - var links = getNodeLinks(openingLikeElement); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(elementType); - if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { - return; - } - else if (links.resolvedSignatures.get(cacheKey)) { - return links.resolvedSignatures.get(cacheKey); - } - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + var apparentElemType = getApparentType(elementType); // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(elementType, 1 /* Construct */); + var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); if (signatures.length === 0) { // No construct signatures, try call signatures - signatures = getSignaturesOfType(elementType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - if (reportErrors) { - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - } + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0 /* Component */) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { // Mixed + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { return; } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - // Instantiate in context of source type - var results = instantiateJsxSignatures(openingLikeElement, signatures); - links.resolvedSignatures.set(cacheKey, results); - return results; - } - /** - * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. - * For instance: - * declare function Foo(attr: { p1: string}): JSX.Element; - * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" - * - * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. - * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component - * - * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement - * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature - * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present - * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) - * @return attributes type if able to resolve the type of node - * anyType if there is no type ElementAttributesProperty or there is an error - * emptyObjectType if there is no "prop" in the element instance type - */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType.flags & 262144 /* Union */) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), 2 /* Subtype */); - } - // Shortcircuit any - if (isTypeAny(elementType)) { - return elementType; - } - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - else if (elementType.flags & 4 /* String */) { - return anyType; - } - else if (elementType.flags & 64 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - // If we need to report an error, we already done so here. So just return any to prevent any more error downstream - return anyType; - } - // Get the element instance type (the result of newing or invoking this tag) - var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); - if (!ts.length(instantiatedSignatures)) { - return errorType; - } - var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */); - // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. - // Otherwise get only attributes type from the signature picked by choose-overload logic. - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -45644,53 +47827,6 @@ var ts; } return links.resolvedJsxElementAttributesType; } - /** - * Get attributes type of the given custom opening-like JSX element. - * This function is intended to be called from a caller that handles intrinsic JSX element already. - * @param node a custom JSX opening-like element - * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component - */ - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); - } - /** - * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. - * This function is called by language service (see: completions-tryGetGlobalSymbols). - * @param node a JSX opening-like element to get attributes type for - */ - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - // Because in language service, the given JSX opening-like element may be incomplete and therefore, - // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); - } - } - /** - * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. - * @param node a JSXOpeningLikeElement node - * @return an attributes type of the given node - */ - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); - } - } - /** - * Given a JSX attribute, returns the symbol for the corresponds property - * of the element attributes type. Will return unknownSymbol for attributes - * that have no matching element attributes type property. - */ - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.escapedText); - return prop || unknownSymbol; - } function getJsxElementClassTypeAt(location) { var type = getJsxType(JsxNames.ElementClass, location); if (type === errorType) @@ -45724,7 +47860,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -45735,7 +47871,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45746,10 +47882,8 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } /** @@ -45766,7 +47900,7 @@ var ts; * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType */ function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 131072 /* Object */) { + if (targetType.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -45776,7 +47910,7 @@ var ts; return true; } } - else if (targetType.flags & 786432 /* UnionOrIntersection */) { + else if (targetType.flags & 3145728 /* UnionOrIntersection */) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -45784,55 +47918,12 @@ var ts; } } } - else if (targetType.flags & 4194304 /* Conditional */) { + else if (targetType.flags & 16777216 /* Conditional */) { return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); } return false; } - /** - * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. - * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" - * Check assignablity between given attributes property, "source attributes", and the "target attributes" - * @param openingLikeElement an opening-like JSX element to check its JSXAttributes - */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { - // The function involves following steps: - // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. - // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) - // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. - // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); - // sourceAttributesType is a type of an attributes properties. - // i.e
- // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); - // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties - var isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); - // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { - var attribute = _a[_i]; - if (!ts.isJsxAttribute(attribute)) { - continue; - } - var attrName = attribute.name; - var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); - // We break here so that errors won't be cascading - break; - } - } - } - else if (!isSourceAttributeTypeAssignableToTarget) { - checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); - } - } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -45856,10 +47947,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45872,7 +47963,7 @@ var ts; */ function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name; + var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); @@ -45904,7 +47995,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -45944,13 +48035,13 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { return true; } - if (type.flags & 65536 /* TypeParameter */) { + if (type.flags & 262144 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } @@ -45970,19 +48061,26 @@ var ts; function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + return getNonNullableType(type); + } + return type; + } function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { if (type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 24576 /* Nullable */; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 8192 /* Undefined */ ? kind & 16384 /* Null */ ? + error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); - return t.flags & (24576 /* Nullable */ | 32768 /* Never */) ? errorType : t; + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } @@ -46015,7 +48113,7 @@ var ts; return anyType; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } return errorType; } @@ -46026,12 +48124,12 @@ var ts; } else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); + markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } } @@ -46040,9 +48138,9 @@ var ts; // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 187 /* PropertyAccessExpression */ || + if (node.kind !== 189 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 262144 /* Union */)) { + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } // If strict null checks and strict property initialization checks are enabled, if we have @@ -46050,17 +48148,23 @@ var ts; // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && left.kind === 99 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 155 /* Constructor */ && flowContainer.parent === declaration.parent) { + if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) { assumeUninitialized = true; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -46079,8 +48183,8 @@ var ts; && !isPropertyDeclaredInAncestorClass(prop)) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 238 /* ClassDeclaration */ && - node.parent.kind !== 162 /* TypeReference */ && + else if (valueDeclaration.kind === 240 /* ClassDeclaration */ && + node.parent.kind !== 164 /* TypeReference */ && !(valueDeclaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -46092,9 +48196,9 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return true; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: @@ -46132,7 +48236,7 @@ var ts; function reportNonexistentProperty(propNode, containingType) { var errorInfo; var relatedInfo; - if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { + if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -46172,7 +48276,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46224,7 +48328,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -46241,16 +48345,16 @@ var ts; } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: - return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 146 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 148 /* QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 181 /* ImportType */: + case 183 /* ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -46277,20 +48381,20 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * 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 === 236 /* VariableDeclarationList */) { + if (initializer.kind === 238 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 71 /* Identifier */) { + else if (initializer.kind === 72 /* Identifier */) { return getResolvedSymbol(initializer); } return undefined; @@ -46307,13 +48411,13 @@ var ts; */ function isForInVariableForNumericPropertyNames(expr) { var e = ts.skipParentheses(expr); - if (e.kind === 71 /* Identifier */) { + if (e.kind === 72 /* Identifier */) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3 /* Variable */) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 224 /* ForInStatement */ && + if (node.kind === 226 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -46331,7 +48435,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 190 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 192 /* 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); @@ -46343,15 +48447,15 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) { error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46362,7 +48466,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 3072 /* ESSymbolLike */) === 0) { + if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -46389,8 +48493,7 @@ var ts; return true; } function callLikeExpressionMayHaveTypeArguments(node) { - // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) - return ts.isCallOrNewExpression(node); + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); } function resolveUntypedCall(node) { if (callLikeExpressionMayHaveTypeArguments(node)) { @@ -46398,10 +48501,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 191 /* TaggedTemplateExpression */) { + if (node.kind === 193 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 150 /* Decorator */) { + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -46428,8 +48534,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -46465,25 +48571,23 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 206 /* SpreadElement */ || arg.kind === 213 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call + var argCount; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". - return true; - } - if (node.kind === 191 /* TaggedTemplateExpression */) { - // 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 + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193 /* TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 204 /* TemplateExpression */) { + if (node.template.kind === 206 /* 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 lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -46494,35 +48598,53 @@ var ts; // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. var templateLiteral = node.template; - ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */); + ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + else if (node.kind === 152 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 190 /* NewExpression */); + ts.Debug.assert(node.kind === 192 /* NewExpression */); return getMinArgumentCount(signature) === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. - if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { return false; } // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = argCount >= getMinArgumentCount(signature); - return callIsIncomplete || hasEnoughArguments; + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; } function hasCorrectTypeArgumentArity(signature, typeArguments) { // If the user supplied type arguments, but the number of type arguments does not match @@ -46534,7 +48656,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -46545,7 +48667,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,16 +48676,11 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, node, context) { - // Skip context sensitive pass - var skipContextParamType = getTypeAtPosition(signature, 0); - var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); - inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); - // Standard pass - var paramType = getTypeAtPosition(signature, 0); - var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } @@ -46579,11 +48696,14 @@ var ts; inference.inferredType = undefined; } } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (node.kind !== 150 /* Decorator */) { + if (node.kind !== 152 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -46612,71 +48732,50 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; 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 !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. - return arg.kind === 213 /* SyntheticExpression */ ? + return arg.kind === 215 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; - var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 32764 /* Primitive */ | 1048576 /* Index */); + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */); var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,27 +48784,40 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2 /* Mixed */; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. * @param node a JSX opening-like element we are trying to figure its call signature @@ -46713,37 +48825,20 @@ var ts; * @param relation a relationship to check parameter and argument type * @param excludeArgument */ - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: - // 1. callIsIncomplete - // 2. attributes property has same number of properties as the parameter object type. - // We can figure that out by resolving attributes property and check number of properties in the resolved type - // If the call has correct arity, we will then check if the argument type and parameter type is assignable - var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete - if (callIsIncomplete) { - return true; - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, // can be specified by users through attributes property. - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 190 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -46756,346 +48851,142 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; 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 !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); - if (callee.kind === 187 /* PropertyAccessExpression */ || callee.kind === 188 /* ElementAccessExpression */) { + if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) { return callee.expression; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { - if (node.kind === 191 /* TaggedTemplateExpression */) { + if (node.kind === 193 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 - if (template.kind === 204 /* TemplateExpression */) { + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 152 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* 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); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* 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. + var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 1; + case 154 /* PropertyDeclaration */: + return 2; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 151 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,15 +48995,19 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; var minCount = getMinArgumentCount(sig); var maxCount = getParameterCount(sig); if (minCount < argCount && minCount > belowArgCount) belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,22 +49018,31 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -47146,14 +49050,15 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { - var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 150 /* Decorator */; + var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 152 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; var typeArguments; if (!isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -47161,40 +49066,26 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47222,7 +49113,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -47246,32 +49137,33 @@ var ts; // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, // skip the checkApplicableSignature check. - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". - return candidateForArgumentError; + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); - } - else if (candidateForArgumentArityError) { - diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); - } - else if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); - } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +49183,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47364,7 +49276,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47375,7 +49287,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47414,17 +49326,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47443,7 +49365,7 @@ var ts; return maxParamsIndex; } function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { @@ -47477,11 +49399,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47493,16 +49415,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47515,8 +49444,8 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -47575,11 +49504,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47592,7 +49523,7 @@ var ts; return false; } var firstBase = baseTypes[0]; - if (firstBase.flags & 524288 /* Intersection */) { + if (firstBase.flags & 2097152 /* Intersection */) { var types = firstBase.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); var i = 0; @@ -47649,10 +49580,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47676,8 +49608,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47691,16 +49623,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 149 /* Parameter */: + case 151 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -47716,8 +49648,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47736,6 +49668,46 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node); + var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.type = result; + return createSignature(declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } /** * Sometimes, we have a decorator that could accept zero arguments, * but is receiving too many arguments as part of the decorator invocation. @@ -47745,52 +49717,22 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } - /** - * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. - * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName - * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) - * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. - * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function - * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); - if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); - } - return undefined; - } function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); - case 150 /* Decorator */: + case 152 /* Decorator */: return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: - // This code-path is called by language service - var exprTypes = checkExpression(node.tagName); - return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); - if (sfcResult && sfcResult !== unknownSignature) { - return sfcResult; - } - var sigs = getInstantiatedJsxSignatures(node, exprType); - if (candidatesOutArray && ts.length(sigs)) { - candidatesOutArray.push.apply(candidatesOutArray, sigs); - } - return ts.length(sigs) ? sigs[0] : unknownSignature; - }) || unknownSignature; + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -47824,34 +49766,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { - if (type.flags & 131072 /* Object */) { + function isJSConstructorType(type) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,22 +49810,19 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } var parent = node.parent; - while (parent && parent.kind === 187 /* PropertyAccessExpression */) { + while (parent && parent.kind === 189 /* PropertyAccessExpression */) { parent = parent.parent; } - if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) { var right = ts.getInitializerOfBinaryExpression(parent); return ts.isObjectLiteralExpression(right) && right; } @@ -47905,15 +49848,15 @@ var ts; if (!checkGrammarTypeArguments(node, node.typeArguments)) checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { return voidType; } - if (node.kind === 190 /* NewExpression */) { + if (node.kind === 192 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 155 /* Constructor */ && - declaration.kind !== 159 /* ConstructSignature */ && - declaration.kind !== 164 /* ConstructorType */ && + declaration.kind !== 157 /* Constructor */ && + declaration.kind !== 161 /* ConstructSignature */ && + declaration.kind !== 166 /* 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 @@ -47921,10 +49864,10 @@ var ts; // Note:JS inferred classes might come from a variable declaration instead of a function declaration. // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. var funcSymbol = checkExpression(node.expression).symbol; - if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { + if (!funcSymbol && node.expression.kind === 72 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,18 +49878,18 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property // as a fresh unique symbol literal type. - if (returnType.flags & 3072 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49915,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -47987,7 +49930,7 @@ var ts; for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 8192 /* Undefined */ || specifierType.flags & 16384 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal @@ -48031,7 +49974,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48040,9 +49983,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 237 /* FunctionDeclaration */ + ? 239 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 235 /* VariableDeclaration */ + ? 237 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -48078,10 +50021,10 @@ var ts; } function checkMetaProperty(node) { checkGrammarMetaProperty(node); - if (node.keywordToken === 94 /* NewKeyword */) { + if (node.keywordToken === 95 /* NewKeyword */) { return checkNewTargetMetaProperty(node); } - if (node.keywordToken === 91 /* ImportKeyword */) { + if (node.keywordToken === 92 /* ImportKeyword */) { return checkImportMetaProperty(node); } return ts.Debug.assertNever(node.keywordToken); @@ -48092,7 +50035,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 155 /* Constructor */) { + else if (container.kind === 157 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -48156,14 +50099,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +50112,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,15 +50136,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48222,6 +50143,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48274,7 +50206,7 @@ var ts; for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71 /* Identifier */) { + if (element.name.kind === 72 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } else { @@ -48288,7 +50220,7 @@ var ts; if (!links.type) { links.type = contextualType; var decl = parameter.valueDeclaration; - if (decl.name.kind !== 71 /* Identifier */) { + if (decl.name.kind !== 72 /* Identifier */) { // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType) { links.type = getTypeFromBindingPattern(decl.name); @@ -48307,6 +50239,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48328,7 +50270,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 216 /* Block */) { + if (func.body.kind !== 218 /* Block */) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any @@ -48424,10 +50366,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 199 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48442,7 +50435,7 @@ var ts; if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - if (ts.some(func.body.statements, function (statement) { return statement.kind === 230 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -48464,7 +50457,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -48477,7 +50470,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48485,11 +50478,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; - case 154 /* MethodDeclaration */: - return func.parent.kind === 186 /* ObjectLiteralExpression */; + case 156 /* MethodDeclaration */: + return func.parent.kind === 188 /* ObjectLiteralExpression */; default: return false; } @@ -48508,16 +50501,16 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 153 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 216 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 32768 /* Never */) { + if (returnType && returnType.flags & 131072 /* Never */) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -48546,7 +50539,8 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48556,14 +50550,16 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 194 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -48598,7 +50594,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48609,7 +50604,7 @@ var ts; getAwaitedType(type) || errorType : type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function @@ -48625,7 +50620,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 216 /* Block */) { + if (node.body.kind === 218 /* Block */) { checkSourceElement(node.body); } else { @@ -48648,34 +50643,66 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAssignableToKind(type, 168 /* NumberLike */)) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { error(operand, diagnostic); return false; } return true; } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } 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 + // Object.defineProperty assignments with writable false or no setter // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || - symbol.flags & 8 /* EnumMember */); + symbol.flags & 8 /* EnumMember */ || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); } 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 === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) && - expr.expression.kind === 99 /* ThisKeyword */) { + (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) && + expr.expression.kind === 100 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 155 /* Constructor */)) { + if (!(func && func.kind === 157 /* Constructor */)) { return true; } // If func.parent is a class and symbol is a (readonly) property of that class, or @@ -48688,13 +50715,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) { + if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return !!declaration && declaration.kind === 249 /* NamespaceImport */; + return !!declaration && declaration.kind === 251 /* NamespaceImport */; } } } @@ -48703,7 +50730,7 @@ var ts; function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); - if (node.kind !== 71 /* Identifier */ && node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { + if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -48712,7 +50739,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -48749,37 +50776,52 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operand.kind === 8 /* NumericLiteral */) { - if (node.operator === 38 /* MinusToken */) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - else if (node.operator === 37 /* PlusToken */) { - return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); - } + switch (node.operand.kind) { + case 8 /* NumericLiteral */: + switch (node.operator) { + case 39 /* MinusToken */: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38 /* PlusToken */: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9 /* BigIntLiteral */: + if (node.operator === 39 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } } switch (node.operator) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 3072 /* ESSymbolLike */)) { + if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } - return numberType; - case 51 /* ExclamationToken */: + if (node.operator === 38 /* PlusToken */) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52 /* ExclamationToken */: checkTruthinessExpression(node.operand); - var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); - return facts === 1048576 /* Truthy */ ? falseType : - facts === 2097152 /* Falsy */ ? trueType : + var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : + facts === 8388608 /* Falsy */ ? trueType : booleanType; - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } - return numberType; + return getUnaryResultType(operandType); } return errorType; } @@ -48788,11 +50830,20 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number return numberType; } // Return true if type might be of the given kind. A union or intersection type might be of a given @@ -48801,10 +50852,10 @@ var ts; if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { return true; } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48816,21 +50867,22 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (3 /* AnyOrUnknown */ | 4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */)) { + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { return false; } - return !!(kind & 168 /* NumberLike */) && isTypeAssignableTo(source, numberType) || - !!(kind & 68 /* StringLike */) && isTypeAssignableTo(source, stringType) || - !!(kind & 272 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || - !!(kind & 4096 /* Void */) && isTypeAssignableTo(source, voidType) || - !!(kind & 32768 /* Never */) && isTypeAssignableTo(source, neverType) || - !!(kind & 16384 /* Null */) && isTypeAssignableTo(source, nullType) || - !!(kind & 8192 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || - !!(kind & 1024 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || - !!(kind & 16777216 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { - return source.flags & 262144 /* Union */ ? + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : isTypeAssignableToKind(source, kind, strict); } @@ -48850,7 +50902,7 @@ var ts; // 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 (!isTypeAny(leftType) && - allTypesAssignableToKind(leftType, 32764 /* Primitive */)) { + allTypesAssignableToKind(leftType, 131068 /* 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 @@ -48869,10 +50921,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 168 /* NumberLike */ | 3072 /* ESSymbolLike */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + if (!isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -48882,8 +50934,8 @@ var ts; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; @@ -48891,9 +50943,9 @@ var ts; /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { if (rightIsThis === void 0) { rightIsThis = false; } - if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { + if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -48902,13 +50954,13 @@ var ts; var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 275 /* SpreadAssignment */) { + else if (property.kind === 277 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } @@ -48960,11 +51012,11 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 208 /* OmittedExpression */) { - if (element.kind !== 206 /* SpreadElement */) { + if (element.kind !== 210 /* OmittedExpression */) { + if (element.kind !== 208 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48985,13 +51037,13 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 202 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49002,14 +51054,14 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 8192 /* Undefined */)) { - sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); } @@ -49018,21 +51070,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 202 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 186 /* ObjectLiteralExpression */) { + if (target.kind === 188 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 185 /* ArrayLiteralExpression */) { + if (target.kind === 187 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 275 /* SpreadAssignment */ ? + var error = target.parent.kind === 277 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { @@ -49051,72 +51103,73 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 191 /* TaggedTemplateExpression */: - case 204 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 193 /* TaggedTemplateExpression */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 140 /* UndefinedKeyword */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: - case 195 /* ArrowFunction */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 197 /* TypeOfExpression */: - case 211 /* NonNullExpression */: - case 259 /* JsxSelfClosingElement */: - case 258 /* JsxElement */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 141 /* UndefinedKeyword */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 199 /* TypeOfExpression */: + case 213 /* NonNullExpression */: + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: return true; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { - case 51 /* ExclamationToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: + case 52 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: return true; } return false; // Some forms listed here for clarity - case 198 /* VoidExpression */: // Explicit opt-out - case 192 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 210 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 200 /* VoidExpression */: // Explicit opt-out + case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */); + if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */); } var leftType; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { leftType = checkTruthinessExpression(left, checkMode); } else { @@ -49124,28 +51177,28 @@ var ts; } var rightType = checkExpression(right, checkMode); switch (operator) { - case 39 /* AsteriskToken */: - case 40 /* AsteriskAsteriskToken */: - case 61 /* AsteriskEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 42 /* PercentToken */: - case 64 /* PercentEqualsToken */: - case 38 /* MinusToken */: - case 60 /* MinusEqualsToken */: - case 45 /* LessThanLessThanToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: + case 40 /* AsteriskToken */: + case 41 /* AsteriskAsteriskToken */: + case 62 /* AsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 43 /* PercentToken */: + case 65 /* PercentEqualsToken */: + case 39 /* MinusToken */: + case 61 /* MinusEqualsToken */: + case 46 /* LessThanLessThanToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -49154,36 +51207,61 @@ var ts; 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 & 272 /* BooleanLike */) && - (rightType.flags & 272 /* BooleanLike */) && + if ((leftType.flags & 528 /* BooleanLike */) && + (rightType.flags & 528 /* BooleanLike */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; } else { // otherwise just check each operand separately and report errors as normal - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType_1 = numberType; } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) { + switch (operator) { + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; } - return numberType; - case 37 /* PlusToken */: - case 59 /* PlusEqualsToken */: + case 38 /* PlusToken */: + case 60 /* PlusEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 68 /* StringLike */) && !isTypeAssignableToKind(rightType, 68 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeAssignableToKind(leftType, 168 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 168 /* NumberLike */, /*strict*/ true)) { + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) { // 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 (isTypeAssignableToKind(leftType, 68 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 68 /* StringLike */, /*strict*/ true)) { + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -49200,26 +51278,27 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 59 /* PlusEqualsToken */) { + if (operator === 60 /* PlusEqualsToken */) { checkAssignmentOperator(resultType); } return resultType; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: if (checkForDisallowedESSymbolOperand(operator)) { leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { reportOperatorError(); } } return booleanType; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -49230,29 +51309,38 @@ var ts; reportOperatorError(); } return booleanType; - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return checkInstanceOfExpression(left, right, leftType, rightType); - case 92 /* InKeyword */: + case 93 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); - case 53 /* AmpersandAmpersandToken */: - return getTypeFacts(leftType) & 1048576 /* Truthy */ ? + case 54 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 4194304 /* Truthy */ ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; - case 54 /* BarBarToken */: - return getTypeFacts(leftType) & 2097152 /* Falsy */ ? + case 55 /* BarBarToken */: + return getTypeFacts(leftType) & 8388608 /* Falsy */ ? getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; - case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + case 59 /* EqualsToken */: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || + declKind !== 2 /* ModuleExports */ && + declKind !== 6 /* Prototype */ && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1 /* Class */)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } return leftType; } else { checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); } - case 26 /* CommaToken */: + case 27 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -49260,15 +51348,14 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { - var rightType_1 = checkExpression(right, checkMode); - for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2 /* ModuleExports */) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49278,12 +51365,12 @@ var ts; } } function isEvalNode(node) { - return node.kind === 71 /* Identifier */ && node.escapedText === "eval"; + return node.kind === 72 /* Identifier */ && node.escapedText === "eval"; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 3072 /* ESSymbolLike */) ? left : - maybeTypeOfKind(rightType, 3072 /* ESSymbolLike */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -49293,15 +51380,15 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - return 54 /* BarBarToken */; - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - return 35 /* ExclamationEqualsEqualsToken */; - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: - return 53 /* AmpersandAmpersandToken */; + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + return 55 /* BarBarToken */; + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + return 36 /* ExclamationEqualsEqualsToken */; + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + return 54 /* AmpersandAmpersandToken */; default: return undefined; } @@ -49321,8 +51408,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +51418,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49348,11 +51435,11 @@ var ts; } function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { switch (operatorToken.kind) { - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); } return undefined; @@ -49430,14 +51517,14 @@ var ts; // A place where we actually *are* concerned with the expressions' types are // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { - if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) { error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49473,25 +51560,21 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 192 /* TypeAssertionExpression */ || node.kind === 210 /* AsExpression */; + return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */; } function checkDeclarationInitializer(declaration) { var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { - if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304 /* Nullable */) { + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49499,34 +51582,36 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 786432 /* UnionOrIntersection */) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { var types = contextualType.types; return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } - if (contextualType.flags & 14745600 /* InstantiableNonPrimitive */) { + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { // If the contextual type is a type variable constrained to a primitive type, consider // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || - maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || - maybeTypeOfKind(constraint, 1024 /* ESSymbol */) && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (64 /* StringLiteral */ | 1048576 /* Index */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || - contextualType.flags & 128 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || - contextualType.flags & 256 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 256 /* BooleanLiteral */) || - contextualType.flags & 2048 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */)); + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || + contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49534,7 +51619,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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -49545,7 +51630,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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -49573,15 +51658,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +51684,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +51701,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; - if (node.kind === 146 /* QualifiedName */) { + if (node.kind === 148 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49622,10 +51715,10 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 165 /* TypeQuery */ && node.parent.exprName === node)); + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === 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_or_type_query); } @@ -49633,102 +51726,105 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return checkIdentifier(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return checkThisExpression(node); - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return checkSuperExpression(node); - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: return nullWideningType; - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101 /* TrueKeyword */: + case 9 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102 /* TrueKeyword */: return trueType; - case 86 /* FalseKeyword */: + case 87 /* FalseKeyword */: return falseType; - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return checkTemplateExpression(node); - case 12 /* RegularExpressionLiteral */: + case 13 /* RegularExpressionLiteral */: return globalRegExpType; - case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); - case 186 /* ObjectLiteralExpression */: + case 187 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 189 /* CallExpression */: - if (node.expression.kind === 91 /* ImportKeyword */) { + case 191 /* CallExpression */: + if (node.expression.kind === 92 /* ImportKeyword */) { return checkImportCallExpression(node); } /* falls through */ - case 190 /* NewExpression */: + case 192 /* NewExpression */: return checkCallExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return checkClassExpression(node); - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return checkAssertion(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return checkNonNullAssertion(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return checkMetaProperty(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return checkDeleteExpression(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return checkVoidExpression(node); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return checkAwaitExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 208 /* OmittedExpression */: + case 210 /* OmittedExpression */: return undefinedWideningType; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return checkYieldExpression(node); - case 213 /* SyntheticExpression */: + case 215 /* SyntheticExpression */: return node.type; - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return checkJsxElement(node, checkMode); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 262 /* JsxFragment */: - return checkJsxFragment(node, checkMode); - case 266 /* JsxAttributes */: + case 264 /* JsxFragment */: + return checkJsxFragment(node); + case 268 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -49757,9 +51853,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49769,7 +51862,7 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 155 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -49780,16 +51873,16 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { + if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 195 /* ArrowFunction */) { + if (func.kind === 197 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -49838,13 +51931,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 195 /* ArrowFunction */: - case 158 /* CallSignature */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 163 /* FunctionType */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 197 /* ArrowFunction */: + case 160 /* CallSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 165 /* FunctionType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -49858,11 +51951,11 @@ var ts; continue; } var name = element.name; - if (name.kind === 71 /* Identifier */ && name.escapedText === predicateVariableName) { + if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 183 /* ArrayBindingPattern */ || name.kind === 182 /* ObjectBindingPattern */) { + else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -49871,13 +51964,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 160 /* IndexSignature */) { + if (node.kind === 162 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 163 /* FunctionType */ || node.kind === 237 /* FunctionDeclaration */ || node.kind === 164 /* ConstructorType */ || - node.kind === 158 /* CallSignature */ || node.kind === 155 /* Constructor */ || - node.kind === 159 /* ConstructSignature */) { + else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ || + node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ || + node.kind === 161 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -49907,10 +52000,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 158 /* CallSignature */: + case 160 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -49940,7 +52033,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -49957,7 +52050,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 155 /* Constructor */) { + if (member.kind === 157 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -49972,16 +52065,16 @@ var ts; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (name && memberName) { switch (member.kind) { - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: addName(names, name, memberName, 1 /* Getter */); break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: addName(names, name, memberName, 2 /* Setter */); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: addName(names, name, memberName, 3 /* Property */); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: addName(names, name, memberName, 4 /* Method */); break; } @@ -50044,15 +52137,15 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151 /* PropertySignature */) { + if (member.kind === 153 /* PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: memberName = name.text; break; - case 71 /* Identifier */: + case 72 /* Identifier */: memberName = ts.idText(name); break; default: @@ -50069,7 +52162,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 239 /* InterfaceDeclaration */) { + if (node.kind === 241 /* 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 @@ -50089,7 +52182,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -50097,7 +52190,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -50124,7 +52217,7 @@ var ts; checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 154 /* MethodDeclaration */ && node.body) { + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -50149,7 +52242,7 @@ var ts; return; } function isInstancePropertyWithInitializer(n) { - return n.kind === 152 /* PropertyDeclaration */ && + return n.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } @@ -50179,7 +52272,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -50204,7 +52297,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -50214,13 +52307,13 @@ 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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(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 === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); @@ -50238,7 +52331,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -50255,7 +52348,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +52379,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50334,7 +52427,7 @@ var ts; var seenOptionalElement = false; for (var i = 0; i < elementTypes.length; i++) { var e = elementTypes[i]; - if (e.kind === 170 /* RestType */) { + if (e.kind === 172 /* RestType */) { if (i !== elementTypes.length - 1) { grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); break; @@ -50343,7 +52436,7 @@ var ts; error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); } } - else if (e.kind === 169 /* OptionalType */) { + else if (e.kind === 171 /* OptionalType */) { seenOptionalElement = true; } else if (seenOptionalElement) { @@ -50358,14 +52451,14 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 2097152 /* IndexedAccess */)) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { return type; } // Check if the index type is assignable to 'keyof T' for the object type. var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 188 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -50373,7 +52466,7 @@ var ts; } // Check if we're indexing with a numeric type and if either object or index types // is a generic type with a constraint that has a numeric index signature. - if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -50387,8 +52480,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50405,7 +52498,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 173 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -50422,9 +52515,9 @@ var ts; var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 239 /* InterfaceDeclaration */ && - n.parent.kind !== 238 /* ClassDeclaration */ && - n.parent.kind !== 207 /* ClassExpression */ && + if (n.parent.kind !== 241 /* InterfaceDeclaration */ && + n.parent.kind !== 240 /* ClassDeclaration */ && + n.parent.kind !== 209 /* ClassExpression */ && n.flags & 4194304 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -50515,7 +52608,7 @@ var ts; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */) && + var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) && ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -50554,7 +52647,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = node.flags & 4194304 /* Ambient */; - var inAmbientContextOrInterface = node.parent.kind === 239 /* InterfaceDeclaration */ || node.parent.kind === 166 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -50565,7 +52658,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 === 237 /* FunctionDeclaration */ || node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */ || node.kind === 155 /* Constructor */) { + if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -50617,8 +52710,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var signature = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -50627,6 +52720,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,32 +52784,25 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return 2 /* ExportType */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values if (!ts.isEntityNameExpression(d.expression)) { return 1 /* ExportValue */; @@ -50717,17 +52810,17 @@ var ts; d = d.expression; /* falls through */ // The below options all declare an Alias, which is allowed to merge with other values within the importing module - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 248 /* ImportClause */: - var result_3 = 0 /* None */; + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 237 /* FunctionDeclaration */: - case 251 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 239 /* FunctionDeclaration */: + case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); @@ -50774,7 +52867,7 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -50805,7 +52898,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -50953,10 +53046,10 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { - if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { @@ -50976,7 +53069,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -50995,24 +53088,24 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 149 /* Parameter */: + case 151 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -51033,7 +53126,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51058,50 +53151,55 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 172 /* IntersectionType */: - case 171 /* UnionType */: - var commonEntityName = void 0; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175 /* ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 131 /* NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); - if (!individualEntityName) { - // Individual is something like string number - // So it would be serialized to either that type or object - // Safe to return here - return undefined; - } - if (commonEntityName) { - // Note this is in sync with the transformation that happens for type node. - // Keep this in sync with serializeUnionOrIntersectionType - // Verify if they refer to same entity and is identifier - // return undefined if they dont match because we would emit object - if (!ts.isIdentifier(commonEntityName) || - !ts.isIdentifier(individualEntityName) || - commonEntityName.escapedText !== individualEntityName.escapedText) { - return undefined; - } - } - else { - commonEntityName = individualEntityName; - } - } - return commonEntityName; - case 175 /* ParenthesizedType */: + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; } } } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } function getParameterTypeNodeForDecoratorCheck(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; @@ -51121,14 +53219,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 149 /* Parameter */) { + if (node.kind === 151 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -51137,23 +53235,23 @@ var ts; } } break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 149 /* Parameter */: + case 151 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -51206,16 +53304,22 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); } } } } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } function checkJSDocAugmentsTag(node) { var classLike = ts.getJSDocHost(node); if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { @@ -51238,9 +53342,9 @@ var ts; } function getIdentifierFromEntityNameExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return node.name; default: return undefined; @@ -51253,7 +53357,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 && node.name.kind === 147 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -51282,7 +53386,7 @@ var ts; } } } - var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); @@ -51291,8 +53395,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51302,7 +53406,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51311,7 +53415,7 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. - if (produceDiagnostics) { + if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) { var sourceFile = ts.getSourceFileOfNode(node); var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); if (!potentiallyUnusedIdentifiers) { @@ -51327,44 +53431,44 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 239 /* InterfaceDeclaration */: - checkUnusedTypeParameters(node, addDiagnostic); - break; - case 277 /* SourceFile */: - case 242 /* ModuleDeclaration */: - case 216 /* Block */: - case 244 /* CaseBlock */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 279 /* SourceFile */: + case 244 /* ModuleDeclaration */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - if (node.body) { + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 240 /* TypeAliasDeclaration */: - case 174 /* InferType */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; + case 176 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; default: ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); } @@ -51379,77 +53483,73 @@ var ts; return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 154 /* MethodDeclaration */: - case 152 /* PropertyDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - if (member.kind === 157 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { - // Already would have reported an error on the getter. - break; - } - var symbol = getSymbolOfNode(member); - if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. break; - case 155 /* Constructor */: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } - break; - case 160 /* IndexSignature */: - case 215 /* SemicolonClassElement */: - // Can't be private - break; - default: - ts.Debug.fail(); - } + } + break; + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) + if (ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174 /* InferType */) { - var typeParameter = node.typeParameter; - if (isTypeParameterUnused(typeParameter)) { - addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } } - } - else { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - var seenParentsWithEveryUnused = new ts.NodeSet(); - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var typeParameter = typeParameters_2[_i]; - if (!isTypeParameterUnused(typeParameter)) - continue; - var name = ts.idText(typeParameter.name); - var parent = typeParameter.parent; - if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { - if (seenParentsWithEveryUnused.tryAdd(parent)) { - var range = ts.isJSDocTemplateTag(parent) - // Whole @template tag - ? ts.rangeOfNode(parent) - // Include the `<>` in the error message - : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; - var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; - var arg0 = only ? name : undefined; - addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); - } - } - else { - addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); - } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } @@ -51520,7 +53620,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 @@ -51538,7 +53638,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 235 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 236 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -51559,7 +53659,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -51571,24 +53671,24 @@ var ts; } function bindingNameText(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.idText(name); - case 183 /* ArrayBindingPattern */: - case 182 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 248 /* ImportClause */ || node.kind === 251 /* ImportSpecifier */ || node.kind === 249 /* NamespaceImport */; + return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 248 /* ImportClause */ ? decl : decl.kind === 249 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 216 /* Block */) { + if (node.kind === 218 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -51618,12 +53718,12 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 151 /* PropertySignature */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 153 /* MethodSignature */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { + if (node.kind === 154 /* PropertyDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 156 /* MethodDeclaration */ || + node.kind === 155 /* MethodSignature */ || + node.kind === 158 /* GetAccessor */ || + node.kind === 159 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -51632,7 +53732,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 149 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -51642,7 +53742,7 @@ var ts; function checkIfThisIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { - var isDeclaration_1 = node.kind !== 71 /* Identifier */; + var isDeclaration_1 = node.kind !== 72 /* Identifier */; if (isDeclaration_1) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -51657,7 +53757,7 @@ var ts; function checkIfNewTargetIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { - var isDeclaration_2 = node.kind !== 71 /* Identifier */; + var isDeclaration_2 = node.kind !== 72 /* Identifier */; if (isDeclaration_2) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } @@ -51683,7 +53783,7 @@ var ts; } // 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 === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 279 /* 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)); } @@ -51698,7 +53798,7 @@ var ts; } // 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 === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -51733,7 +53833,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 235 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -51745,17 +53845,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 236 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 217 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 219 /* 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 === 216 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 243 /* ModuleBlock */ || - container.kind === 242 /* ModuleDeclaration */ || - container.kind === 277 /* SourceFile */); + (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 245 /* ModuleBlock */ || + container.kind === 244 /* ModuleDeclaration */ || + container.kind === 279 /* 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 @@ -51770,7 +53870,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 !== 149 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -51781,14 +53881,14 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 187 /* PropertyAccessExpression */) { + if (n.kind === 189 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } - else if (n.kind === 71 /* Identifier */) { + else if (n.kind === 72 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51800,8 +53900,8 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 149 /* Parameter */ || - symbol.valueDeclaration.kind === 184 /* BindingElement */) { + if (symbol.valueDeclaration.kind === 151 /* Parameter */ || + symbol.valueDeclaration.kind === 186 /* BindingElement */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -51815,7 +53915,7 @@ var ts; return ts.isFunctionLike(current.parent) || // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - (current.parent.kind === 152 /* PropertyDeclaration */ && + (current.parent.kind === 154 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)); })) { @@ -51848,18 +53948,18 @@ 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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 184 /* BindingElement */) { - if (node.parent.kind === 182 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + if (node.kind === 186 /* BindingElement */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 147 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -51870,29 +53970,29 @@ var ts; var nameText = ts.getTextOfPropertyName(name); if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { - checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property); } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 183 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 149 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) { var initializerType = checkExpressionCached(node.initializer); if (strictNullChecks && node.name.elements.length === 0) { checkNonNullType(initializerType, node); @@ -51911,15 +54011,20 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); checkParameterInitializer(node); } } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } } else { // Node is a secondary declaration, check that type is identical to primary declaration and check that @@ -51927,21 +54032,20 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */) { + if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -51950,14 +54054,14 @@ var ts; } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 152 /* PropertyDeclaration */ || nextDeclaration.kind === 151 /* PropertySignature */ + var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 149 /* Parameter */ && right.kind === 235 /* VariableDeclaration */) || - (left.kind === 235 /* VariableDeclaration */ && right.kind === 149 /* Parameter */)) { + if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) || + (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -51996,7 +54100,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 218 /* EmptyStatement */) { + if (node.thenStatement.kind === 220 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -52015,7 +54119,7 @@ var ts; } function checkTruthinessExpression(node, checkMode) { var type = checkExpression(node, checkMode); - if (type.flags & 4096 /* Void */) { + if (type.flags & 16384 /* Void */) { error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); } return type; @@ -52023,12 +54127,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -52062,14 +54166,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 === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side - if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* 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. @@ -52095,13 +54199,13 @@ var ts; function checkForInStatement(node) { // Grammar checking checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* 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); @@ -52115,7 +54219,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 === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -52128,7 +54232,7 @@ var ts; } // 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 (rightType === neverType || !isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -52183,16 +54287,16 @@ var ts; // This allows us to find other non-string element types from an array unioned with // a string. if (allowStringInput) { - if (arrayType.flags & 262144 /* Union */) { + if (arrayType.flags & 1048576 /* Union */) { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the result of filter is a new array. var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 68 /* StringLike */); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } } - else if (arrayType.flags & 68 /* StringLike */) { + else if (arrayType.flags & 132 /* StringLike */) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -52205,7 +54309,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType.flags & 32768 /* Never */) { + if (arrayType.flags & 131072 /* Never */) { return stringType; } } @@ -52236,7 +54340,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); if (hasStringConstituent && arrayElementType) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 68 /* StringLike */) { + if (arrayElementType.flags & 132 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], 2 /* Subtype */); @@ -52301,13 +54405,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52334,9 +54442,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52444,7 +54554,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 4096 /* Void */ | 3 /* AnyOrUnknown */); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { // Grammar checking @@ -52460,7 +54570,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); var functionFlags = ts.getFunctionFlags(func); var isGenerator = functionFlags & 1 /* Generator */; - if (strictNullChecks || node.expression || returnType.flags & 32768 /* Never */) { + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (isGenerator) { // AsyncGenerator function or Generator function // A generator does not need its return expressions checked against its return type. @@ -52469,12 +54579,12 @@ var ts; // for generators. return; } - else if (func.kind === 157 /* SetAccessor */) { + else if (func.kind === 159 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 155 /* Constructor */) { + else if (func.kind === 157 /* Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -52495,7 +54605,7 @@ var ts; } } } - else if (func.kind !== 155 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -52524,7 +54634,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 270 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -52536,7 +54646,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 269 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 271 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -52565,7 +54675,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 231 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -52672,8 +54782,8 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 202 /* BinaryExpression */ || - name.kind === 147 /* ComputedPropertyName */ || + (propDeclaration.kind === 204 /* BinaryExpression */ || + name.kind === 149 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -52702,6 +54812,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -52877,18 +54988,21 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 2162688 /* TypeVariable */)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52916,7 +55030,7 @@ var ts; } } else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -52931,7 +55045,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52950,7 +55064,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -52976,7 +55090,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 238 /* ClassDeclaration */ || d.kind === 239 /* InterfaceDeclaration */; + return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -53015,7 +55129,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 || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { - if (derivedClassDecl.kind === 207 /* ClassExpression */) { + if (derivedClassDecl.kind === 209 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -53065,8 +55179,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -53097,7 +55211,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 8192 /* Undefined */)) { + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -53107,16 +55221,18 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 152 /* PropertyDeclaration */ && + return node.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 8192 /* Undefined */); + return !(getFalsyFlags(flowType) & 32768 /* Undefined */); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -53129,7 +55245,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -53234,60 +55350,60 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { - case 37 /* PlusToken */: return value_2; - case 38 /* MinusToken */: return -value_2; - case 52 /* TildeToken */: return ~value_2; + case 38 /* PlusToken */: return value_2; + case 39 /* MinusToken */: return -value_2; + case 53 /* TildeToken */: return ~value_2; } } break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { switch (expr.operatorToken.kind) { - case 49 /* BarToken */: return left | right; - case 48 /* AmpersandToken */: return left & right; - case 46 /* GreaterThanGreaterThanToken */: return left >> right; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; - case 45 /* LessThanLessThanToken */: return left << right; - case 50 /* CaretToken */: return left ^ right; - case 39 /* AsteriskToken */: return left * right; - case 41 /* SlashToken */: return left / right; - case 37 /* PlusToken */: return left + right; - case 38 /* MinusToken */: return left - right; - case 42 /* PercentToken */: return left % right; - case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right); + case 50 /* BarToken */: return left | right; + case 49 /* AmpersandToken */: return left & right; + case 47 /* GreaterThanGreaterThanToken */: return left >> right; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 46 /* LessThanLessThanToken */: return left << right; + case 51 /* CaretToken */: return left ^ right; + case 40 /* AsteriskToken */: return left * right; + case 42 /* SlashToken */: return left / right; + case 38 /* PlusToken */: return left + right; + case 39 /* MinusToken */: return left - right; + case 43 /* PercentToken */: return left % right; + case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right); } } - else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 37 /* PlusToken */) { + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) { return left + right; } break; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return expr.text; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return evaluate(expr.expression); - case 71 /* Identifier */: + case 72 /* Identifier */: var identifier = expr; if (isInfinityOrNaNString(identifier.escapedText)) { return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 188 /* ElementAccessExpression */: - case 187 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 187 /* PropertyAccessExpression */) { + if (ex.kind === 189 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -53318,10 +55434,10 @@ var ts; } } function isConstantMemberAccess(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 187 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 188 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && - node.argumentExpression.kind === 9 /* StringLiteral */; + return node.kind === 72 /* Identifier */ || + node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10 /* StringLiteral */; } function checkEnumDeclaration(node) { if (!produceDiagnostics) { @@ -53358,7 +55474,7 @@ var ts; 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 !== 241 /* EnumDeclaration */) { + if (declaration.kind !== 243 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -53381,8 +55497,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { var declaration = declarations_8[_i]; - if ((declaration.kind === 238 /* ClassDeclaration */ || - (declaration.kind === 237 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 240 /* ClassDeclaration */ || + (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304 /* Ambient */)) { return declaration; } @@ -53419,7 +55535,7 @@ var ts; return; } if (!checkGrammarDecoratorsAndModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { + if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } @@ -53445,7 +55561,7 @@ 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, 238 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -53495,23 +55611,23 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* 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 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 184 /* BindingElement */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -53522,12 +55638,12 @@ var ts; break; } // falls through - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 237 /* FunctionDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -53540,7 +55656,7 @@ var ts; var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { // symbol should not originate in augmentation - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -53548,17 +55664,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: do { node = node.left; - } while (node.kind !== 71 /* Identifier */); + } while (node.kind !== 72 /* Identifier */); return node; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: do { node = node.expression; - } while (node.kind !== 71 /* Identifier */); + } while (node.kind !== 72 /* Identifier */); return node; } } @@ -53572,9 +55688,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 253 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -53603,19 +55719,19 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 255 /* ExportSpecifier */ ? + var message = node.kind === 257 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && node.kind === 257 /* ExportSpecifier */ + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53641,7 +55757,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -53665,17 +55781,17 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53701,10 +55817,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 243 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; - if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -53721,7 +55837,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 277 /* SourceFile */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 242 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -53729,13 +55845,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53750,8 +55866,8 @@ 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 === 277 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -53764,9 +55880,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 71 /* Identifier */) { + if (node.expression.kind === 72 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +55914,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53839,14 +55955,14 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 237 /* FunctionDeclaration */ && declaration.kind !== 154 /* MethodDeclaration */) || + return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -53857,163 +55973,163 @@ var ts; // 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 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return checkTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return checkParameter(node); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return checkPropertyDeclaration(node); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return checkSignatureDeclaration(node); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return checkMethodDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return checkConstructorDeclaration(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return checkAccessorDeclaration(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return checkTypeReferenceNode(node); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return checkTypePredicate(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return checkTypeQuery(node); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return checkTypeLiteral(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return checkArrayType(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return checkTupleType(node); - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 175 /* ParenthesizedType */: - case 169 /* OptionalType */: - case 170 /* RestType */: + case 177 /* ParenthesizedType */: + case 171 /* OptionalType */: + case 172 /* RestType */: return checkSourceElement(node.type); - case 176 /* ThisType */: + case 178 /* ThisType */: return checkThisType(node); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return checkTypeOperator(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return checkConditionalType(node); - case 174 /* InferType */: + case 176 /* InferType */: return checkInferType(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return checkImportType(node); - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 297 /* JSDocParameterTag */: + case 299 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 287 /* JSDocFunctionType */: - checkSignatureDeclaration(node); + case 289 /* JSDocFunctionType */: + checkJSDocFunctionType(node); // falls through - case 285 /* JSDocNonNullableType */: - case 284 /* JSDocNullableType */: - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: - case 290 /* JSDocTypeLiteral */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + case 292 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 281 /* JSDocTypeExpression */: + case 283 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return checkMappedType(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return checkBlock(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return checkVariableStatement(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return checkExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return checkIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return checkDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return checkWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return checkForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return checkForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return checkForOfStatement(node); - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return checkReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return checkWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return checkSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return checkLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return checkThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return checkTryStatement(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return checkBindingElement(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return checkClassDeclaration(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return checkImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return checkExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return checkExportAssignment(node); - case 218 /* EmptyStatement */: - case 234 /* DebuggerStatement */: + case 220 /* EmptyStatement */: + case 236 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return checkMissingDeclaration(node); } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54084,31 +56200,38 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: checkClassExpressionDeferred(node); break; - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 258 /* JsxElement */: + case 260 /* JsxElement */: checkJsxElementDeferred(node); break; } @@ -54144,9 +56267,9 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54157,7 +56280,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54239,13 +56361,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 242 /* ModuleDeclaration */: + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + // falls through + case 244 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -54253,17 +56379,17 @@ var ts; // falls through // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* 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 (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -54305,17 +56431,17 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 71 /* Identifier */ && + return name.kind === 72 /* Identifier */ && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 148 /* TypeParameter */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: + case 150 /* TypeParameter */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: return true; default: return false; @@ -54323,16 +56449,16 @@ var ts; } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 146 /* QualifiedName */) { + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 162 /* TypeReference */; + return node.parent.kind === 164 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 187 /* PropertyAccessExpression */) { + while (node.parent.kind === 189 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 209 /* ExpressionWithTypeArguments */; + return node.parent.kind === 211 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -54345,12 +56471,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54360,13 +56486,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 146 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 246 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 252 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -54375,7 +56501,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54392,7 +56518,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 181 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -54401,8 +56527,8 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 187 /* PropertyAccessExpression */ && + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -54410,17 +56536,17 @@ var ts; return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } } else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 246 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } @@ -54438,11 +56564,11 @@ 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 === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) { + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54454,11 +56580,11 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 297 /* JSDocParameterTag */) { + if (entityName.parent.kind === 299 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54467,19 +56593,19 @@ var ts; // Missing entity name. return undefined; } - if (entityName.kind === 71 /* Identifier */) { + if (entityName.kind === 72 /* Identifier */) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { + else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 187 /* PropertyAccessExpression */) { + if (entityName.kind === 189 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -54489,20 +56615,17 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 265 /* JsxAttribute */) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 161 /* TypePredicate */) { + if (entityName.parent.kind === 163 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -54513,17 +56636,20 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(parent); + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(parent.parent); } - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (parent.kind === 184 /* BindingElement */ && - grandParent.kind === 182 /* ObjectBindingPattern */ && + else if (parent.kind === 186 /* BindingElement */ && + grandParent.kind === 184 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -54533,11 +56659,11 @@ var ts; } } switch (node.kind) { - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -54549,29 +56675,32 @@ var ts; return checkExpression(node).symbol; } // falls through - case 176 /* ThisType */: + case 178 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return checkExpression(node).symbol; - case 123 /* ConstructorKeyword */: + case 124 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 155 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } // falls through case 8 /* NumericLiteral */: // index access @@ -54581,19 +56710,22 @@ var ts; ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); - case 79 /* DefaultKeyword */: - case 89 /* FunctionKeyword */: - case 36 /* EqualsGreaterThanToken */: + case 80 /* DefaultKeyword */: + case 90 /* FunctionKeyword */: + case 37 /* EqualsGreaterThanToken */: + case 76 /* ClassKeyword */: return getSymbolOfNode(node.parent); - case 181 /* ImportType */: + case 183 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85 /* ExportKeyword */: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + if (location && location.kind === 276 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,30 +56733,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54665,28 +56792,28 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 186 /* ObjectLiteralExpression */ || expr.kind === 185 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 225 /* ForOfStatement */) { + if (expr.parent.kind === 227 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 202 /* BinaryExpression */) { + if (expr.parent.kind === 204 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 273 /* PropertyAssignment */) { + if (expr.parent.kind === 275 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 185 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; @@ -54719,13 +56846,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return getLiteralType(name.text); + case 149 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54765,7 +56911,7 @@ var ts; if (!ts.isGeneratedIdentifier(nodeIn)) { var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -54786,13 +56932,13 @@ var ts; // 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 & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54821,7 +56967,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 277 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -54841,7 +56987,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,11 +57000,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54874,9 +57020,9 @@ var ts; // * 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 isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -54917,18 +57063,18 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return node.expression - && node.expression.kind === 71 /* Identifier */ + && node.expression.kind === 72 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -54936,7 +57082,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 277 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -54950,7 +57096,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +57109,8 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && + target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +57155,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55017,15 +57183,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 276 /* EnumMember */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 278 /* EnumMember */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 276 /* EnumMember */) { + if (node.kind === 278 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -55039,7 +57205,7 @@ var ts; return undefined; } function isFunctionType(type) { - return !!(type.flags & 131072 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeNameIn, location) { // ensure both `typeName` and `location` are parse tree nodes. @@ -55052,9 +57218,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55076,22 +57242,25 @@ var ts; else if (type.flags & 3 /* AnyOrUnknown */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 4096 /* Void */ | 24576 /* Nullable */ | 32768 /* Never */)) { + else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeAssignableToKind(type, 272 /* BooleanLike */)) { + else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeAssignableToKind(type, 168 /* NumberLike */)) { + else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 68 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 3072 /* ESSymbolLike */)) { + else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -55107,14 +57276,14 @@ var ts; function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; - if (type.flags & 2048 /* UniqueESSymbol */ && + if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } @@ -55126,7 +57295,7 @@ var ts; function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); @@ -55134,7 +57303,7 @@ var ts; function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } var type = getWidenedType(getRegularTypeOfExpression(expr)); return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); @@ -55156,7 +57325,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +57340,19 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } - function createLiteralConstValue(node) { + function createLiteralConstValue(node, tracker) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node, tracker); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +57395,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55253,12 +57425,12 @@ var ts; getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 157 /* SetAccessor */ ? 156 /* GetAccessor */ : 157 /* SetAccessor */; + var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 157 /* SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 156 /* GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -55266,10 +57438,15 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { - return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; + return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -55280,9 +57457,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55332,7 +57509,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 277 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -55347,12 +57524,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 242 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 277 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -55371,6 +57548,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55415,6 +57595,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55442,31 +57624,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55478,7 +57659,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55526,14 +57707,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 154 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 156 /* 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 === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */) { + else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* 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); @@ -55550,23 +57731,23 @@ var ts; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 132 /* ReadonlyKeyword */) { - if (node.kind === 151 /* PropertySignature */ || node.kind === 153 /* MethodSignature */) { + if (modifier.kind !== 133 /* ReadonlyKeyword */) { + if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 160 /* IndexSignature */) { + if (node.kind === 162 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 76 /* ConstKeyword */: - if (node.kind !== 241 /* EnumDeclaration */) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); + case 77 /* ConstKeyword */: + if (node.kind !== 243 /* EnumDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */)); } break; - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: + case 115 /* PublicKeyword */: + case 114 /* ProtectedKeyword */: + case 113 /* PrivateKeyword */: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); @@ -55580,11 +57761,11 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { - if (modifier.kind === 112 /* PrivateKeyword */) { + if (modifier.kind === 113 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -55593,7 +57774,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -55603,10 +57784,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -55615,18 +57796,18 @@ var ts; flags |= 32 /* Static */; lastStatic = modifier; break; - case 132 /* ReadonlyKeyword */: + case 133 /* ReadonlyKeyword */: if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */ && node.kind !== 160 /* IndexSignature */ && node.kind !== 149 /* Parameter */) { + else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; lastReadonly = modifier; break; - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: if (flags & 1 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -55639,52 +57820,52 @@ 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 === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; - case 79 /* DefaultKeyword */: - var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + case 80 /* DefaultKeyword */: + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; break; - case 124 /* DeclareKeyword */: + case 125 /* DeclareKeyword */: if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 243 /* ModuleBlock */) { + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; lastDeclare = modifier; break; - case 117 /* AbstractKeyword */: + case 118 /* AbstractKeyword */: if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 238 /* ClassDeclaration */) { - if (node.kind !== 154 /* MethodDeclaration */ && - node.kind !== 152 /* PropertyDeclaration */ && - node.kind !== 156 /* GetAccessor */ && - node.kind !== 157 /* SetAccessor */) { + if (node.kind !== 240 /* ClassDeclaration */) { + if (node.kind !== 156 /* MethodDeclaration */ && + node.kind !== 154 /* PropertyDeclaration */ && + node.kind !== 158 /* GetAccessor */ && + node.kind !== 159 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 238 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -55696,14 +57877,14 @@ var ts; } flags |= 128 /* Abstract */; break; - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -55711,7 +57892,7 @@ var ts; break; } } - if (node.kind === 155 /* Constructor */) { + if (node.kind === 157 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -55726,13 +57907,13 @@ var ts; } return false; } - else if ((node.kind === 247 /* ImportDeclaration */ || node.kind === 246 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -55753,38 +57934,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 242 /* ModuleDeclaration */: - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 149 /* Parameter */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 244 /* ModuleDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 151 /* Parameter */: return false; default: - if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return false; } switch (node.kind) { - case 237 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 238 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 239 /* InterfaceDeclaration */: - case 217 /* VariableStatement */: - case 240 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */); + case 240 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */); + case 241 /* InterfaceDeclaration */: + case 219 /* VariableStatement */: + case 242 /* TypeAliasDeclaration */: return true; - case 241 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); + case 243 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */); default: ts.Debug.fail(); return false; @@ -55796,10 +57977,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -55852,11 +58033,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -55896,12 +58098,12 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 137 /* StringKeyword */ && parameter.type.kind !== 134 /* NumberKeyword */) { + if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) { var type = getTypeFromTypeNode(parameter.type); if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); } - if (type.flags & 262144 /* Union */ && allTypesAssignableToKind(type, 64 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); @@ -55932,7 +58134,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 208 /* OmittedExpression */) { + if (arg.kind === 210 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -55962,7 +58164,7 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (heritageClause.token === 86 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -55975,7 +58177,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -55991,14 +58193,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (heritageClause.token === 86 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } // Grammar checking heritageClause inside class declaration @@ -56009,20 +58211,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 147 /* ComputedPropertyName */) { + if (node.kind !== 149 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 202 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 237 /* FunctionDeclaration */ || - node.kind === 194 /* FunctionExpression */ || - node.kind === 154 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 156 /* MethodDeclaration */); if (node.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -56034,6 +58236,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56045,15 +58250,15 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 /* SpreadAssignment */) { + if (prop.kind === 277 /* SpreadAssignment */) { continue; } var name = prop.name; - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 274 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 276 /* 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); @@ -56062,7 +58267,7 @@ var ts; if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 154 /* MethodDeclaration */) { + if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -56077,21 +58282,23 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 275 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { checkGrammarNumericLiteral(name); } // falls through - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: currentKind = 1 /* Property */; break; - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: currentKind = 2 /* GetAccessor */; break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: currentKind = 4 /* SetAccessor */; break; default: @@ -56128,7 +58335,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 267 /* JsxSpreadAttribute */) { + if (attr.kind === 269 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -56138,7 +58345,7 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 268 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -56147,12 +58354,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 225 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 236 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -56167,20 +58374,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* 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 === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* 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); @@ -56207,11 +58414,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 156 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 157 /* SetAccessor */) { + else if (kind === 159 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -56235,23 +58442,23 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } function checkGrammarTypeOperatorNode(node) { - if (node.operator === 141 /* UniqueKeyword */) { - if (node.type.kind !== 138 /* SymbolKeyword */) { - return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(138 /* SymbolKeyword */)); + if (node.operator === 142 /* UniqueKeyword */) { + if (node.type.kind !== 139 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */)); } var parent = ts.walkUpParenthesizedTypes(node.parent); switch (parent.kind) { - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: var decl = parent; - if (decl.name.kind !== 71 /* Identifier */) { + if (decl.name.kind !== 72 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); } if (!ts.isVariableDeclarationInVariableStatement(decl)) { @@ -56261,13 +58468,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: if (!ts.hasModifier(parent, 32 /* Static */) || !ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: if (!ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -56286,15 +58493,18 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 154 /* MethodDeclaration */) { - if (node.parent.kind === 186 /* ObjectLiteralExpression */) { + if (node.kind === 156 /* MethodDeclaration */) { + if (node.parent.kind === 188 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 120 /* AsyncKeyword */)) { + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56312,14 +58522,14 @@ var ts; if (node.flags & 4194304 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 154 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 156 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 239 /* InterfaceDeclaration */) { + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 166 /* TypeLiteral */) { + else if (node.parent.kind === 168 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -56330,11 +58540,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 226 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 228 /* 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); @@ -56342,8 +58552,8 @@ var ts; return false; } break; - case 230 /* SwitchStatement */: - if (node.kind === 227 /* BreakStatement */ && !node.label) { + case 232 /* SwitchStatement */: + if (node.kind === 229 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -56358,13 +58568,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 227 /* BreakStatement */ + var message = node.kind === 229 /* 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 === 227 /* BreakStatement */ + var message = node.kind === 229 /* 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); @@ -56387,30 +58597,45 @@ var ts; } } function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 /* BigIntLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 9 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { + if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56421,7 +58646,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 217 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && @@ -56438,7 +58663,7 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkESModuleMarker(name) { - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } @@ -56455,8 +58680,8 @@ var ts; return false; } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71 /* Identifier */) { - if (name.originalKeywordKind === 110 /* LetKeyword */) { + if (name.kind === 72 /* Identifier */) { + if (name.originalKeywordKind === 111 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -56483,15 +58708,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return false; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -56509,12 +58734,12 @@ var ts; function checkGrammarMetaProperty(node) { var escapedText = node.name.escapedText; switch (node.keywordToken) { - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: if (escapedText !== "target") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); } break; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: if (escapedText !== "meta") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); } @@ -56550,10 +58775,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56568,7 +58794,7 @@ var ts; return true; } } - else if (node.parent.kind === 239 /* InterfaceDeclaration */) { + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -56576,7 +58802,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 166 /* TypeLiteral */) { + else if (node.parent.kind === 168 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -56584,8 +58810,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -56605,13 +58831,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 239 /* InterfaceDeclaration */ || - node.kind === 240 /* TypeAliasDeclaration */ || - node.kind === 247 /* ImportDeclaration */ || - node.kind === 246 /* ImportEqualsDeclaration */ || - node.kind === 253 /* ExportDeclaration */ || - node.kind === 252 /* ExportAssignment */ || - node.kind === 245 /* NamespaceExportDeclaration */ || + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 242 /* TypeAliasDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 255 /* ExportDeclaration */ || + node.kind === 254 /* ExportAssignment */ || + node.kind === 247 /* NamespaceExportDeclaration */ || ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -56620,7 +58846,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 === 217 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -56647,7 +58873,7 @@ var ts; // 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 === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -56669,20 +58895,32 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 180 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 276 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */; + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */; var literal = (withMinus ? "-" : "") + "0o" + node.text; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } return false; } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6 /* ESNext */) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { @@ -56727,8 +58965,8 @@ var ts; /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); @@ -56736,14 +58974,14 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 248 /* ImportClause */: // For default import - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: // For rename import `x as y` + case 250 /* ImportClause */: // For default import + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: // For rename import `x as y` return true; - case 71 /* Identifier */: + case 72 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 251 /* ImportSpecifier */; + return decl.parent.kind === 253 /* ImportSpecifier */; default: return false; } @@ -56763,7 +59001,7 @@ var ts; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); function typeIsLiteralType(type) { - return !!(type.flags & 448 /* Literal */); + return !!(type.flags & 2944 /* Literal */); } })(ts || (ts = {})); var ts; @@ -56827,6 +59065,9 @@ var ts; if (typeof value === "number") { return createNumericLiteral(value + ""); } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } @@ -56846,14 +59087,20 @@ var ts; return node; } ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9 /* BigIntLiteral */); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; function createStringLiteral(text) { - var node = createSynthesizedNode(9 /* StringLiteral */); + var node = createSynthesizedNode(10 /* StringLiteral */); node.text = text; return node; } ts.createStringLiteral = createStringLiteral; function createRegularExpressionLiteral(text) { - var node = createSynthesizedNode(12 /* RegularExpressionLiteral */); + var node = createSynthesizedNode(13 /* RegularExpressionLiteral */); node.text = text; return node; } @@ -56864,7 +59111,7 @@ var ts; return node; } function createIdentifier(text, typeArguments) { - var node = createSynthesizedNode(71 /* Identifier */); + var node = createSynthesizedNode(72 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateFlags = 0 /* None */; @@ -56945,23 +59192,23 @@ var ts; ts.createToken = createToken; // Reserved words function createSuper() { - return createSynthesizedNode(97 /* SuperKeyword */); + return createSynthesizedNode(98 /* SuperKeyword */); } ts.createSuper = createSuper; function createThis() { - return createSynthesizedNode(99 /* ThisKeyword */); + return createSynthesizedNode(100 /* ThisKeyword */); } ts.createThis = createThis; function createNull() { - return createSynthesizedNode(95 /* NullKeyword */); + return createSynthesizedNode(96 /* NullKeyword */); } ts.createNull = createNull; function createTrue() { - return createSynthesizedNode(101 /* TrueKeyword */); + return createSynthesizedNode(102 /* TrueKeyword */); } ts.createTrue = createTrue; function createFalse() { - return createSynthesizedNode(86 /* FalseKeyword */); + return createSynthesizedNode(87 /* FalseKeyword */); } ts.createFalse = createFalse; // Modifiers @@ -56972,44 +59219,44 @@ var ts; function createModifiersFromModifierFlags(flags) { var result = []; if (flags & 1 /* Export */) { - result.push(createModifier(84 /* ExportKeyword */)); + result.push(createModifier(85 /* ExportKeyword */)); } if (flags & 2 /* Ambient */) { - result.push(createModifier(124 /* DeclareKeyword */)); + result.push(createModifier(125 /* DeclareKeyword */)); } if (flags & 512 /* Default */) { - result.push(createModifier(79 /* DefaultKeyword */)); + result.push(createModifier(80 /* DefaultKeyword */)); } if (flags & 2048 /* Const */) { - result.push(createModifier(76 /* ConstKeyword */)); + result.push(createModifier(77 /* ConstKeyword */)); } if (flags & 4 /* Public */) { - result.push(createModifier(114 /* PublicKeyword */)); + result.push(createModifier(115 /* PublicKeyword */)); } if (flags & 8 /* Private */) { - result.push(createModifier(112 /* PrivateKeyword */)); + result.push(createModifier(113 /* PrivateKeyword */)); } if (flags & 16 /* Protected */) { - result.push(createModifier(113 /* ProtectedKeyword */)); + result.push(createModifier(114 /* ProtectedKeyword */)); } if (flags & 128 /* Abstract */) { - result.push(createModifier(117 /* AbstractKeyword */)); + result.push(createModifier(118 /* AbstractKeyword */)); } if (flags & 32 /* Static */) { - result.push(createModifier(115 /* StaticKeyword */)); + result.push(createModifier(116 /* StaticKeyword */)); } if (flags & 64 /* Readonly */) { - result.push(createModifier(132 /* ReadonlyKeyword */)); + result.push(createModifier(133 /* ReadonlyKeyword */)); } if (flags & 256 /* Async */) { - result.push(createModifier(120 /* AsyncKeyword */)); + result.push(createModifier(121 /* AsyncKeyword */)); } return result; } ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; // Names function createQualifiedName(left, right) { - var node = createSynthesizedNode(146 /* QualifiedName */); + var node = createSynthesizedNode(148 /* QualifiedName */); node.left = left; node.right = asName(right); return node; @@ -57028,7 +59275,7 @@ var ts; : expression; } function createComputedPropertyName(expression) { - var node = createSynthesizedNode(147 /* ComputedPropertyName */); + var node = createSynthesizedNode(149 /* ComputedPropertyName */); node.expression = parenthesizeForComputedName(expression); return node; } @@ -57041,7 +59288,7 @@ var ts; ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(148 /* TypeParameter */); + var node = createSynthesizedNode(150 /* TypeParameter */); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -57057,7 +59304,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149 /* Parameter */); + var node = createSynthesizedNode(151 /* Parameter */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -57081,7 +59328,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(150 /* Decorator */); + var node = createSynthesizedNode(152 /* Decorator */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -57094,7 +59341,7 @@ var ts; ts.updateDecorator = updateDecorator; // Type Elements function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(151 /* PropertySignature */); + var node = createSynthesizedNode(153 /* PropertySignature */); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -57114,12 +59361,12 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createSynthesizedNode(152 /* PropertyDeclaration */); + var node = createSynthesizedNode(154 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); - node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined; - node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined; + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined; node.type = type; node.initializer = initializer; return node; @@ -57129,8 +59376,8 @@ var ts; return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name - || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined) - || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined) + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) @@ -57138,7 +59385,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(153 /* MethodSignature */, typeParameters, parameters, type); + var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -57155,7 +59402,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(154 /* MethodDeclaration */); + var node = createSynthesizedNode(156 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -57183,7 +59430,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(155 /* Constructor */); + var node = createSynthesizedNode(157 /* Constructor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -57203,7 +59450,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(156 /* GetAccessor */); + var node = createSynthesizedNode(158 /* GetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57226,7 +59473,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(157 /* SetAccessor */); + var node = createSynthesizedNode(159 /* SetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57247,7 +59494,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(158 /* CallSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -57255,7 +59502,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(159 /* ConstructSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -57263,7 +59510,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(160 /* IndexSignature */); + var node = createSynthesizedNode(162 /* IndexSignature */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -57303,7 +59550,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(161 /* TypePredicate */); + var node = createSynthesizedNode(163 /* TypePredicate */); node.parameterName = asName(parameterName); node.type = type; return node; @@ -57317,7 +59564,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(162 /* TypeReference */); + var node = createSynthesizedNode(164 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -57331,7 +59578,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(163 /* FunctionType */, typeParameters, parameters, type); + return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -57339,7 +59586,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(164 /* ConstructorType */, typeParameters, parameters, type); + return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -57347,7 +59594,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(165 /* TypeQuery */); + var node = createSynthesizedNode(167 /* TypeQuery */); node.exprName = exprName; return node; } @@ -57359,7 +59606,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(166 /* TypeLiteral */); + var node = createSynthesizedNode(168 /* TypeLiteral */); node.members = createNodeArray(members); return node; } @@ -57371,7 +59618,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(167 /* ArrayType */); + var node = createSynthesizedNode(169 /* ArrayType */); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -57383,7 +59630,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(168 /* TupleType */); + var node = createSynthesizedNode(170 /* TupleType */); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -57395,7 +59642,7 @@ var ts; } ts.updateTupleTypeNode = updateTupleTypeNode; function createOptionalTypeNode(type) { - var node = createSynthesizedNode(169 /* OptionalType */); + var node = createSynthesizedNode(171 /* OptionalType */); node.type = ts.parenthesizeArrayTypeMember(type); return node; } @@ -57407,7 +59654,7 @@ var ts; } ts.updateOptionalTypeNode = updateOptionalTypeNode; function createRestTypeNode(type) { - var node = createSynthesizedNode(170 /* RestType */); + var node = createSynthesizedNode(172 /* RestType */); node.type = type; return node; } @@ -57419,7 +59666,7 @@ var ts; } ts.updateRestTypeNode = updateRestTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(171 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(173 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -57427,7 +59674,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(172 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -57446,7 +59693,7 @@ var ts; : node; } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createSynthesizedNode(173 /* ConditionalType */); + var node = createSynthesizedNode(175 /* ConditionalType */); node.checkType = ts.parenthesizeConditionalTypeMember(checkType); node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); node.trueType = trueType; @@ -57464,7 +59711,7 @@ var ts; } ts.updateConditionalTypeNode = updateConditionalTypeNode; function createInferTypeNode(typeParameter) { - var node = createSynthesizedNode(174 /* InferType */); + var node = createSynthesizedNode(176 /* InferType */); node.typeParameter = typeParameter; return node; } @@ -57476,7 +59723,7 @@ var ts; } ts.updateInferTypeNode = updateInferTypeNode; function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { - var node = createSynthesizedNode(181 /* ImportType */); + var node = createSynthesizedNode(183 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = asNodeArray(typeArguments); @@ -57494,7 +59741,7 @@ var ts; } ts.updateImportTypeNode = updateImportTypeNode; function createParenthesizedType(type) { - var node = createSynthesizedNode(175 /* ParenthesizedType */); + var node = createSynthesizedNode(177 /* ParenthesizedType */); node.type = type; return node; } @@ -57506,12 +59753,12 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(176 /* ThisType */); + return createSynthesizedNode(178 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; function createTypeOperatorNode(operatorOrType, type) { - var node = createSynthesizedNode(177 /* TypeOperator */); - node.operator = typeof operatorOrType === "number" ? operatorOrType : 128 /* KeyOfKeyword */; + var node = createSynthesizedNode(179 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */; node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } @@ -57521,7 +59768,7 @@ var ts; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(178 /* IndexedAccessType */); + var node = createSynthesizedNode(180 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -57535,7 +59782,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(179 /* MappedType */); + var node = createSynthesizedNode(181 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -57553,7 +59800,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(180 /* LiteralType */); + var node = createSynthesizedNode(182 /* LiteralType */); node.literal = literal; return node; } @@ -57566,7 +59813,7 @@ var ts; ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(182 /* ObjectBindingPattern */); + var node = createSynthesizedNode(184 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -57578,7 +59825,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(183 /* ArrayBindingPattern */); + var node = createSynthesizedNode(185 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -57590,7 +59837,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(184 /* BindingElement */); + var node = createSynthesizedNode(186 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -57609,7 +59856,7 @@ var ts; ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(185 /* ArrayLiteralExpression */); + var node = createSynthesizedNode(187 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -57623,7 +59870,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(186 /* ObjectLiteralExpression */); + var node = createSynthesizedNode(188 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -57637,7 +59884,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(187 /* PropertyAccessExpression */); + var node = createSynthesizedNode(189 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); @@ -57654,7 +59901,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(188 /* ElementAccessExpression */); + var node = createSynthesizedNode(190 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -57668,7 +59915,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(189 /* CallExpression */); + var node = createSynthesizedNode(191 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -57684,7 +59931,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(190 /* NewExpression */); + var node = createSynthesizedNode(192 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -57700,7 +59947,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { - var node = createSynthesizedNode(191 /* TaggedTemplateExpression */); + var node = createSynthesizedNode(193 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); if (template) { node.typeArguments = asNodeArray(typeArgumentsOrTemplate); @@ -57723,7 +59970,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(192 /* TypeAssertionExpression */); + var node = createSynthesizedNode(194 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -57737,7 +59984,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(193 /* ParenthesizedExpression */); + var node = createSynthesizedNode(195 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -57749,7 +59996,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(194 /* FunctionExpression */); + var node = createSynthesizedNode(196 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -57773,12 +60020,12 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(195 /* ArrowFunction */); + var node = createSynthesizedNode(197 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(36 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */); node.body = ts.parenthesizeConciseBody(body); return node; } @@ -57795,7 +60042,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(196 /* DeleteExpression */); + var node = createSynthesizedNode(198 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57807,7 +60054,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(197 /* TypeOfExpression */); + var node = createSynthesizedNode(199 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57819,7 +60066,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(198 /* VoidExpression */); + var node = createSynthesizedNode(200 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57831,7 +60078,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(199 /* AwaitExpression */); + var node = createSynthesizedNode(201 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57843,7 +60090,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(200 /* PrefixUnaryExpression */); + var node = createSynthesizedNode(202 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -57856,7 +60103,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(201 /* PostfixUnaryExpression */); + var node = createSynthesizedNode(203 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -57869,7 +60116,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(202 /* BinaryExpression */); + var node = createSynthesizedNode(204 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -57886,11 +60133,11 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(203 /* ConditionalExpression */); + var node = createSynthesizedNode(205 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); - node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); - node.colonToken = whenFalse ? colonToken : createToken(56 /* ColonToken */); + node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */); node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); return node; } @@ -57906,7 +60153,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(204 /* TemplateExpression */); + var node = createSynthesizedNode(206 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -57920,33 +60167,33 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createTemplateHead(text) { - var node = createSynthesizedNode(14 /* TemplateHead */); + var node = createSynthesizedNode(15 /* TemplateHead */); node.text = text; return node; } ts.createTemplateHead = createTemplateHead; function createTemplateMiddle(text) { - var node = createSynthesizedNode(15 /* TemplateMiddle */); + var node = createSynthesizedNode(16 /* TemplateMiddle */); node.text = text; return node; } ts.createTemplateMiddle = createTemplateMiddle; function createTemplateTail(text) { - var node = createSynthesizedNode(16 /* TemplateTail */); + var node = createSynthesizedNode(17 /* TemplateTail */); node.text = text; return node; } ts.createTemplateTail = createTemplateTail; function createNoSubstitutionTemplateLiteral(text) { - var node = createSynthesizedNode(13 /* NoSubstitutionTemplateLiteral */); + var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */); node.text = text; return node; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(205 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + var node = createSynthesizedNode(207 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; } ts.createYield = createYield; @@ -57958,7 +60205,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(206 /* SpreadElement */); + var node = createSynthesizedNode(208 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -57970,7 +60217,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(207 /* ClassExpression */); + var node = createSynthesizedNode(209 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57991,11 +60238,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(208 /* OmittedExpression */); + return createSynthesizedNode(210 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(209 /* ExpressionWithTypeArguments */); + var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -58009,7 +60256,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(210 /* AsExpression */); + var node = createSynthesizedNode(212 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -58023,7 +60270,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(211 /* NonNullExpression */); + var node = createSynthesizedNode(213 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -58035,7 +60282,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(212 /* MetaProperty */); + var node = createSynthesizedNode(214 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -58049,7 +60296,7 @@ var ts; ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(214 /* TemplateSpan */); + var node = createSynthesizedNode(216 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -58063,12 +60310,12 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(215 /* SemicolonClassElement */); + return createSynthesizedNode(217 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(216 /* Block */); + var block = createSynthesizedNode(218 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -58082,7 +60329,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(217 /* VariableStatement */); + var node = createSynthesizedNode(219 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -58097,11 +60344,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(218 /* EmptyStatement */); + return createSynthesizedNode(220 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; function createExpressionStatement(expression) { - var node = createSynthesizedNode(219 /* ExpressionStatement */); + var node = createSynthesizedNode(221 /* ExpressionStatement */); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -58117,7 +60364,7 @@ var ts; /** @deprecated Use `updateExpressionStatement` instead. */ ts.updateStatement = updateExpressionStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(220 /* IfStatement */); + var node = createSynthesizedNode(222 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -58133,7 +60380,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(221 /* DoStatement */); + var node = createSynthesizedNode(223 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -58147,7 +60394,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(222 /* WhileStatement */); + var node = createSynthesizedNode(224 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -58161,7 +60408,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(223 /* ForStatement */); + var node = createSynthesizedNode(225 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -58179,7 +60426,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(224 /* ForInStatement */); + var node = createSynthesizedNode(226 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -58195,7 +60442,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(225 /* ForOfStatement */); + var node = createSynthesizedNode(227 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -58213,7 +60460,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(226 /* ContinueStatement */); + var node = createSynthesizedNode(228 /* ContinueStatement */); node.label = asName(label); return node; } @@ -58225,7 +60472,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(227 /* BreakStatement */); + var node = createSynthesizedNode(229 /* BreakStatement */); node.label = asName(label); return node; } @@ -58237,7 +60484,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(228 /* ReturnStatement */); + var node = createSynthesizedNode(230 /* ReturnStatement */); node.expression = expression; return node; } @@ -58249,7 +60496,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(229 /* WithStatement */); + var node = createSynthesizedNode(231 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -58263,7 +60510,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(230 /* SwitchStatement */); + var node = createSynthesizedNode(232 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -58277,7 +60524,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(231 /* LabeledStatement */); + var node = createSynthesizedNode(233 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -58291,7 +60538,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(232 /* ThrowStatement */); + var node = createSynthesizedNode(234 /* ThrowStatement */); node.expression = expression; return node; } @@ -58303,7 +60550,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(233 /* TryStatement */); + var node = createSynthesizedNode(235 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -58319,11 +60566,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(234 /* DebuggerStatement */); + return createSynthesizedNode(236 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(235 /* VariableDeclaration */); + var node = createSynthesizedNode(237 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -58340,7 +60587,7 @@ var ts; ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(236 /* VariableDeclarationList */); + var node = createSynthesizedNode(238 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; @@ -58353,7 +60600,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(237 /* FunctionDeclaration */); + var node = createSynthesizedNode(239 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -58379,7 +60626,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(238 /* ClassDeclaration */); + var node = createSynthesizedNode(240 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58401,7 +60648,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(239 /* InterfaceDeclaration */); + var node = createSynthesizedNode(241 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58423,7 +60670,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(240 /* TypeAliasDeclaration */); + var node = createSynthesizedNode(242 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58443,7 +60690,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(241 /* EnumDeclaration */); + var node = createSynthesizedNode(243 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58462,7 +60709,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(242 /* ModuleDeclaration */); + var node = createSynthesizedNode(244 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -58481,7 +60728,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(243 /* ModuleBlock */); + var node = createSynthesizedNode(245 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -58493,7 +60740,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(244 /* CaseBlock */); + var node = createSynthesizedNode(246 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -58505,7 +60752,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(245 /* NamespaceExportDeclaration */); + var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -58517,7 +60764,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(246 /* ImportEqualsDeclaration */); + var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58535,7 +60782,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(247 /* ImportDeclaration */); + var node = createSynthesizedNode(249 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -58553,7 +60800,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(248 /* ImportClause */); + var node = createSynthesizedNode(250 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -58567,7 +60814,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(249 /* NamespaceImport */); + var node = createSynthesizedNode(251 /* NamespaceImport */); node.name = name; return node; } @@ -58579,7 +60826,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(250 /* NamedImports */); + var node = createSynthesizedNode(252 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -58591,7 +60838,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(251 /* ImportSpecifier */); + var node = createSynthesizedNode(253 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -58605,11 +60852,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(252 /* ExportAssignment */); + var node = createSynthesizedNode(254 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -58622,7 +60869,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(253 /* ExportDeclaration */); + var node = createSynthesizedNode(255 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -58640,7 +60887,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(254 /* NamedExports */); + var node = createSynthesizedNode(256 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -58652,7 +60899,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(255 /* ExportSpecifier */); + var node = createSynthesizedNode(257 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -58667,7 +60914,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(257 /* ExternalModuleReference */); + var node = createSynthesizedNode(259 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -58678,9 +60925,57 @@ var ts; : node; } ts.updateExternalModuleReference = updateExternalModuleReference; + // JSDoc + /* @internal */ + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + /* @internal */ + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + /* @internal */ + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + /* @internal */ + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + /* @internal */ + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291 /* JSDocComment */); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + /* @internal */ + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(258 /* JsxElement */); + var node = createSynthesizedNode(260 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -58696,7 +60991,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); + var node = createSynthesizedNode(261 /* JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -58712,7 +61007,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(260 /* JsxOpeningElement */); + var node = createSynthesizedNode(262 /* JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -58728,7 +61023,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(261 /* JsxClosingElement */); + var node = createSynthesizedNode(263 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -58740,7 +61035,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxFragment(openingFragment, children, closingFragment) { - var node = createSynthesizedNode(262 /* JsxFragment */); + var node = createSynthesizedNode(264 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -58756,7 +61051,7 @@ var ts; } ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(265 /* JsxAttribute */); + var node = createSynthesizedNode(267 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -58770,7 +61065,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(266 /* JsxAttributes */); + var node = createSynthesizedNode(268 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -58782,7 +61077,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(267 /* JsxSpreadAttribute */); + var node = createSynthesizedNode(269 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -58794,7 +61089,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(268 /* JsxExpression */); + var node = createSynthesizedNode(270 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -58808,7 +61103,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(269 /* CaseClause */); + var node = createSynthesizedNode(271 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -58822,7 +61117,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(270 /* DefaultClause */); + var node = createSynthesizedNode(272 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -58834,7 +61129,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(271 /* HeritageClause */); + var node = createSynthesizedNode(273 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -58847,7 +61142,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(272 /* CatchClause */); + var node = createSynthesizedNode(274 /* CatchClause */); node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -58862,7 +61157,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(273 /* PropertyAssignment */); + var node = createSynthesizedNode(275 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = ts.parenthesizeExpressionForList(initializer); @@ -58877,7 +61172,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(274 /* ShorthandPropertyAssignment */); + var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -58891,7 +61186,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(275 /* SpreadAssignment */); + var node = createSynthesizedNode(277 /* SpreadAssignment */); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } @@ -58904,7 +61199,7 @@ var ts; ts.updateSpreadAssignment = updateSpreadAssignment; // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(276 /* EnumMember */); + var node = createSynthesizedNode(278 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -58925,7 +61220,7 @@ var ts; (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { - var updated = createSynthesizedNode(277 /* SourceFile */); + var updated = createSynthesizedNode(279 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -59009,7 +61304,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(305 /* NotEmittedStatement */); + var node = createSynthesizedNode(307 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -59021,7 +61316,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -59033,7 +61328,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(308 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -59048,7 +61343,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -59064,17 +61359,17 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 307 /* CommaListExpression */) { + if (node.kind === 309 /* CommaListExpression */) { return node.elements; } - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { return [node.left, node.right]; } } return node; } function createCommaList(elements) { - var node = createSynthesizedNode(307 /* CommaListExpression */); + var node = createSynthesizedNode(309 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -59087,14 +61382,14 @@ var ts; ts.updateCommaList = updateCommaList; function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = ts.createNode(278 /* Bundle */); + var node = ts.createNode(280 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; function createUnparsedSourceFile(text, mapPath, map) { - var node = ts.createNode(279 /* UnparsedSource */); + var node = ts.createNode(281 /* UnparsedSource */); node.text = text; node.sourceMapPath = mapPath; node.sourceMapText = map; @@ -59102,7 +61397,7 @@ var ts; } ts.createUnparsedSourceFile = createUnparsedSourceFile; function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { - var node = ts.createNode(280 /* InputFiles */); + var node = ts.createNode(282 /* InputFiles */); node.javascriptText = javascript; node.javascriptMapPath = javascriptMapPath; node.javascriptMapText = javascriptMapText; @@ -59144,47 +61439,47 @@ var ts; } ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { - return createBinary(left, 26 /* CommaToken */, right); + return createBinary(left, 27 /* CommaToken */, right); } ts.createComma = createComma; function createLessThan(left, right) { - return createBinary(left, 27 /* LessThanToken */, right); + return createBinary(left, 28 /* LessThanToken */, right); } ts.createLessThan = createLessThan; function createAssignment(left, right) { - return createBinary(left, 58 /* EqualsToken */, right); + return createBinary(left, 59 /* EqualsToken */, right); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 34 /* EqualsEqualsEqualsToken */, right); + return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 35 /* ExclamationEqualsEqualsToken */, right); + return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 37 /* PlusToken */, right); + return createBinary(left, 38 /* PlusToken */, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 38 /* MinusToken */, right); + return createBinary(left, 39 /* MinusToken */, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand) { - return createPostfix(operand, 43 /* PlusPlusToken */); + return createPostfix(operand, 44 /* PlusPlusToken */); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 53 /* AmpersandAmpersandToken */, right); + return createBinary(left, 54 /* AmpersandAmpersandToken */, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 54 /* BarBarToken */, right); + return createBinary(left, 55 /* BarBarToken */, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(51 /* ExclamationToken */, operand); + return createPrefix(52 /* ExclamationToken */, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { @@ -59245,7 +61540,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -59756,7 +62051,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 231 /* LabeledStatement */ + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -59768,19 +62063,20 @@ var ts; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = ts.skipParentheses(node); switch (target.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return cacheIdentifiers; - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: return false; - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -59795,7 +62091,7 @@ var ts; thisArg = ts.createThis(); target = callee; } - else if (callee.kind === 97 /* SuperKeyword */) { + else if (callee.kind === 98 /* SuperKeyword */) { thisArg = ts.createThis(); target = languageVersion < 2 /* ES2015 */ ? ts.setTextRange(ts.createIdentifier("_super"), callee) @@ -59807,7 +62103,7 @@ var ts; } else { switch (callee.kind) { - case 187 /* PropertyAccessExpression */: { + case 189 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -59820,7 +62116,7 @@ var ts; } break; } - case 188 /* ElementAccessExpression */: { + case 190 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -59877,14 +62173,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -59892,7 +62188,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_9 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -59903,7 +62199,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_9.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -59915,15 +62211,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_9.push(setter); + properties_8.push(setter); } - properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_9, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -60161,6 +62457,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +62485,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -60207,7 +62506,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 193 /* ParenthesizedExpression */) { + if (skipped.kind === 195 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -60241,10 +62540,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -60256,7 +62555,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 205 /* YieldExpression */) { + && operand.kind === 207 /* YieldExpression */) { return false; } return true; @@ -60293,7 +62592,7 @@ var ts; // the same kind (recursively). // "a"+(1+2) => "a"+(1+2) // "a"+("b"+"c") => "a"+"b"+"c" - if (binaryOperator === 37 /* PlusToken */) { + if (binaryOperator === 38 /* PlusToken */) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -60328,10 +62627,10 @@ var ts; // // While addition is associative in mathematics, JavaScript's `+` is not // guaranteed to be associative as it is overloaded with string concatenation. - return binaryOperator === 39 /* AsteriskToken */ - || binaryOperator === 49 /* BarToken */ - || binaryOperator === 48 /* AmpersandToken */ - || binaryOperator === 50 /* CaretToken */; + return binaryOperator === 40 /* AsteriskToken */ + || binaryOperator === 50 /* BarToken */ + || binaryOperator === 49 /* AmpersandToken */ + || binaryOperator === 51 /* CaretToken */; } /** * This function determines whether an expression consists of a homogeneous set of @@ -60344,7 +62643,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -60359,7 +62658,7 @@ var ts; return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(203 /* ConditionalExpression */, 55 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { @@ -60394,8 +62693,8 @@ var ts; var needsParens = isCommaSequence(check); if (!needsParens) { switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: needsParens = true; } } @@ -60411,9 +62710,9 @@ var ts; function parenthesizeForNew(expression) { var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return ts.createParen(expression); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return !leftmostExpr.arguments ? ts.createParen(expression) : expression; @@ -60436,7 +62735,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 190 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -60474,7 +62773,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, 26 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -60485,29 +62784,29 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 194 /* FunctionExpression */ || kind === 195 /* ArrowFunction */) { + if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 186 /* ObjectLiteralExpression */ || leftmostExpressionKind === 194 /* FunctionExpression */) { + if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeConditionalTypeMember(member) { - return member.kind === 173 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; } ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return ts.createParenthesizedType(member); } return parenthesizeConditionalTypeMember(member); @@ -60515,9 +62814,9 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 165 /* TypeQuery */: - case 177 /* TypeOperator */: - case 174 /* InferType */: + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 176 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -60543,28 +62842,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: node = node.operand; continue; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: node = node.left; continue; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: node = node.condition; continue; - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: node = node.tag; continue; - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 210 /* AsExpression */: - case 188 /* ElementAccessExpression */: - case 187 /* PropertyAccessExpression */: - case 211 /* NonNullExpression */: - case 306 /* PartiallyEmittedExpression */: + case 212 /* AsExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 213 /* NonNullExpression */: + case 308 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -60572,15 +62871,15 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 186 /* ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) { return ts.setTextRange(ts.createParen(body), body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { - return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || - node.kind === 307 /* CommaListExpression */; + return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 309 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; @@ -60593,13 +62892,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 211 /* NonNullExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 213 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -60624,7 +62923,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 211 /* NonNullExpression */) { + while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) { node = node.expression; } return node; @@ -60632,11 +62931,11 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 193 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); - case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -60654,7 +62953,7 @@ var ts; * the containing expression is created/updated. */ function isIgnorableParen(node) { - return node.kind === 193 /* ParenthesizedExpression */ + return node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -60719,10 +63018,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 247 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 249 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 253 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -60738,7 +63037,7 @@ var ts; */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 - if (moduleName.kind === 9 /* StringLiteral */) { + if (moduleName.kind === 10 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) || ts.getSynthesizedClone(moduleName); @@ -60841,7 +63140,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -60853,11 +63152,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -60889,12 +63188,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 149 /* Parameter */: - case 184 /* BindingElement */: + case 151 /* Parameter */: + case 186 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 206 /* SpreadElement */: - case 275 /* SpreadAssignment */: + case 208 /* SpreadElement */: + case 277 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -60906,7 +63205,7 @@ var ts; */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 184 /* BindingElement */: + case 186 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -60918,7 +63217,7 @@ var ts; : propertyName; } break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -60930,7 +63229,7 @@ var ts; : propertyName; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -60945,7 +63244,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; - return kind === 9 /* StringLiteral */ + return kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */; } /** @@ -60953,13 +63252,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -60999,11 +63298,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 182 /* ObjectBindingPattern */: - case 186 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -61164,276 +63463,276 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */) || kind === 176 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) { return node; } switch (kind) { // Names - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 149 /* Parameter */: + case 151 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 150 /* Decorator */: + case 152 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); // Type elements - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 153 /* MethodSignature */: + case 155 /* MethodSignature */: return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 155 /* Constructor */: + case 157 /* Constructor */: return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 158 /* CallSignature */: + case 160 /* CallSignature */: return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 163 /* FunctionType */: + case 165 /* FunctionType */: return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 164 /* ConstructorType */: + case 166 /* ConstructorType */: return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); - case 168 /* TupleType */: + case 170 /* TupleType */: return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 170 /* RestType */: + case 172 /* RestType */: return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 171 /* UnionType */: + case 173 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); - case 174 /* InferType */: + case 176 /* InferType */: return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 181 /* ImportType */: + case 183 /* ImportType */: return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 179 /* MappedType */: + case 181 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); // Binding patterns - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); // Expression - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 210 /* AsExpression */: + case 212 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 216 /* Block */: + case 218 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 250 /* NamedImports */: + case 252 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 254 /* NamedExports */: + case 256 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 255 /* ExportSpecifier */: + case 257 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -61475,58 +63774,58 @@ var ts; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 161 /* TypePredicate */ && kind <= 180 /* LiteralType */)) { + if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 215 /* SemicolonClassElement */: - case 218 /* EmptyStatement */: - case 208 /* OmittedExpression */: - case 234 /* DebuggerStatement */: - case 305 /* NotEmittedStatement */: + case 217 /* SemicolonClassElement */: + case 220 /* EmptyStatement */: + case 210 /* OmittedExpression */: + case 236 /* DebuggerStatement */: + case 307 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 149 /* Parameter */: + case 151 /* Parameter */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 150 /* Decorator */: + case 152 /* Decorator */: result = reduceNode(node.expression, cbNode, result); break; // Type member - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61535,12 +63834,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 155 /* Constructor */: + case 157 /* Constructor */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61548,7 +63847,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61556,49 +63855,50 @@ var ts; result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 190 /* NewExpression */: + case 192 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNode(node.template, cbNode, result); break; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -61606,123 +63906,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 193 /* ParenthesizedExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 199 /* AwaitExpression */: - case 205 /* YieldExpression */: - case 206 /* SpreadElement */: - case 211 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 210 /* AsExpression */: + case 212 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; // Element - case 216 /* Block */: + case 218 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 221 /* DoStatement */: + case 223 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 222 /* WhileStatement */: - case 229 /* WithStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61731,7 +64031,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61739,139 +64039,140 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 250 /* NamedImports */: - case 254 /* NamedExports */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: result = reduceNode(node.openingFragment, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingFragment, cbNode, result); break; - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); // falls through - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 272 /* CatchClause */: + case 274 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 277 /* SourceFile */: + case 279 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -61944,7 +64245,7 @@ var ts; function aggregateTransformFlagsForSubtree(node) { // We do not transform ambient declarations or types, so there is no need to // recursively aggregate transform flags. - if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 209 /* ExpressionWithTypeArguments */)) { + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) { return 0 /* None */; } // Aggregate the transform flags of each child. @@ -61994,7 +64295,7 @@ var ts; }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, - __debugObjectFlags: { get: function () { return this.flags & 131072 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ @@ -62031,288 +64332,623 @@ var ts; /* @internal */ var ts; (function (ts) { - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + // Current source map file and its index in the sources list + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + // Last recorded and encoded mappings + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - // And failing that, check the disk - var text = host.readFile(path); // TODO: GH#18217 - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + // Then reencode all the updated mappings into the overall map + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } } - }; - cached.set(path, file); - return file; + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } + } + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + /** + * Tries to find the sourceMappingURL comment at the end of a file. + * @param text The source text of the file. + * @param lineStarts The line starts of the file. + */ + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + // empty + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + // Next entry is on same line - no action needed + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); } }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 /* comma */ || + mappings.charCodeAt(pos) === 59 /* semicolon */); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + // 6 digit number + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } } - ts.createSourceFileLikeCache = createSourceFileLikeCache; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - var sourcemaps; - (function (sourcemaps) { - sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; - function decode(host, mapPath, map, program, fallbackCache) { - if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } - var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; - var decodedMappings; - var generatedOrderedMappings; - var sourceOrderedMappings; - return { - getOriginalPosition: getOriginalPosition, - getGeneratedPosition: getGeneratedPosition - }; - function getGeneratedPosition(loc) { - var maps = getSourceOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { - return loc; - } - return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos - } - function getOriginalPosition(loc) { - var maps = getGeneratedOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos - } - function getSourceFileLike(fileName, location) { - // Lookup file in program, if provided - var path = ts.toPath(fileName, location, host.getCanonicalFileName); - var file = program && program.getSourceFile(path); - // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file - if (!file || file.resolvedPath !== path) { - // Otherwise check the cache (which may hit disk) - return fallbackCache.get(path); - } - return file; - } - function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { - var file = getSourceFileLike(fileName, directory); - if (!file) { - return -1; - } - return ts.getPositionOfLineAndCharacter(file, line, character); - } - function getDecodedMappings() { - return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host)); - } - function getSourceOrderedMappings() { - return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); - } - function getGeneratedOrderedMappings() { - return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); - } - function compareProcessedPositionSourcePositions(a, b) { - return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || - ts.compareValues(a.sourcePosition, b.sourcePosition); - } - function compareProcessedPositionEmittedPositions(a, b) { - return ts.compareValues(a.emittedPosition, b.emittedPosition); - } - function processPosition(position) { - var sourcePath = map.sources[position.sourceIndex]; - return { - emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), - sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), - sourcePath: sourcePath, - }; - } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : + value >= 26 && value < 52 ? 97 /* a */ + value - 26 : + value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : + value === 62 ? 43 /* plus */ : + value === 63 ? 47 /* slash */ : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : + ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : + ch === 43 /* plus */ ? 62 : + ch === 47 /* slash */ ? 63 : + -1; + } + 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; } - sourcemaps.decode = decode; - /*@internal*/ - function decodeMappings(map) { - var state = { - encodedText: map.mappings, - currentNameIndex: undefined, - sourceMapNamesLength: map.names ? map.names.length : undefined, - currentEmittedColumn: 0, - currentEmittedLine: 0, - currentSourceColumn: 0, - currentSourceLine: 0, - currentSourceIndex: 0, - decodingIndex: 0 - }; - function captureSpan() { - return { - emittedColumn: state.currentEmittedColumn, - emittedLine: state.currentEmittedLine, - sourceColumn: state.currentSourceColumn, - sourceIndex: state.currentSourceIndex, - sourceLine: state.currentSourceLine, - nameIndex: state.currentNameIndex - }; + 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 + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; } return { - get decodingIndex() { return state.decodingIndex; }, - get error() { return state.error; }, - get lastSpan() { return captureSpan(); }, - next: function () { - if (hasCompletedDecoding(state) || state.error) - return { done: true, value: undefined }; - if (!decodeSinglePosition(state)) - return { done: true, value: undefined }; - return { done: false, value: captureSpan() }; - } + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex }; } - sourcemaps.decodeMappings = decodeMappings; - function calculateDecodedMappings(map, processPosition, host) { - var decoder = decodeMappings(map); - var positions = ts.arrayFrom(decoder, processPosition); - if (decoder.error) { - if (host && host.log) { - host.log("Encountered error while decoding sourcemap: " + decoder.error); - } - return []; - } - return positions; - } - function hasCompletedDecoding(state) { - return state.decodingIndex === state.encodedText.length; - } - function decodeSinglePosition(state) { - while (state.decodingIndex < state.encodedText.length) { - var char = state.encodedText.charCodeAt(state.decodingIndex); - if (char === 59 /* semicolon */) { - // New line - state.currentEmittedLine++; - state.currentEmittedColumn = 0; - state.decodingIndex++; - continue; - } - if (char === 44 /* comma */) { - // Next entry is on same line - no action needed - state.decodingIndex++; - continue; - } - // Read the current position - // 1. Column offset from prev read jsColumn - state.currentEmittedColumn += base64VLQFormatDecode(); - // Incorrect emittedColumn dont support this map - if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { - return false; - } - // 2. Relative sourceIndex - state.currentSourceIndex += base64VLQFormatDecode(); - // Incorrect sourceIndex dont support this map - if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { - return false; - } - // Dont support reading mappings that dont have information about original source position - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { - return false; - } - // 3. Relative sourceLine 0 based - state.currentSourceLine += base64VLQFormatDecode(); - // Incorrect sourceLine dont support this map - if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { - return false; - } - // 4. Relative sourceColumn 0 based - state.currentSourceColumn += base64VLQFormatDecode(); - // Incorrect sourceColumn dont support this map - if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { - return false; - } - // 5. Check if there is name: - if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { - if (state.currentNameIndex === undefined) { - state.currentNameIndex = 0; + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); } - state.currentNameIndex += base64VLQFormatDecode(); - // Incorrect nameIndex dont support this map - // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap - // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { - // return; - // } - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { - return false; - } - // Entry should be complete - return true; - } - createErrorIfCondition(/*condition*/ true, "No encoded entry found"); - return false; - function createErrorIfCondition(condition, errormsg) { - if (state.error) { - // An error was already reported - return true; - } - if (condition) { - state.error = errormsg; - } - return condition; - } - function base64VLQFormatDecode() { - var moreDigits = true; - var shiftCount = 0; - var value = 0; - for (; moreDigits; state.decodingIndex++) { - if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return undefined; // TODO: GH#18217 - } - // 6 digit number - var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); - // If msb is set, we still have more bits to continue - moreDigits = (currentByte & 32) !== 0; - // least significant 5 bits are the next msbs in the final value. - value = value | ((currentByte & 31) << shiftCount); - shiftCount += 5; - } - // Least significant bit if 1 represents negative and rest of the msb is actual absolute value - if ((value & 1) === 0) { - // + number - value = value >> 1; + decodedMappings = ts.emptyArray; } else { - // - number - value = value >> 1; - value = -value; + decodedMappings = mappings; } - return value; } + return decodedMappings; } - function base64FormatDecode(char) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; } - function isSourceMappingSegmentEnd(encodedText, pos) { - return (pos === encodedText.length || - encodedText.charCodeAt(pos) === 44 /* comma */ || - encodedText.charCodeAt(pos) === 59 /* semicolon */); + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; } - })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; })(ts || (ts = {})); /* @internal */ var ts; @@ -62335,7 +64971,7 @@ var ts; function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 277 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -62381,7 +65017,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -62389,13 +65025,13 @@ var ts; externalImports.push(node); hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; - case 246 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { + case 248 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -62425,13 +65061,13 @@ var ts; } } break; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -62439,7 +65075,7 @@ var ts; } } break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default function() { } @@ -62459,7 +65095,7 @@ var ts; } } break; - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default class { } @@ -62811,8 +65447,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62878,7 +65514,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63075,8 +65711,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -63106,14 +65742,14 @@ var ts; var pendingExpressions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 278 /* Bundle */) { + if (node.kind === 280 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280 /* InputFiles */) { + if (prepend.kind === 282 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); } return prepend; @@ -63162,16 +65798,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 277 /* SourceFile */: - case 244 /* CaseBlock */: - case 243 /* ModuleBlock */: - case 216 /* Block */: + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 245 /* ModuleBlock */: + case 218 /* Block */: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 238 /* ClassDeclaration */: - case 237 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: if (ts.hasModifier(node, 2 /* Ambient */)) { break; } @@ -63183,7 +65819,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 238 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); } if (ts.isClassDeclaration(node)) { // XXX: should probably also cover interfaces and type aliases that can have type variables? @@ -63231,10 +65867,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -63255,13 +65891,13 @@ var ts; return node; } switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -63281,11 +65917,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 253 /* ExportDeclaration */ || - node.kind === 247 /* ImportDeclaration */ || - node.kind === 248 /* ImportClause */ || - (node.kind === 246 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 257 /* ExternalModuleReference */)) { + if (node.kind === 255 /* ExportDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 250 /* ImportClause */ || + (node.kind === 248 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 259 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -63315,19 +65951,19 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 152 /* PropertyDeclaration */: - case 160 /* IndexSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); @@ -63337,7 +65973,7 @@ var ts; if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { return undefined; } - else if (currentNamespace && node.kind === 84 /* ExportKeyword */) { + else if (currentNamespace && node.kind === 85 /* ExportKeyword */) { return undefined; } return node; @@ -63354,67 +65990,67 @@ var ts; return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 133 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 169 /* OptionalType */: - case 170 /* RestType */: - case 166 /* TypeLiteral */: - case 161 /* TypePredicate */: - case 148 /* TypeParameter */: - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 105 /* VoidKeyword */: - case 138 /* SymbolKeyword */: - case 164 /* ConstructorType */: - case 163 /* FunctionType */: - case 165 /* TypeQuery */: - case 162 /* TypeReference */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 173 /* ConditionalType */: - case 175 /* ParenthesizedType */: - case 176 /* ThisType */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 180 /* LiteralType */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 168 /* TypeLiteral */: + case 163 /* TypePredicate */: + case 150 /* TypeParameter */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 123 /* BooleanKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 132 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 139 /* SymbolKeyword */: + case 166 /* ConstructorType */: + case 165 /* FunctionType */: + case 167 /* TypeQuery */: + case 164 /* TypeReference */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 177 /* ParenthesizedType */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: // TypeScript type nodes are elided. - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: // TypeScript index signatures are elided. - case 150 /* Decorator */: + case 152 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 155 /* Constructor */: + case 157 /* Constructor */: return visitConstructor(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -63425,7 +66061,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -63436,35 +66072,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 149 /* Parameter */: + case 151 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -63474,35 +66110,35 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: @@ -63539,7 +66175,7 @@ var ts; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); - if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) facts |= 2 /* HasConstructorDecorators */; @@ -63608,7 +66244,7 @@ var ts; // return C; // }(); // - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18 /* CloseBraceToken */); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */); var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -63810,7 +66446,7 @@ var ts; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85 /* ExtendsKeyword */; })); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; })); var classExpression = ts.createClassExpression( /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, heritageClauses, members); @@ -63818,7 +66454,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63866,9 +66502,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -63984,7 +66622,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -64055,7 +66693,7 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 152 /* PropertyDeclaration */ + return member.kind === 154 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } @@ -64066,8 +66704,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -64083,8 +66721,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { - var property = properties_11[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var expression = transformInitializedProperty(property, receiver); ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -64195,12 +66833,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -64353,7 +66991,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 152 /* PropertyDeclaration */ + ? member.kind === 154 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? ts.createVoidZero() @@ -64454,13 +67092,13 @@ var ts; if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); } if (properties) { decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); @@ -64476,10 +67114,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 152 /* PropertyDeclaration */; + return kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 154 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -64489,7 +67127,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 154 /* MethodDeclaration */; + return node.kind === 156 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -64500,12 +67138,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return true; } return false; @@ -64522,15 +67160,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 152 /* PropertyDeclaration */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: return serializeTypeNode(node.type); - case 157 /* SetAccessor */: - case 156 /* GetAccessor */: + case 159 /* SetAccessor */: + case 158 /* GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 154 /* MethodDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 156 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -64567,7 +67205,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 156 /* GetAccessor */) { + if (container && node.kind === 158 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -64612,77 +67250,83 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: return ts.createVoidZero(); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return ts.createIdentifier("Function"); - case 167 /* ArrayType */: - case 168 /* TupleType */: + case 169 /* ArrayType */: + case 170 /* TupleType */: return ts.createIdentifier("Array"); - case 161 /* TypePredicate */: - case 122 /* BooleanKeyword */: + case 163 /* TypePredicate */: + case 123 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: return ts.createIdentifier("String"); - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 180 /* LiteralType */: + case 182 /* LiteralType */: switch (node.literal.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return ts.createIdentifier("String"); case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 9 /* BigIntLiteral */: + return getGlobalBigIntNameWithFallback(); + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: return ts.Debug.failBadSyntaxKind(node.literal); } - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: return ts.createIdentifier("Number"); - case 138 /* SymbolKeyword */: + case 146 /* BigIntKeyword */: + return getGlobalBigIntNameWithFallback(); + case 139 /* SymbolKeyword */: return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return serializeTypeReferenceNode(node); - case 172 /* IntersectionType */: - case 171 /* UnionType */: - return serializeUnionOrIntersectionType(node); - case 165 /* TypeQuery */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 166 /* TypeLiteral */: - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 176 /* ThisType */: - case 181 /* ImportType */: + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return serializeTypeList(node.types); + case 175 /* ConditionalType */: + return serializeTypeList([node.trueType, node.falseType]); + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 168 /* TypeLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 178 /* ThisType */: + case 183 /* ImportType */: break; default: return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } - function serializeUnionOrIntersectionType(node) { + function serializeTypeList(types) { // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175 /* ParenthesizedType */) { + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } - if (typeNode.kind === 131 /* NeverKeyword */) { + if (typeNode.kind === 132 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedIndividual = serializeTypeNode(typeNode); @@ -64718,6 +67362,10 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); @@ -64725,6 +67373,8 @@ var ts; return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); case ts.TypeReferenceSerializationKind.BooleanType: return ts.createIdentifier("Boolean"); case ts.TypeReferenceSerializationKind.NumberLikeType: @@ -64756,12 +67406,12 @@ var ts; * @param node The entity name to serialize. */ function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { // A -> typeof A !== undefined && A var copied = serializeEntityNameAsExpression(node); return createCheckedValue(copied, copied); } - if (node.left.kind === 71 /* Identifier */) { + if (node.left.kind === 72 /* Identifier */) { // A.B -> typeof A !== undefined && A.B return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); } @@ -64777,7 +67427,7 @@ var ts; */ function serializeEntityNameAsExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were // a source tree node for the purposes of the checker. var name = ts.getMutableClone(node); @@ -64785,7 +67435,7 @@ var ts; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. return name; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -64806,6 +67456,15 @@ var ts; function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 /* ESNext */ + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } /** * A simple inlinable expression is an expression which can be copied into multiple locations * without risk of repeating any sideeffects and whose value could not possibly change between @@ -64886,9 +67545,9 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 85 /* ExtendsKeyword */) { + if (node.token === 86 /* ExtendsKeyword */) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(85 /* ExtendsKeyword */, types), node); + return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); } return undefined; } @@ -65284,7 +67943,7 @@ var ts; var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); var valueExpression = transformEnumMemberDeclarationValue(member); var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); - var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? innerAssignment : ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); @@ -65365,12 +68024,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 277 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 241 /* EnumDeclaration */) { + if (node.kind === 243 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -65495,7 +68154,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 243 /* ModuleBlock */) { + if (body.kind === 245 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -65541,13 +68200,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 243 /* ModuleBlock */) { + if (body.kind !== 245 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -65588,7 +68247,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 249 /* NamespaceImport */) { + if (node.kind === 251 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -65782,7 +68441,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65801,7 +68460,7 @@ var ts; function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } function enableSubstitutionForClassAliases() { @@ -65809,7 +68468,7 @@ var ts; enabledSubstitutions |= 1 /* ClassAliases */; // We need to enable substitutions for identifiers. This allows us to // substitute class names inside of a class declaration. - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); // Keep track of class aliases. classAliases = []; } @@ -65819,17 +68478,17 @@ var ts; enabledSubstitutions |= 2 /* NamespaceExports */; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. - context.enableSubstitution(71 /* Identifier */); - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); + context.enableSubstitution(72 /* Identifier */); + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(242 /* ModuleDeclaration */); + context.enableEmitNotification(244 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 242 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 241 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */; } /** * Hook for node emit. @@ -65888,11 +68547,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -65904,7 +68563,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // 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. @@ -65930,9 +68589,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 277 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 242 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 241 /* EnumDeclaration */); + if (container && container.kind !== 279 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), /*location*/ node); @@ -66044,6 +68703,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66064,19 +68731,29 @@ var ts; return node; } switch (node.kind) { - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitAwaitExpression(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66084,27 +68761,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 216 /* Block */: - case 230 /* SwitchStatement */: - case 244 /* CaseBlock */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 233 /* TryStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 220 /* IfStatement */: - case 229 /* WithStatement */: - case 231 /* LabeledStatement */: + case 218 /* Block */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 231 /* WithStatement */: + case 233 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -66305,7 +68982,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 195 /* ArrowFunction */; + var isArrowFunction = node.kind === 197 /* 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 @@ -66318,23 +68995,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66352,6 +69039,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66378,15 +69067,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(189 /* CallExpression */); - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(238 /* ClassDeclaration */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); } } /** @@ -66409,6 +69100,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66426,24 +69125,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66462,24 +69161,68 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 /* ClassDeclaration */ - || kind === 155 /* Constructor */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66489,7 +69232,7 @@ var ts; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); var generatorFunc = ts.createFunctionExpression( - /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), /*name*/ undefined, /*typeParameters*/ undefined, /*parameters*/ [], @@ -66507,12 +69250,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66535,6 +69278,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66551,7 +69300,7 @@ var ts; return visitorWorker(node, /*noDestructuringValue*/ true); } function visitorNoAsyncModifier(node) { - if (node.kind === 120 /* AsyncKeyword */) { + if (node.kind === 121 /* AsyncKeyword */) { return undefined; } return node; @@ -66561,48 +69310,58 @@ var ts; return node; } switch (node.kind) { - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitAwaitExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return visitVoidExpression(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return visitConstructorDeclaration(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: return visitGetAccessorDeclaration(node); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitParameter(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitExpressionStatement(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66635,7 +69394,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 225 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); @@ -66647,7 +69406,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 275 /* SpreadAssignment */) { + if (e.kind === 277 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -66656,7 +69415,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 273 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */ ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -66667,14 +69426,14 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); // If the first element is a spread element, then the first argument to __assign is {}: // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 186 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -66699,10 +69458,10 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } - else if (node.operatorToken.kind === 26 /* CommaToken */) { + else if (node.operatorToken.kind === 27 /* CommaToken */) { return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); @@ -66714,7 +69473,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66731,7 +69490,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66828,7 +69587,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66925,25 +69684,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( - /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66967,7 +69738,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -66987,15 +69758,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(189 /* CallExpression */); - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(238 /* ClassDeclaration */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); } } /** @@ -67018,6 +69791,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67035,24 +69816,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67071,19 +69852,19 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 /* ClassDeclaration */ - || kind === 155 /* Constructor */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67184,13 +69965,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67198,15 +69979,15 @@ var ts; } function transformJsxChildToExpression(node) { switch (node.kind) { - case 10 /* JsxText */: + case 11 /* JsxText */: return visitJsxText(node); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitJsxExpression(node); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -67274,14 +70055,14 @@ var ts; if (node === undefined) { return ts.createTrue(); } - else if (node.kind === 9 /* StringLiteral */) { + else if (node.kind === 10 /* StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); return ts.setTextRange(literal, node); } - else if (node.kind === 268 /* JsxExpression */) { + else if (node.kind === 270 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } @@ -67375,7 +70156,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 258 /* JsxElement */) { + if (node.kind === 260 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -67681,7 +70462,7 @@ var ts; return node; } switch (node.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67689,9 +70470,9 @@ var ts; } function visitBinaryExpression(node) { switch (node.operatorToken.kind) { - case 62 /* AsteriskAsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: return visitExponentiationAssignmentExpression(node); - case 40 /* AsteriskAsteriskToken */: + case 41 /* AsteriskAsteriskToken */: return visitExponentiationExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67741,6 +70522,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67914,14 +70700,14 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 228 /* ReturnStatement */ + && node.kind === 230 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -67939,104 +70725,104 @@ var ts; return node; } function callExpressionVisitor(node) { - if (node.kind === 97 /* SuperKeyword */) { + if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); } return visitor(node); } function visitJavaScript(node) { switch (node.kind) { - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: return undefined; // elide static keyword - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return visitClassExpression(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitParameter(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 71 /* Identifier */: + case 72 /* Identifier */: return visitIdentifier(node); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitCaseBlock(node); - case 216 /* Block */: + case 218 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitExpressionStatement(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node, /*needsDestructuringValue*/ true); - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: return visitTemplateLiteral(node); - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return visitTemplateExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return visitSpreadElement(node); - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return visitThisKeyword(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return visitMetaProperty(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return visitAccessorDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -68123,14 +70909,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 227 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 227 /* BreakStatement */) { + if (node.kind === 229 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -68141,7 +70927,7 @@ var ts; } } else { - if (node.kind === 227 /* BreakStatement */) { + if (node.kind === 229 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -68160,10 +70946,10 @@ var ts; expr = copyExpr; } else { - expr = ts.createBinary(expr, 26 /* CommaToken */, copyExpr); + expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr); } } - returnExpression = ts.createBinary(expr, 26 /* CommaToken */, returnExpression); + returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression); } return ts.createReturn(returnExpression); } @@ -68297,7 +71083,7 @@ var ts; addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); // Create a synthetic text range for the return statement. - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18 /* CloseBraceToken */); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */); var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -68402,7 +71188,7 @@ var ts; } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); // The last statement expression was replaced. Skip it. if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { @@ -68441,11 +71227,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 228 /* ReturnStatement */) { + if (statement.kind === 230 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 220 /* IfStatement */) { + else if (statement.kind === 222 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -68453,7 +71239,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 216 /* Block */) { + else if (statement.kind === 218 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -68511,7 +71297,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -68519,10 +71305,10 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 202 /* BinaryExpression */ - || superCallExpression.left.kind !== 189 /* CallExpression */) { + if (superCallExpression.kind !== 204 /* BinaryExpression */ + || superCallExpression.left.kind !== 191 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } // Shift comments from the original super call to the return statement. @@ -68590,7 +71376,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68667,7 +71453,7 @@ var ts; * synthesized call to `super` */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 71 /* Identifier */ && !inConstructorWithSynthesizedSuper; + return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; } /** * Adds statements to the body of a function-like node if it contains a rest parameter. @@ -68719,7 +71505,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68738,25 +71524,25 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return statements; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = ts.createVoidZero(); break; - case 155 /* Constructor */: + case 157 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. - newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); break; default: return ts.Debug.failBadSyntaxKind(node); @@ -68784,20 +71570,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 155 /* Constructor */: + case 157 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -68907,7 +71693,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -68989,7 +71775,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 237 /* FunctionDeclaration */ || node.kind === 194 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); @@ -69034,7 +71820,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 195 /* ArrowFunction */); + ts.Debug.assert(node.kind === 197 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -69072,7 +71858,7 @@ var ts; ts.setEmitFlags(block, 1 /* SingleLine */); } if (closeBraceLocation) { - ts.setTokenSourceMapRange(block, 18 /* CloseBraceToken */, closeBraceLocation); + ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -69102,9 +71888,9 @@ var ts; function visitExpressionStatement(node) { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); @@ -69123,9 +71909,9 @@ var ts; // expression. If we are in a state where we do not need the destructuring value, // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } @@ -69160,7 +71946,7 @@ var ts; assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); } else { - assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); @@ -69197,19 +71983,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69257,8 +72051,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69326,14 +72120,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -69513,11 +72307,11 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 147 /* ComputedPropertyName */) { + if (property.name.kind === 149 /* ComputedPropertyName */) { numInitialProperties = i; break; } @@ -69544,7 +72338,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69556,7 +72366,7 @@ var ts; } visit(node.name); function visit(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { state.hoistedLocalVariables.push(node); } else { @@ -69570,7 +72380,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69586,14 +72396,76 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 236 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 238 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -69603,165 +72475,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // 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 - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.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 = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.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'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 58 /* EqualsToken */, source); + return ts.createBinary(target, 59 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69769,38 +72752,38 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); } if (state.nonLocalJumps & 2 /* Break */) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69840,21 +72823,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69873,20 +72864,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -69994,10 +72985,10 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -70173,15 +73164,15 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || - node.expression.kind === 97 /* SuperKeyword */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70210,7 +73201,7 @@ var ts; resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { var actualThis = ts.createThis(); ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); var initializer = ts.createLogicalOr(resultingCall, actualThis); @@ -70228,7 +73219,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70275,7 +73266,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 185 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -70392,7 +73383,7 @@ var ts; // thus we need to remove those characters. // First template piece starts with "`", others with "}" // Last template piece ends with "`", others with "${" - var isLast = node.kind === 13 /* NoSubstitutionTemplateLiteral */ || node.kind === 16 /* TemplateTail */; + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; text = text.substring(1, text.length - (isLast ? 1 : 2)); // Newline normalization: // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's @@ -70490,7 +73481,7 @@ var ts; : ts.createFileLevelUniqueName("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") { + if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { if (hierarchyFacts & 8192 /* ComputedPropertyName */) { hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; } @@ -70527,7 +73518,7 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } /** @@ -70537,14 +73528,14 @@ var ts; function enableSubstitutionsForCapturedThis() { if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; - context.enableSubstitution(99 /* ThisKeyword */); - context.enableEmitNotification(155 /* Constructor */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(195 /* ArrowFunction */); - context.enableEmitNotification(194 /* FunctionExpression */); - context.enableEmitNotification(237 /* FunctionDeclaration */); + context.enableSubstitution(100 /* ThisKeyword */); + context.enableEmitNotification(157 /* Constructor */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(197 /* ArrowFunction */); + context.enableEmitNotification(196 /* FunctionExpression */); + context.enableEmitNotification(239 /* FunctionDeclaration */); } } /** @@ -70585,10 +73576,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 237 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -70601,9 +73592,9 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return substituteThisKeyword(node); } return node; @@ -70670,19 +73661,19 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 219 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 189 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 97 /* SuperKeyword */) { + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) { return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 206 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -70710,7 +73701,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -70735,15 +73726,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(260 /* JsxOpeningElement */); - context.enableEmitNotification(261 /* JsxClosingElement */); - context.enableEmitNotification(259 /* JsxSelfClosingElement */); + context.enableEmitNotification(262 /* JsxOpeningElement */); + context.enableEmitNotification(263 /* JsxClosingElement */); + context.enableEmitNotification(261 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(273 /* PropertyAssignment */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(275 /* PropertyAssignment */); return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -70762,9 +73753,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -70821,7 +73812,7 @@ var ts; */ function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { + if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -71096,13 +74087,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitWhileStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -71115,30 +74106,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return visitAccessorDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return visitBreakStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return visitContinueStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71153,21 +74144,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return visitConditionalExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -71180,9 +74171,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -71341,7 +74332,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71381,23 +74372,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 59 /* FirstCompoundAssignment */ - && kind <= 70 /* LastCompoundAssignment */; + return kind >= 60 /* FirstCompoundAssignment */ + && kind <= 71 /* LastCompoundAssignment */; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 59 /* PlusEqualsToken */: return 37 /* PlusToken */; - case 60 /* MinusEqualsToken */: return 38 /* MinusToken */; - case 61 /* AsteriskEqualsToken */: return 39 /* AsteriskToken */; - case 62 /* AsteriskAsteriskEqualsToken */: return 40 /* AsteriskAsteriskToken */; - case 63 /* SlashEqualsToken */: return 41 /* SlashToken */; - case 64 /* PercentEqualsToken */: return 42 /* PercentToken */; - case 65 /* LessThanLessThanEqualsToken */: return 45 /* LessThanLessThanToken */; - case 66 /* GreaterThanGreaterThanEqualsToken */: return 46 /* GreaterThanGreaterThanToken */; - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanGreaterThanToken */; - case 68 /* AmpersandEqualsToken */: return 48 /* AmpersandToken */; - case 69 /* BarEqualsToken */: return 49 /* BarToken */; - case 70 /* CaretEqualsToken */: return 50 /* CaretToken */; + case 60 /* PlusEqualsToken */: return 38 /* PlusToken */; + case 61 /* MinusEqualsToken */: return 39 /* MinusToken */; + case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */; + case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */; + case 64 /* SlashEqualsToken */: return 42 /* SlashToken */; + case 65 /* PercentEqualsToken */: return 43 /* PercentToken */; + case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */; + case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */; + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */; + case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */; + case 70 /* BarEqualsToken */: return 50 /* BarToken */; + case 71 /* CaretEqualsToken */: return 51 /* CaretToken */; } } /** @@ -71410,7 +74401,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -71422,7 +74413,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -71454,7 +74445,7 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 26 /* CommaToken */) { + else if (node.operatorToken.kind === 27 /* CommaToken */) { return visitCommaExpression(node); } // [source] @@ -71465,10 +74456,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71509,7 +74500,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { // Logical `&&` shortcuts when the left-hand operand is falsey. emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); } @@ -71540,7 +74531,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { visit(node.left); visit(node.right); } @@ -71729,10 +74720,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -71798,35 +74789,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 216 /* Block */: + case 218 /* Block */: return transformAndEmitBlock(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return transformAndEmitIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return transformAndEmitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return transformAndEmitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return transformAndEmitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -72256,7 +75247,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 270 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -72269,7 +75260,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 269 /* CaseClause */) { + if (clause.kind === 271 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -72399,7 +75390,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72431,10 +75422,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -72581,7 +75572,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = []; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } renamedCatchVariables.set(text, true); renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -73497,12 +76488,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -73516,7 +76507,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +76564,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +76595,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73824,23 +76821,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 308 /* MergeDeclarationMarker */: + case 310 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 309 /* EndOfDeclarationMarker */: + case 311 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -73849,7 +76846,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73867,24 +76864,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -73916,7 +76913,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74362,7 +77359,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -74417,10 +77414,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -74602,8 +77599,8 @@ var ts; function modifierVisitor(node) { // Elide module-specific modifiers. switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: return undefined; } return node; @@ -74619,7 +77616,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -74681,12 +77678,12 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return substituteBinaryExpression(node); - case 201 /* PostfixUnaryExpression */: - case 200 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -74707,7 +77704,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -74775,15 +77772,15 @@ var ts; // - We do not substitute identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only substitute identifiers that are exported at the top level. - if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 /* PostfixUnaryExpression */ - ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { @@ -74857,12 +77854,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -74881,7 +77878,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75083,7 +78080,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 253 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -75108,7 +78105,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 253 /* ExportDeclaration */) { + if (externalImport.kind !== 255 /* ExportDeclaration */) { continue; } if (!externalImport.exportClause) { @@ -75186,19 +78183,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -75248,15 +78245,15 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: // ExportDeclarations are elided as they are handled via // `appendExportsOfDeclaration`. return undefined; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -75432,7 +78429,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 277 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -75496,7 +78493,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -75558,10 +78555,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -75741,43 +78738,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitWhileStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return visitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitCaseBlock(node); - case 269 /* CaseClause */: + case 271 /* CaseClause */: return visitCaseClause(node); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return visitDefaultClause(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return visitTryStatement(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); - case 216 /* Block */: + case 218 /* Block */: return visitBlock(node); - case 308 /* MergeDeclarationMarker */: + case 310 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 309 /* EndOfDeclarationMarker */: + case 311 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -75960,13 +78957,13 @@ var ts; */ function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 202 /* BinaryExpression */) { + && node.kind === 204 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76025,7 +79022,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 277 /* SourceFile */; + return container !== undefined && container.kind === 279 /* SourceFile */; } else { return false; @@ -76041,8 +79038,8 @@ var ts; */ function modifierVisitor(node) { switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: return undefined; } return node; @@ -76058,7 +79055,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -76106,7 +79103,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -76140,12 +79137,12 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return substituteBinaryExpression(node); - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -76231,22 +79228,22 @@ var ts; // - We do not substitute identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only substitute identifiers that are exported at the top level. - if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 /* PostfixUnaryExpression */ + var expression = node.kind === 203 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 201 /* PostfixUnaryExpression */) { - expression = node.operator === 43 /* PlusPlusToken */ + if (node.kind === 203 /* PostfixUnaryExpression */) { + expression = node.operator === 44 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); } @@ -76267,7 +79264,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -76306,8 +79303,8 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(277 /* SourceFile */); - context.enableSubstitution(71 /* Identifier */); + context.enableEmitNotification(279 /* SourceFile */); + context.enableSubstitution(72 /* Identifier */); var currentSourceFile; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { @@ -76335,10 +79332,10 @@ var ts; } function visitor(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); } return node; @@ -76445,7 +79442,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* 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 : @@ -76474,7 +79471,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -76521,7 +79518,7 @@ var ts; return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { 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 : @@ -76530,8 +79527,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 152 /* PropertyDeclaration */ || node.kind === 151 /* PropertySignature */ || - (node.kind === 149 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -76540,7 +79537,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */ || node.kind === 149 /* Parameter */) { + else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -76565,7 +79562,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 157 /* SetAccessor */) { + if (node.kind === 159 /* SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.hasModifier(node, 32 /* Static */)) { @@ -76604,26 +79601,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named 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 158 /* CallSignature */: + case 160 /* CallSignature */: // Interfaces cannot have return types that cannot be named 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 160 /* IndexSignature */: + case 162 /* IndexSignature */: // Interfaces cannot have return types that cannot be named 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 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -76631,7 +79628,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* 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 : @@ -76645,7 +79642,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 237 /* FunctionDeclaration */: + case 239 /* 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 : @@ -76670,30 +79667,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 155 /* Constructor */: + case 157 /* 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 159 /* ConstructSignature */: - case 164 /* ConstructorType */: + case 161 /* ConstructSignature */: + case 166 /* ConstructorType */: // Interfaces cannot have parameter types that cannot be named 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 158 /* CallSignature */: + case 160 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named 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 160 /* IndexSignature */: + case 162 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -76701,7 +79698,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 240 /* 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 : @@ -76714,8 +79711,8 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 237 /* FunctionDeclaration */: - case 163 /* FunctionType */: + case 239 /* FunctionDeclaration */: + case 165 /* FunctionType */: 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 : @@ -76729,34 +79726,34 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 158 /* CallSignature */: + case 160 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node.parent, 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 === 238 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 240 /* 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 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -76771,9 +79768,9 @@ var ts; function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + if (node.parent.parent.kind === 240 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ? 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; } @@ -76808,11 +79805,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +79835,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76849,6 +79846,7 @@ var ts; reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode @@ -76856,6 +79854,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +79864,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76936,16 +79935,22 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } - if (node.kind === 278 /* Bundle */) { + if (node.kind === 280 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,23 +79962,25 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280 /* InputFiles */) { + if (prepend.kind === 282 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +79999,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +80012,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77038,7 +80049,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77046,13 +80057,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,12 +80078,21 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { return name; } else { - if (name.kind === 183 /* ArrayBindingPattern */) { + if (name.kind === 185 /* ArrayBindingPattern */) { return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -77075,7 +80100,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 208 /* OmittedExpression */) { + if (elem.kind === 210 /* OmittedExpression */) { return elem; } return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -77088,7 +80113,7 @@ var ts; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } var newParam = ts.updateParameter(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -77100,7 +80125,7 @@ var ts; } function ensureNoInitializer(node) { if (shouldPrintWithInitializer(node)) { - return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe } return undefined; } @@ -77113,19 +80138,19 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 149 /* Parameter */ && + var shouldUseResolverType = node.kind === 151 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { return ts.visitNode(type, visitDeclarationSubtree); } if (!ts.getParseTreeNode(node)) { - return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */); } - if (node.kind === 157 /* SetAccessor */) { + if (node.kind === 159 /* SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } errorNameNode = node.name; var oldDiag; @@ -77133,12 +80158,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 149 /* Parameter */ - || node.kind === 152 /* PropertyDeclaration */ - || node.kind === 151 /* PropertySignature */) { + if (node.kind === 151 /* Parameter */ + || node.kind === 154 /* PropertyDeclaration */ + || node.kind === 153 /* PropertySignature */) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -77149,26 +80174,26 @@ var ts; if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } - return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */); + return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */); } } function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: return false; } return false; @@ -77222,7 +80247,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -77242,7 +80267,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 257 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return ts.updateImportEqualsDeclaration(decl, @@ -77269,7 +80294,7 @@ var ts; return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -77374,68 +80399,68 @@ var ts; checkEntityNameVisibility(input.exprName, enclosingDeclaration); } var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 /* TypeLiteral */ || input.kind === 179 /* MappedType */) && input.parent.kind !== 240 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */); if (shouldEnterSuppressNewDiagnosticsContextContext) { // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. suppressNewDiagnosticContexts = true; } if (isProcessedComponent(input)) { switch (input.kind) { - case 209 /* ExpressionWithTypeArguments */: { + case 211 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); } - case 162 /* TypeReference */: { + case 164 /* TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); } - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 155 /* Constructor */: { + case 157 /* Constructor */: { var isPrivate = ts.hasModifier(input, 8 /* Private */); // A constructor declaration may not have a type annotation - var ctor = ts.createSignatureDeclaration(155 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), // TODO: GH#18217 isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), /*type*/ undefined); ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); return cleanup(ctor); } - case 154 /* MethodDeclaration */: { - var sig = ts.createSignatureDeclaration(153 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + case 156 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); sig.name = input.name; sig.modifiers = ts.createNodeArray(ensureModifiers(input)); sig.questionToken = input.questionToken; return cleanup(sig); } - case 156 /* GetAccessor */: { + case 158 /* GetAccessor */: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 157 /* SetAccessor */: { + case 159 /* SetAccessor */: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return cleanup(ts.updateProperty(input, /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 153 /* MethodSignature */: { + case 155 /* MethodSignature */: { return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); } - case 158 /* CallSignature */: { + case 160 /* CallSignature */: { return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 160 /* IndexSignature */: { + case 162 /* IndexSignature */: { return cleanup(ts.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */))); } - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -77443,13 +80468,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); } - case 148 /* TypeParameter */: { + case 150 /* TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 173 /* ConditionalType */: { + case 175 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -77461,13 +80486,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 163 /* FunctionType */: { + case 165 /* FunctionType */: { return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 164 /* ConstructorType */: { + case 166 /* ConstructorType */: { return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 181 /* ImportType */: { + case 183 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -77496,7 +80521,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 154 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -77506,7 +80531,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 253 /* ExportDeclaration */: { + case 255 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; @@ -77515,13 +80540,13 @@ var ts; // Rewrite external module names if necessary return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 252 /* ExportAssignment */: { + case 254 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; } - if (input.expression.kind === 71 /* Identifier */) { + if (input.expression.kind === 72 /* Identifier */) { return input; } else { @@ -77531,7 +80556,7 @@ var ts; errorNode: input }); }; var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } @@ -77545,10 +80570,10 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 246 /* ImportEqualsDeclaration */: { + case 248 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 247 /* ImportDeclaration */: { + case 249 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -77569,24 +80594,39 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 240 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(ts.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 239 /* InterfaceDeclaration */: { + case 241 /* InterfaceDeclaration */: { return cleanup(ts.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 237 /* FunctionDeclaration */: { + case 239 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } - case 242 /* ModuleDeclaration */: { + case 244 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 243 /* ModuleBlock */) { + if (inner && inner.kind === 245 /* ModuleBlock */) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; @@ -77607,7 +80647,7 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 238 /* ClassDeclaration */: { + case 240 /* ClassDeclaration */: { var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -77618,7 +80658,7 @@ var ts; if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); - if (param.name.kind === 71 /* Identifier */) { + if (param.name.kind === 72 /* Identifier */) { return preserveJsDoc(ts.createProperty( /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } @@ -77648,7 +80688,7 @@ var ts; } var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); - if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 getSymbolAccessibilityDiagnostic = function () { return ({ @@ -77657,16 +80697,16 @@ var ts; typeName: input.name }); }; var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { - if (clause.token === 85 /* ExtendsKeyword */) { + if (clause.token === 86 /* ExtendsKeyword */) { var oldDiag_2 = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); getSymbolAccessibilityDiagnostic = oldDiag_2; return newClause; } - return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree)); })); return [statement, cleanup(ts.updateClassDeclaration(input, /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 @@ -77677,10 +80717,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { return cleanup(transformVariableStatement(input, isPrivate)); } - case 241 /* EnumDeclaration */: { + case 243 /* EnumDeclaration */: { return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -77699,7 +80739,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242 /* ModuleDeclaration */) { + if (input.kind === 244 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -77720,7 +80760,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 208 /* OmittedExpression */) { + if (e.kind === 210 /* OmittedExpression */) { return; } if (e.name) { @@ -77783,7 +80823,7 @@ var ts; function ensureModifierFlags(node, privateDeclaration) { var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 277 /* SourceFile */; + var parentIsFile = node.parent.kind === 279 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; @@ -77804,7 +80844,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77818,20 +80858,20 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; } function transformHeritageClauses(nodes) { return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { - return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */); + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */); })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); } } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 239 /* InterfaceDeclaration */) { + if (node.kind === 241 /* InterfaceDeclaration */) { return true; } return false; @@ -77856,7 +80896,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 156 /* GetAccessor */ + return accessor.kind === 158 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -77865,51 +80905,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: - case 217 /* VariableStatement */: - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 219 /* VariableStatement */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 159 /* ConstructSignature */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 160 /* IndexSignature */: - case 235 /* VariableDeclaration */: - case 148 /* TypeParameter */: - case 209 /* ExpressionWithTypeArguments */: - case 162 /* TypeReference */: - case 173 /* ConditionalType */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 181 /* ImportType */: + case 161 /* ConstructSignature */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 237 /* VariableDeclaration */: + case 150 /* TypeParameter */: + case 211 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 175 /* ConditionalType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 183 /* ImportType */: return true; } return false; @@ -77974,6 +81015,14 @@ var ts; return transformers; } ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -77985,7 +81034,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(310 /* Count */); + var enabledSyntaxKindFeatures = new Array(312 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -77993,8 +81042,8 @@ var ts; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; - var onSubstituteNode = function (_, node) { return node; }; - var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; var state = 0 /* Uninitialized */; var diagnostics = []; // The transformation context is provided to each transformer as part of transformer @@ -78243,825 +81292,11 @@ var ts; } ts.transformNodes = transformNodes; })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans - var defaultLastEncodedSourceMapSpan = { - emittedLine: 0, - emittedColumn: 0, - sourceLine: 0, - sourceColumn: 0, - sourceIndex: 0 - }; - function createSourceMapWriter(host, writer, compilerOptions) { - if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } - var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSource; - var currentSourceText; - var sourceMapDir; // The directory in which sourcemap will be - // 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; - var sourceMapDataList; - var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); - return { - initialize: initialize, - reset: reset, - setSourceFile: setSourceFile, - emitPos: emitPos, - emitNodeWithSourceMap: emitNodeWithSourceMap, - emitTokenWithSourceMap: emitTokenWithSourceMap, - getText: getText, - getSourceMappingURL: getSourceMappingURL, - }; - /** - * Skips trivia such as comments and white-space that can optionally overriden by the source map source - */ - function skipSourceTrivia(pos) { - return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); - } - /** - * Initialize the SourceMapWriter for a new output file. - * - * @param filePath The path to the generated output file. - * @param sourceMapFilePath The path to the output source map file. - * @param sourceFileOrBundle The input source file or bundle for the program. - */ - function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) { - return; - } - if (sourceMapData) { - reset(); - } - sourceMapDataList = outputSourceMapDataList; - currentSource = undefined; - currentSourceText = 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, - }; - // 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 (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file - // 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(sourceFileOrBundle.fileName, 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)); - } - } - /** - * Reset the SourceMapWriter to an empty state. - */ - function reset() { - if (disabled) { - return; - } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMapData); - } - currentSource = undefined; - sourceMapDir = undefined; - sourceMapSourceIndex = undefined; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = undefined; - lastEncodedNameIndex = undefined; - sourceMapData = undefined; - sourceMapDataList = undefined; - } - function captureSection() { - return { - version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent, - }; - } - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - ts.Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative"); - 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 = 0; - } - // 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; - } - /** - * Emits a mapping. - * - * If the position is synthetic (undefined or a negative value), no mapping will be - * created. - * - * @param pos The position. - */ - function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); - 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 - }; - } - 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; - } - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } - } - function isPossiblySourceMap(x) { - return typeof x === "object" && !!x.mappings && typeof x.mappings === "string" && !!x.sources; - } - /** - * Emits a node with possible leading and trailing source maps. - * - * @param hint A hint as to the intended usage of the node. - * @param node The node to emit. - * @param emitCallback The callback used to emit the node. - */ - function emitNodeWithSourceMap(hint, node, emitCallback) { - var _a; - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(hint, node); - } - if (node) { - if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { - var text = node.sourceMapText; - var parsed = void 0; - try { - parsed = JSON.parse(text); - } - catch (_b) { - // empty - } - if (!parsed || !isPossiblySourceMap(parsed)) { - return emitCallback(hint, node); - } - var offsetLine = writer.getLine(); - var firstLineColumnOffset = writer.getColumn(); - // First, decode the old component sourcemap - var originalMap = parsed; - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var resolvedPathCache = ts.createMap(); - var absolutePathCache = ts.createMap(); - var sourcemapIterator = ts.sourcemaps.decodeMappings(originalMap); - for (var _c = sourcemapIterator.next(), raw = _c.value, done = _c.done; !done; _a = sourcemapIterator.next(), raw = _a.value, done = _a.done, _a) { - var pathCacheKey = "" + raw.sourceIndex; - // Apply offsets to each position and fixup source entries - if (!resolvedPathCache.has(pathCacheKey)) { - var rawPath = originalMap.sources[raw.sourceIndex]; - var relativePath = originalMap.sourceRoot ? ts.combinePaths(originalMap.sourceRoot, rawPath) : rawPath; - var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath); - var resolvedPath_1 = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - resolvedPathCache.set(pathCacheKey, resolvedPath_1); - absolutePathCache.set(pathCacheKey, ts.getNormalizedAbsolutePath(resolvedPath_1, sourcesDirectoryPath)); - } - var resolvedPath = resolvedPathCache.get(pathCacheKey); - var absolutePath = absolutePathCache.get(pathCacheKey); - // tslint:disable-next-line:no-null-keyword - setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); // TODO: Lookup content for inlining? - var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath); - // Then reencode all the updated spans into the overall map - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = __assign({}, raw, { emittedLine: raw.emittedLine + offsetLine, emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, sourceIndex: newIndex }); - } - // And actually emit the text these sourcemaps are for - return emitCallback(hint, node); - } - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0 /* None */; - var range = emitNode && emitNode.sourceMapRange; - var _d = range || node, pos = _d.pos, end = _d.end; - var source = range && range.source; - var oldSource = currentSource; - if (source === oldSource) - source = undefined; - if (source) - setSourceFile(source); - if (node.kind !== 305 /* NotEmittedStatement */ - && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && pos >= 0) { - emitPos(skipSourceTrivia(pos)); - } - if (source) - setSourceFile(oldSource); - if (emitFlags & 64 /* NoNestedSourceMaps */) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - if (source) - setSourceFile(source); - if (node.kind !== 305 /* NotEmittedStatement */ - && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && end >= 0) { - emitPos(end); - } - if (source) - setSourceFile(oldSource); - } - } - /** - * Emits a token of a node with possible leading and trailing source maps. - * - * @param node The node containing the token. - * @param token The token to emit. - * @param tokenStartPos The start pos of the token. - * @param emitCallback The callback used to emit the token. - */ - function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(token, writer, tokenPos); - } - var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0 /* None */; - var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); - if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - tokenPos = emitCallback(token, writer, tokenPos); - if (range) - tokenPos = range.end; - if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - return tokenPos; - } - function isJsonSourceMapSource(sourceFile) { - return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); - } - /** - * Set the current source file. - * - * @param sourceFile The source file. - */ - function setSourceFile(sourceFile) { - if (disabled) { - return; - } - currentSource = sourceFile; - currentSourceText = currentSource.text; - if (isJsonSourceMapSource(sourceFile)) { - return; - } - setupSourceEntry(sourceFile.fileName, sourceFile.text); - } - function setupSourceEntry(fileName, content, source) { - if (!source) { - // 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; - source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(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(fileName); - if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(content); - } - } - } - /** - * Gets the text for the source map. - */ - function getText() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; // TODO: GH#18217 - } - encodeLastRecordedSourceMapSpan(); - return JSON.stringify(captureSection()); - } - /** - * Gets the SourceMappingURL for the source map. - */ - function getSourceMappingURL() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; // TODO: GH#18217 - } - if (compilerOptions.inlineSourceMap) { - // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.base64encode(ts.sys, 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 createCommentWriter(printerOptions, emitPos) { - var extendedDiagnostics = printerOptions.extendedDiagnostics; - var newLine = ts.getNewLineCharacter(printerOptions); - var writer; - var containerPos = -1; - var containerEnd = -1; - var declarationListContainerEnd = -1; - var currentSourceFile; - var currentText; - var currentLineMap; - var detachedCommentsInfo; - var hasWrittenComment = false; - var disabled = !!printerOptions.removeComments; - return { - reset: reset, - setWriter: setWriter, - setSourceFile: setSourceFile, - emitNodeWithComments: emitNodeWithComments, - emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, - emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, - }; - function emitNodeWithComments(hint, node, emitCallback) { - if (disabled) { - emitCallback(hint, node); - return; - } - if (node) { - hasWrittenComment = false; - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0; - var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; - if ((pos < 0 && end < 0) || (pos === end)) { - // Both pos and end are synthesized, so just emit the node without comments. - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - } - else { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithComment"); - } - var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */; - // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. - // It is expensive to walk entire tree just to set one kind of node to have no comments. - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; - var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 10 /* JsxText */; - // Emit leading comments if the position is not synthesized and the node - // has not opted out from emitting leading comments. - if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); - } - // Save current container state on the stack. - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { - // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. - containerPos = pos; - } - if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { - // As above. - containerEnd = end; - // To avoid invalid comment emit in a down-level binding pattern, we - // keep track of the last declaration list container's end - if (node.kind === 236 /* VariableDeclarationList */) { - declarationListContainerEnd = end; - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithComment"); - } - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithComment"); - } - // Restore previous container state. - containerPos = savedContainerPos; - containerEnd = savedContainerEnd; - declarationListContainerEnd = savedDeclarationListContainerEnd; - // Emit trailing comments if the position is not synthesized and the node - // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { - emitTrailingComments(end); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithComment"); - } - } - } - } - function emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback) { - var leadingComments = emitNode && emitNode.leadingComments; - if (ts.some(leadingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithSynthesizedComments"); - } - ts.forEach(leadingComments, emitLeadingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithSynthesizedComments"); - } - } - emitNodeWithNestedComments(hint, node, emitFlags, emitCallback); - var trailingComments = emitNode && emitNode.trailingComments; - if (ts.some(trailingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithSynthesizedComments"); - } - ts.forEach(trailingComments, emitTrailingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithSynthesizedComments"); - } - } - } - function emitLeadingSynthesizedComment(comment) { - if (comment.kind === 2 /* SingleLineCommentTrivia */) { - writer.writeLine(); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function emitTrailingSynthesizedComment(comment) { - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - } - function writeSynthesizedComment(comment) { - var text = formatSynthesizedComment(comment); - var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; - ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); - } - function formatSynthesizedComment(comment) { - return comment.kind === 3 /* MultiLineCommentTrivia */ - ? "/*" + comment.text + "*/" - : "//" + comment.text; - } - function emitNodeWithNestedComments(hint, node, emitFlags, emitCallback) { - if (emitFlags & 2048 /* NoNestedComments */) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - } - function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitBodyWithDetachedComments"); - } - var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = ts.getEmitFlags(node); - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; - if (!skipLeadingComments) { - emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); - } - if (emitFlags & 2048 /* NoNestedComments */ && !disabled) { - disabled = true; - emitCallback(node); - disabled = false; - } - else { - emitCallback(node); - } - if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); - } - if (!skipTrailingComments) { - emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); - if (hasWrittenComment && !writer.isAtStartOfLine()) { - writer.writeLine(); - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); - } - } - function emitLeadingComments(pos, isEmittedNode) { - hasWrittenComment = false; - if (isEmittedNode) { - forEachLeadingCommentToEmit(pos, emitLeadingComment); - } - else if (pos === 0) { - // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, - // unless it is a triple slash comment at the top of the file. - // For Example: - // /// - // declare var x; - // /// - // interface F {} - // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted - forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); - } - } - function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (isTripleSlashComment(commentPos, commentEnd)) { - emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); - } - } - function shouldWriteComment(text, pos) { - if (printerOptions.onlyPrintJsDocStyle) { - return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); - } - return true; - } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (!hasWrittenComment) { - ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); - hasWrittenComment = true; - } - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else if (kind === 3 /* MultiLineCommentTrivia */) { - writer.write(" "); - } - } - function emitLeadingCommentsOfPosition(pos) { - if (disabled || pos === -1) { - return; - } - emitLeadingComments(pos, /*isEmittedNode*/ true); - } - function emitTrailingComments(pos) { - forEachTrailingCommentToEmit(pos, emitTrailingComment); - } - function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - } - function emitTrailingCommentsOfPosition(pos, prefixSpace) { - if (disabled) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); - } - forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); - } - } - function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { - // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function forEachLeadingCommentToEmit(pos, cb) { - // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments - if (containerPos === -1 || pos !== containerPos) { - if (hasDetachedComments(pos)) { - forEachLeadingCommentWithoutDetachedComments(cb); - } - else { - ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - } - } - function forEachTrailingCommentToEmit(end, cb) { - // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments - if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { - ts.forEachTrailingCommentRange(currentText, end, cb); - } - } - function reset() { - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - detachedCommentsInfo = undefined; - } - function setWriter(output) { - writer = output; - } - function setSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = currentSourceFile.text; - currentLineMap = ts.getLineStarts(currentSourceFile); - detachedCommentsInfo = undefined; - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; - } - function forEachLeadingCommentWithoutDetachedComments(cb) { - // get the leading comments from detachedPos - var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - function emitDetachedCommentsAndUpdateCommentsInfo(range) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - } - /** - * Determine if the given comment is a triple-slash - * - * @return true if the comment is a triple-slash comment else false - */ - function isTripleSlashComment(commentPos, commentEnd) { - return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); - } - } - ts.createCommentWriter = createCommentWriter; -})(ts || (ts = {})); var ts; (function (ts) { var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ /** * Iterates over the source files that are expected to have an emit output. @@ -79099,21 +81334,26 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + if (sourceFile.kind === 280 /* Bundle */) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79136,7 +81376,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79156,22 +81396,16 @@ var ts; var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var newLine = host.getNewLine(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); var writer = ts.createTextWriter(newLine); - var sourceMap = ts.createSourceMapWriter(host, writer); - var declarationSourceMap = ts.createSourceMapWriter(host, writer, { - sourceMap: compilerOptions.declarationMap, - sourceRoot: compilerOptions.sourceRoot, - mapRoot: compilerOptions.mapRoot, - extendedDiagnostics: compilerOptions.extendedDiagnostics, - }); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; var exportedModulesFromDeclarationEmit; // Emit each output file - ts.performance.mark("beforePrint"); + enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); - ts.performance.measure("printTime", "beforePrint"); + exit(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -79185,56 +81419,66 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; // Create a printer to print the nodes - var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { + var printer = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, // transform hooks onEmitNode: transform.emitNodeWithNotification, substituteNode: transform.substituteNode, - // sourcemap hooks - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - // emitter hooks - onSetSourceFile: setSourceFile, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79248,14 +81492,20 @@ var ts; emitterDiagnostics.add(diagnostic); } } - var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true, noEmitHelpers: true }), { + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, - // sourcemap hooks - onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: declarationSourceMap.emitPos, - onSetSourceFile: setSourceFileForDeclarationSourceMaps, // transform hooks onEmitNode: declarationTransform.emitNodeWithNotification, substituteNode: declarationTransform.substituteNode, @@ -79264,8 +81514,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); - if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -79274,7 +81529,7 @@ var ts; } function collectLinkedAliases(node) { if (ts.isExportAssignment(node)) { - if (node.expression.kind === 71 /* Identifier */) { + if (node.expression.kind === 72 /* Identifier */) { resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); } return; @@ -79285,25 +81540,41 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { - var bundle = sourceFileOrBundle.kind === 278 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 277 /* SourceFile */ ? sourceFileOrBundle : undefined; + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } if (bundle) { - printer.writeBundle(bundle, writer, bundleInfo); + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); } else { - printer.writeFile(sourceFile, writer); + printer.writeFile(sourceFile, writer, sourceMapGenerator); } - writer.writeLine(); - var sourceMappingURL = mapRecorder.getSourceMappingURL(); - if (sourceMappingURL) { - writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } } - // Write the source map - if (sourceMapFilePath) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); + else { + writer.writeLine(); } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); @@ -79313,32 +81584,84 @@ var ts; ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); } // Reset state - mapRecorder.reset(); writer.clear(); bundleInfo = createDefaultBundleInfo(); } - function setSourceFile(node) { - sourceMap.setSourceFile(node); + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } - function setSourceFileForDeclarationSourceMaps(node) { - declarationSourceMap.setSourceFile(node); + function getSourceRoot(mapOptions) { + // 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 + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; } } ts.emitFiles = emitFiles; var PipelinePhase; (function (PipelinePhase) { PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; - PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; - PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; - PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); - var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); var currentSourceFile; var nodeIdToGeneratedName; // Map of generated names for specific nodes. var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. @@ -79348,19 +81671,23 @@ var ts; var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; - var ownWriter; + var ownWriter; // Reusable `EmitTextWriter` for basic printing. var write = writeBase; - var commitPendingSemicolon = ts.noop; - var writeSemicolon = writeSemicolonInternal; - var pendingSemicolon = false; - if (printerOptions.omitTrailingSemicolon) { - commitPendingSemicolon = commitPendingSemicolonInternal; - writeSemicolon = deferWriteSemicolon; - } - var syntheticParent = { pos: -1, end: -1 }; - var moduleKind = ts.getEmitModuleKind(printerOptions); - var bundledHelpers = ts.createMap(); var isOwnFileEmit; + // Source Maps + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + // Comments + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; reset(); return { // public API @@ -79387,9 +81714,9 @@ var ts; break; } switch (node.kind) { - case 277 /* SourceFile */: return printFile(node); - case 278 /* Bundle */: return printBundle(node); - case 279 /* UnparsedSource */: return printUnparsedSource(node); + case 279 /* SourceFile */: return printFile(node); + case 280 /* Bundle */: return printBundle(node); + case 281 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -79399,11 +81726,11 @@ var ts; return endPrint(); } function printBundle(bundle) { - writeBundle(bundle, beginPrint()); + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printFile(sourceFile) { - writeFile(sourceFile, beginPrint()); + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printUnparsedSource(unparsed) { @@ -79412,14 +81739,14 @@ var ts; } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(hint, node, sourceFile); reset(); writer = previousWriter; } function writeList(format, nodes, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); if (sourceFile) { setSourceFile(sourceFile); } @@ -79427,18 +81754,18 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output, bundleInfo) { + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { isOwnFileEmit = false; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { var prepend = _b[_a]; - print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); writeLine(); + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); } if (bundleInfo) { bundleInfo.originalOffset = writer.getTextPos(); @@ -79452,15 +81779,15 @@ var ts; } function writeUnparsedSource(unparsed, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); reset(); writer = previousWriter; } - function writeFile(sourceFile, output) { + function writeFile(sourceFile, output, sourceMapGenerator) { isOwnFileEmit = true; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(sourceFile); emitPrologueDirectivesIfNeeded(sourceFile); print(0 /* SourceFile */, sourceFile, sourceFile); @@ -79479,19 +81806,24 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - var pipelinePhase = getPipelinePhase(0 /* Notification */, hint); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; - comments.setSourceFile(sourceFile); - if (onSetSourceFile) { - onSetSourceFile(sourceFile); + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); } } - function setWriter(output) { - writer = output; // TODO: GH#18217 - comments.setWriter(output); + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; } function reset() { nodeIdToGeneratedName = []; @@ -79500,68 +81832,66 @@ var ts; tempFlagsStack = []; tempFlags = 0 /* Auto */; reservedNamesStack = []; - comments.reset(); - setWriter(/*output*/ undefined); + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } function emit(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(4 /* Unspecified */, node); } function emitIdentifierName(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(2 /* IdentifierName */, node); } function emitExpression(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(1 /* Expression */, node); } - function getPipelinePhase(phase, hint) { + function getPipelinePhase(phase, node) { switch (phase) { case 0 /* Notification */: - if (onEmitNode) { + if (onEmitNode !== ts.noEmitNotification) { return pipelineEmitWithNotification; } // falls through - case 1 /* Comments */: - if (emitNodeWithComments && hint !== 0 /* SourceFile */) { + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { return pipelineEmitWithComments; } - return pipelineEmitWithoutComments; - case 2 /* SourceMaps */: - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */) { + // falls through + case 3 /* SourceMaps */: + if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { return pipelineEmitWithSourceMap; } // falls through - case 3 /* Emit */: + case 4 /* Emit */: return pipelineEmitWithHint; default: - return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + return ts.Debug.assertNever(phase); } } - function getNextPipelinePhase(currentPhase, hint) { - return getPipelinePhase(currentPhase + 1, hint); + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); - } - function pipelineEmitWithComments(hint, node) { - ts.Debug.assertDefined(emitNodeWithComments); - ts.Debug.assert(hint !== 0 /* SourceFile */); - emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint)); - } - function pipelineEmitWithoutComments(hint, node) { - var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint); - pipelinePhase(hint, trySubstituteNode(hint, node)); - } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(hint !== 0 /* SourceFile */); - ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node); + onEmitNode(hint, node, pipelinePhase); } function pipelineEmitWithHint(hint, node) { if (hint === 0 /* SourceFile */) @@ -79570,254 +81900,285 @@ var ts; return emitIdentifier(ts.cast(node, ts.isIdentifier)); if (hint === 3 /* MappedTypeParameter */) return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } if (hint === 4 /* Unspecified */) { if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); switch (node.kind) { // Pseudo-literals - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: return emitLiteral(node); - case 279 /* UnparsedSource */: + case 281 /* UnparsedSource */: return emitUnparsedSource(node); // Identifiers - case 71 /* Identifier */: + case 72 /* Identifier */: return emitIdentifier(node); // Parse tree nodes // Names - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return emitQualifiedName(node); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return emitTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return emitParameter(node); - case 150 /* Decorator */: + case 152 /* Decorator */: return emitDecorator(node); // Type members - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return emitPropertySignature(node); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 153 /* MethodSignature */: + case 155 /* MethodSignature */: return emitMethodSignature(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return emitConstructor(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return emitAccessorDeclaration(node); - case 158 /* CallSignature */: + case 160 /* CallSignature */: return emitCallSignature(node); - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return emitConstructSignature(node); - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return emitIndexSignature(node); // Types - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return emitTypePredicate(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return emitTypeReference(node); - case 163 /* FunctionType */: + case 165 /* FunctionType */: return emitFunctionType(node); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return emitJSDocFunctionType(node); - case 164 /* ConstructorType */: + case 166 /* ConstructorType */: return emitConstructorType(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return emitTypeQuery(node); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return emitTypeLiteral(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return emitArrayType(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return emitTupleType(node); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return emitOptionalType(node); - case 171 /* UnionType */: + case 173 /* UnionType */: return emitUnionType(node); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return emitIntersectionType(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return emitConditionalType(node); - case 174 /* InferType */: + case 176 /* InferType */: return emitInferType(node); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return emitParenthesizedType(node); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 176 /* ThisType */: + case 178 /* ThisType */: return emitThisType(); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return emitTypeOperator(node); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return emitMappedType(node); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return emitLiteralType(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return emitImportTypeNode(node); - case 282 /* JSDocAllType */: - write("*"); + case 284 /* JSDocAllType */: + writePunctuation("*"); return; - case 283 /* JSDocUnknownType */: - write("?"); + case 285 /* JSDocUnknownType */: + writePunctuation("?"); return; - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return emitJSDocNullableType(node); - case 285 /* JSDocNonNullableType */: + case 287 /* JSDocNonNullableType */: return emitJSDocNonNullableType(node); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return emitJSDocOptionalType(node); - case 170 /* RestType */: - case 288 /* JSDocVariadicType */: + case 172 /* RestType */: + case 290 /* JSDocVariadicType */: return emitRestOrJSDocVariadicType(node); // Binding patterns - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return emitBindingElement(node); // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return emitTemplateSpan(node); - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 216 /* Block */: + case 218 /* Block */: return emitBlock(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return emitVariableStatement(node); - case 218 /* EmptyStatement */: - return emitEmptyStatement(); - case 219 /* ExpressionStatement */: + case 220 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 221 /* ExpressionStatement */: return emitExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return emitIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return emitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return emitWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return emitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return emitForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return emitForOfStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return emitContinueStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return emitBreakStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return emitReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return emitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return emitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return emitLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return emitThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return emitTryStatement(node); - case 234 /* DebuggerStatement */: + case 236 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return emitClassDeclaration(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return emitModuleBlock(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return emitCaseBlock(node); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return emitImportDeclaration(node); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return emitImportClause(node); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return emitNamespaceImport(node); - case 250 /* NamedImports */: + case 252 /* NamedImports */: return emitNamedImports(node); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return emitImportSpecifier(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return emitExportAssignment(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return emitExportDeclaration(node); - case 254 /* NamedExports */: + case 256 /* NamedExports */: return emitNamedExports(node); - case 255 /* ExportSpecifier */: + case 257 /* ExportSpecifier */: return emitExportSpecifier(node); - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return; // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) - case 10 /* JsxText */: + case 11 /* JsxText */: return emitJsxText(node); - case 260 /* JsxOpeningElement */: - case 263 /* JsxOpeningFragment */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 261 /* JsxClosingElement */: - case 264 /* JsxClosingFragment */: + case 263 /* JsxClosingElement */: + case 266 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return emitJsxAttribute(node); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return emitJsxAttributes(node); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: return emitCaseClause(node); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return emitDefaultClause(node); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return emitHeritageClause(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: return emitEnumMember(node); - // JSDoc nodes (ignored) + // JSDoc nodes (only used in codefixes currently) + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return emitJSDocSimpleTypedTag(node); + case 295 /* JSDocAugmentsTag */: + return emitJSDocAugmentsTag(node); + case 303 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 304 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 297 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 293 /* JSDocSignature */: + return emitJSDocSignature(node); + case 292 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 296 /* JSDocClassTag */: + case 294 /* JSDocTag */: + return emitJSDocSimpleTag(node); + case 291 /* JSDocComment */: + return emitJSDoc(node); // Transformation nodes (ignored) } if (ts.isExpression(node)) { hint = 1 /* Expression */; - node = trySubstituteNode(1 /* Expression */, node); + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } } else if (ts.isToken(node)) { return writeTokenNode(node, writePunctuation); @@ -79827,89 +82188,90 @@ var ts; switch (node.kind) { // Literals case 8 /* NumericLiteral */: - return emitNumericLiteral(node); - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return emitLiteral(node); // Identifiers - case 71 /* Identifier */: + case 72 /* Identifier */: return emitIdentifier(node); // Reserved words - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 101 /* TrueKeyword */: - case 99 /* ThisKeyword */: - case 91 /* ImportKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 102 /* TrueKeyword */: + case 100 /* ThisKeyword */: + case 92 /* ImportKeyword */: writeTokenNode(node, writeKeyword); return; // Expressions - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return emitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return emitNewExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return emitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return emitArrowFunction(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return emitDeleteExpression(node); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return emitVoidExpression(node); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return emitAwaitExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return emitBinaryExpression(node); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return emitConditionalExpression(node); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return emitTemplateExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return emitYieldExpression(node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return emitSpreadExpression(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return emitClassExpression(node); - case 208 /* OmittedExpression */: + case 210 /* OmittedExpression */: return; - case 210 /* AsExpression */: + case 212 /* AsExpression */: return emitAsExpression(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return emitNonNullExpression(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return emitMetaProperty(node); // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: return emitJsxElement(node); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return emitCommaList(node); } } @@ -79921,12 +82283,13 @@ var ts; writeSpace(); emit(node.constraint); } - function trySubstituteNode(hint, node) { - return node && substituteNode && substituteNode(hint, node) || node; + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); + pipelinePhase(hint, substituteNode(hint, node)); } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 278 /* Bundle */ ? node : undefined; + var bundle = node.kind === 280 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -79963,7 +82326,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79975,7 +82338,8 @@ var ts; // Literals/Pseudo-literals // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } // SyntaxKind.StringLiteral @@ -79985,9 +82349,9 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) - && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); } else { @@ -80005,7 +82369,7 @@ var ts; function emitIdentifier(node) { var writeText = node.symbol ? writeSymbol : write; writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); - emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments + emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names @@ -80016,7 +82380,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -80052,7 +82416,7 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 287 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { @@ -80074,7 +82438,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -80084,7 +82448,7 @@ var ts; emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); - writeSemicolon(); + writeTrailingSemicolon(); } function emitMethodSignature(node) { pushNameGenerationScope(node); @@ -80095,7 +82459,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -80114,7 +82478,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 156 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -80126,7 +82490,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -80138,7 +82502,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -80146,10 +82510,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // // Types @@ -80176,22 +82540,22 @@ var ts; popNameGenerationScope(node); } function emitJSDocFunctionType(node) { - write("function"); + writeKeyword("function"); emitParameters(node, node.parameters); - write(":"); + writePunctuation(":"); emit(node.type); } function emitJSDocNullableType(node) { - write("?"); + writePunctuation("?"); emit(node.type); } function emitJSDocNonNullableType(node) { - write("!"); + writePunctuation("!"); emit(node.type); } function emitJSDocOptionalType(node) { emit(node.type); - write("="); + writePunctuation("="); } function emitConstructorType(node) { pushNameGenerationScope(node); @@ -80212,8 +82576,8 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */; - emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); writePunctuation("}"); } function emitArrayType(node) { @@ -80222,23 +82586,23 @@ var ts; writePunctuation("]"); } function emitRestOrJSDocVariadicType(node) { - write("..."); + writePunctuation("..."); emit(node.type); } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 272 /* TupleTypeElements */); + emitList(node, node.elementTypes, 528 /* TupleTypeElements */); writePunctuation("]"); } function emitOptionalType(node) { emit(node.type); - write("?"); + writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 260 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */); } function emitIntersectionType(node) { - emitList(node, node.types, 264 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */); } function emitConditionalType(node) { emit(node.checkType); @@ -80291,25 +82655,25 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) { + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { writeKeyword("readonly"); } writeSpace(); } writePunctuation("["); - var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter); pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); - if (node.questionToken.kind !== 55 /* QuestionToken */) { + if (node.questionToken.kind !== 56 /* QuestionToken */) { writePunctuation("?"); } } writePunctuation(":"); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); if (emitFlags & 1 /* SingleLine */) { writeSpace(); } @@ -80342,12 +82706,12 @@ var ts; // function emitObjectBindingPattern(node) { writePunctuation("{"); - emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); writePunctuation("}"); } function emitArrayBindingPattern(node) { writePunctuation("["); - emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); writePunctuation("]"); } function emitBindingElement(node) { @@ -80365,8 +82729,8 @@ var ts; // function emitArrayLiteralExpression(node) { var elements = node.elements; - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -80374,9 +82738,9 @@ var ts; if (indentedFlag) { increaseIndent(); } - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */; - emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); } @@ -80387,20 +82751,20 @@ var ts; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = ts.createToken(23 /* DotToken */); + var dotToken = ts.createToken(24 /* DotToken */); dotToken.pos = dotRangeStart; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); - increaseIndentIf(indentBeforeDot); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); if (shouldEmitDotDot) { writePunctuation("."); } - emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node); - increaseIndentIf(indentAfterDot); + emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); } @@ -80410,9 +82774,9 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); + && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -80425,21 +82789,21 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); } function emitNewExpression(node) { - emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); @@ -80454,9 +82818,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node); + var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { generateNameIfNeeded(node.name); @@ -80475,22 +82839,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -80515,24 +82879,24 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 200 /* PrefixUnaryExpression */ - && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) - || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); + return operand.kind === 202 /* PrefixUnaryExpression */ + && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */)) + || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; + var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); - increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + increaseIndentIf(indentBeforeOperator, isCommaOperator); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, writeOperator); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - increaseIndentIf(indentAfterOperator, " "); + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); } @@ -80542,28 +82906,28 @@ var ts; var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); - increaseIndentIf(indentBeforeQuestion, " "); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); - increaseIndentIf(indentAfterQuestion, " "); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); - increaseIndentIf(indentBeforeColon, " "); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); - increaseIndentIf(indentAfterColon, " "); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); } function emitTemplateExpression(node) { emit(node.head); - emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - writePunctuation("..."); + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); emitExpression(node.expression); } function emitClassExpression(node) { @@ -80606,36 +82970,45 @@ var ts; emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); } function emitBlockStatements(node, forceSingleLine) { - emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); - var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; emitList(node, node.statements, format); - emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); + emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - writeSemicolon(); + writeTrailingSemicolon(); } - function emitEmptyStatement() { - writeSemicolon(); + function emitEmptyStatement(isEmbeddedStatement) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { - writeSemicolon(); + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); } } function emitIfStatement(node) { - var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 220 /* IfStatement */) { + emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -80645,14 +83018,14 @@ var ts; } } function emitWhileClause(node, startPos) { - var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node); + var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { - emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -80668,45 +83041,45 @@ var ts; emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.condition); - pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.incrementor); - emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(145 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 236 /* VariableDeclarationList */) { + if (node.kind === 238 /* VariableDeclarationList */) { emit(node); } else { @@ -80715,14 +83088,14 @@ var ts; } } function emitContinueStatement(node) { - emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitBreakStatement(node) { - emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { var node = ts.getParseTreeNode(contextNode); @@ -80748,40 +83121,40 @@ var ts; return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitWithStatement(node) { - var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node); + emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTryStatement(node) { - emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -80790,14 +83163,14 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); - writeSemicolon(); + writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); } // // Declarations @@ -80810,7 +83183,7 @@ var ts; function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); writeSpace(); - emitList(node, node.declarations, 272 /* VariableDeclarationList */); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { emitFunctionDeclarationOrExpression(node); @@ -80858,7 +83231,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -80910,7 +83283,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -80922,7 +83295,7 @@ var ts; emitHelpers(body); if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { decreaseIndent(); - emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); increaseIndent(); } else { @@ -80949,7 +83322,7 @@ var ts; emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65 /* ClassMembers */); + emitList(node, node.members, 129 /* ClassMembers */); writePunctuation("}"); if (indentedFlag) { decreaseIndent(); @@ -80962,10 +83335,10 @@ var ts; writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256 /* HeritageClauses */); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65 /* InterfaceMembers */); + emitList(node, node.members, 129 /* InterfaceMembers */); writePunctuation("}"); } function emitTypeAliasDeclaration(node) { @@ -80979,7 +83352,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -80988,7 +83361,7 @@ var ts; emit(node.name); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 81 /* EnumMembers */); + emitList(node, node.members, 145 /* EnumMembers */); writePunctuation("}"); } function emitModuleDeclaration(node) { @@ -81000,8 +83373,8 @@ var ts; emit(node.name); var body = node.body; if (!body) - return writeSemicolon(); - while (body.kind === 242 /* ModuleDeclaration */) { + return writeTrailingSemicolon(); + while (body.kind === 244 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); body = body.body; @@ -81016,23 +83389,23 @@ var ts; popNameGenerationScope(node); } function emitCaseBlock(node) { - emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node); - emitList(node, node.clauses, 65 /* CaseBlockClauses */); - emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node); + emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); - writeSemicolon(); + writeTrailingSemicolon(); } function emitModuleReference(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81041,29 +83414,29 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - emitTokenWithComment(143 /* FromKeyword */, node.importClause.end, writeKeyword, node); + emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); - writeSemicolon(); + writeTrailingSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); + var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node); writeSpace(); - emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node); + emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -81074,45 +83447,45 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node); + emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node); } else { - emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node); + emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitExportDeclaration(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node); + nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); var fromPos = node.exportClause ? node.exportClause.end : nextPos; - emitTokenWithComment(143 /* FromKeyword */, fromPos, writeKeyword, node); + emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamespaceExportDeclaration(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node); writeSpace(); emit(node.name); - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -81122,14 +83495,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -81148,7 +83521,7 @@ var ts; // function emitJsxElement(node) { emit(node.openingElement); - emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); emit(node.closingElement); } function emitJsxSelfClosingElement(node) { @@ -81160,7 +83533,7 @@ var ts; } function emitJsxFragment(node) { emit(node.openingFragment); - emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { @@ -81175,7 +83548,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { @@ -81186,7 +83558,7 @@ var ts; writePunctuation(">"); } function emitJsxAttributes(node) { - emitList(node, node.properties, 131328 /* JsxElementAttributes */); + emitList(node, node.properties, 262656 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); @@ -81206,7 +83578,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81217,13 +83589,13 @@ var ts; // Clauses // function emitCaseClause(node) { - emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node); + var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node); emitCaseOrDefaultClauseRest(node, node.statements, pos); } function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { @@ -81233,14 +83605,14 @@ var ts; ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); - var format = 81985 /* CaseOrDefaultClauseStatements */; + var format = 163969 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode); writeSpace(); - format &= ~(1 /* MultiLine */ | 64 /* Indented */); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); } else { - emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode); } emitList(parentNode, statements, format); } @@ -81248,15 +83620,15 @@ var ts; writeSpace(); writeTokenText(node.token, writeKeyword); writeSpace(); - emitList(node, node.types, 272 /* HeritageClauseTypes */); + emitList(node, node.types, 528 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -81293,7 +83665,7 @@ var ts; } function emitSpreadAssignment(node) { if (node.expression) { - writePunctuation("..."); + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); emitExpression(node.expression); } } @@ -81305,6 +83677,142 @@ var ts; emitInitializer(node.initializer, node.name.end, node); } // + // JSDoc + // + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // // Top-level nodes // function emitSourceFile(node) { @@ -81324,41 +83832,46 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.moduleName) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.amdDependencies) { for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { var dep = _b[_a]; if (dep.name) { - write("/// "); + writeComment("/// "); } else { - write("/// "); + writeComment("/// "); } writeLine(); } } for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { var directive = files_1[_c]; - write("/// "); + writeComment("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; - write("/// "); + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); writeLine(); } } @@ -81377,7 +83890,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 272 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -81417,13 +83930,14 @@ var ts; setSourceFile(sourceFile); emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); } + setSourceFile(undefined); } } function emitShebangIfNeeded(sourceFileOrBundle) { if (ts.isSourceFile(sourceFileOrBundle)) { var shebang = ts.getShebang(sourceFileOrBundle.text); if (shebang) { - write(shebang); + writeComment(shebang); writeLine(); return true; } @@ -81451,7 +83965,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328 /* Modifiers */); + emitList(node, modifiers, 262656 /* Modifiers */); writeSpace(); } } @@ -81465,7 +83979,7 @@ var ts; function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -81502,30 +84016,37 @@ var ts; else { writeLine(); increaseIndent(); - emit(node); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(5 /* EmbeddedStatement */, node); + } + else { + emit(node); + } decreaseIndent(); } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 24577 /* Decorators */); + emitList(parentNode, decorators, 49153 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26896 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures return emitTypeArguments(parentNode, parentNode.typeArguments); } - emitList(parentNode, typeParameters, 26896 /* TypeParameters */); + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1296 /* Parameters */); + emitList(parentNode, parameters, 2576 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81539,14 +84060,14 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); } else { emitParameters(parentNode, parameters); } } function emitParametersForIndexSignature(parentNode, parameters) { - emitList(parentNode, parameters, 4432 /* IndexSignatureParameters */); + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } function emitList(parentNode, children, format, start, count) { emitNodeList(emit, parentNode, children, format, start, count); @@ -81555,7 +84076,7 @@ var ts; emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 } function writeDelimiter(format) { - switch (format & 28 /* DelimitersMask */) { + switch (format & 60 /* DelimitersMask */) { case 0 /* None */: break; case 16 /* CommaDelimited */: @@ -81565,6 +84086,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8 /* AmpersandDelimited */: writeSpace(); writePunctuation("&"); @@ -81575,11 +84101,11 @@ var ts; if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; - if (isUndefined && format & 8192 /* OptionalIfUndefined */) { + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { return; } var isEmpty = children === undefined || start >= children.length || count === 0; - if (isEmpty && format & 16384 /* OptionalIfEmpty */) { + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); } @@ -81588,7 +84114,7 @@ var ts; } return; } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { // TODO: GH#18217 @@ -81603,23 +84129,23 @@ var ts; if (format & 1 /* MultiLine */) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { + else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { writeSpace(); } } else { // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; + var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 writeLine(); shouldEmitInterveningComments = false; } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 256 /* SpaceBetweenBraces */) { writeSpace(); } // Increase the indent, if requested. - if (format & 64 /* Indented */) { + if (format & 128 /* Indented */) { increaseIndent(); } // Emit each child. @@ -81628,14 +84154,19 @@ var ts; for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. - if (previousSibling) { + if (format & 32 /* AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { // i.e // function commentedParameters( // /* Parameter a */ // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -81643,14 +84174,14 @@ var ts; if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new // line, we should increase the indent. - if ((format & (3 /* LinesMask */ | 64 /* Indented */)) === 0 /* SingleLine */) { + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { increaseIndent(); shouldDecreaseIndentAfterEmit = true; } writeLine(); shouldEmitInterveningComments = false; } - else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { + else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { writeSpace(); } } @@ -81672,7 +84203,7 @@ var ts; previousSibling = child; } // Write a trailing comma, if requested. - var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; + var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { writePunctuation(","); } @@ -81682,25 +84213,25 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. - if (format & 64 /* Indented */) { + if (format & 128 /* Indented */) { decreaseIndent(); } // Write the closing line terminator or closing whitespace. if (shouldWriteClosingLineTerminator(parentNode, children, format)) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 256 /* SpaceBetweenBraces */) { writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { if (isEmpty && !isUndefined) { // TODO: GH#18217 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists @@ -81708,73 +84239,55 @@ var ts; writePunctuation(getClosingBracket(format)); } } - function commitPendingSemicolonInternal() { - if (pendingSemicolon) { - writeSemicolonInternal(); - pendingSemicolon = false; - } - } + // Writers function writeLiteral(s) { - commitPendingSemicolon(); writer.writeLiteral(s); } function writeStringLiteral(s) { - commitPendingSemicolon(); writer.writeStringLiteral(s); } function writeBase(s) { - commitPendingSemicolon(); writer.write(s); } function writeSymbol(s, sym) { - commitPendingSemicolon(); writer.writeSymbol(s, sym); } function writePunctuation(s) { - commitPendingSemicolon(); writer.writePunctuation(s); } - function deferWriteSemicolon() { - pendingSemicolon = true; - } - function writeSemicolonInternal() { - writer.writePunctuation(";"); + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); } function writeKeyword(s) { - commitPendingSemicolon(); writer.writeKeyword(s); } function writeOperator(s) { - commitPendingSemicolon(); writer.writeOperator(s); } function writeParameter(s) { - commitPendingSemicolon(); writer.writeParameter(s); } + function writeComment(s) { + writer.writeComment(s); + } function writeSpace() { - commitPendingSemicolon(); writer.writeSpace(" "); } function writeProperty(s) { - commitPendingSemicolon(); writer.writeProperty(s); } function writeLine() { - commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { - commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { - commitPendingSemicolon(); writer.decreaseIndent(); } function writeToken(token, pos, writer, contextNode) { - return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) : writeTokenText(token, writer, pos); } function writeTokenNode(node, writer) { @@ -81802,23 +84315,23 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = ts.guessIndentation(lines); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var lineText = lines_2[_a]; + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); - writeLine(); + writer.rawWrite(newLine); } } } - function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + function increaseIndentIf(value, writeSpaceIfNotIndenting) { if (value) { increaseIndent(); writeLine(); } - else if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); + else if (writeSpaceIfNotIndenting) { + writeSpace(); } } // Helper function to decrease the indent if we previously indented. Allows multiple @@ -81838,7 +84351,7 @@ var ts; return true; } if (format & 2 /* PreserveLines */) { - if (format & 32768 /* PreferNewLine */) { + if (format & 65536 /* PreferNewLine */) { return true; } var firstChild = children[0]; @@ -81877,10 +84390,10 @@ var ts; } function shouldWriteClosingLineTerminator(parentNode, children, format) { if (format & 1 /* MultiLine */) { - return (format & 65536 /* NoTrailingNewLine */) === 0; + return (format & 131072 /* NoTrailingNewLine */) === 0; } else if (format & 2 /* PreserveLines */) { - if (format & 32768 /* PreferNewLine */) { + if (format & 65536 /* PreferNewLine */) { return true; } var lastChild = ts.lastOrUndefined(children); @@ -81902,11 +84415,11 @@ var ts; if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { - return (format & 32768 /* PreferNewLine */) !== 0; + return (format & 65536 /* PreferNewLine */) !== 0; } return startsOnNewLine; } - return (format & 32768 /* PreferNewLine */) !== 0; + return (format & 65536 /* PreferNewLine */) !== 0; } function needsIndentation(parent, node1, node2) { parent = skipSynthesizedParentheses(parent); @@ -81926,7 +84439,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -81938,7 +84451,7 @@ var ts; else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } - else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); } else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { @@ -81946,19 +84459,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { - if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -81991,81 +84504,81 @@ var ts; if (!node) return; switch (node.kind) { - case 216 /* Block */: + case 218 /* Block */: ts.forEach(node.statements, generateNames); break; - case 231 /* LabeledStatement */: - case 229 /* WithStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 233 /* LabeledStatement */: + case 231 /* WithStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: generateNames(node.statement); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 272 /* CatchClause */: + case 274 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: generateNames(node.declarationList); break; - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: generateNames(node.importClause); break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -82074,12 +84587,12 @@ var ts; if (!node) return; switch (node.kind) { - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: generateNameIfNeeded(node.name); break; } @@ -82137,7 +84650,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +84729,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82259,23 +84772,23 @@ var ts; */ function generateNameForNode(node, flags) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 252 /* ExportAssignment */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 254 /* ExportAssignment */: return generateNameForExportDefault(); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return generateNameForClassExpression(); - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0 /* Auto */); @@ -82316,21 +84829,396 @@ var ts; // otherwise, return the original node for the source; return node; } + // Comments + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 238 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + // Source Maps + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, + /*nameIndex*/ undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } } ts.createPrinter = createPrinter; function createBracketsMap() { var brackets = []; - brackets[512 /* Braces */] = ["{", "}"]; - brackets[1024 /* Parenthesis */] = ["(", ")"]; - brackets[2048 /* AngleBrackets */] = ["<", ">"]; - brackets[4096 /* SquareBrackets */] = ["[", "]"]; + brackets[1024 /* Braces */] = ["{", "}"]; + brackets[2048 /* Parenthesis */] = ["(", ")"]; + brackets[4096 /* AngleBrackets */] = ["<", ">"]; + brackets[8192 /* SquareBrackets */] = ["[", "]"]; return brackets; } function getOpeningBracket(format) { - return brackets[format & 7680 /* BracketsMask */][0]; + return brackets[format & 15360 /* BracketsMask */][0]; } function getClosingBracket(format) { - return brackets[format & 7680 /* BracketsMask */][1]; + return brackets[format & 15360 /* BracketsMask */][1]; } // Flags enum to track count of temp variables and a few dedicated names var TempFlags; @@ -82730,17 +85618,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +85651,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +85661,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +85669,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +85681,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +85693,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +85709,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(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); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +85743,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +85770,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +85858,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +85874,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83021,7 +85913,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -83034,7 +85926,7 @@ var ts; result = cache.get(name); } else { - cache.set(name, result = loader(name, containingFile)); + cache.set(name, result = loader(name, containingFile, redirectedReference)); } resolutions.push(result); } @@ -83044,7 +85936,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +85945,11 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + var seenResolvedRefs; + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,9 +85970,39 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || + return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolution(sourceFile.path); } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + // If child project references are upto date, this project reference is uptodate + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { @@ -83084,21 +86011,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83121,7 +86044,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var modifiedFilePaths; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -83149,16 +86072,15 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; - var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; @@ -83170,16 +86092,16 @@ var ts; } else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217 - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; } else { - var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217 - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). @@ -83195,30 +86117,34 @@ var ts; // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files - var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; if (projectReferences) { - for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { - var ref = projectReferences_1[_i]; - var parsedRef = parseProjectReferenceConfigFile(ref); - resolvedProjectReferences.push(parsedRef); - if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); - processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); } } } ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); @@ -83232,7 +86158,7 @@ var ts; // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. - if (!skipDefaultLib) { + if (rootNames.length && !skipDefaultLib) { // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file var defaultLibraryFileName = getDefaultLibraryFileName(); @@ -83257,10 +86183,18 @@ var ts; var oldSourceFiles = oldProgram.getSourceFiles(); for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { var oldSourceFile = oldSourceFiles_1[_a]; - if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { - host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); } // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; @@ -83299,7 +86233,12 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +86272,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83362,13 +86301,13 @@ var ts; } return classifiableNames; } - function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, // the best we can do is fallback to the default logic. - return resolveModuleNamesWorker(moduleNames, containingFile); + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); } - var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { // `file` was created for the new program. // @@ -83378,13 +86317,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83431,7 +86370,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -83442,7 +86381,7 @@ var ts; } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) : ts.emptyArray; // Combine results of resolutions and predicted results if (!result) { @@ -83468,9 +86407,9 @@ var ts; return result; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,24 +86417,35 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); - if (!firstUnmodifiedFile) { + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { return false; } if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); } return true; } } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + // If array of references is changed, we cant resue old program + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return 0 /* Not */; @@ -83516,36 +86466,14 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); - if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } - for (var i = 0; i < projectReferences.length; i++) { - var oldRef = oldRefs[i]; - if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); - if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { - // Resolved project reference has gone missing or changed - return oldProgram.structureIsReused = 0 /* Not */; - } - } - else { - // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { - return oldProgram.structureIsReused = 0 /* Not */; - } - } - } + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0 /* Not */; } - else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; - var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2 /* Completely */; // If the missing file paths are now present, it can change the progam structure, @@ -83564,7 +86492,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,8 +86519,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; - filePaths.push(newSourceFile.path); + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { // If there are 2 different source files for the same package name and at least one of them changes, @@ -83653,15 +86584,23 @@ var ts; if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } - modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } // try to verify results of module resolution - for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { - var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { @@ -83673,8 +86612,9 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -83694,28 +86634,29 @@ var ts; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping - for (var i = 0; i < newSourceFiles.length; i++) { - filesByName.set(filePaths[i], newSourceFiles[i]); + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); // Set the file as found during node modules search if it was found that way in old progra, - if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { - sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { - var modifiedFile = modifiedSourceFiles_2[_c]; + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +86667,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +86682,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +86745,7 @@ var ts; // get any preEmit diagnostics, not just the ones 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) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +86811,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +86902,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -83969,22 +86912,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } // falls through - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 235 /* VariableDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 237 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -83992,41 +86935,41 @@ var ts; } } switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: var heritageClause = node; - if (heritageClause.token === 108 /* ImplementsKeyword */) { + if (heritageClause.token === 109 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 210 /* AsExpression */: + case 212 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; @@ -84039,51 +86982,51 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, 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)); } switch (parent.kind) { - case 238 /* ClassDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 240 /* ClassDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } // falls through - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 217 /* VariableStatement */); + return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */); } break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 115 /* StaticKeyword */) { + if (modifier.kind !== 116 /* StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } return; } break; - case 149 /* Parameter */: + case 151 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 209 /* ExpressionWithTypeArguments */: - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -84100,24 +87043,24 @@ var ts; for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { var modifier = modifiers_1[_i]; switch (modifier.kind) { - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: if (isConstValid) { continue; } // to report error, // falls through - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 124 /* DeclareKeyword */: - case 117 /* AbstractKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 125 /* DeclareKeyword */: + case 118 /* AbstractKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. - case 115 /* StaticKeyword */: - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 116 /* StaticKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: } } } @@ -84165,10 +87108,22 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; } function getGlobalDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; } function getConfigFileParsingDiagnostics() { return configFileParsingDiagnostics || ts.emptyArray; @@ -84180,15 +87135,15 @@ var ts; return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 71 /* Identifier */ - ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText - : b.kind === 9 /* StringLiteral */ && a.text === b.text; + return a.kind === 72 /* Identifier */ + ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 10 /* StringLiteral */ && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84210,12 +87165,9 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, /*inAmbientModule*/ false); - if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(node); - } } if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(file.endOfFileToken); + collectDynamicImportOrRequireCalls(file); } file.imports = imports || ts.emptyArray; file.moduleAugmentations = moduleAugmentations || ts.emptyArray; @@ -84263,24 +87215,37 @@ var ts; } } } - function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { - imports = ts.append(imports, node.arguments[0]); - } - // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. - else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { - imports = ts.append(imports, node.arguments[0]); - } - else if (ts.isLiteralImportTypeNode(node)) { - imports = ts.append(imports, node.argument.literal); - } - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } } } - function collectDynamicImportOrRequireCallsForEachChild(node) { - ts.forEachChild(node, collectDynamicImportOrRequireCalls); + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } } } function getLibFileFromReference(ref) { @@ -84296,7 +87261,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84352,11 +87317,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84371,6 +87339,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84436,9 +87405,9 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); - filesByName.set(path, dupFile); + addFileToFilesByName(dupFile, path, redirectedPath); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); return dupFile; @@ -84449,14 +87418,12 @@ var ts; sourceFileToPackageName.set(path, packageId.name); } } - filesByName.set(path, file); - if (redirectedPath) { - filesByName.set(redirectedPath, file); - } + addFileToFilesByName(file, path, redirectedPath); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84485,25 +87452,90 @@ var ts; } return file; } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { - return undefined; - } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); }); - return result; + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + // Visit project references first + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +87545,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84531,6 +87563,8 @@ var ts; } var saveResolution = true; if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 @@ -84555,6 +87589,8 @@ var ts; processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; } else { fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 @@ -84599,8 +87635,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +87644,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +87664,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,61 +87684,61 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } return allFilesBelongToPath; } function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); return undefined; } - sourceFile.path = toPath(refPath); + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); - return { commandLine: commandLine, sourceFile: sourceFile }; - } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84731,41 +87766,18 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); } } - if (projectReferences) { - for (var i = 0; i < projectReferences.length; i++) { - var ref = projectReferences[i]; - var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; - if (resolvedRefOpts === undefined) { - createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); - continue; - } - if (!resolvedRefOpts.composite) { - createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - } - if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); - } - } - else { - createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); - } - } - } - } + verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +87827,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84833,12 +87845,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -84850,7 +87862,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84863,9 +87875,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84876,19 +87888,19 @@ var ts; // 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; })) { + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -84946,6 +87958,35 @@ var ts; } } } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { var needCompilerDiagnostic = true; var pathsSyntax = getOptionPathsSyntax(); @@ -84996,10 +88037,10 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } - function createDiagnosticForReference(index, message, arg0, arg1) { - var referencesSyntax = getProjectReferencesSyntax(); + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); if (referencesSyntax && referencesSyntax.elements.length > index) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); } else { programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); @@ -85013,22 +88054,6 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } - function getProjectReferencesSyntax() { - if (_referencesArrayLiteralSyntax === undefined) { - _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile) { - var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217 - for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { - var prop = _a[_i]; - if (ts.isArrayLiteralExpression(prop.initializer)) { - _referencesArrayLiteralSyntax = prop.initializer; - break; - } - } - } - } - return _referencesArrayLiteralSyntax; - } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword @@ -85079,7 +88104,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,25 +88121,26 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85153,7 +88179,7 @@ var ts; var res = imports.map(function (i) { return i.text; }); for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9 /* StringLiteral */) { + if (aug.kind === 10 /* StringLiteral */) { res.push(aug.text); } // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. @@ -85184,7 +88210,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +88220,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +88249,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,11 +88260,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85338,6 +88404,11 @@ var ts; var latestSignature; if (sourceFile.isDeclarationFile) { latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } } else { var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); @@ -85403,7 +88474,7 @@ var ts; return getAllFileNames(state, programOfThisState); } // If this is non module emit, or its a global file, it depends on all the source files - if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { return getAllFileNames(state, programOfThisState); } // Get the references, traversing deep from the referenceMap @@ -85462,6 +88533,20 @@ var ts; } return true; } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } /** * Gets all files of the program excluding the default library file */ @@ -85502,7 +88587,7 @@ var ts; * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { - if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } var compilerOptions = programOfThisState.getCompilerOptions(); @@ -85552,8 +88637,9 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && - !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { @@ -85568,6 +88654,8 @@ var ts; // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -85585,6 +88673,13 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } // Unchanged file copy diagnostics var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { @@ -85668,18 +88763,31 @@ var ts; // If there are no more diagnostics from old cache, done return; } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } // If there was change in signature for the changed file, // then delete the semantic diagnostics for files that are affected by using exports of this module if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { return; } ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { return exportedModules && exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); })) { return; } @@ -85687,16 +88795,44 @@ var ts; ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); }); } /** * removes the semantic diagnostics of files referencing referencedPath and * returns true if there are no more semantic diagnostics from old state */ - function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { - return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); }); } /** @@ -85705,7 +88841,7 @@ var ts; */ function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -85752,7 +88888,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +88901,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +89082,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -85971,6 +89114,10 @@ var ts; /*@internal*/ var ts; (function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; ts.maxNumberOfFilesToIterateForInvalidation = 256; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; @@ -85984,11 +89131,11 @@ var ts; // The key in the map is source file's path. // The values are Map of resolutions with key being name lookedup. var resolvedModuleNames = ts.createMap(); - var perDirectoryResolvedModuleNames = ts.createMap(); - var nonRelaticeModuleNameCache = ts.createMap(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); var resolvedTypeReferenceDirectives = ts.createMap(); - var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -86012,6 +89159,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -86073,7 +89221,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -86089,15 +89237,15 @@ var ts; } }); } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { return primaryResult; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86108,10 +89256,11 @@ var ts; // Default return the result from the first pass return primaryResult; } - function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { var path = resolutionHost.toPath(containingFile); var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); var perDirectoryResolution = perDirectoryCache.get(dirPath); if (!perDirectoryResolution) { perDirectoryResolution = ts.createMap(); @@ -86120,22 +89269,28 @@ var ts; var resolvedModules = []; var compilerOptions = resolutionHost.getCompilationSettings(); var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; var seenNamesInFile = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { var name = names_2[_i]; var resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { var existingResolution = resolution; var resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { resolution = resolutionInDirectory; } else { - resolution = loader(name, containingFile, compilerOptions, resolutionHost); + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); @@ -86151,7 +89306,7 @@ var ts; } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217 + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); } // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { @@ -86179,12 +89334,14 @@ var ts; return oldResult.resolvedFileName === newResult.resolvedFileName; } } - function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { - return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, /*reusedNames*/ undefined, /*logChanges*/ false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); } function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); @@ -86227,15 +89384,10 @@ var ts; } return true; } - function filterFSRootDirectoriesToWatch(watchPath, dirPath) { - if (!canWatchDirectory(dirPath)) { - watchPath.ignore = true; - } - return watchPath; - } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86251,13 +89403,13 @@ var ts; } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // If directory path contains node module, get the most parent node_modules directory for watching - while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { + while (ts.pathContainsNodeModules(dirPath)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } // If the directory is node_modules use it to watch, always watch it recursively if (isNodeModulesDirectory(dirPath)) { - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -86275,7 +89427,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive }, dirPath); + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -86304,8 +89456,9 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, nonRecursive = _a.nonRecursive, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; // If the failed lookup location path is not one of the supported extensions, // store it in the custom path if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { @@ -86358,8 +89511,9 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { if (refCount === 1) { @@ -86407,6 +89561,22 @@ var ts; cache.delete(filePath); } } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + // If this file is input file for the referenced project, get it + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } function removeResolutionsOfFile(filePath) { removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); @@ -86468,6 +89638,9 @@ var ts; isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; } else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; // Some file or directory in the watching directory is created // Return early if it does not have any of the watching extension or not the custom failed lookup path var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); @@ -86508,8 +89681,8 @@ var ts; if (isInDirectoryPath(rootPath, typeRootPath)) { return rootPath; } - var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info @@ -86575,121 +89748,118 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +89923,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +89940,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +89961,30 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86827,20 +89993,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86855,12 +90019,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86923,13 +90089,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +90157,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,13 +90165,12 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } return false; } - /** @internal */ ts.screenStartingMessageCodes = [ ts.Diagnostics.Starting_compilation_in_watch_mode.code, ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, @@ -87028,10 +90211,27 @@ var ts; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +90247,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87066,7 +90266,7 @@ var ts; } } if (reportSummary) { - reportSummary(diagnostics.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length); + reportSummary(getErrorCountForSummary(diagnostics)); } if (emitSkipped && diagnostics.length > 0) { // If the emitter didn't emit anything, then pass that value along. @@ -87081,6 +90281,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +90312,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +90326,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87133,15 +90345,7 @@ var ts; function emitFilesAndReportErrorUsingBuilder(builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - var reportSummary = function (errorCount) { - if (errorCount === 1) { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions); - } - else { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions); - } - }; - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); } } /** @@ -87166,18 +90370,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,9 +90405,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87215,7 +90421,8 @@ var ts; fileExists: function (path) { return host.fileExists(path); }, readFile: readFile, getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); @@ -87273,7 +90480,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87282,11 +90490,11 @@ var ts; /*logChangesWhenResolvingModule*/ false); // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names compilerHost.resolveModuleNames = host.resolveModuleNames ? - (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : - (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? - (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : - (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; synchronizeProgram(); // Update the wild card directory watch @@ -87311,9 +90519,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +90546,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87460,8 +90668,8 @@ var ts; var hostSourceFile = sourceFilesCache.get(path); return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); } - function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { - var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); // If this is the source file thats in the cache and new program doesnt need it, // remove the cached entry. // Note we arent deleting entry if file became missing in new program or @@ -87475,8 +90683,10 @@ var ts; if (hostSourceFileInfo.fileWatcher) { hostSourceFileInfo.fileWatcher.close(); } - sourceFilesCache.delete(oldSourceFile.path); - resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } } } } @@ -87519,12 +90729,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87550,7 +90755,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87559,6 +90766,7 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { resolutionCache.invalidateResolutionOfFile(path); } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program scheduleProgramUpdate(); @@ -87599,6 +90807,8 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { @@ -87637,6 +90847,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +90869,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +90887,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +90958,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +90973,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,808 +90994,827 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects - }; - } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } - } - ts.performBuild = performBuild; /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +91850,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +91862,144 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +92007,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88684,7 +92036,6 @@ var ts; : undefined; } server.findArgument = findArgument; - /*@internal*/ function nowString() { // E.g. "12:34:56.789" var d = new Date(); @@ -88698,13 +92049,11 @@ var ts; (function (ts) { var JsTyping; (function (JsTyping) { - /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; - /* @internal */ JsTyping.nodeCoreModuleList = [ "assert", "async_hooks", @@ -88743,7 +92092,6 @@ var ts; "vm", "zlib" ]; - /* @internal */ JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); @@ -88776,7 +92124,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +92209,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +92247,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +92338,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89085,12 +92368,6 @@ var ts; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); /* @internal */ ts.emptyOptions = {}; - var TextChange = /** @class */ (function () { - function TextChange() { - } - return TextChange; - }()); - ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { HighlightSpanKind["none"] = "none"; @@ -89104,6 +92381,32 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + function getDefaultFormatCodeSettings(newLineCharacter) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: newLineCharacter || "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + /* @internal */ + ts.testFormatSettings = getDefaultFormatCodeSettings("\n"); var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89165,8 +92468,9 @@ var ts; TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; - TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; - TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; + TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral"; + TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral"; })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); var ScriptElementKind; (function (ScriptElementKind) { @@ -89249,6 +92553,12 @@ var ts; ScriptElementKindModifier["staticModifier"] = "static"; ScriptElementKindModifier["abstractModifier"] = "abstract"; ScriptElementKindModifier["optionalModifier"] = "optional"; + ScriptElementKindModifier["dtsModifier"] = ".d.ts"; + ScriptElementKindModifier["tsModifier"] = ".ts"; + ScriptElementKindModifier["tsxModifier"] = ".tsx"; + ScriptElementKindModifier["jsModifier"] = ".js"; + ScriptElementKindModifier["jsxModifier"] = ".jsx"; + ScriptElementKindModifier["jsonModifier"] = ".json"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); var ClassificationTypeNames; (function (ClassificationTypeNames) { @@ -89256,6 +92566,7 @@ var ts; ClassificationTypeNames["identifier"] = "identifier"; ClassificationTypeNames["keyword"] = "keyword"; ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["bigintLiteral"] = "bigint"; ClassificationTypeNames["operator"] = "operator"; ClassificationTypeNames["stringLiteral"] = "string"; ClassificationTypeNames["whiteSpace"] = "whitespace"; @@ -89302,6 +92613,7 @@ var ts; ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral"; })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); })(ts || (ts = {})); // These utilities are common to multiple language service features. @@ -89319,36 +92631,37 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 272 /* CatchClause */: - case 265 /* JsxAttribute */: + case 237 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 274 /* CatchClause */: + case 267 /* JsxAttribute */: return 1 /* Value */; - case 148 /* TypeParameter */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 166 /* TypeLiteral */: + case 150 /* TypeParameter */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 168 /* TypeLiteral */: return 2 /* Type */; - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 276 /* EnumMember */: - case 238 /* ClassDeclaration */: + case 278 /* EnumMember */: + case 240 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -89358,26 +92671,26 @@ var ts; else { return 4 /* Namespace */; } - case 241 /* EnumDeclaration */: - case 250 /* NamedImports */: - case 251 /* ImportSpecifier */: - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: - case 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 243 /* EnumDeclaration */: + case 252 /* NamedImports */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89409,11 +92722,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 146 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 246 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + var name = node.kind === 148 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 248 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 146 /* QualifiedName */) { + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -89425,27 +92738,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 146 /* QualifiedName */) { - while (root.parent && root.parent.kind === 146 /* QualifiedName */) { + if (root.parent.kind === 148 /* QualifiedName */) { + while (root.parent && root.parent.kind === 148 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 162 /* TypeReference */ && !isLastClause; + return root.parent.kind === 164 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 187 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 187 /* PropertyAccessExpression */) { + if (root.parent.kind === 189 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 189 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 209 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 271 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 211 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 273 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 238 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || - (decl.kind === 239 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); + return (decl.kind === 240 /* ClassDeclaration */ && root.parent.parent.token === 109 /* ImplementsKeyword */) || + (decl.kind === 241 /* InterfaceDeclaration */ && root.parent.parent.token === 86 /* ExtendsKeyword */); } return false; } @@ -89454,17 +92767,17 @@ var ts; node = node.parent; } switch (node.kind) { - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 176 /* ThisType */: + case 178 /* ThisType */: return true; } switch (node.parent.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return true; - case 181 /* ImportType */: + case 183 /* ImportType */: return !node.parent.isTypeOf; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; @@ -89491,7 +92804,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 231 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 233 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -89499,53 +92812,64 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { - return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; + return node.kind === 72 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; + return node.kind === 72 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; } ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; function isLabelName(node) { return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } ts.isLabelName = isLabelName; + function isTagName(node) { + return ts.isJSDocTag(node.parent) && node.parent.tagName === node; + } + ts.isTagName = isTagName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 242 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 244 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { - return node.kind === 71 /* Identifier */ && + return node.kind === 72 /* Identifier */ && ts.isFunctionLike(node.parent) && node.parent.name === node; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 273 /* PropertyAssignment */: - case 276 /* EnumMember */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 242 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 275 /* PropertyAssignment */: + case 278 /* EnumMember */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 244 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return true; - case 180 /* LiteralType */: - return node.parent.parent.kind === 178 /* IndexedAccessType */; + case 182 /* LiteralType */: + return node.parent.parent.kind === 180 /* IndexedAccessType */; default: return false; } @@ -89569,17 +92893,17 @@ var ts; return undefined; } switch (node.kind) { - case 277 /* SourceFile */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: return node; } } @@ -89587,51 +92911,54 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return "class" /* classElement */; - case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 240 /* TypeAliasDeclaration */: - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 242 /* TypeAliasDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 241 /* EnumDeclaration */: return "enum" /* enumElement */; - case 235 /* VariableDeclaration */: + case 243 /* EnumDeclaration */: return "enum" /* enumElement */; + case 237 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return "function" /* functionElement */; - case 156 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 157 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 158 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 159 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return "method" /* memberFunctionElement */; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return "property" /* memberVariableElement */; - case 160 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 159 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 158 /* CallSignature */: return "call" /* callSignatureElement */; - case 155 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 148 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 276 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 149 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 246 /* ImportEqualsDeclaration */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: - case 249 /* NamespaceImport */: + case 162 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 161 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 160 /* CallSignature */: return "call" /* callSignatureElement */; + case 157 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 150 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 278 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 151 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: + case 251 /* NamespaceImport */: return "alias" /* alias */; - case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: case 0 /* None */: return "" /* unknown */; case 1 /* ExportsProperty */: @@ -89652,7 +92979,7 @@ var ts; return "" /* unknown */; } } - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; @@ -89668,12 +92995,12 @@ var ts; ts.getNodeKind = getNodeKind; function isThis(node) { switch (node.kind) { - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: // case SyntaxKind.ThisType: TODO: GH#9267 return true; - case 71 /* Identifier */: + case 72 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 149 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 151 /* Parameter */; default: return false; } @@ -89738,42 +93065,42 @@ var ts; return false; } switch (n.kind) { - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 186 /* ObjectLiteralExpression */: - case 182 /* ObjectBindingPattern */: - case 166 /* TypeLiteral */: - case 216 /* Block */: - case 243 /* ModuleBlock */: - case 244 /* CaseBlock */: - case 250 /* NamedImports */: - case 254 /* NamedExports */: - return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile); - case 272 /* CatchClause */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 168 /* TypeLiteral */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 246 /* CaseBlock */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); + case 274 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 190 /* NewExpression */: + case 192 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 189 /* CallExpression */: - case 193 /* ParenthesizedExpression */: - case 175 /* ParenthesizedType */: - return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 191 /* CallExpression */: + case 195 /* ParenthesizedExpression */: + case 177 /* ParenthesizedType */: + return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 159 /* ConstructSignature */: - case 158 /* CallSignature */: - case 195 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 197 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -89782,66 +93109,66 @@ var ts; } // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. - return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); - case 242 /* ModuleDeclaration */: + return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); + case 244 /* ModuleDeclaration */: return !!n.body && isCompletedNode(n.body, sourceFile); - case 220 /* IfStatement */: + case 222 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile); - case 185 /* ArrayLiteralExpression */: - case 183 /* ArrayBindingPattern */: - case 188 /* ElementAccessExpression */: - case 147 /* ComputedPropertyName */: - case 168 /* TupleType */: - return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile); - case 160 /* IndexSignature */: + hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); + case 187 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 190 /* ElementAccessExpression */: + case 149 /* ComputedPropertyName */: + case 170 /* TupleType */: + return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); + case 162 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 221 /* DoStatement */: + case 223 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile) - ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile) + return hasChildOfKind(n, 107 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 197 /* TypeOfExpression */: - case 196 /* DeleteExpression */: - case 198 /* VoidExpression */: - case 205 /* YieldExpression */: - case 206 /* SpreadElement */: + case 199 /* TypeOfExpression */: + case 198 /* DeleteExpression */: + case 200 /* VoidExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 253 /* ExportDeclaration */: - case 247 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -89858,7 +93185,7 @@ var ts; if (lastChild.kind === expectedLastToken) { return true; } - else if (lastChild.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -89993,7 +93320,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +93338,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); 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, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +93347,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90084,25 +93409,25 @@ var ts; if (!token) { return false; } - if (token.kind === 10 /* JsxText */) { + if (token.kind === 11 /* JsxText */) { return true; } //
Hello |
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 10 /* JsxText */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) { return true; } //
{ |
or
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 268 /* JsxExpression */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 270 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 268 /* JsxExpression */) { + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 270 /* JsxExpression */) { return true; } //
|
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 261 /* JsxClosingElement */) { + if (token.kind === 28 /* LessThanToken */ && token.parent.kind === 263 /* JsxClosingElement */) { return true; } return false; @@ -90116,6 +93441,20 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; + function isInJSXText(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (ts.isJsxText(token)) { + return true; + } + if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + if (token.kind === 28 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) { + return true; + } + return false; + } + ts.isInJSXText = isInJSXText; function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { var tokenKind = token.kind; var remainingMatchingTokens = 0; @@ -90162,7 +93501,7 @@ var ts; var nTypeArguments = 0; while (token) { switch (token.kind) { - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // Found the beginning of the generic argument expression token = findPrecedingToken(token.getFullStart(), sourceFile); if (!token || !ts.isIdentifier(token)) @@ -90172,53 +93511,54 @@ var ts; } remainingLessThanTokens--; break; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: remainingLessThanTokens = +3; break; - case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: remainingLessThanTokens = +2; break; - case 29 /* GreaterThanToken */: + case 30 /* GreaterThanToken */: remainingLessThanTokens++; break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); + token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile); if (!token) return undefined; break; - case 20 /* CloseParenToken */: + case 21 /* CloseParenToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); + token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile); if (!token) return undefined; break; - case 22 /* CloseBracketToken */: + case 23 /* CloseBracketToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token - token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); + token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile); if (!token) return undefined; break; // Valid tokens in a type name. Skip. - case 26 /* CommaToken */: + case 27 /* CommaToken */: nTypeArguments++; break; - case 36 /* EqualsGreaterThanToken */: - case 71 /* Identifier */: - case 9 /* StringLiteral */: + case 37 /* EqualsGreaterThanToken */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 103 /* TypeOfKeyword */: - case 85 /* ExtendsKeyword */: - case 128 /* KeyOfKeyword */: - case 23 /* DotToken */: - case 49 /* BarToken */: - case 55 /* QuestionToken */: - case 56 /* ColonToken */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 104 /* TypeOfKeyword */: + case 86 /* ExtendsKeyword */: + case 129 /* KeyOfKeyword */: + case 24 /* DotToken */: + case 50 /* BarToken */: + case 56 /* QuestionToken */: + case 57 /* ColonToken */: break; default: if (ts.isTypeNode(token)) { @@ -90250,7 +93590,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90273,10 +93613,10 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 162 /* TypeReference */ || node.kind === 189 /* CallExpression */) { + if (node.kind === 164 /* TypeReference */ || node.kind === 191 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 238 /* ClassDeclaration */ || node.kind === 239 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 240 /* ClassDeclaration */ || node.kind === 241 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -90287,8 +93627,8 @@ var ts; } ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { - if (kind === 9 /* StringLiteral */ - || kind === 12 /* RegularExpressionLiteral */ + if (kind === 10 /* StringLiteral */ + || kind === 13 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; } @@ -90296,7 +93636,7 @@ var ts; } ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; function isPunctuation(kind) { - return 17 /* FirstPunctuation */ <= kind && kind <= 70 /* LastPunctuation */; + return 18 /* FirstPunctuation */ <= kind && kind <= 71 /* LastPunctuation */; } ts.isPunctuation = isPunctuation; function isInsideTemplateLiteral(node, position, sourceFile) { @@ -90306,9 +93646,9 @@ var ts; ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: return true; } return false; @@ -90321,18 +93661,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 185 /* ArrayLiteralExpression */ || - node.kind === 186 /* ObjectLiteralExpression */) { + if (node.kind === 187 /* ArrayLiteralExpression */ || + node.kind === 188 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 202 /* BinaryExpression */ && + if (node.parent.kind === 204 /* BinaryExpression */ && node.parent.left === node && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { + node.parent.operatorToken.kind === 59 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 225 /* ForOfStatement */ && + if (node.parent.kind === 227 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -90340,7 +93680,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 273 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 275 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -90364,7 +93704,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +93712,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90384,21 +93724,22 @@ var ts; } ts.createTextChange = createTextChange; ts.typeKeywords = [ - 119 /* AnyKeyword */, - 122 /* BooleanKeyword */, - 86 /* FalseKeyword */, - 128 /* KeyOfKeyword */, - 131 /* NeverKeyword */, - 95 /* NullKeyword */, - 134 /* NumberKeyword */, - 135 /* ObjectKeyword */, - 137 /* StringKeyword */, - 138 /* SymbolKeyword */, - 101 /* TrueKeyword */, - 105 /* VoidKeyword */, - 140 /* UndefinedKeyword */, - 141 /* UniqueKeyword */, - 142 /* UnknownKeyword */, + 120 /* AnyKeyword */, + 146 /* BigIntKeyword */, + 123 /* BooleanKeyword */, + 87 /* FalseKeyword */, + 129 /* KeyOfKeyword */, + 132 /* NeverKeyword */, + 96 /* NullKeyword */, + 135 /* NumberKeyword */, + 136 /* ObjectKeyword */, + 138 /* StringKeyword */, + 139 /* SymbolKeyword */, + 102 /* TrueKeyword */, + 106 /* VoidKeyword */, + 141 /* UndefinedKeyword */, + 142 /* UniqueKeyword */, + 143 /* UnknownKeyword */, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); @@ -90434,7 +93775,7 @@ var ts; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { - return name.kind === 147 /* ComputedPropertyName */ + return name.kind === 149 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.getTextOfIdentifierOrLiteral(name); @@ -90510,19 +93851,20 @@ var ts; } return ts.firstDefined(symbol.declarations, function (decl) { var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined; + return name && name.kind === 72 /* Identifier */ ? name.escapedText : undefined; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { - // See GH#16922 - ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); - return propSymbol.target; - } - return propSymbol; + return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; /** @@ -90575,7 +93917,6 @@ var ts; return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); } ts.findModifier = findModifier; - /* @internal */ function insertImport(changes, sourceFile, importDecl) { var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); if (lastImportDeclaration) { @@ -90599,7 +93940,7 @@ var ts; /* @internal */ (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 149 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 151 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -90625,6 +93966,7 @@ var ts; writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, @@ -90633,7 +93975,7 @@ var ts; writeSymbol: writeSymbol, writeLine: writeLine, write: unknownWrite, - writeTextOfNode: unknownWrite, + writeComment: unknownWrite, getText: function () { return ""; }, getTextPos: function () { return 0; }, getColumn: function () { return 0; }, @@ -90784,7 +94126,6 @@ var ts; return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; - /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -90818,9 +94159,7 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { - return !!location.parent && - (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && - location.parent.propertyName === location; + return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; /** @@ -90866,6 +94205,13 @@ var ts; return position; } ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; + function getPrecedingNonSpaceCharacterPosition(text, position) { + while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) { + position -= 1; + } + return position + 1; + } + ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition; /** * Creates a deep, memberwise clone of a node with no source map location. * @@ -90883,7 +94229,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +94237,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -90906,14 +94252,14 @@ var ts; ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_7 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_7)) { - clone_7.textSourceNode = node; + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_7)) { - clone_7.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_7, node); + return ts.setTextRange(clone_8, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -90932,7 +94278,6 @@ var ts; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - /* @internal */ function suppressLeadingAndTrailingTrivia(node) { suppressLeadingTrivia(node); suppressTrailingTrivia(node); @@ -90941,7 +94286,6 @@ var ts; /** * Sets EmitFlags to suppress leading trivia on the node. */ - /* @internal */ function suppressLeadingTrivia(node) { addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); } @@ -90949,7 +94293,6 @@ var ts; /** * Sets EmitFlags to suppress trailing trivia on the node. */ - /* @internal */ function suppressTrailingTrivia(node) { addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } @@ -90963,7 +94306,6 @@ var ts; function getFirstChild(node) { return node.forEachChild(function (child) { return child; }); } - /* @internal */ function getUniqueName(baseName, sourceFile) { var nameText = baseName; for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { @@ -90977,7 +94319,6 @@ var ts; * to be on the reference, rather than the declaration, because it's closer to where the * user was before extracting it. */ - /* @internal */ function getRenameLocation(edits, renameFilename, name, preferLastLocation) { var delta = 0; var lastPos = -1; @@ -91031,6 +94372,72 @@ var ts; idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 192 /* NewExpression */: + return checker.getContextualType(parent); + case 204 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 271 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + ts.getContextualTypeFromParent = getContextualTypeFromParent; + function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } + } + ts.quote = quote; + function isEqualityOperatorKind(kind) { + switch (kind) { + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + return true; + default: + return false; + } + } + ts.isEqualityOperatorKind = isEqualityOperatorKind; + function isStringLiteralOrTemplate(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + return true; + default: + return false; + } + } + ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate; + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + ts.hasIndexSignature = hasIndexSignature; + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } + ts.getSwitchedType = getSwitchedType; })(ts || (ts = {})); var ts; (function (ts) { @@ -91069,7 +94476,7 @@ var ts; text = prefix + text; var offset = prefix.length; if (pushTemplate) { - templateStack.push(14 /* TemplateHead */); + templateStack.push(15 /* TemplateHead */); } scanner.setText(text); var endOfLineState = 0 /* None */; @@ -91111,65 +94518,65 @@ var ts; } while (token !== 1 /* EndOfFileToken */); function handleToken() { switch (token) { - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 12 /* RegularExpressionLiteral */) { - token = 12 /* RegularExpressionLiteral */; + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) { + token = 13 /* RegularExpressionLiteral */; } break; - case 27 /* LessThanToken */: - if (lastNonTriviaToken === 71 /* Identifier */) { + case 28 /* LessThanToken */: + if (lastNonTriviaToken === 72 /* Identifier */) { // Could be the start of something generic. Keep track of that by bumping // up the current count of generic contexts we may be in. angleBracketStack++; } break; - case 29 /* GreaterThanToken */: + case 30 /* GreaterThanToken */: if (angleBracketStack > 0) { // If we think we're currently in something generic, then mark that that // generic entity is complete. angleBracketStack--; } break; - case 119 /* AnyKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: + case 120 /* AnyKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* 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, // causing a noisy experience for the user. - token = 71 /* Identifier */; + token = 72 /* Identifier */; } break; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: templateStack.push(token); break; - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { templateStack.push(token); } break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 14 /* TemplateHead */) { + if (lastTemplateStackToken === 15 /* TemplateHead */) { token = scanner.reScanTemplateToken(); // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. - if (token === 16 /* TemplateTail */) { + if (token === 17 /* TemplateTail */) { templateStack.pop(); } else { - ts.Debug.assertEqual(token, 15 /* TemplateMiddle */, "Should have been a template middle."); + ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle."); } } else { - ts.Debug.assertEqual(lastTemplateStackToken, 17 /* OpenBraceToken */, "Should have been an open brace"); + ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace"); templateStack.pop(); } } @@ -91178,15 +94585,15 @@ var ts; if (!ts.isKeyword(token)) { break; } - if (lastNonTriviaToken === 23 /* DotToken */) { - token = 71 /* Identifier */; + if (lastNonTriviaToken === 24 /* DotToken */) { + token = 72 /* Identifier */; } else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { // We have two keywords in a row. Only treat the second as a keyword if // it's a sequence that could legally occur in the language. Otherwise // treat it as an identifier. This way, if someone writes "private var" // we recognize that 'var' is actually an identifier here. - token = 71 /* Identifier */; + token = 72 /* Identifier */; } } } @@ -91200,22 +94607,23 @@ var ts; /// we have a series of divide operator. this list allows us to be more accurate by ruling out /// locations where a regexp cannot exist. var noRegexTable = ts.arrayToNumericMap([ - 71 /* Identifier */, - 9 /* StringLiteral */, + 72 /* Identifier */, + 10 /* StringLiteral */, 8 /* NumericLiteral */, - 12 /* RegularExpressionLiteral */, - 99 /* ThisKeyword */, - 43 /* PlusPlusToken */, - 44 /* MinusMinusToken */, - 20 /* CloseParenToken */, - 22 /* CloseBracketToken */, - 18 /* CloseBraceToken */, - 101 /* TrueKeyword */, - 86 /* FalseKeyword */, + 9 /* BigIntLiteral */, + 13 /* RegularExpressionLiteral */, + 100 /* ThisKeyword */, + 44 /* PlusPlusToken */, + 45 /* MinusMinusToken */, + 21 /* CloseParenToken */, + 23 /* CloseBracketToken */, + 19 /* CloseBraceToken */, + 102 /* TrueKeyword */, + 87 /* FalseKeyword */, ], function (token) { return token; }, function () { return true; }); function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { switch (token) { - case 9 /* StringLiteral */: { + case 10 /* StringLiteral */: { // Check to see if we finished up on a multiline string literal. if (!scanner.isUnterminated()) return undefined; @@ -91239,15 +94647,15 @@ var ts; return undefined; } switch (token) { - case 16 /* TemplateTail */: + case 17 /* TemplateTail */: return 5 /* InTemplateMiddleOrTail */; - case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; default: return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } - return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; } } function pushEncodedClassification(start, end, offset, classification, result) { @@ -91273,7 +94681,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +94690,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -91296,6 +94704,7 @@ var ts; case 1 /* comment */: return ts.TokenClass.Comment; case 3 /* keyword */: return ts.TokenClass.Keyword; case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral; case 5 /* operator */: return ts.TokenClass.Operator; case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; @@ -91322,10 +94731,10 @@ var ts; return true; } switch (keyword2) { - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 123 /* ConstructorKeyword */: - case 115 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 124 /* ConstructorKeyword */: + case 116 /* StaticKeyword */: return true; // Allow things like "public get", "public constructor" and "public static". default: return false; // Any other keyword following "public" is actually an identifier, not a real keyword. @@ -91358,43 +94767,43 @@ var ts; } function isBinaryExpressionOperatorToken(token) { switch (token) { - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 48 /* AmpersandToken */: - case 50 /* CaretToken */: - case 49 /* BarToken */: - case 53 /* AmpersandAmpersandToken */: - case 54 /* BarBarToken */: - case 69 /* BarEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 58 /* EqualsToken */: - case 26 /* CommaToken */: + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 49 /* AmpersandToken */: + case 51 /* CaretToken */: + case 50 /* BarToken */: + case 54 /* AmpersandAmpersandToken */: + case 55 /* BarBarToken */: + case 70 /* BarEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 59 /* EqualsToken */: + case 27 /* CommaToken */: return true; default: return false; @@ -91402,12 +94811,12 @@ var ts; } function isPrefixUnaryExpressionOperatorToken(token) { switch (token) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: return true; default: return false; @@ -91420,15 +94829,17 @@ var ts; else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { return 5 /* operator */; } - else if (token >= 17 /* FirstPunctuation */ && token <= 70 /* LastPunctuation */) { + else if (token >= 18 /* FirstPunctuation */ && token <= 71 /* LastPunctuation */) { return 10 /* punctuation */; } switch (token) { case 8 /* NumericLiteral */: return 4 /* numericLiteral */; - case 9 /* StringLiteral */: + case 9 /* BigIntLiteral */: + return 25 /* bigintLiteral */; + case 10 /* StringLiteral */: return 6 /* stringLiteral */; - case 12 /* RegularExpressionLiteral */: + case 13 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; case 7 /* ConflictMarkerTrivia */: case 3 /* MultiLineCommentTrivia */: @@ -91437,7 +94848,7 @@ var ts; case 5 /* WhitespaceTrivia */: case 4 /* NewLineTrivia */: return 8 /* whiteSpace */; - case 71 /* Identifier */: + case 72 /* Identifier */: default: if (ts.isTemplateLiteralKind(token)) { return 6 /* stringLiteral */; @@ -91462,10 +94873,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 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -91540,6 +94951,7 @@ var ts; case 2 /* identifier */: return "identifier" /* identifier */; case 3 /* keyword */: return "keyword" /* keyword */; case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */; case 5 /* operator */: return "operator" /* operator */; case 6 /* stringLiteral */: return "string" /* stringLiteral */; case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; @@ -91673,22 +95085,22 @@ var ts; if (tag.pos !== pos) { pushCommentRange(pos, tag.pos - pos); } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); // "@" + pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 297 /* JSDocParameterTag */: + case 299 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; break; - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; break; - case 298 /* JSDocReturnTag */: + case 300 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; break; @@ -91759,10 +95171,10 @@ var ts; return true; } var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 10 /* JsxText */ && classifiedElementName === undefined) { + if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) { return false; } - var tokenStart = node.kind === 10 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { @@ -91775,22 +95187,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -91807,7 +95219,7 @@ var ts; } // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. - if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { + if (tokenKind === 28 /* LessThanToken */ || tokenKind === 30 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { @@ -91817,19 +95229,19 @@ var ts; if (ts.isPunctuation(tokenKind)) { if (token) { var parent = token.parent; - if (tokenKind === 58 /* EqualsToken */) { + if (tokenKind === 59 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (parent.kind === 235 /* VariableDeclaration */ || - parent.kind === 152 /* PropertyDeclaration */ || - parent.kind === 149 /* Parameter */ || - parent.kind === 265 /* JsxAttribute */) { + if (parent.kind === 237 /* VariableDeclaration */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 151 /* Parameter */ || + parent.kind === 267 /* JsxAttribute */) { return 5 /* operator */; } } - if (parent.kind === 202 /* BinaryExpression */ || - parent.kind === 200 /* PrefixUnaryExpression */ || - parent.kind === 201 /* PostfixUnaryExpression */ || - parent.kind === 203 /* ConditionalExpression */) { + if (parent.kind === 204 /* BinaryExpression */ || + parent.kind === 202 /* PrefixUnaryExpression */ || + parent.kind === 203 /* PostfixUnaryExpression */ || + parent.kind === 205 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -91838,11 +95250,14 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 265 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + else if (tokenKind === 9 /* BigIntLiteral */) { + return 25 /* bigintLiteral */; } - else if (tokenKind === 12 /* RegularExpressionLiteral */) { + else if (tokenKind === 10 /* StringLiteral */) { + // TODO: GH#18217 + return token.parent.kind === 267 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + } + else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */; } @@ -91850,38 +95265,38 @@ var ts; // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } - else if (tokenKind === 10 /* JsxText */) { + else if (tokenKind === 11 /* JsxText */) { return 23 /* jsxText */; } - else if (tokenKind === 71 /* Identifier */) { + else if (tokenKind === 72 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 149 /* Parameter */: + case 151 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -91915,37 +95330,245 @@ var ts; (function (ts) { var Completions; (function (Completions) { - var PathCompletions; - (function (PathCompletions) { - function nameAndKind(name, kind) { - return { name: name, kind: kind }; + var StringCompletions; + (function (StringCompletions) { + function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + if (ts.isInReferenceComment(sourceFile, position)) { + var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host), sourceFile, checker, log, preferences); + } + } + StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + if (completion === undefined) { + return undefined; + } + switch (completion.kind) { + case 0 /* Paths */: + return convertPathCompletions(completion.paths); + case 1 /* Properties */: { + var entries = []; + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; + } + case 2 /* Types */: { + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; + } + default: + return ts.Debug.assertNever(completion); + } + } + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + if (!contextToken || !ts.isStringLiteralLike(contextToken)) + return undefined; + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); + } + StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function convertPathCompletions(pathCompletions) { + var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. + var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. + var entries = pathCompletions.map(function (_a) { + var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension; + return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span }); + }); + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function kindModifiersFromExtension(extension) { + switch (extension) { + case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */; + case ".js" /* Js */: return ".js" /* jsModifier */; + case ".json" /* Json */: return ".json" /* jsonModifier */; + case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */; + case ".ts" /* Ts */: return ".ts" /* tsModifier */; + case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */; + case undefined: return "" /* none */; + default: + return ts.Debug.assertNever(extension); + } + } + var StringLiteralCompletionKind; + (function (StringLiteralCompletionKind) { + StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; + StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; + })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + var parent = node.parent; + switch (parent.kind) { + case 182 /* LiteralType */: + switch (parent.parent.kind) { + case 164 /* TypeReference */: + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; + case 180 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); + case 183 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 173 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } + default: + return undefined; + } + case 275 /* PropertyAssignment */: + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); + } + return fromContextualType(); + case 190 /* ElementAccessExpression */: { + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return undefined; + } + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through (is `require("")` or `import("")`) + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 259 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + default: + return fromContextualType(); + } + function fromContextualType() { + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; + } + } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } + function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { + var isNewIdentifier = false; + var uniques = ts.createMap(); + var candidates = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + var types = ts.flatMap(candidates, function (candidate) { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + return; + var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); + return getStringLiteralTypes(type, uniques); + }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; + } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: ts.hasIndexSignature(type) }; + } + function getStringLiteralTypes(type, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } + if (!type) + return ts.emptyArray; + type = ts.skipConstraint(type); + return type.isUnion() + ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) + : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) + ? [type] + : ts.emptyArray; + } + function nameAndKind(name, kind, extension) { + return { name: name, kind: kind, extension: extension }; + } + function directoryResult(name) { + return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined); } function addReplacementSpans(text, textStart, names) { var span = getDirectoryFragmentTextSpan(text, textStart); return names.map(function (_a) { - var name = _a.name, kind = _a.kind; - return ({ name: name, kind: kind, span: span }); + var name = _a.name, kind = _a.kind, extension = _a.extension; + return ({ name: name, kind: kind, extension: extension, span: span }); }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); } - PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { - var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); - if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); - } - else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); - } + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + } + function getExtensionOptions(compilerOptions, includeExtensions) { + if (includeExtensions === void 0) { includeExtensions = false; } + return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; + } + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { + var extensionOptions = getExtensionOptions(compilerOptions); + if (compilerOptions.rootDirs) { + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); } } function getSupportedExtensionsForModuleResolution(compilerOptions) { @@ -91958,31 +95581,27 @@ var ts; * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option */ - function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { // Make all paths absolute/normalized if they are not already rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { - return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; + return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined; }); // TODO: GH#18217 // Now find a path for each potential directory that is to be merged with the one containing the script - return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); - var result = []; - for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { - var baseDirectory = baseDirectories_1[_i]; - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); - } - return result; + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); + return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); } /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) { + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { + var extensions = _a.extensions, includeExtensions = _a.includeExtensions; if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; @@ -92003,46 +95622,77 @@ var ts; var absolutePath = ts.resolvePath(scriptPath, fragment); var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - if (tryDirectoryExists(host, baseDirectory)) { - // Enumerate the available files if possible - var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); - if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - var foundFiles = ts.createMap(); - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var filePath = files_3[_i]; - filePath = ts.normalizePath(filePath); - if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { - continue; - } - var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.has(foundFileName)) { - foundFiles.set(foundFileName, true); - } + if (!tryDirectoryExists(host, baseDirectory)) + return result; + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ + var foundFiles = ts.createMap(); // maps file to its extension + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { + continue; } - ts.forEachKey(foundFiles, function (foundFile) { - result.push(nameAndKind(foundFile, "script" /* scriptElement */)); - }); + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); } - // If possible, get folder completion as well - var directories = tryGetDirectories(host, baseDirectory); - if (directories) { - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var directory = directories_1[_a]; - var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - if (directoryName !== "@types") { - result.push(nameAndKind(directoryName, "directory" /* directory */)); - } + foundFiles.forEach(function (ext, foundFile) { + result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext)); + }); + } + // If possible, get folder completion as well + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var directory = directories_1[_b]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + if (directoryName !== "@types") { + result.push(directoryResult(directoryName)); + } + } + } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); } } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind, extension) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind, extension)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; + _loop_10(name, kind, extension); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92053,60 +95703,51 @@ var ts; function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; - var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); + var extensionOptions = getExtensionOptions(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); } } - var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; - result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); + var fragmentDirectory = getFragmentDirectory(fragment); + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; + result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined)); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_11 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; - result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); } } if (!foundGlobal) { ts.forEachAncestorDirectory(scriptPath, function (ancestor) { var nodeModules = ts.combinePaths(ancestor, "node_modules"); if (tryDirectoryExists(host, nodeModules)) { - getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result); } }); } } return result; } + function getFragmentDirectory(fragment) { + return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + } function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. @@ -92118,7 +95759,7 @@ var ts; return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); function justPathMappingName(name) { - return ts.startsWith(name, fragment) ? [{ name: name, kind: "directory" /* directory */ }] : ts.emptyArray; + return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; } } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { @@ -92146,15 +95787,20 @@ var ts; // that encodes the suffix, but we would have to escape the character "?" which readDirectory // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]).map(function (name) { return ({ name: name, kind: "script" /* scriptElement */ }); }); - var directories = tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }).map(function (name) { return ({ name: name, kind: "directory" /* directory */ }); }); - // Trim away prefix and suffix - return ts.mapDefined(ts.concatenate(matches, directories), function (_a) { - var name = _a.name, kind = _a.kind; - var normalizedMatch = ts.normalizePath(name); - var inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix); - return inner !== undefined ? { name: removeLeadingDirectorySeparator(ts.removeFileExtension(inner)), kind: kind } : undefined; + var matches = ts.mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var extension = ts.tryGetExtensionFromPath(match); + var name = trimPrefixAndSuffix(match); + return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension); }); + var directories = ts.mapDefined(tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { + var name = trimPrefixAndSuffix(dir); + return name === undefined ? undefined : directoryResult(name); + }); + return matches.concat(directories); + function trimPrefixAndSuffix(path) { + var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); + return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner); + } } function withoutStartAndEnd(s, start, end) { return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; @@ -92189,62 +95835,48 @@ var ts; } var prefix = match[1], kind = match[2], toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) - : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) - : undefined; - return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) + : ts.Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, names); } - PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; - function getCompletionEntriesFromTypings(host, options, scriptPath, result) { + function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options var seen = ts.createMap(); - if (options.types) { - for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); - pushResult(moduleName); - } + var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; + for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) { + var root = typeRoots_2[_i]; + getCompletionEntriesFromDirectories(root); } - else if (host.getDirectories) { - var typeRoots = void 0; - try { - typeRoots = ts.getEffectiveTypeRoots(options, host); - } - catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ } - if (typeRoots) { - for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { - var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(root); - } - } - // Also get all @types typings installed in visible node_modules directories - for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { - var packageJson = _e[_d]; - var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(typesDir); - } + // Also get all @types typings installed in visible node_modules directories + for (var _a = 0, _b = findPackageJsons(scriptPath, host); _a < _b.length; _a++) { + var packageJson = _b[_a]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); } return result; function getCompletionEntriesFromDirectories(directory) { - ts.Debug.assert(!!host.getDirectories); - if (tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); - pushResult(moduleName); + if (!tryDirectoryExists(host, directory)) + return; + for (var _i = 0, _a = tryGetDirectories(host, directory); _i < _a.length; _i++) { + var typeDirectoryName = _a[_i]; + var packageName = ts.unmangleScopedPackageName(typeDirectoryName); + if (options.types && !ts.contains(options.types, packageName)) + continue; + if (fragmentDirectory === undefined) { + if (!seen.has(packageName)) { + result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined)); + seen.set(packageName, true); + } + } + else { + var baseDirectory = ts.combinePaths(directory, typeDirectoryName); + var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host)); + if (remainingFragment !== undefined) { + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result); } } - } - } - function pushResult(moduleName) { - if (!seen.has(moduleName)) { - result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); - seen.set(moduleName, true); } } } @@ -92259,6 +95891,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92322,27 +95966,27 @@ var ts; return tryIOAndConsumeErrors(host, host.fileExists, path); } function tryDirectoryExists(host, path) { - try { - return ts.directoryProbablyExists(path, host); - } - catch ( /*ignore*/_a) { /*ignore*/ } - return false; + return tryAndIgnoreErrors(function () { return ts.directoryProbablyExists(path, host); }) || false; } function tryIOAndConsumeErrors(host, toApply) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } + return tryAndIgnoreErrors(function () { return toApply && toApply.apply(host, args); }); + } + function tryAndIgnoreErrors(cb) { try { - return toApply && toApply.apply(host, args); + return cb(); + } + catch (_a) { + return undefined; } - catch ( /*ignore*/_a) { /*ignore*/ } - return undefined; } function containsSlash(fragment) { return ts.stringContains(fragment, ts.directorySeparator); } - })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); + })(StringCompletions = Completions.StringCompletions || (Completions.StringCompletions = {})); })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -92366,11 +96010,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92381,20 +96026,15 @@ var ts; function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); - if (ts.isInReferenceComment(sourceFile, position)) { - var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries && convertPathCompletions(entries); - } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; - if (ts.isInString(sourceFile, position, contextToken)) { - return !contextToken || !ts.isStringLiteralLike(contextToken) - ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); + var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); + if (stringCompletions) { + return stringCompletions; } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) - && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { + && (contextToken.kind === 73 /* BreakKeyword */ || contextToken.kind === 78 /* ContinueKeyword */ || contextToken.kind === 72 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined); @@ -92417,35 +96057,6 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { - if (completion === undefined) { - return undefined; - } - switch (completion.kind) { - case 0 /* Paths */: - return convertPathCompletions(completion.paths); - case 1 /* Properties */: { - var entries = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; - } - case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; - } - default: - return ts.Debug.assertNever(completion); - } - } - function convertPathCompletions(pathCompletions) { - var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. - var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. - var entries = pathCompletions.map(function (_a) { - var name = _a.name, kind = _a.kind, span = _a.span; - return ({ name: name, kind: kind, kindModifiers: "" /* none */, sortText: "0", replacementSpan: span }); - }); - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - } function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } @@ -92459,7 +96070,7 @@ var ts; // The completion list at "1" will contain "div>" with type any // And at `
` (with a closing `>`), the completion list will contain "div". var tagName = location.parent.parent.openingElement.tagName; - var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile); + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 30 /* GreaterThanToken */, sourceFile); var entry = { name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), kind: "class" /* classElement */, @@ -92471,7 +96082,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +96090,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +96118,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92523,7 +96135,9 @@ var ts; } }); } - var completionNameForLiteral = JSON.stringify; + var completionNameForLiteral = function (literal) { + return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); + }; function createCompletionEntryForLiteral(literal) { return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" }; } @@ -92536,13 +96150,13 @@ var ts; var insertText; var replacementSpan; if (origin && origin.kind === 0 /* ThisType */) { - insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; + insertText = needsConvertPropertyAccess ? "this[" + ts.quote(name, preferences) + "]" : "this." + name; } // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { - insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]"; - var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); + insertText = needsConvertPropertyAccess ? "[" + ts.quote(name, preferences) + "]" : "[" + name + "]"; + var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); @@ -92577,18 +96191,6 @@ var ts; replacementSpan: replacementSpan, }; } - function quote(text, preferences) { - var quoted = JSON.stringify(text); - switch (preferences.quotePreference) { - case undefined: - case "double": - return quoted; - case "single": - return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; - default: - return ts.Debug.assertNever(preferences.quotePreference); - } - } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; @@ -92626,6 +96228,7 @@ var ts; log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniques; } + Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { var entries = getLabelStatementCompletions(node); if (entries.length) { @@ -92656,120 +96259,6 @@ var ts; } return entries; } - var StringLiteralCompletionKind; - (function (StringLiteralCompletionKind) { - StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths"; - StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; - StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; - })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); - function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { - case 180 /* LiteralType */: - switch (node.parent.parent.kind) { - case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; - case 178 /* IndexedAccessType */: - // Get all apparent property names - // i.e. interface Foo { - // foo: string; - // bar: string; - // } - // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); - case 181 /* ImportType */: - return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; - default: - return undefined; - } - case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); - } - return fromContextualType(); - case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; - if (node === argumentExpression) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); - } - return undefined; - } - case 189 /* CallExpression */: - case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { - var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); - } - // falls through (is `require("")` or `import("")`) - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 257 /* ExternalModuleReference */: - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - default: - return fromContextualType(); - } - function fromContextualType() { - // Get completion for string literal from string literal type - // i.e. var x: "hi" | "hello" = "/*completion position*/" - return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; - } - } - function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { - var isNewIdentifier = false; - var uniques = ts.createMap(); - var candidates = []; - checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); - var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) - return; - var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); - isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); - return getStringLiteralTypes(type, uniques); - }); - return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; - } - function stringLiteralCompletionsFromProperties(type) { - return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; - } - function getStringLiteralTypes(type, uniques) { - if (uniques === void 0) { uniques = ts.createMap(); } - if (!type) - return ts.emptyArray; - type = ts.skipConstraint(type); - return type.isUnion() - ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) - : type.isStringLiteral() && !(type.flags & 512 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) - ? [type] - : ts.emptyArray; - } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { var compilerOptions = program.getCompilerOptions(); var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); @@ -92808,10 +96297,7 @@ var ts; var name = entryId.name; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { - var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) - ? undefined - : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); - return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); @@ -92855,25 +96341,11 @@ var ts; }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } - function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { - switch (completion.kind) { - case 0 /* Paths */: { - var match = ts.find(completion.paths, function (p) { return p.name === name; }); - return match && createCompletionDetails(name, "" /* none */, match.kind, [ts.textPart(name)]); - } - case 1 /* Properties */: { - var match = ts.find(completion.symbols, function (s) { return s.name === name; }); - return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); - } - case 2 /* Types */: - return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; - default: - return ts.Debug.assertNever(completion); - } - } + Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; } + Completions.createCompletionDetails = createCompletionDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { @@ -92904,7 +96376,7 @@ var ts; CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; CompletionKind[CompletionKind["String"] = 4] = "String"; CompletionKind[CompletionKind["None"] = 5] = "None"; - })(CompletionKind || (CompletionKind = {})); + })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {})); function getRecommendedCompletion(previousToken, contextualType, checker) { // For a union, return the first one with a recommended completion. return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { @@ -92918,56 +96390,36 @@ var ts; function getContextualType(previousToken, position, sourceFile, checker) { var parent = previousToken.parent; switch (previousToken.kind) { - case 71 /* Identifier */: - return getContextualTypeFromParent(previousToken, checker); - case 58 /* EqualsToken */: + case 72 /* Identifier */: + return ts.getContextualTypeFromParent(previousToken, checker); + case 59 /* EqualsToken */: switch (parent.kind) { - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return checker.getContextualType(parent.initializer); // TODO: GH#18217 - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; } - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: return checker.getContextualType(parent); - case 73 /* CaseKeyword */: - return getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); - case 17 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 258 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + case 74 /* CaseKeyword */: + return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); + case 18 /* OpenBraceToken */: + return ts.isJsxExpression(parent) && parent.parent.kind !== 260 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo // At `,`, treat this as the next argument after the comma. - ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 26 /* CommaToken */ ? 1 : 0)) - : isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) + : ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) // completion at `x ===/**/` should be for the right side ? checker.getTypeAtLocation(parent.left) : checker.getContextualType(previousToken); } } - function getContextualTypeFromParent(node, checker) { - var parent = node.parent; - switch (parent.kind) { - case 190 /* NewExpression */: - return checker.getContextualType(parent); - case 202 /* BinaryExpression */: { - var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; - return isEqualityOperatorKind(operatorToken.kind) - ? checker.getTypeAtLocation(node === right ? left : right) - : checker.getContextualType(node); - } - case 269 /* CaseClause */: - return parent.expression === node ? getSwitchedType(parent, checker) : undefined; - default: - return checker.getContextualType(node); - } - } - function getSwitchedType(caseClause, checker) { - return checker.getTypeAtLocation(caseClause.parent.parent.expression); - } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); if (chain) @@ -92975,7 +96427,7 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 277 /* SourceFile */; }); + return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; }); } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { var typeChecker = program.getTypeChecker(); @@ -93026,11 +96478,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 281 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 303 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -93056,9 +96508,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.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { - var start_4 = ts.timestamp(); + var start_3 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 - log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -93077,21 +96529,21 @@ var ts; return undefined; } var parent = contextToken.parent; - if (contextToken.kind === 23 /* DotToken */) { + if (contextToken.kind === 24 /* DotToken */) { isRightOfDot = true; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; break; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: node = parent.left; break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: node = parent.name; break; - case 181 /* ImportType */: - case 212 /* MetaProperty */: + case 183 /* ImportType */: + case 214 /* MetaProperty */: node = parent; break; default: @@ -93104,53 +96556,56 @@ var ts; // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 187 /* PropertyAccessExpression */) { + if (parent && parent.kind === 189 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } // Fix location if (currentToken.parent === location) { switch (currentToken.kind) { - case 29 /* GreaterThanToken */: - if (currentToken.parent.kind === 258 /* JsxElement */ || currentToken.parent.kind === 260 /* JsxOpeningElement */) { + case 30 /* GreaterThanToken */: + if (currentToken.parent.kind === 260 /* JsxElement */ || currentToken.parent.kind === 262 /* JsxOpeningElement */) { location = currentToken; } break; - case 41 /* SlashToken */: - if (currentToken.parent.kind === 259 /* JsxSelfClosingElement */) { + case 42 /* SlashToken */: + if (currentToken.parent.kind === 261 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 261 /* JsxClosingElement */: - if (contextToken.kind === 41 /* SlashToken */) { + case 263 /* JsxClosingElement */: + if (contextToken.kind === 42 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 259 /* JsxSelfClosingElement */: - case 258 /* JsxElement */: - case 260 /* JsxOpeningElement */: - if (contextToken.kind === 27 /* LessThanToken */) { + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: + case 262 /* JsxOpeningElement */: + if (contextToken.kind === 28 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: switch (previousToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: isJsxInitializer = true; break; - case 71 /* Identifier */: + case 72 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 59 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +96627,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +96636,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93196,11 +96653,11 @@ var ts; return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: - case 298 /* JSDocReturnTag */: - case 300 /* JSDocTypeTag */: - case 302 /* JSDocTypedefTag */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 304 /* JSDocTypedefTag */: return true; default: return false; @@ -93240,15 +96697,15 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 277 /* SourceFile */ && d.kind !== 242 /* ModuleDeclaration */ && d.kind !== 241 /* EnumDeclaration */; })) { + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; } } } - if (ts.isMetaProperty(node) && (node.keywordToken === 94 /* NewKeyword */ || node.keywordToken === 91 /* ImportKeyword */)) { - var completion = (node.keywordToken === 94 /* NewKeyword */) ? "target" : "meta"; + if (ts.isMetaProperty(node) && (node.keywordToken === 95 /* NewKeyword */ || node.keywordToken === 92 /* ImportKeyword */)) { + var completion = (node.keywordToken === 95 /* NewKeyword */) ? "target" : "meta"; symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); return; } @@ -93269,7 +96726,7 @@ var ts; else { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 181 /* ImportType */ ? node : node.parent, type, symbol)) { + if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 183 /* ImportType */ ? node : node.parent, type, symbol)) { addPropertySymbol(symbol); } } @@ -93317,24 +96774,22 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { var jsxContainer = tryGetContainingJsxElement(contextToken); // Cursor is inside a JSX self-closing element or opening element - var attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); if (!attrsType) return 0 /* Continue */; - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties); completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,10 +96826,11 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var isTypeOnly = isTypeOnlyCompletion(); + var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode); if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { @@ -93399,31 +96855,31 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 277 /* SourceFile */: - case 204 /* TemplateExpression */: - case 268 /* JsxExpression */: - case 216 /* Block */: + case 279 /* SourceFile */: + case 206 /* TemplateExpression */: + case 270 /* JsxExpression */: + case 218 /* Block */: return true; default: return ts.isStatement(scopeNode); } } function filterGlobalCompletion(symbols) { - var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); - if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + var isTypeOnly = isTypeOnlyCompletion(); + var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); + if (isTypeOnly) + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93438,52 +96894,49 @@ var ts; if (allowTypes) { // Its a type, but you can reach it by namespace.type as well var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); - if (symbolAllowedAsType || isTypeOnlyCompletion) { + if (symbolAllowedAsType || isTypeOnly) { return symbolAllowedAsType; } } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } + function isTypeOnlyCompletion() { + return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 103 /* TypeOfKeyword */ && - (contextToken.parent.kind === 165 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + contextToken.kind === 104 /* TypeOfKeyword */ && + (contextToken.parent.kind === 167 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { - case 56 /* ColonToken */: - return parentKind === 152 /* PropertyDeclaration */ || - parentKind === 151 /* PropertySignature */ || - parentKind === 149 /* Parameter */ || - parentKind === 235 /* VariableDeclaration */ || + case 57 /* ColonToken */: + return parentKind === 154 /* PropertyDeclaration */ || + parentKind === 153 /* PropertySignature */ || + parentKind === 151 /* Parameter */ || + parentKind === 237 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); - case 58 /* EqualsToken */: - return parentKind === 240 /* TypeAliasDeclaration */; - case 118 /* AsKeyword */: - return parentKind === 210 /* AsExpression */; + case 59 /* EqualsToken */: + return parentKind === 242 /* TypeAliasDeclaration */; + case 119 /* AsKeyword */: + return parentKind === 212 /* AsExpression */; } } return false; } - function symbolCanBeReferencedAtTypeLocation(symbol) { - symbol = symbol.exportSymbol || symbol; - // This is an alias, follow what it aliases - symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { - return true; - } - if (symbol.flags & 1536 /* Module */) { - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - // If the exported symbols contains type, - // symbol can be referenced at locations where type is allowed - return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); - } - return false; + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { + if (seenModules === void 0) { seenModules = ts.createMap(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); + return !!(sym.flags & 67897832 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { var tokenTextLowerCase = tokenText.toLowerCase(); @@ -93498,19 +96951,29 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details. // This is just to avoid adding duplicate completion entries. // - // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. - // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + // If `symbol.parent !== ...`, this is an `export * from "foo"` re-export. Those don't create new symbols. if (typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol - || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + || ts.some(symbol.declarations, function (d) { + // If `!!d.name.originalKeywordKind`, this is `export { _break as break };` -- skip this and prefer the keyword completion. + // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + return ts.isExportSpecifier(d) && (d.propertyName ? ts.isIdentifierANonContextualKeyword(d.name) : !!d.parent.parent.moduleSpecifier); + })) { continue; } - var isDefaultExport = symbol.name === "default" /* Default */; + var isDefaultExport = symbol.escapedName === "default" /* Default */; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } @@ -93564,15 +97027,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 10 /* JsxText */) { + if (contextToken.kind === 11 /* JsxText */) { return true; } - if (contextToken.kind === 29 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 260 /* JsxOpeningElement */) { + if (contextToken.kind === 30 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 262 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 261 /* JsxClosingElement */ || contextToken.parent.kind === 259 /* JsxSelfClosingElement */) { - return !!contextToken.parent.parent && contextToken.parent.parent.kind === 258 /* JsxElement */; + if (contextToken.parent.kind === 263 /* JsxClosingElement */ || contextToken.parent.kind === 261 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 260 /* JsxElement */; } } return false; @@ -93582,41 +97045,41 @@ var ts; var containingNodeKind = previousToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(previousToken)) { - case 26 /* CommaToken */: - return containingNodeKind === 189 /* CallExpression */ // func( a, | - || containingNodeKind === 155 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 190 /* NewExpression */ // new C(a, | - || containingNodeKind === 185 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 202 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 163 /* FunctionType */; // var x: (s: string, list| - case 19 /* OpenParenToken */: - return containingNodeKind === 189 /* CallExpression */ // func( | - || containingNodeKind === 155 /* Constructor */ // constructor( | - || containingNodeKind === 190 /* NewExpression */ // new C(a| - || containingNodeKind === 193 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 175 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ - case 21 /* OpenBracketToken */: - return containingNodeKind === 185 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 160 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 147 /* ComputedPropertyName */; // [ | /* this can become an index signature */ - case 129 /* ModuleKeyword */: // module | - case 130 /* NamespaceKeyword */: // namespace | + case 27 /* CommaToken */: + return containingNodeKind === 191 /* CallExpression */ // func( a, | + || containingNodeKind === 157 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 192 /* NewExpression */ // new C(a, | + || containingNodeKind === 187 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 204 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 165 /* FunctionType */; // var x: (s: string, list| + case 20 /* OpenParenToken */: + return containingNodeKind === 191 /* CallExpression */ // func( | + || containingNodeKind === 157 /* Constructor */ // constructor( | + || containingNodeKind === 192 /* NewExpression */ // new C(a| + || containingNodeKind === 195 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 177 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 22 /* OpenBracketToken */: + return containingNodeKind === 187 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 162 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 149 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 130 /* ModuleKeyword */: // module | + case 131 /* NamespaceKeyword */: // namespace | return true; - case 23 /* DotToken */: - return containingNodeKind === 242 /* ModuleDeclaration */; // module A.| - case 17 /* OpenBraceToken */: - return containingNodeKind === 238 /* ClassDeclaration */; // class A{ | - case 58 /* EqualsToken */: - return containingNodeKind === 235 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 202 /* BinaryExpression */; // x = a| - case 14 /* TemplateHead */: - return containingNodeKind === 204 /* TemplateExpression */; // `aa ${| - case 15 /* TemplateMiddle */: - return containingNodeKind === 214 /* TemplateSpan */; // `aa ${10} dd ${| - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - return containingNodeKind === 152 /* PropertyDeclaration */; // class A{ public | + case 24 /* DotToken */: + return containingNodeKind === 244 /* ModuleDeclaration */; // module A.| + case 18 /* OpenBraceToken */: + return containingNodeKind === 240 /* ClassDeclaration */; // class A{ | + case 59 /* EqualsToken */: + return containingNodeKind === 237 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 204 /* BinaryExpression */; // x = a| + case 15 /* TemplateHead */: + return containingNodeKind === 206 /* TemplateExpression */; // `aa ${| + case 16 /* TemplateMiddle */: + return containingNodeKind === 216 /* TemplateSpan */; // `aa ${10} dd ${| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */; // class A{ public | } } return false; @@ -93643,16 +97106,16 @@ var ts; completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 186 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 188 /* ObjectLiteralExpression */) { var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return 2 /* Fail */; - isNewIdentifierLocation = hasIndexSignature(typeForObject); + isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker); existingMembers = objectLikeContainer.properties; } else { - ts.Debug.assert(objectLikeContainer.kind === 182 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 184 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -93663,12 +97126,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 225 /* ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 149 /* Parameter */) { + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 227 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 151 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 154 /* MethodDeclaration */ || rootDeclaration.parent.kind === 157 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 156 /* MethodDeclaration */ || rootDeclaration.parent.kind === 159 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -93704,13 +97167,13 @@ var ts; */ function tryGetImportOrExportClauseCompletionSymbols() { // `import { |` or `import { a as 0, | }` - var namedImportsOrExports = contextToken && (contextToken.kind === 17 /* OpenBraceToken */ || contextToken.kind === 26 /* CommaToken */) + var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; if (!namedImportsOrExports) return 0 /* Continue */; // cursor is in an import clause // try to show exported member for imported module - var moduleSpecifier = (namedImportsOrExports.kind === 250 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifier = (namedImportsOrExports.kind === 252 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -93733,14 +97196,15 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 40 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; var classElement = contextToken.parent; var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; // If this is context token is not something we are editing now, consider if this would lead to be modifier - if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + if (contextToken.kind === 72 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { switch (contextToken.getText()) { case "private": classElementModifierFlags = classElementModifierFlags | 8 /* Private */; @@ -93767,14 +97231,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { - case 17 /* OpenBraceToken */: // const x = { | - case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; + case 18 /* OpenBraceToken */: // const x = { | + case 27 /* CommaToken */: // const x = { a: 0, | if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 40 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 72 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93791,8 +97260,8 @@ var ts; if (contextToken) { var parent = contextToken.parent; switch (contextToken.kind) { - case 19 /* OpenParenToken */: - case 26 /* CommaToken */: + case 20 /* OpenParenToken */: + case 27 /* CommaToken */: return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; default: if (isConstructorParameterCompletion(contextToken)) { @@ -93822,17 +97291,23 @@ var ts; if (contextToken) { var parent = contextToken.parent; switch (contextToken.kind) { - case 28 /* LessThanSlashToken */: - case 41 /* SlashToken */: - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: - case 266 /* JsxAttributes */: - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 259 /* JsxSelfClosingElement */ || parent.kind === 260 /* JsxOpeningElement */)) { + case 30 /* GreaterThanToken */: // End of a type argument list + case 29 /* LessThanSlashToken */: + case 42 /* SlashToken */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 268 /* JsxAttributes */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) { + if (contextToken.kind === 30 /* GreaterThanToken */) { + var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); + if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */)) + break; + } return parent; } - else if (parent.kind === 265 /* JsxAttribute */) { + else if (parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93843,8 +97318,8 @@ var ts; // 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 && ((parent.kind === 265 /* JsxAttribute */) || (parent.kind === 267 /* JsxSpreadAttribute */))) { + case 10 /* StringLiteral */: + if (parent && ((parent.kind === 267 /* JsxAttribute */) || (parent.kind === 269 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93852,10 +97327,10 @@ var ts; return parent.parent.parent; } break; - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: if (parent && - parent.kind === 268 /* JsxExpression */ && - parent.parent && parent.parent.kind === 265 /* JsxAttribute */) { + parent.kind === 270 /* JsxExpression */ && + parent.parent && parent.parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93863,7 +97338,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 267 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 269 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93882,67 +97357,66 @@ var ts; var parent = contextToken.parent; var containingNodeKind = parent.kind; switch (contextToken.kind) { - case 26 /* CommaToken */: - return containingNodeKind === 235 /* VariableDeclaration */ || - containingNodeKind === 236 /* VariableDeclarationList */ || - containingNodeKind === 217 /* VariableStatement */ || - containingNodeKind === 241 /* EnumDeclaration */ || // enum a { foo, | + case 27 /* CommaToken */: + return containingNodeKind === 237 /* VariableDeclaration */ || + containingNodeKind === 238 /* VariableDeclarationList */ || + containingNodeKind === 219 /* VariableStatement */ || + containingNodeKind === 243 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A= contextToken.pos); - case 23 /* DotToken */: - return containingNodeKind === 183 /* ArrayBindingPattern */; // var [.| - case 56 /* ColonToken */: - return containingNodeKind === 184 /* BindingElement */; // var {x :html| - case 21 /* OpenBracketToken */: - return containingNodeKind === 183 /* ArrayBindingPattern */; // var [x| - case 19 /* OpenParenToken */: - return containingNodeKind === 272 /* CatchClause */ || + case 24 /* DotToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [.| + case 57 /* ColonToken */: + return containingNodeKind === 186 /* BindingElement */; // var {x :html| + case 22 /* OpenBracketToken */: + return containingNodeKind === 185 /* ArrayBindingPattern */; // var [x| + case 20 /* OpenParenToken */: + return containingNodeKind === 274 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); - case 17 /* OpenBraceToken */: - return containingNodeKind === 241 /* EnumDeclaration */; // enum a { | - case 27 /* LessThanToken */: - return containingNodeKind === 238 /* ClassDeclaration */ || // class A< | - containingNodeKind === 207 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 240 /* TypeAliasDeclaration */ || // type List< | + case 18 /* OpenBraceToken */: + return containingNodeKind === 243 /* EnumDeclaration */; // enum a { | + case 28 /* LessThanToken */: + return containingNodeKind === 240 /* ClassDeclaration */ || // class A< | + containingNodeKind === 209 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 241 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 242 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); - case 115 /* StaticKeyword */: - return containingNodeKind === 152 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); - case 24 /* DotDotDotToken */: - return containingNodeKind === 149 /* Parameter */ || - (!!parent.parent && parent.parent.kind === 183 /* ArrayBindingPattern */); // var [...z| - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - return containingNodeKind === 149 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); - case 118 /* AsKeyword */: - return containingNodeKind === 251 /* ImportSpecifier */ || - containingNodeKind === 255 /* ExportSpecifier */ || - containingNodeKind === 249 /* NamespaceImport */; - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 109 /* InterfaceKeyword */: - case 89 /* FunctionKeyword */: - case 104 /* VarKeyword */: - case 91 /* ImportKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 116 /* YieldKeyword */: - case 139 /* TypeKeyword */: // type htm| + case 116 /* StaticKeyword */: + return containingNodeKind === 154 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + case 25 /* DotDotDotToken */: + return containingNodeKind === 151 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 185 /* ArrayBindingPattern */); // var [...z| + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + return containingNodeKind === 151 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + case 119 /* AsKeyword */: + return containingNodeKind === 253 /* ImportSpecifier */ || + containingNodeKind === 257 /* ExportSpecifier */ || + containingNodeKind === 251 /* NamespaceImport */; + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return !isFromObjectTypeDeclaration(contextToken); + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 110 /* InterfaceKeyword */: + case 90 /* FunctionKeyword */: + case 105 /* VarKeyword */: + case 92 /* ImportKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 117 /* YieldKeyword */: + case 140 /* TypeKeyword */: // type htm| return true; + case 40 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93962,22 +97436,23 @@ var ts; } // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 75 /* ClassKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 83 /* EnumKeyword */: - case 89 /* FunctionKeyword */: - case 109 /* InterfaceKeyword */: - case 110 /* LetKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 115 /* StaticKeyword */: - case 104 /* VarKeyword */: - case 116 /* YieldKeyword */: + case 118 /* AbstractKeyword */: + case 76 /* ClassKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 90 /* FunctionKeyword */: + case 110 /* InterfaceKeyword */: + case 111 /* LetKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 116 /* StaticKeyword */: + case 105 /* VarKeyword */: + case 117 /* YieldKeyword */: return true; + case 121 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -93986,7 +97461,7 @@ var ts; && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 155 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 157 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -94009,12 +97484,12 @@ 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 !== 273 /* PropertyAssignment */ && - m.kind !== 274 /* ShorthandPropertyAssignment */ && - m.kind !== 184 /* BindingElement */ && - m.kind !== 154 /* MethodDeclaration */ && - m.kind !== 156 /* GetAccessor */ && - m.kind !== 157 /* SetAccessor */) { + if (m.kind !== 275 /* PropertyAssignment */ && + m.kind !== 276 /* ShorthandPropertyAssignment */ && + m.kind !== 186 /* BindingElement */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -94024,7 +97499,7 @@ var ts; var existingName = void 0; if (ts.isBindingElement(m) && m.propertyName) { // include only identifiers in completion list - if (m.propertyName.kind === 71 /* Identifier */) { + if (m.propertyName.kind === 72 /* Identifier */) { existingName = m.propertyName.escapedText; } } @@ -94049,10 +97524,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 152 /* PropertyDeclaration */ && - m.kind !== 154 /* MethodDeclaration */ && - m.kind !== 156 /* GetAccessor */ && - m.kind !== 157 /* SetAccessor */) { + if (m.kind !== 154 /* PropertyDeclaration */ && + m.kind !== 156 /* MethodDeclaration */ && + m.kind !== 158 /* GetAccessor */ && + m.kind !== 159 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -94092,7 +97567,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 265 /* JsxAttribute */) { + if (attr.kind === 267 /* JsxAttribute */) { seenNames.set(attr.name.escapedText, true); } } @@ -94136,7 +97611,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 72 /* FirstKeyword */; i <= 145 /* LastKeyword */; i++) { + for (var i = 73 /* FirstKeyword */; i <= 147 /* LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -94151,17 +97626,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 121 /* AsyncKeyword */ || 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 125 /* DeclareKeyword */ || kind === 130 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 141 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94169,37 +97646,26 @@ var ts; })); } function isInterfaceOrTypeLiteralCompletionKeyword(kind) { - return kind === 132 /* ReadonlyKeyword */; + return kind === 133 /* ReadonlyKeyword */; } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 117 /* AbstractKeyword */: - case 123 /* ConstructorKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 120 /* AsyncKeyword */: + case 118 /* AbstractKeyword */: + case 124 /* ConstructorKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + case 121 /* AsyncKeyword */: return true; default: return ts.isClassMemberModifier(kind); } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 121 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } - function isEqualityOperatorKind(kind) { - switch (kind) { - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - return true; - default: - return false; - } - } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { var jsdoc = ts.findAncestor(node, ts.isJSDoc); @@ -94209,7 +97675,7 @@ var ts; return contextualType.isUnion() ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. - return !(memberType.flags & 32764 /* Primitive */ || + return !(memberType.flags & 131068 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker) || checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); @@ -94232,31 +97698,31 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 304 /* SyntaxList */: + case 306 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); - if (cls && !ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile)) { + if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) { return cls; } } if (!contextToken) return undefined; switch (contextToken.kind) { - case 25 /* SemicolonToken */: // class c {getValue(): number; | } - case 18 /* CloseBraceToken */: // class c { method() { } | } + case 26 /* SemicolonToken */: // class c {getValue(): number; | } + case 19 /* CloseBraceToken */: // class c { method() { } | } // class c { method() { } b| } return isFromObjectTypeDeclaration(location) && location.parent.name === location ? location.parent.parent : ts.tryCast(location, ts.isObjectTypeDeclaration); - case 17 /* OpenBraceToken */: // class c { | - case 26 /* CommaToken */: // class c {getValue(): number, | } + case 18 /* OpenBraceToken */: // class c { | + case 27 /* CommaToken */: // class c {getValue(): number, | } return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); default: if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 40 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94264,9 +97730,6 @@ var ts; function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); } - function hasIndexSignature(type) { - return !!type.getStringIndexType() || !!type.getNumberIndexType(); - } function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { case ".": @@ -94276,14 +97739,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 28 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 42 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94292,17 +97755,6 @@ var ts; var left = _a.left; return ts.nodeIsMissing(left); } - function isStringLiteralOrTemplate(node) { - switch (node.kind) { - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 191 /* TaggedTemplateExpression */: - return true; - default: - return false; - } - } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -94355,40 +97807,40 @@ var ts; } function getHighlightSpans(node, sourceFile) { switch (node.kind) { - case 90 /* IfKeyword */: - case 82 /* ElseKeyword */: + case 91 /* IfKeyword */: + case 83 /* ElseKeyword */: return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; - case 96 /* ReturnKeyword */: + case 97 /* ReturnKeyword */: return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); - case 100 /* ThrowKeyword */: + case 101 /* ThrowKeyword */: return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); - case 102 /* TryKeyword */: - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: - var tryStatement = node.kind === 74 /* CatchKeyword */ ? node.parent.parent : node.parent; + case 103 /* TryKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: + var tryStatement = node.kind === 75 /* CatchKeyword */ ? node.parent.parent : node.parent; return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); - case 98 /* SwitchKeyword */: + case 99 /* SwitchKeyword */: return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); - case 73 /* CaseKeyword */: - case 79 /* DefaultKeyword */: + case 74 /* CaseKeyword */: + case 80 /* DefaultKeyword */: return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); - case 72 /* BreakKeyword */: - case 77 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 78 /* ContinueKeyword */: return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); - case 88 /* ForKeyword */: - case 106 /* WhileKeyword */: - case 81 /* DoKeyword */: + case 89 /* ForKeyword */: + case 107 /* WhileKeyword */: + case 82 /* DoKeyword */: return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); - case 123 /* ConstructorKeyword */: - return getFromAllDeclarations(ts.isConstructorDeclaration, [123 /* ConstructorKeyword */]); - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]); - case 121 /* AwaitKeyword */: + case 124 /* ConstructorKeyword */: + return getFromAllDeclarations(ts.isConstructorDeclaration, [124 /* ConstructorKeyword */]); + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: + return getFromAllDeclarations(ts.isAccessor, [126 /* GetKeyword */, 137 /* SetKeyword */]); + case 122 /* AwaitKeyword */: return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: return highlightSpans(getAsyncAndAwaitOccurrences(node)); - case 116 /* YieldKeyword */: + case 117 /* YieldKeyword */: return highlightSpans(getYieldOccurrences(node)); default: return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) @@ -94431,7 +97883,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 277 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -94463,16 +97915,16 @@ var ts; function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 230 /* SwitchStatement */: - if (statement.kind === 226 /* ContinueStatement */) { + case 232 /* SwitchStatement */: + if (statement.kind === 228 /* ContinueStatement */) { return false; } // falls through - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. @@ -94488,11 +97940,11 @@ var ts; // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 243 /* ModuleBlock */: - case 277 /* SourceFile */: - case 216 /* Block */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 218 /* Block */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return declaration.members.concat([declaration]); @@ -94500,12 +97952,12 @@ var ts; else { return container.statements; } - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 237 /* FunctionDeclaration */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: var 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. @@ -94536,12 +97988,12 @@ var ts; } function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) { + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 89 /* ForKeyword */, 107 /* WhileKeyword */, 82 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 221 /* DoStatement */) { + if (loopNode.kind === 223 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) { + if (pushKeywordIf(keywords, loopTokens[i], 107 /* WhileKeyword */)) { break; } } @@ -94549,7 +98001,7 @@ var ts; } ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) { if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */, 77 /* ContinueKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */, 78 /* ContinueKeyword */); } }); return keywords; @@ -94558,13 +98010,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -94572,13 +98024,13 @@ var ts; } function getSwitchCaseDefaultOccurrences(switchStatement) { var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 98 /* SwitchKeyword */); + pushKeywordIf(keywords, switchStatement.getFirstToken(), 99 /* SwitchKeyword */); // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 73 /* CaseKeyword */, 79 /* DefaultKeyword */); + pushKeywordIf(keywords, clause.getFirstToken(), 74 /* CaseKeyword */, 80 /* DefaultKeyword */); ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) { if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 73 /* BreakKeyword */); } }); }); @@ -94586,13 +98038,13 @@ var ts; } function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 102 /* TryKeyword */); + pushKeywordIf(keywords, tryStatement.getFirstToken(), 103 /* TryKeyword */); if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 74 /* CatchKeyword */); + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 75 /* CatchKeyword */); } if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 87 /* FinallyKeyword */); + var finallyKeyword = ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 88 /* FinallyKeyword */); } return keywords; } @@ -94603,13 +98055,13 @@ var ts; } var keywords = []; ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - keywords.push(ts.findChildOfKind(throwStatement, 100 /* ThrowKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); }); // If the "owner" is a function, then we equate 'return' and 'throw' statements in their // ability to "jump out" of the function, and include occurrences for both. if (ts.isFunctionBlock(owner)) { ts.forEachReturnStatement(owner, function (returnStatement) { - keywords.push(ts.findChildOfKind(returnStatement, 96 /* ReturnKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); }); } return keywords; @@ -94621,11 +98073,11 @@ var ts; } var keywords = []; ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { - keywords.push(ts.findChildOfKind(returnStatement, 96 /* ReturnKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(returnStatement, 97 /* ReturnKeyword */, sourceFile)); }); // Include 'throw' statements that do not occur within a try block. ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - keywords.push(ts.findChildOfKind(throwStatement, 100 /* ThrowKeyword */, sourceFile)); + keywords.push(ts.findChildOfKind(throwStatement, 101 /* ThrowKeyword */, sourceFile)); }); return keywords; } @@ -94637,13 +98089,13 @@ var ts; var keywords = []; if (func.modifiers) { func.modifiers.forEach(function (modifier) { - pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */); + pushKeywordIf(keywords, modifier, 121 /* AsyncKeyword */); }); } ts.forEachChild(func, function (child) { traverseWithoutCrossingFunction(child, function (node) { if (ts.isAwaitExpression(node)) { - pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */); + pushKeywordIf(keywords, node.getFirstToken(), 122 /* AwaitKeyword */); } }); }); @@ -94658,7 +98110,7 @@ var ts; ts.forEachChild(func, function (child) { traverseWithoutCrossingFunction(child, function (node) { if (ts.isYieldExpression(node)) { - pushKeywordIf(keywords, node.getFirstToken(), 116 /* YieldKeyword */); + pushKeywordIf(keywords, node.getFirstToken(), 117 /* YieldKeyword */); } }); }); @@ -94677,7 +98129,7 @@ var ts; // We'd like to highlight else/ifs together if they are only separated by whitespace // (i.e. the keywords are separated by no comments, no newlines). for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 82 /* ElseKeyword */ && i < keywords.length - 1) { + if (keywords[i].kind === 83 /* ElseKeyword */ && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. var shouldCombineElseAndIf = true; @@ -94712,10 +98164,10 @@ var ts; // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. while (true) { var children = ifStatement.getChildren(sourceFile); - pushKeywordIf(keywords, children[0], 90 /* IfKeyword */); + pushKeywordIf(keywords, children[0], 91 /* IfKeyword */); // Generally the 'else' keyword is second-to-last, so we traverse backwards. for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 82 /* ElseKeyword */)) { + if (pushKeywordIf(keywords, children[i], 83 /* ElseKeyword */)) { break; } } @@ -94748,16 +98200,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } - function getBucketForCompilationSettings(key, createIfMissing) { - var bucket = buckets.get(key); - if (!bucket && createIfMissing) { - buckets.set(key, bucket = ts.createMap()); - } - return bucket; // TODO: GH#18217 - } function reportStats() { var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = buckets.get(name); @@ -94793,9 +98235,9 @@ var ts; return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); + var bucket = ts.getOrUpdate(buckets, key, ts.createMap); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +98251,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94847,8 +98289,7 @@ var ts; return releaseDocumentWithKey(path, key); } function releaseDocumentWithKey(path, key) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); - ts.Debug.assert(bucket !== undefined); + var bucket = ts.Debug.assertDefined(buckets.get(key)); var entry = bucket.get(path); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); @@ -94876,6 +98317,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -94939,12 +98383,12 @@ var ts; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 235 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 237 /* VariableDeclaration */) { var name = parent.name; - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { directImports.push(name); break; } @@ -94953,22 +98397,22 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; - case 71 /* Identifier */: // for 'const x = require("y"); + case 72 /* Identifier */: // for 'const x = require("y"); break; // TODO: GH#23879 - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 251 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); @@ -94978,7 +98422,7 @@ var ts; directImports.push(direct); } break; - case 181 /* ImportType */: + case 183 /* ImportType */: directImports.push(direct); break; default: @@ -94995,7 +98439,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 277 /* SourceFile */ || sourceFileLike.kind === 242 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -95050,17 +98494,17 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 246 /* ImportEqualsDeclaration */) { + if (decl.kind === 248 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } return; } - if (decl.kind === 71 /* Identifier */) { + if (decl.kind === 72 /* Identifier */) { handleNamespaceImportLike(decl); return; } - if (decl.kind === 181 /* ImportType */) { + if (decl.kind === 183 /* ImportType */) { if (decl.qualifier) { if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { singleReferences.push(decl.qualifier); @@ -95072,20 +98516,20 @@ var ts; return; } // Ignore if there's a grammar error - if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) { + if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { return; } - if (decl.kind === 253 /* ExportDeclaration */) { + if (decl.kind === 255 /* ExportDeclaration */) { searchForNamedImport(decl.exportClause); return; } var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: handleNamespaceImportLike(namedBindings.name); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: // 'default' might be accessed as a named import `{ default as foo }`. if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { searchForNamedImport(namedBindings); @@ -95135,7 +98579,7 @@ var ts; } } else { - var localSymbol = element.kind === 255 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 257 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -95161,10 +98605,10 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 277 /* SourceFile */) { + if (searchSourceFile.kind === 279 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -95192,8 +98636,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95212,7 +98656,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 277 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -95227,15 +98671,15 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 253 /* ExportDeclaration */: - case 247 /* ImportDeclaration */: { + case 255 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 246 /* ImportEqualsDeclaration */: { + case 248 /* ImportEqualsDeclaration */: { var decl = statement; if (isExternalModuleImportEquals(decl)) { action(decl, decl.moduleReference.expression); @@ -95259,7 +98703,7 @@ var ts; var parent = node.parent; var grandParent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 187 /* PropertyAccessExpression */) { + if (parent.kind === 189 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) @@ -95279,7 +98723,7 @@ var ts; return undefined; } var lhsSymbol = checker.getSymbolAtLocation(exportNode.name); - return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false }; + return { kind: 0 /* Import */, symbol: lhsSymbol }; } else { return exportInfo(symbol, getExportKindForDeclaration(exportNode)); @@ -95312,7 +98756,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95349,7 +98793,7 @@ var ts; // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { - return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); + return { kind: 0 /* Import */, symbol: importedSymbol }; } } function exportInfo(symbol, kind) { @@ -95381,10 +98825,10 @@ var ts; // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent, node) { - if (parent.kind === 235 /* VariableDeclaration */) { + if (parent.kind === 237 /* VariableDeclaration */) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 272 /* CatchClause */ ? undefined : p.parent.parent.kind === 217 /* VariableStatement */ ? p.parent.parent : undefined; + p.parent.kind === 274 /* CatchClause */ ? undefined : p.parent.parent.kind === 219 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -95393,19 +98837,17 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 246 /* ImportEqualsDeclaration */: - return parent.name === node && isExternalModuleImportEquals(parent) - ? { isNamedImport: false } - : undefined; - case 251 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + return parent.name === node && isExternalModuleImportEquals(parent); + case 253 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. - return parent.propertyName ? undefined : { isNamedImport: true }; - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: + return !parent.propertyName; + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: ts.Debug.assert(parent.name === node); - return { isNamedImport: false }; + return true; default: - return undefined; + return false; } } function getExportInfo(exportSymbol, exportKind, checker) { @@ -95434,21 +98876,21 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 277 /* SourceFile */) { + if (parent.kind === 279 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 243 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 245 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; + return node.kind === 244 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; } function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 257 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */; + return eq.moduleReference.kind === 259 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95457,8 +98899,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95483,18 +98942,18 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } - else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" var symbol = checker.getSymbolAtLocation(node); @@ -95505,10 +98964,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95521,28 +98980,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95556,28 +99015,67 @@ var ts; } function getDefinitionKindAndDisplayParts(symbol, checker, node) { var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); - var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node; + var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode, checker) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), - isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + isDefinition: node.kind === 80 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode, checker) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + var prefixColon = { prefixText: name + ": " }; + var suffixColon = { suffixText: ": " + name }; + return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon + : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : isShorthandAssignment ? suffixColon : prefixColon; + } + else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + // If the original symbol was using this alias, just rename the alias. + var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); + return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions; + } + else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name }; + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95592,16 +99090,16 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 186 /* ObjectLiteralExpression */) { + else if (node.kind === 188 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, - displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] }; } - else if (node.kind === 207 /* ClassExpression */) { + else if (node.kind === 209 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, - displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] + displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] }; } else { @@ -95609,17 +99107,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95627,7 +99125,7 @@ var ts; function getTextSpan(node, sourceFile) { var start = node.getStart(sourceFile); var end = node.getEnd(); - if (node.kind === 9 /* StringLiteral */) { + if (node.kind === 10 /* StringLiteral */) { start += 1; end -= 1; } @@ -95635,7 +99133,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 80 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 204 /* BinaryExpression */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 80 /* DefaultKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 257 /* ExportSpecifier */: + case 250 /* ImportClause */: // default import + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 241 /* InterfaceDeclaration */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 267 /* JsxAttribute */: + case 244 /* ModuleDeclaration */: + case 247 /* NamespaceExportDeclaration */: + case 251 /* NamespaceImport */: + case 151 /* Parameter */: + case 276 /* ShorthandPropertyAssignment */: + case 242 /* TypeAliasDeclaration */: + case 150 /* TypeParameter */: + return true; + case 275 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return !!decl.body; + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 155 /* MethodSignature */: + case 153 /* PropertySignature */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95668,6 +99221,9 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } + if (symbol.escapedName === "export=" /* ExportEquals */) { + return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } var moduleReferences = ts.emptyArray; var moduleSourceFile = isModuleSymbol(symbol); var referencedNode = node; @@ -95699,11 +99255,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95712,12 +99268,12 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95725,7 +99281,23 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + var exported = symbol.exports.get("export=" /* ExportEquals */); + if (exported) { + for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { + var decl = _c[_b]; + var sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + // At `module.exports = ...`, reference node is `module` + var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) + ? decl.left.expression + : ts.isExportAssignment(decl) + ? ts.Debug.assertDefined(ts.findChildOfKind(decl, 85 /* ExportKeyword */, sourceFile)) + : ts.getNameOfDeclaration(decl) || decl; + references.push(FindAllReferences.nodeEntry(node)); + } + } + } + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95746,24 +99318,29 @@ var ts; if (ts.isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); } - if (node.kind === 97 /* SuperKeyword */) { + if (node.kind === 98 /* SuperKeyword */) { return getReferencesForSuperKeyword(node); } return undefined; } /** Core find-all-references algorithm for a normal symbol. */ - function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; // Compute the meaning from the location and the symbol it references var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - if (node && node.kind === 79 /* DefaultKeyword */) { + var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + if (exportSpecifier) { + // When renaming at an export specifier, rename the export and not the thing being exported. + getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); + } + else if (node && node.kind === 80 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -95783,9 +99360,9 @@ var ts; } function getSpecialSearchKind(node) { switch (node.kind) { - case 123 /* ConstructorKeyword */: + case 124 /* ConstructorKeyword */: return 1 /* Constructor */; - case 71 /* Identifier */: + case 72 /* Identifier */: if (ts.isClassLike(node.parent)) { ts.Debug.assert(node.parent.name === node); return 2 /* Class */; @@ -95796,15 +99373,11 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { var parent = node.parent; - if (ts.isExportSpecifier(parent)) { + if (ts.isExportSpecifier(parent) && !isForRename) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); } - if (ts.isImportSpecifier(parent) && parent.propertyName === node) { - // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. - return checker.getImmediateAliasedSymbol(symbol); - } // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. return ts.firstDefined(symbol.declarations, function (decl) { if (!decl.parent) { @@ -95894,15 +99467,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -95967,7 +99540,8 @@ var ts; var indirectUser = indirectUsers_2[_b]; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; - if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) { + // Import specifiers should be handled by importSearches + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { cb(node); } } @@ -95983,7 +99557,7 @@ var ts; if (!ts.isIdentifier(singleRef)) return false; // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */); } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { @@ -96005,19 +99579,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -96030,7 +99591,7 @@ 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 declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 194 /* FunctionExpression */ || valueDeclaration.kind === 207 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 196 /* FunctionExpression */ || valueDeclaration.kind === 209 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -96040,14 +99601,14 @@ var ts; if (flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 238 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 240 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -96062,14 +99623,14 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -96090,7 +99651,9 @@ var ts; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { - var symbol = checker.getSymbolAtLocation(definition); + var symbol = ts.isParameterPropertyDeclaration(definition.parent) + ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) + : checker.getSymbolAtLocation(definition); if (!symbol) return undefined; for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { @@ -96112,8 +99675,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,21 +99733,21 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node.text.length === searchSymbolName.length; - case 9 /* StringLiteral */: { + case 10 /* StringLiteral */: { var str = node; - return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && str.text.length === searchSymbolName.length; } case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; - case 79 /* DefaultKeyword */: + case 80 /* DefaultKeyword */: return "default".length === searchSymbolName.length; default: return false; @@ -96197,7 +99760,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96248,7 +99811,7 @@ var ts; return; } if (ts.isExportSpecifier(parent)) { - ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */); + ts.Debug.assert(referenceLocation.kind === 72 /* Identifier */); getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); return; } @@ -96273,16 +99836,16 @@ var ts; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) { + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); - if (!search.includes(localSymbol)) { + if (!alwaysGetReferences && !search.includes(localSymbol)) { return; } if (!propertyName) { // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) - if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) { + if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) { addRef(); } } @@ -96293,7 +99856,7 @@ var ts; addRef(); } if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { - addReference(name, referenceSymbol, state); + addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state); } } else { @@ -96302,15 +99865,14 @@ var ts; } } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!(referenceLocation === propertyName && state.options.isForRename)) { - var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; - var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); - if (!exportInfo) - return ts.Debug.fail(); - searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); + if (!state.options.isForRename || alwaysGetReferences) { + var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; + var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); + var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. - if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) { + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (imported) searchForImportedSymbol(imported, state); @@ -96342,12 +99904,11 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0 /* Import */) { - if (!state.options.isForRename || importOrExport.isNamedImport) { + if (!state.options.isForRename) { searchForImportedSymbol(symbol, state); } } else { - // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching. searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); } } @@ -96367,12 +99928,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96382,7 +99944,7 @@ var ts; } var pusher = function () { return state.referenceAdder(search.symbol); }; if (ts.isClassLike(referenceLocation.parent)) { - ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); + ts.Debug.assert(referenceLocation.kind === 80 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. findOwnConstructorReferences(search.symbol, sourceFile, pusher()); } @@ -96408,7 +99970,7 @@ var ts; } if (member.body) { member.body.forEachChild(function cb(node) { - if (node.kind === 99 /* ThisKeyword */) { + if (node.kind === 100 /* ThisKeyword */) { addRef(node); } else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { @@ -96425,16 +99987,16 @@ var ts; function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 155 /* Constructor */ && !!ctrKeyword); + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 154 /* MethodDeclaration */) { + if (decl && decl.kind === 156 /* MethodDeclaration */) { var body = decl.body; if (body) { - forEachDescendantOfKind(body, 99 /* ThisKeyword */, function (thisKeyword) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { if (ts.isNewExpressionTarget(thisKeyword)) { addNode(thisKeyword); } @@ -96451,10 +100013,10 @@ var ts; } for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 155 /* Constructor */); + ts.Debug.assert(decl.kind === 157 /* Constructor */); var body = decl.body; if (body) { - forEachDescendantOfKind(body, 97 /* SuperKeyword */, function (node) { + forEachDescendantOfKind(body, 98 /* SuperKeyword */, function (node) { if (ts.isCallExpressionTarget(node)) { addNode(node); } @@ -96468,10 +100030,10 @@ var ts; addReference(refNode); return; } - if (refNode.kind !== 71 /* Identifier */) { + if (refNode.kind !== 72 /* Identifier */) { return; } - if (refNode.parent.kind === 274 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 276 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -96491,7 +100053,7 @@ var ts; } else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { var body = typeHavingNode.body; - if (body.kind === 216 /* Block */) { + if (body.kind === 218 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression) addIfImplementation(returnStatement.expression); @@ -96519,13 +100081,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 195 /* ArrowFunction */: - case 194 /* FunctionExpression */: - case 186 /* ObjectLiteralExpression */: - case 207 /* ClassExpression */: - case 185 /* ArrayLiteralExpression */: + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 187 /* ArrayLiteralExpression */: return true; default: return false; @@ -96578,13 +100140,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -96593,7 +100155,7 @@ var ts; } var sourceFile = searchSpaceNode.getSourceFile(); var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) { - if (node.kind !== 97 /* SuperKeyword */) { + if (node.kind !== 98 /* SuperKeyword */) { return; } var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); @@ -96602,41 +100164,41 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // falls through - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // falls through - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* 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. default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 277 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -96644,24 +100206,25 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: return searchSpaceNode.symbol === container.symbol; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; - case 277 /* SourceFile */: - return container.kind === 277 /* SourceFile */ && !ts.isExternalModule(container); + case 279 /* SourceFile */: + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96669,39 +100232,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // 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 - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96713,8 +100262,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // 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 + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96727,11 +100294,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96739,19 +100308,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96777,8 +100346,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_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +100409,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96855,7 +100424,7 @@ var ts; function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); return function (path) { - var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 }); var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); return originalPath ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) @@ -96874,7 +100443,7 @@ var ts; var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); return combinePathsSafe(ts.getDirectoryPath(a1), rel); } - function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; if (!configFile) return; @@ -96892,7 +100461,8 @@ var ts; var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); // If there isn't some include for this, add a new one. - if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if (ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); } } @@ -96943,9 +100513,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_12 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +100541,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_12(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +100571,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +100601,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +100643,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97078,7 +100655,7 @@ var ts; else { var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; // For a 'super()' call, put the signature first, else put the variable first. - return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); + return node.kind === 98 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -97086,7 +100663,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; } @@ -97239,18 +100816,18 @@ var ts; // (2) when the aliased symbol is originating from an import. // function shouldSkipAlias(node, declaration) { - if (node.kind !== 71 /* Identifier */) { + if (node.kind !== 72 /* Identifier */) { return false; } if (node.parent === declaration) { return true; } switch (declaration.kind) { - case 248 /* ImportClause */: - case 246 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: return true; - case 251 /* ImportSpecifier */: - return declaration.parent.kind === 250 /* NamedImports */; + case 253 /* ImportSpecifier */: + return declaration.parent.kind === 252 /* NamedImports */; default: return false; } @@ -97260,7 +100837,7 @@ var ts; function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */)) { + if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 124 /* ConstructorKeyword */)) { var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } @@ -97332,6 +100909,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97444,11 +101031,11 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: return [declaration]; - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -97469,16 +101056,16 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return withNode(tag.class); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 303 /* JSDocPropertyTag */: - case 297 /* JSDocParameterTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -97542,7 +101129,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +101162,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +101225,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97655,7 +101242,7 @@ var ts; function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { return parameters.map(function (_a, i) { var name = _a.name, dotDotDotToken = _a.dotDotDotToken; - var paramName = name.kind === 71 /* Identifier */ ? name.text : "param" + i; + var paramName = name.kind === 72 /* Identifier */ ? name.text : "param" + i; var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; return indentationStr + " * @param " + type + paramName + newLine; }).join(""); @@ -97665,23 +101252,23 @@ var ts; } function getCommentOwnerInfoWorker(commentOwner) { switch (commentOwner.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 155 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return getCommentOwnerInfoWorker(commentOwner.initializer); - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 151 /* PropertySignature */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 240 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 153 /* PropertySignature */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 242 /* TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer @@ -97689,16 +101276,16 @@ var ts; : undefined; return { commentOwner: commentOwner, parameters: parameters_1 }; } - case 277 /* SourceFile */: + case 279 /* SourceFile */: return "quit"; - case 242 /* ModuleDeclaration */: + case 244 /* 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 { }'. - return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 202 /* BinaryExpression */: { + return commentOwner.parent.kind === 244 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 204 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97715,14 +101302,14 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 193 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 195 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return rightHandSide.parameters; - case 207 /* ClassExpression */: { + case 209 /* ClassExpression */: { var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); return ctr ? ctr.parameters : ts.emptyArray; } @@ -97741,7 +101328,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +101338,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +101353,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -97784,9 +101371,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 248 /* ImportClause */: - case 251 /* ImportSpecifier */: - case 246 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 253 /* ImportSpecifier */: + case 248 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -97796,7 +101383,7 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - return !!name && (pushLiteral(name, containers) || name.kind === 147 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + return !!name && (pushLiteral(name, containers) || name.kind === 149 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // @@ -97813,7 +101400,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + if (name && name.kind === 149 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } // Don't include the last portion. @@ -97982,7 +101569,7 @@ var ts; return; } switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -97994,21 +101581,21 @@ var ts; } } break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 155 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -98020,7 +101607,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings.kind === 251 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -98031,8 +101618,8 @@ var ts; } } break; - case 184 /* BindingElement */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); @@ -98053,12 +101640,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -98068,9 +101655,9 @@ var ts; } endNode(); break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -98078,19 +101665,19 @@ var ts; } endNode(); break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 255 /* ExportSpecifier */: - case 246 /* ImportEqualsDeclaration */: - case 160 /* IndexSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 240 /* TypeAliasDeclaration */: + case 257 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 162 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 242 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: { + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98101,6 +101688,9 @@ var ts; case 4 /* ThisProperty */: case 5 /* Property */: case 0 /* None */: + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: break; default: ts.Debug.assertNever(special); @@ -98168,12 +101758,12 @@ var ts; return false; } switch (a.kind) { - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return areSameModule(a, b); default: return true; @@ -98189,7 +101779,7 @@ var ts; // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { // TODO: GH#18217 - return a.body.kind === b.body.kind && (a.body.kind !== 242 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 244 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { @@ -98219,7 +101809,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 242 /* ModuleDeclaration */) { + if (node.kind === 244 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -98227,16 +101817,16 @@ var ts; return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 207 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: return getFunctionOrClassName(node); default: return undefined; } } function getItemName(node, name) { - if (node.kind === 242 /* ModuleDeclaration */) { + if (node.kind === 244 /* ModuleDeclaration */) { return getModuleName(node); } if (name) { @@ -98246,16 +101836,16 @@ var ts; } } switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -98263,13 +101853,13 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the // navigation bar. return getFunctionOrClassName(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return "constructor"; - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return "new()"; - case 158 /* CallSignature */: + case 160 /* CallSignature */: return "()"; - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return "[]"; default: return ""; @@ -98293,25 +101883,25 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 241 /* EnumDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 277 /* SourceFile */: - case 240 /* TypeAliasDeclaration */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 279 /* SourceFile */: + case 242 /* TypeAliasDeclaration */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return true; - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 235 /* VariableDeclaration */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 237 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 195 /* ArrowFunction */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -98321,10 +101911,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 243 /* ModuleBlock */: - case 277 /* SourceFile */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: + case 245 /* ModuleBlock */: + case 279 /* SourceFile */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: return true; default: return hasSomeImportantChild(item); @@ -98333,7 +101923,7 @@ var ts; function hasSomeImportantChild(item) { return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 235 /* VariableDeclaration */ && childKind !== 184 /* BindingElement */; + return childKind !== 237 /* VariableDeclaration */ && childKind !== 186 /* BindingElement */; }); } } @@ -98390,7 +101980,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -98404,47 +101994,68 @@ var ts; return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 147 /* ComputedPropertyName */; + return !member.name || member.name.kind === 149 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 277 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 235 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 195 /* ArrowFunction */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: return true; default: return false; @@ -98571,7 +102182,7 @@ var ts; ? specifier.text : undefined; } - /* @internal */ // Internal for testing + // Internal for testing /** * @param importGroup a list of ImportDeclarations, all with the same module name. */ @@ -98670,7 +102281,7 @@ var ts; } } OrganizeImports.coalesceImports = coalesceImports; - /* @internal */ // Internal for testing + // Internal for testing /** * @param exportGroup a list of ExportDeclarations, all with the same module name. */ @@ -98773,7 +102384,7 @@ var ts; } var lastImport = current - 1; if (lastImport !== firstImport) { - out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 92 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); } } function visitNonImportNode(n) { @@ -98880,31 +102491,31 @@ var ts; } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(n)) { - return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 195 /* ArrowFunction */); + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 197 /* ArrowFunction */); } // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { - case 221 /* DoStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 220 /* IfStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 272 /* CatchClause */: + case 223 /* DoStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 274 /* CatchClause */: return spanForNode(n.parent); - case 233 /* TryStatement */: + case 235 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { return spanForNode(n.parent); } else if (tryStatement.finallyBlock === n) { - return spanForNode(ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile)); + return spanForNode(ts.findChildOfKind(tryStatement, 88 /* FinallyKeyword */, sourceFile)); } // falls through default: @@ -98912,21 +102523,21 @@ var ts; // the span of the block, independent of any parent span. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return spanForNode(n.parent); - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 244 /* CaseBlock */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 246 /* CaseBlock */: return spanForNode(n); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 185 /* ArrayLiteralExpression */: - return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); - case 258 /* JsxElement */: + case 187 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); + case 260 /* JsxElement */: return spanForJSXElement(n); - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); } function spanForJSXElement(node) { @@ -98942,7 +102553,7 @@ var ts; return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } function spanForObjectOrArrayLiteral(node, open) { - if (open === void 0) { open = 17 /* OpenBraceToken */; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } // If the block has no leading keywords and is inside an array literal, // we only want to collapse the span of the block. // Otherwise, the collapsed section will include the end of the previous line. @@ -98951,9 +102562,9 @@ var ts; function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { if (autoCollapse === void 0) { autoCollapse = false; } if (useFullStart === void 0) { useFullStart = true; } - if (open === void 0) { open = 17 /* OpenBraceToken */; } + if (open === void 0) { open = 18 /* OpenBraceToken */; } var openToken = ts.findChildOfKind(n, open, sourceFile); - var close = open === 17 /* OpenBraceToken */ ? 18 /* CloseBraceToken */ : 22 /* CloseBracketToken */; + var close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; var closeToken = ts.findChildOfKind(n, close, sourceFile); if (!openToken || !closeToken) { return undefined; @@ -99248,13 +102859,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_14 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_14(start); if (typeof state_3 === "object") return state_3.value; } @@ -99312,11 +102923,11 @@ var ts; characterSpans: breakIntoCharacterSpans(text) }; } - /* @internal */ function breakIntoCharacterSpans(identifier) { + function breakIntoCharacterSpans(identifier) { return breakIntoSpans(identifier, /*word:*/ false); } ts.breakIntoCharacterSpans = breakIntoCharacterSpans; - /* @internal */ function breakIntoWordSpans(identifier) { + function breakIntoWordSpans(identifier) { return breakIntoSpans(identifier, /*word:*/ true); } ts.breakIntoWordSpans = breakIntoWordSpans; @@ -99456,10 +103067,10 @@ var ts; function nextToken() { lastToken = currentToken; currentToken = ts.scanner.scan(); - if (currentToken === 17 /* OpenBraceToken */) { + if (currentToken === 18 /* OpenBraceToken */) { braceNesting++; } - else if (currentToken === 18 /* CloseBraceToken */) { + else if (currentToken === 19 /* CloseBraceToken */) { braceNesting--; } return currentToken; @@ -99489,12 +103100,12 @@ var ts; */ function tryConsumeDeclare() { var token = ts.scanner.getToken(); - if (token === 124 /* DeclareKeyword */) { + if (token === 125 /* DeclareKeyword */) { // declare module "mod" token = nextToken(); - if (token === 129 /* ModuleKeyword */) { + if (token === 130 /* ModuleKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { recordAmbientExternalModule(); } } @@ -99506,42 +103117,42 @@ var ts; * Returns true if at least one token was consumed from the stream */ function tryConsumeImport() { - if (lastToken === 23 /* DotToken */) { + if (lastToken === 24 /* DotToken */) { return false; } var token = ts.scanner.getToken(); - if (token === 91 /* ImportKeyword */) { + if (token === 92 /* ImportKeyword */) { token = nextToken(); - if (token === 19 /* OpenParenToken */) { + if (token === 20 /* OpenParenToken */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import("mod"); recordModuleName(); return true; } } - else if (token === 9 /* StringLiteral */) { + else if (token === 10 /* StringLiteral */) { // import "mod"; recordModuleName(); return true; } else { - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import d from "mod"; recordModuleName(); return true; } } - else if (token === 58 /* EqualsToken */) { + else if (token === 59 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } - else if (token === 26 /* CommaToken */) { + else if (token === 27 /* CommaToken */) { // consume comma and keep going token = nextToken(); } @@ -99550,18 +103161,18 @@ var ts; return true; } } - if (token === 17 /* OpenBraceToken */) { + if (token === 18 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure that it stops on EOF - while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import {a as A} from "mod"; // import d, {a, b as B} from "mod" recordModuleName(); @@ -99569,15 +103180,15 @@ var ts; } } } - else if (token === 39 /* AsteriskToken */) { + else if (token === 40 /* AsteriskToken */) { token = nextToken(); - if (token === 118 /* AsKeyword */) { + if (token === 119 /* AsKeyword */) { token = nextToken(); - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // import * as NS from "mod" // import d, * as NS from "mod" recordModuleName(); @@ -99593,21 +103204,21 @@ var ts; } function tryConsumeExport() { var token = ts.scanner.getToken(); - if (token === 84 /* ExportKeyword */) { + if (token === 85 /* ExportKeyword */) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 17 /* OpenBraceToken */) { + if (token === 18 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure it stops on EOF - while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // export {a as A} from "mod"; // export {a, b as B} from "mod" recordModuleName(); @@ -99615,21 +103226,21 @@ var ts; } } } - else if (token === 39 /* AsteriskToken */) { + else if (token === 40 /* AsteriskToken */) { token = nextToken(); - if (token === 143 /* FromKeyword */) { + if (token === 144 /* FromKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // export * from "mod" recordModuleName(); } } } - else if (token === 91 /* ImportKeyword */) { + else if (token === 92 /* ImportKeyword */) { token = nextToken(); - if (token === 71 /* Identifier */ || ts.isKeyword(token)) { + if (token === 72 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 58 /* EqualsToken */) { + if (token === 59 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } @@ -99642,11 +103253,11 @@ var ts; } function tryConsumeRequireCall(skipCurrentToken) { var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); - if (token === 133 /* RequireKeyword */) { + if (token === 134 /* RequireKeyword */) { token = nextToken(); - if (token === 19 /* OpenParenToken */) { + if (token === 20 /* OpenParenToken */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // require("mod"); recordModuleName(); } @@ -99657,16 +103268,16 @@ var ts; } function tryConsumeDefine() { var token = ts.scanner.getToken(); - if (token === 71 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + if (token === 72 /* Identifier */ && ts.scanner.getTokenValue() === "define") { token = nextToken(); - if (token !== 19 /* OpenParenToken */) { + if (token !== 20 /* OpenParenToken */) { return true; } token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { // looks like define ("modname", ... - skip string literal and comma token = nextToken(); - if (token === 26 /* CommaToken */) { + if (token === 27 /* CommaToken */) { token = nextToken(); } else { @@ -99675,15 +103286,15 @@ var ts; } } // should be start of dependency list - if (token !== 21 /* OpenBracketToken */) { + if (token !== 22 /* OpenBracketToken */) { return true; } // skip open bracket token = nextToken(); // scan until ']' or EOF - while (token !== 22 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { // record string literals as module names - if (token === 9 /* StringLiteral */) { + if (token === 10 /* StringLiteral */) { recordModuleName(); } token = nextToken(); @@ -99791,47 +103402,61 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; - if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + if (ts.isIdentifier(node) && node.originalKeywordKind === 80 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); var width = node.getWidth(sourceFile); - if (node.kind === 9 /* StringLiteral */) { + if (node.kind === 10 /* StringLiteral */) { // Exclude the quotes start += 1; width -= 2; @@ -99840,9 +103465,9 @@ var ts; } function nodeIsEligibleForRename(node) { switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 99 /* ThisKeyword */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: return true; case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); @@ -99877,22 +103502,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // 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. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +103536,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99921,19 +103560,19 @@ var ts; return false; var invocationChildren = node.getChildren(sourceFile); switch (startingToken.kind) { - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return ts.contains(invocationChildren, startingToken); - case 26 /* CommaToken */: { + case 27 /* CommaToken */: { var containingList = ts.findContainingList(startingToken); return !!containingList && ts.contains(invocationChildren, containingList); } - case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + case 28 /* LessThanToken */: + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +103589,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -99973,7 +103612,7 @@ var ts; return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; } function getArgumentOrParameterListAndIndex(node, sourceFile) { - if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { + if (node.kind === 28 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; @@ -100026,10 +103665,10 @@ var ts; } return undefined; } - else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) { + else if (ts.isTemplateHead(node) && parent.parent.kind === 193 /* TaggedTemplateExpression */) { var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 204 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 206 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } @@ -100092,24 +103731,24 @@ var ts; return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) { - if (startingToken.kind !== 19 /* OpenParenToken */ && startingToken.kind !== 26 /* CommaToken */) + if (startingToken.kind !== 20 /* OpenParenToken */ && startingToken.kind !== 27 /* CommaToken */) return undefined; var parent = startingToken.parent; switch (parent.kind) { - case 193 /* ParenthesizedExpression */: - case 154 /* MethodDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ParenthesizedExpression */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: var info = getArgumentOrParameterListInfo(startingToken, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var highestBinary = getHighestBinary(parent); var contextualType_1 = checker.getContextualType(highestBinary); - var argumentIndex_1 = startingToken.kind === 19 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; + var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; var argumentCount_1 = countBinaryExpressionParameters(highestBinary); return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) }; } @@ -100141,7 +103780,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 26 /* CommaToken */) { + if (child.kind !== 27 /* CommaToken */) { argumentIndex++; } } @@ -100160,8 +103799,8 @@ var ts; // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. var listChildren = argumentsList.getChildren(); - var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 26 /* CommaToken */; }); - if (listChildren.length > 0 && ts.last(listChildren).kind === 26 /* CommaToken */) { + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; }); + if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -100230,7 +103869,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 === 204 /* TemplateExpression */) { + if (template.kind === 206 /* TemplateExpression */) { var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -100238,8 +103877,8 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100248,8 +103887,8 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +103903,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } - var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +103920,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(28 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(30 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100307,9 +103966,9 @@ var ts; var parameterParts = ts.mapToDisplayParts(function (writer) { var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); + printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer); }); - return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(27 /* LessThanToken */)], suffix: [ts.punctuationPart(29 /* GreaterThanToken */)].concat(parameterParts) }; + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { var isVariadic = candidateSignature.hasRestParameter; @@ -100317,11 +103976,11 @@ var ts; var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); - printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); + printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); - return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(19 /* OpenParenToken */)]), suffix: [ts.punctuationPart(20 /* CloseParenToken */)] }; + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] }; } function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { @@ -100336,60 +103995,53 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); /* @internal */ var ts; (function (ts) { - // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) - var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; - var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) { + function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var sourcemappedFileCache; - return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + var mappedFile = sourcemappedFileCache.get(toPath(fileName)); if (!mappedFile) { return; } - var starts = ts.getLineStarts(mappedFile); - for (var index = starts.length - 1; index >= 0; index--) { - var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); - var comment = sourceMapCommentRegExp.exec(lineText); - if (comment) { - return comment[1]; - } - // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file - else if (!lineText.match(whitespaceOrMapCommentRegExp)) { - break; - } - } + return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); } function convertDocumentToSourceMapper(file, contents, mapFileName) { - var maps; - try { - maps = JSON.parse(contents); - } - catch (_a) { - // swallow error - } - if (!maps || !maps.sources || !maps.file || !maps.mappings) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { // obviously invalid map - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } - return file.sourceMapper = ts.sourcemaps.decode({ - readFile: function (s) { return host.readFile(s); }, - fileExists: function (s) { return host.fileExists(s); }, + var program = getProgram(); + return file.sourceMapper = ts.createDocumentPositionMapper({ + getSourceFileLike: function (s) { + // Lookup file in program, if provided + var file = program && program.getSourceFileByPath(s); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (file === undefined || file.resolvedPath !== s) { + // Otherwise check the cache (which may hit disk) + return sourcemappedFileCache.get(s); + } + return file; + }, getCanonicalFileName: getCanonicalFileName, log: log, - }, mapFileName, maps, getProgram(), sourcemappedFileCache); + }, map, mapFileName); } function getSourceMapper(fileName, file) { if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } if (file.sourceMapper) { return file.sourceMapper; @@ -100418,20 +104070,24 @@ var ts; return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 } } - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + return file.sourceMapper = ts.identitySourceMapConsumer; } - function tryGetOriginalLocation(info) { + function tryGetSourcePosition(info) { if (!ts.isDeclarationFileName(info.fileName)) return undefined; var file = getFile(info.fileName); if (!file) return undefined; - var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); - return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); + return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; } - function tryGetGeneratedLocation(info) { + function tryGetGeneratedPosition(info) { var program = getProgram(); - var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + var options = program.getCompilerOptions(); + var outPath = options.outFile || options.out; + var declarationPath = outPath ? + ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : + ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); if (declarationPath === undefined) return undefined; var declarationFile = getFile(declarationPath); @@ -100441,18 +104097,45 @@ var ts; return newLoc === info ? undefined : newLoc; } function getFile(fileName) { - return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + var path = toPath(fileName); + var file = getProgram().getSourceFileByPath(path); + if (file && file.resolvedPath === path) { + return file; + } + return sourcemappedFileCache.get(path); } function toLineColumnOffset(fileName, position) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 + var file = getFile(fileName); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } function clearCache() { - sourcemappedFileCache = ts.createSourceFileLikeCache(host); + sourcemappedFileCache = createSourceFileLikeCache(host); } } ts.getSourceMapper = getSourceMapper; + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } })(ts || (ts = {})); /* @internal */ var ts; @@ -100460,13 +104143,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100488,8 +104171,8 @@ var ts; function check(node) { if (isJsFile) { switch (node.kind) { - case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + case 196 /* FunctionExpression */: + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100498,7 +104181,7 @@ var ts; } } // falls through if no diagnostic was created - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: var symbol = node.symbol; if (symbol.members && (symbol.members.size > 0)) { diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); @@ -100531,15 +104214,15 @@ var ts; function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 - case 219 /* ExpressionStatement */: { + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 221 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100552,66 +104235,74 @@ var ts; } function importNameForConvertToDefaultImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 249 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 251 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node.name; default: return undefined; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { - return; + if (!ts.isAsyncFunction(node) && + node.body && + ts.isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker)) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } + } + function returnsPromise(node, checker) { + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; - if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { - return; - } - // collect all the return statements - // check that a property access expression exists in there and that it is a handler - var returnStatements = getReturnStatementsWithPromiseHandlers(node); - if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); - } + return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - /** @internal */ - function getReturnStatementsWithPromiseHandlers(node) { - var returnStatements = []; - if (ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - else { - visit(node); - } - function visit(child) { - if (ts.isFunctionLike(child)) { - return; - } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } - } - ts.forEachChild(child, visit); - } - return returnStatements; + function hasReturnStatementWithPromiseHandler(body) { + return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); } - ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + function isReturnStatementWithFixablePromiseHandler(node) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + } + ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + ts.isFixablePromiseHandler = isFixablePromiseHandler; function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100627,7 +104318,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 209 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -100664,7 +104355,7 @@ var ts; if (typeChecker.isArgumentsSymbol(symbol)) { return "local var" /* localVariableElement */; } - if (location.kind === 99 /* ThisKeyword */ && ts.isExpression(location)) { + if (location.kind === 100 /* ThisKeyword */ && ts.isExpression(location)) { return "parameter" /* parameterElement */; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); @@ -100715,11 +104406,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 260 /* JsxOpeningElement */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 265 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + return location.kind === 72 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 267 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -100744,13 +104435,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 100 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 100 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(100 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100759,7 +104453,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 187 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 189 /* 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)) { @@ -100780,7 +104474,7 @@ var ts; if (callExpressionLike) { var candidateSignatures = []; signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 - var useConstructSignatures = callExpressionLike.kind === 190 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 192 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 98 /* 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 @@ -100798,7 +104492,7 @@ var ts; pushSymbolKind(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addFullSymbolName(symbol); @@ -100815,14 +104509,14 @@ var ts; case "parameter" /* parameterElement */: case "local var" /* localVariableElement */: // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(56 /* ColonToken */)); + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); displayParts.push(ts.spacePart()); if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); @@ -100835,29 +104529,29 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 155 /* Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 124 /* ConstructorKeyword */ && location.parent.kind === 157 /* Constructor */)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { - return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + return declaration === (location.kind === 124 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 155 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 157 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 155 /* Constructor */) { + if (functionDeclaration_1.kind === 157 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 158 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 160 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -100867,7 +104561,7 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 209 /* 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 @@ -100875,7 +104569,7 @@ var ts; } else { // Class declaration has name which is not local. - displayParts.push(ts.keywordPart(75 /* ClassKeyword */)); + displayParts.push(ts.keywordPart(76 /* ClassKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -100883,45 +104577,45 @@ var ts; } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); + displayParts.push(ts.keywordPart(110 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { - displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); + displayParts.push(ts.keywordPart(77 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } - displayParts.push(ts.keywordPart(83 /* EnumKeyword */)); + displayParts.push(ts.keywordPart(84 /* EnumKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 242 /* ModuleDeclaration */); - var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 130 /* NamespaceKeyword */ : 129 /* ModuleKeyword */)); + var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 131 /* NamespaceKeyword */ : 130 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); if (symbol.parent) { @@ -100932,7 +104626,7 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 148 /* TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 150 /* TypeParameter */); if (decl === undefined) return ts.Debug.fail(); var declaration = decl.parent; @@ -100940,21 +104634,21 @@ var ts; if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 - if (declaration.kind === 159 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + if (declaration.kind === 161 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(95 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 158 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 160 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 240 /* TypeAliasDeclaration */) { + else if (declaration.kind === 242 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path addInPrefix(); - displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(140 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -100966,11 +104660,11 @@ var ts; symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 276 /* EnumMember */) { + if (declaration.kind === 278 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } @@ -100996,41 +104690,41 @@ var ts; } } switch (symbol.declarations[0].kind) { - case 245 /* NamespaceExportDeclaration */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 247 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(130 /* NamespaceKeyword */)); + displayParts.push(ts.keywordPart(131 /* NamespaceKeyword */)); break; - case 252 /* ExportAssignment */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 254 /* ExportAssignment */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 59 /* EqualsToken */ : 80 /* DefaultKeyword */)); break; - case 255 /* ExportSpecifier */: - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + case 257 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(85 /* ExportKeyword */)); break; default: - displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); + displayParts.push(ts.keywordPart(92 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 246 /* ImportEqualsDeclaration */) { + if (declaration.kind === 248 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(133 /* RequireKeyword */)); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.keywordPart(134 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); } else { var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58 /* EqualsToken */)); + displayParts.push(ts.operatorPart(59 /* EqualsToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(internalAliasSymbol, enclosingDeclaration); } @@ -101044,7 +104738,7 @@ var ts; if (type) { if (isThisExpression) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); + displayParts.push(ts.keywordPart(100 /* ThisKeyword */)); } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); @@ -101055,7 +104749,7 @@ var ts; symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || isThisExpression) { - displayParts.push(ts.punctuationPart(56 /* ColonToken */)); + displayParts.push(ts.punctuationPart(57 /* ColonToken */)); displayParts.push(ts.spacePart()); // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { @@ -101093,10 +104787,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 277 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 202 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -101118,7 +104812,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101139,7 +104833,7 @@ var ts; } function addInPrefix() { displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(92 /* InKeyword */)); + displayParts.push(ts.keywordPart(93 /* InKeyword */)); displayParts.push(ts.spacePart()); } function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { @@ -101149,7 +104843,7 @@ var ts; var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); if (symbol.flags & 16777216 /* Optional */) { - displayParts.push(ts.punctuationPart(55 /* QuestionToken */)); + displayParts.push(ts.punctuationPart(56 /* QuestionToken */)); } } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { @@ -101172,9 +104866,9 @@ var ts; displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); return; } } @@ -101183,20 +104877,21 @@ var ts; ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); - displayParts.push(ts.operatorPart(37 /* PlusToken */)); + displayParts.push(ts.punctuationPart(20 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(38 /* PlusToken */)); displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); displayParts.push(ts.spacePart()); displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(21 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); - getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); + getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -101208,16 +104903,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 194 /* FunctionExpression */) { + if (declaration.kind === 196 /* FunctionExpression */) { return true; } - if (declaration.kind !== 235 /* VariableDeclaration */ && declaration.kind !== 237 /* FunctionDeclaration */) { + if (declaration.kind !== 237 /* VariableDeclaration */ && declaration.kind !== 239 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 277 /* SourceFile */ || parent.kind === 243 /* ModuleBlock */) { + if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) { return false; } } @@ -101257,6 +104952,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +105026,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_16 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +105045,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_16(opt); } return options; } @@ -101376,16 +105072,11 @@ var ts; this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { - ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); - ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); - ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); - ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); - ts.Debug.assert(commonParent !== undefined, "commonParent is null"); - this.currentTokenSpan = currentRange; - this.currentTokenParent = currentTokenParent; - this.nextTokenSpan = nextRange; - this.nextTokenParent = nextTokenParent; - this.contextNode = commonParent; + this.currentTokenSpan = ts.Debug.assertDefined(currentRange); + this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent); + this.nextTokenSpan = ts.Debug.assertDefined(nextRange); + this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent); + this.contextNode = ts.Debug.assertDefined(commonParent); // drop cached results this.contextNodeAllOnSameLine = undefined; this.nextNodeAllOnSameLine = undefined; @@ -101431,8 +105122,8 @@ var ts; return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 17 /* OpenBraceToken */, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 18 /* CloseBraceToken */, this.sourceFile); + var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile); if (openBrace && closeBrace) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; @@ -101514,11 +105205,11 @@ var ts; } function shouldRescanGreaterThanToken(node) { switch (node.kind) { - case 31 /* GreaterThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 46 /* GreaterThanGreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanToken */: return true; } return false; @@ -101526,28 +105217,28 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 265 /* JsxAttribute */: - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 267 /* JsxAttribute */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. - return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; + return ts.isKeyword(node.kind) || node.kind === 72 /* Identifier */; } } return false; } function shouldRescanJsxText(node) { - return node.kind === 10 /* JsxText */; + return node.kind === 11 /* JsxText */; } function shouldRescanSlashToken(container) { - return container.kind === 12 /* RegularExpressionLiteral */; + return container.kind === 13 /* RegularExpressionLiteral */; } function shouldRescanTemplateToken(container) { - return container.kind === 15 /* TemplateMiddle */ || - container.kind === 16 /* TemplateTail */; + return container.kind === 16 /* TemplateMiddle */ || + container.kind === 17 /* TemplateTail */; } function startsWithSlashToken(t) { - return t === 41 /* SlashToken */ || t === 63 /* SlashEqualsToken */; + return t === 42 /* SlashToken */ || t === 64 /* SlashEqualsToken */; } function readTokenInfo(n) { ts.Debug.assert(isOnToken()); @@ -101617,7 +105308,7 @@ var ts; lastScanAction = 0 /* Scan */; switch (expectedScanAction) { case 1 /* RescanGreaterThanToken */: - if (token === 29 /* GreaterThanToken */) { + if (token === 30 /* GreaterThanToken */) { lastScanAction = 1 /* RescanGreaterThanToken */; var newToken = scanner.reScanGreaterToken(); ts.Debug.assert(n.kind === newToken); @@ -101633,7 +105324,7 @@ var ts; } break; case 3 /* RescanTemplateToken */: - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { lastScanAction = 3 /* RescanTemplateToken */; return scanner.reScanTemplateToken(); } @@ -101706,7 +105397,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 145 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 147 /* LastToken */; token++) { allTokens.push(token); } function anyTokenExcept() { @@ -101718,255 +105409,255 @@ var ts; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); - var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 145 /* LastKeyword */); - var binaryOperators = tokenRangeFromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 145 /* OfKeyword */, 118 /* AsKeyword */, 127 /* IsKeyword */]; - var unaryPrefixOperators = [43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]; + var keywords = tokenRangeFromRange(73 /* FirstKeyword */, 147 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(28 /* FirstBinaryOperator */, 71 /* LastBinaryOperator */); + var binaryKeywordOperators = [93 /* InKeyword */, 94 /* InstanceOfKeyword */, 147 /* OfKeyword */, 119 /* AsKeyword */, 128 /* IsKeyword */]; + var unaryPrefixOperators = [44 /* PlusPlusToken */, 45 /* MinusMinusToken */, 53 /* TildeToken */, 52 /* ExclamationToken */]; var unaryPrefixExpressions = [ - 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, - 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 72 /* Identifier */, 20 /* OpenParenToken */, + 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */ ]; - var unaryPreincrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; - var unaryPostincrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; - var unaryPredecrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; - var unaryPostdecrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; + var unaryPreincrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostincrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; + var unaryPredecrementExpressions = [72 /* Identifier */, 20 /* OpenParenToken */, 100 /* ThisKeyword */, 95 /* NewKeyword */]; + var unaryPostdecrementExpressions = [72 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 95 /* NewKeyword */]; var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; - var typeNames = [71 /* Identifier */].concat(ts.typeKeywords); + var typeNames = [72 /* Identifier */].concat(ts.typeKeywords); // Place a space before open brace in a function declaration // TypeScript: Function can have return types, which can be made of tons of different token kinds var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) - var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([72 /* Identifier */, 3 /* MultiLineCommentTrivia */, 76 /* ClassKeyword */, 85 /* ExportKeyword */, 92 /* ImportKeyword */]); // Place a space before open brace in a control flow construct - var controlOpenBraceLeftTokenRange = tokenRangeFrom([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); + var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 82 /* DoKeyword */, 103 /* TryKeyword */, 88 /* FinallyKeyword */, 83 /* ElseKeyword */]); // These rules are higher in priority than user-configurable var highPriorityCommonRules = [ // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), - rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), - rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), - rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NotSpaceBeforeColon", anyToken, 57 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), + rule("SpaceAfterColon", 57 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 56 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // insert space after '?' only when it is used in conditional operator - rule("SpaceAfterQuestionMarkInConditionalOperator", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + rule("SpaceAfterQuestionMarkInConditionalOperator", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), // in other cases there should be no space between '?' and next token - rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), + rule("NoSpaceAfterQuestionMark", 56 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 92 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), - rule("NoSpaceAfterUnaryPreincrementOperator", 43 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterUnaryPredecrementOperator", 44 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 44 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 45 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 45 /* MinusMinusToken */, [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 - rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterPostincrementWhenFollowedByAdd", 44 /* PlusPlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 38 /* PlusToken */, 38 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 38 /* PlusToken */, 44 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 45 /* MinusMinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 39 /* MinusToken */, 39 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 39 /* MinusToken */, 45 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // For functions and control block place } on a new line [multi-line rule] - rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), // Space/new line after }. - rule("SpaceAfterCloseBrace", 18 /* CloseBraceToken */, anyTokenExcept(20 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, 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 // Also should not apply to }) - rule("SpaceBetweenCloseBraceAndElse", 18 /* CloseBraceToken */, 82 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenCloseBraceAndWhile", 18 /* CloseBraceToken */, 106 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 83 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 107 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' - rule("SpaceAfterConditionalClosingParen", 20 /* CloseParenToken */, 21 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), - rule("NoSpaceBetweenFunctionKeywordAndStar", 89 /* FunctionKeyword */, 39 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), - rule("SpaceAfterStarInGeneratorDeclaration", 39 /* AsteriskToken */, [71 /* Identifier */, 19 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), - rule("SpaceAfterFunctionInFuncDecl", 89 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 90 /* FunctionKeyword */, 40 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 40 /* AsteriskToken */, [72 /* Identifier */, 20 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 90 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), // Insert new line after { and before } in multi-line contexts. - rule("NewLineAfterOpenBraceInBlockContext", 17 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: // get x() {} // set x(val) {} - rule("SpaceAfterGetSetInMember", [125 /* GetKeyword */, 136 /* SetKeyword */], 71 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceBetweenYieldKeywordAndStar", 116 /* YieldKeyword */, 39 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), - rule("SpaceBetweenYieldOrYieldStarAndOperand", [116 /* YieldKeyword */, 39 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), - rule("NoSpaceBetweenReturnAndSemicolon", 96 /* ReturnKeyword */, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterCertainKeywords", [104 /* VarKeyword */, 100 /* ThrowKeyword */, 94 /* NewKeyword */, 80 /* DeleteKeyword */, 96 /* ReturnKeyword */, 103 /* TypeOfKeyword */, 121 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceAfterLetConstInVariableDeclaration", [110 /* LetKeyword */, 76 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), - rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), + rule("SpaceAfterGetSetInMember", [126 /* GetKeyword */, 137 /* SetKeyword */], 72 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 117 /* YieldKeyword */, 40 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [117 /* YieldKeyword */, 40 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 97 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [105 /* VarKeyword */, 101 /* ThrowKeyword */, 95 /* NewKeyword */, 81 /* DeleteKeyword */, 97 /* ReturnKeyword */, 104 /* TypeOfKeyword */, 122 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [111 /* LetKeyword */, 77 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("SpaceAfterVoidOperator", 105 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 106 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), // Async-await - rule("SpaceBetweenAsyncAndOpenParen", 120 /* AsyncKeyword */, 19 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 120 /* AsyncKeyword */, 89 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndOpenParen", 121 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 121 /* AsyncKeyword */, 90 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), // Template string - rule("NoSpaceBetweenTagAndTemplateString", [71 /* Identifier */, 20 /* CloseParenToken */], [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenTagAndTemplateString", [72 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // JSX opening elements - rule("SpaceBeforeJsxAttribute", anyToken, 71 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 41 /* SlashToken */, 29 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 58 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterEqualInJsxAttribute", 58 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeJsxAttribute", anyToken, 72 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 42 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 42 /* SlashToken */, 30 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 59 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 59 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), // TypeScript-specific rules // Use of module as a function call. e.g.: import m2 = module("m2"); - rule("NoSpaceAfterModuleImport", [129 /* ModuleKeyword */, 133 /* RequireKeyword */], 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterModuleImport", [130 /* ModuleKeyword */, 134 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Add a space around certain TypeScript keywords rule("SpaceAfterCertainTypeScriptKeywords", [ - 117 /* AbstractKeyword */, - 75 /* ClassKeyword */, - 124 /* DeclareKeyword */, - 79 /* DefaultKeyword */, - 83 /* EnumKeyword */, - 84 /* ExportKeyword */, - 85 /* ExtendsKeyword */, - 125 /* GetKeyword */, - 108 /* ImplementsKeyword */, - 91 /* ImportKeyword */, - 109 /* InterfaceKeyword */, - 129 /* ModuleKeyword */, - 130 /* NamespaceKeyword */, - 112 /* PrivateKeyword */, - 114 /* PublicKeyword */, - 113 /* ProtectedKeyword */, - 132 /* ReadonlyKeyword */, - 136 /* SetKeyword */, - 115 /* StaticKeyword */, - 139 /* TypeKeyword */, - 143 /* FromKeyword */, - 128 /* KeyOfKeyword */, - 126 /* InferKeyword */, + 118 /* AbstractKeyword */, + 76 /* ClassKeyword */, + 125 /* DeclareKeyword */, + 80 /* DefaultKeyword */, + 84 /* EnumKeyword */, + 85 /* ExportKeyword */, + 86 /* ExtendsKeyword */, + 126 /* GetKeyword */, + 109 /* ImplementsKeyword */, + 92 /* ImportKeyword */, + 110 /* InterfaceKeyword */, + 130 /* ModuleKeyword */, + 131 /* NamespaceKeyword */, + 113 /* PrivateKeyword */, + 115 /* PublicKeyword */, + 114 /* ProtectedKeyword */, + 133 /* ReadonlyKeyword */, + 137 /* SetKeyword */, + 116 /* StaticKeyword */, + 140 /* TypeKeyword */, + 144 /* FromKeyword */, + 129 /* KeyOfKeyword */, + 127 /* InferKeyword */, ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 143 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [86 /* ExtendsKeyword */, 109 /* ImplementsKeyword */, 144 /* FromKeyword */], [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" { - rule("SpaceAfterModuleName", 9 /* StringLiteral */, 17 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), + rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), // Lambda expressions - rule("SpaceBeforeArrow", anyToken, 36 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceAfterArrow", 36 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeArrow", anyToken, 37 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 37 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Optional parameters and let args - rule("NoSpaceAfterEllipsis", 24 /* DotDotDotToken */, 71 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOptionalParameters", 55 /* QuestionToken */, [20 /* CloseParenToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 72 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 56 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // Remove spaces in empty interface literals. e.g.: x: {} - rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), // generics and type assertions - rule("NoSpaceBeforeOpenAngularBracket", typeNames, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceBetweenCloseParenAndAngularBracket", 20 /* CloseParenToken */, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterOpenAngularBracket", 27 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 28 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 28 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 30 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 30 /* GreaterThanToken */, [20 /* OpenParenToken */, 22 /* OpenBracketToken */, 30 /* GreaterThanToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), // decorators - rule("SpaceBeforeAt", [20 /* CloseParenToken */, 71 /* Identifier */], 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeAt", [21 /* CloseParenToken */, 72 /* Identifier */], 58 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 58 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after @ in decorator rule("SpaceAfterDecorator", anyToken, [ - 117 /* AbstractKeyword */, - 71 /* Identifier */, - 84 /* ExportKeyword */, - 79 /* DefaultKeyword */, - 75 /* ClassKeyword */, - 115 /* StaticKeyword */, - 114 /* PublicKeyword */, - 112 /* PrivateKeyword */, - 113 /* ProtectedKeyword */, - 125 /* GetKeyword */, - 136 /* SetKeyword */, - 21 /* OpenBracketToken */, - 39 /* AsteriskToken */, + 118 /* AbstractKeyword */, + 72 /* Identifier */, + 85 /* ExportKeyword */, + 80 /* DefaultKeyword */, + 76 /* ClassKeyword */, + 116 /* StaticKeyword */, + 115 /* PublicKeyword */, + 113 /* PrivateKeyword */, + 114 /* ProtectedKeyword */, + 126 /* GetKeyword */, + 137 /* SetKeyword */, + 22 /* OpenBracketToken */, + 40 /* AsteriskToken */, ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), - rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 51 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterNewKeywordOnConstructorSignature", 94 /* NewKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 52 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 95 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), ]; // These rules are applied after high priority var userConfigurableRules = [ // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses - rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), - rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), + rule("SpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 124 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), // Insert space after function keyword for anonymous functions - rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), + rule("SpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 90 /* FunctionKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), // Insert space after keywords in control flow statements - rule("SpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), - rule("NoSpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), + rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), // Insert space after opening and before closing nonempty parenthesis - rule("SpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBetweenOpenParens", 19 /* OpenParenToken */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenParens", 19 /* OpenParenToken */, 20 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing nonempty brackets - rule("SpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceBetweenBrackets", 21 /* OpenBracketToken */, 22 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - rule("SpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), - rule("SpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), - rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), - rule("NoSpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing template string braces - rule("SpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), - rule("NoSpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // No space after { and before } in JSX expression - rule("SpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), - rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), - rule("NoSpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), - rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), // Insert space after semicolon in for statement - rule("SpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), - rule("NoSpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), // Insert space before and after binary operators rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), - rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), - rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), // Open Brace braces after control block - rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), // Open Brace braces after function // TypeScript: Function can have return types, which can be made of tons of different token kinds - rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), // Open Brace braces after TypeScript module/class/interface - rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), - rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), - rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), - rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), - rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 30 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 57 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), ]; // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. var lowPriorityCommonRules = [ // Space after keyword but not before ; or : or ? - rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), - rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // No space before and after indexer `x[]` - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), - rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(121 /* AsyncKeyword */, 74 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Remove extra space between for and await - rule("SpaceBetweenForAndAwaitKeyword", 88 /* ForKeyword */, 121 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenForAndAwaitKeyword", 89 /* ForKeyword */, 122 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), // 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] - rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), + rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 82 /* DoKeyword */, 83 /* ElseKeyword */, 74 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterTryFinally", [103 /* TryKeyword */, 88 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), ]; return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); } @@ -102010,45 +105701,45 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 223 /* ForStatement */; + return context.contextNode.kind === 225 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 202 /* BinaryExpression */: - case 203 /* ConditionalExpression */: - case 173 /* ConditionalType */: - case 210 /* AsExpression */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 161 /* TypePredicate */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 175 /* ConditionalType */: + case 212 /* AsExpression */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 163 /* TypePredicate */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 184 /* BindingElement */: + case 186 /* BindingElement */: // equals in type X = ... - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: // equal in p = 0; - case 149 /* Parameter */: - case 276 /* EnumMember */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; + case 151 /* Parameter */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] - case 148 /* TypeParameter */: - return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; + case 150 /* TypeParameter */: + return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 225 /* ForOfStatement */: - return context.currentTokenSpan.kind === 145 /* OfKeyword */ || context.nextTokenSpan.kind === 145 /* OfKeyword */; + case 227 /* ForOfStatement */: + return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */; } return false; } @@ -102060,22 +105751,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 152 /* PropertyDeclaration */ || - contextKind === 151 /* PropertySignature */ || - contextKind === 149 /* Parameter */ || - contextKind === 235 /* VariableDeclaration */ || + return contextKind === 154 /* PropertyDeclaration */ || + contextKind === 153 /* PropertySignature */ || + contextKind === 151 /* Parameter */ || + contextKind === 237 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 203 /* ConditionalExpression */ || - context.contextNode.kind === 173 /* ConditionalType */; + return context.contextNode.kind === 205 /* ConditionalExpression */ || + context.contextNode.kind === 175 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 182 /* ObjectBindingPattern */ || - context.contextNode.kind === 179 /* MappedType */ || + return context.contextNode.kind === 184 /* ObjectBindingPattern */ || + context.contextNode.kind === 181 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -102101,31 +105792,31 @@ var ts; return true; } switch (node.kind) { - case 216 /* Block */: - case 244 /* CaseBlock */: - case 186 /* ObjectLiteralExpression */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 188 /* ObjectLiteralExpression */: + case 245 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // case SyntaxKind.MethodSignature: - case 158 /* CallSignature */: - case 194 /* FunctionExpression */: - case 155 /* Constructor */: - case 195 /* ArrowFunction */: + case 160 /* CallSignature */: + case 196 /* FunctionExpression */: + case 157 /* Constructor */: + case 197 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 239 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 241 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -102134,40 +105825,40 @@ var ts; return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 237 /* FunctionDeclaration */ || context.contextNode.kind === 194 /* FunctionExpression */; + return context.contextNode.kind === 239 /* FunctionDeclaration */ || context.contextNode.kind === 196 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 166 /* TypeLiteral */: - case 242 /* ModuleDeclaration */: - case 253 /* ExportDeclaration */: - case 254 /* NamedExports */: - case 247 /* ImportDeclaration */: - case 250 /* NamedImports */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 168 /* TypeLiteral */: + case 244 /* ModuleDeclaration */: + case 255 /* ExportDeclaration */: + case 256 /* NamedExports */: + case 249 /* ImportDeclaration */: + case 252 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 272 /* CatchClause */: - case 243 /* ModuleBlock */: - case 230 /* SwitchStatement */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 274 /* CatchClause */: + case 245 /* ModuleBlock */: + case 232 /* SwitchStatement */: return true; - case 216 /* Block */: { + case 218 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 195 /* ArrowFunction */ && blockParent.kind !== 194 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 197 /* ArrowFunction */ && blockParent.kind !== 196 /* FunctionExpression */) { return true; } } @@ -102176,64 +105867,64 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 220 /* IfStatement */: - case 230 /* SwitchStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 222 /* WhileStatement */: - case 233 /* TryStatement */: - case 221 /* DoStatement */: - case 229 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 231 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 272 /* CatchClause */: + case 274 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 186 /* ObjectLiteralExpression */; + return context.contextNode.kind === 188 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 189 /* CallExpression */; + return context.contextNode.kind === 191 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 190 /* NewExpression */; + return context.contextNode.kind === 192 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); } function isPreviousTokenNotComma(context) { - return context.currentTokenSpan.kind !== 26 /* CommaToken */; + return context.currentTokenSpan.kind !== 27 /* CommaToken */; } function isNextTokenNotCloseBracket(context) { - return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; + return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 195 /* ArrowFunction */; + return context.contextNode.kind === 197 /* ArrowFunction */; } function isImportTypeContext(context) { - return context.contextNode.kind === 181 /* ImportType */; + return context.contextNode.kind === 183 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; + return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 258 /* JsxElement */ && context.contextNode.kind !== 262 /* JsxFragment */; + return context.contextNode.kind !== 260 /* JsxElement */ && context.contextNode.kind !== 264 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 268 /* JsxExpression */ || context.contextNode.kind === 267 /* JsxSpreadAttribute */; + return context.contextNode.kind === 270 /* JsxExpression */ || context.contextNode.kind === 269 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 265 /* JsxAttribute */; + return context.nextTokenParent.kind === 267 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 265 /* JsxAttribute */; + return context.contextNode.kind === 267 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 259 /* JsxSelfClosingElement */; + return context.contextNode.kind === 261 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -102248,45 +105939,45 @@ var ts; while (ts.isExpressionNode(node)) { node = node.parent; } - return node.kind === 150 /* Decorator */; + return node.kind === 152 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 236 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 238 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 242 /* ModuleDeclaration */; + return context.contextNode.kind === 244 /* ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 166 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 168 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 159 /* ConstructSignature */; + return context.contextNode.kind === 161 /* ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { - if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { + if (token.kind !== 28 /* LessThanToken */ && token.kind !== 30 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 162 /* TypeReference */: - case 192 /* TypeAssertionExpression */: - case 240 /* TypeAliasDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 209 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 194 /* TypeAssertionExpression */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -102297,16 +105988,16 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 192 /* TypeAssertionExpression */; + return context.contextNode.kind === 194 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 198 /* VoidExpression */; + return context.currentTokenSpan.kind === 106 /* VoidKeyword */ && context.currentTokenParent.kind === 200 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 205 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 207 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 211 /* NonNullExpression */; + return context.contextNode.kind === 213 /* NonNullExpression */; } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -102357,12 +106048,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 145 /* LastKeyword */ && column <= 145 /* LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 147 /* LastKeyword */ && column <= 147 /* LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 145 /* LastToken */ + 1; + var mapRowLength = 147 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; @@ -102451,12 +106142,12 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, formatContext) { - var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25 /* SemicolonToken */, sourceFile); + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; function formatOnOpeningCurly(position, sourceFile, formatContext) { - var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17 /* OpenBraceToken */, sourceFile); + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile); if (!openingCurly) { return []; } @@ -102482,7 +106173,7 @@ var ts; } formatting.formatOnOpeningCurly = formatOnOpeningCurly; function formatOnClosingCurly(position, sourceFile, formatContext) { - var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18 /* CloseBraceToken */, sourceFile); + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; @@ -102540,17 +106231,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 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: var body = parent.body; - return !!body && body.kind === 243 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 277 /* SourceFile */: - case 216 /* Block */: - case 243 /* ModuleBlock */: + return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 279 /* SourceFile */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -102663,7 +106354,6 @@ var ts; } return 0; } - /* @internal */ function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { var range = { pos: 0, end: sourceFileLike.text.length }; return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors @@ -102693,7 +106383,7 @@ var ts; var previousParent; var previousRangeStartLine; var lastIndentedLine; - var indentationOnLastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -102707,7 +106397,7 @@ var ts; if (!formattingScanner.isOnToken()) { var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); // TODO: GH#18217 + indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); trimTrailingWhitespacesForRemainingRange(); } } @@ -102752,7 +106442,7 @@ var ts; }; } else if (inheritedIndentation === -1 /* Unknown */) { - if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) { + if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) { // the is used for chaining methods formatting // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; @@ -102773,19 +106463,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 238 /* ClassDeclaration */: return 75 /* ClassKeyword */; - case 239 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; - case 237 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; - case 241 /* EnumDeclaration */: return 241 /* EnumDeclaration */; - case 156 /* GetAccessor */: return 125 /* GetKeyword */; - case 157 /* SetAccessor */: return 136 /* SetKeyword */; - case 154 /* MethodDeclaration */: + case 240 /* ClassDeclaration */: return 76 /* ClassKeyword */; + case 241 /* InterfaceDeclaration */: return 110 /* InterfaceKeyword */; + case 239 /* FunctionDeclaration */: return 90 /* FunctionKeyword */; + case 243 /* EnumDeclaration */: return 243 /* EnumDeclaration */; + case 158 /* GetAccessor */: return 126 /* GetKeyword */; + case 159 /* SetAccessor */: return 137 /* SetKeyword */; + case 156 /* MethodDeclaration */: if (node.asteriskToken) { - return 39 /* AsteriskToken */; + return 40 /* AsteriskToken */; } // falls through - case 152 /* PropertyDeclaration */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: var name = ts.getNameOfDeclaration(node); if (name) { return name.kind; @@ -102800,15 +106490,25 @@ var ts; // .. { // // comment // } - case 18 /* CloseBraceToken */: - case 22 /* CloseBracketToken */: - case 20 /* CloseParenToken */: + case 19 /* CloseBraceToken */: + case 23 /* CloseBracketToken */: + case 21 /* CloseParenToken */: return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind, container) { - return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; + // if list end token is LessThanToken '>' then its delta should be explicitly suppressed + // so that LessThanToken as a binary operator can still be indented. + // foo.then + // < + // number, + // string, + // >(); + // vs + // var a = xValue + // > yValue; + getIndentationForToken: function (line, kind, container, suppressDelta) { + return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, getDelta: getDelta, @@ -102822,26 +106522,25 @@ var ts; function shouldAddDelta(line, kind, container) { switch (kind) { // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 17 /* OpenBraceToken */: - case 18 /* CloseBraceToken */: - case 19 /* OpenParenToken */: - case 20 /* CloseParenToken */: - case 82 /* ElseKeyword */: - case 106 /* WhileKeyword */: - case 57 /* AtToken */: + case 18 /* OpenBraceToken */: + case 19 /* CloseBraceToken */: + case 21 /* CloseParenToken */: + case 83 /* ElseKeyword */: + case 107 /* WhileKeyword */: + case 58 /* AtToken */: return false; - case 41 /* SlashToken */: - case 29 /* GreaterThanToken */: + case 42 /* SlashToken */: + case 30 /* GreaterThanToken */: switch (container.kind) { - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: return false; } break; - case 21 /* OpenBracketToken */: - case 22 /* CloseBracketToken */: - if (container.kind !== 179 /* MappedType */) { + case 22 /* OpenBracketToken */: + case 23 /* CloseBracketToken */: + if (container.kind !== 181 /* MappedType */) { return false; } break; @@ -102926,22 +106625,22 @@ var ts; return inheritedIndentation; } // JSX text shouldn't affect indenting - if (ts.isToken(child) && child.kind !== 10 /* JsxText */) { + if (ts.isToken(child) && child.kind !== 11 /* JsxText */) { // 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, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 150 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 152 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); - if (child.kind === 10 /* JsxText */) { + if (child.kind === 11 /* JsxText */) { var range = { pos: child.getStart(), end: child.getEnd() }; indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); } childContextNode = node; - if (isFirstListItem && parent.kind === 185 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 187 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -102962,9 +106661,20 @@ var ts; else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta); - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + var indentationOnListStartToken = void 0; + if (indentationOnLastIndentedLine !== -1 /* Unknown */) { + // scanner just processed list start token so consider last indentation as list indentation + // function foo(): { // last indentation was 0, list item will be indented based on this value + // foo: number; + // }: {}; + indentationOnListStartToken = indentationOnLastIndentedLine; + } + else { + var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile); + indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options); + } + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217 } else { // consume any tokens that precede the list as child elements of 'node' using its indentation scope @@ -102980,21 +106690,21 @@ var ts; var listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); - if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true); } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -103026,32 +106736,12 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : -1 /* Unknown */; var indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); - for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { - var triviaItem = _a[_i]; - var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); - switch (triviaItem.kind) { - case 3 /* MultiLineCommentTrivia */: - if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); - } - indentNextTokenOrTrivia = false; - break; - case 2 /* SingleLineCommentTrivia */: - if (indentNextTokenOrTrivia && triviaInRange) { - insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); - } - indentNextTokenOrTrivia = false; - break; - case 4 /* NewLineTrivia */: - indentNextTokenOrTrivia = true; - break; - } - } + var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); }); } // indent token only if is it is in target range and does not overlap with any error ranges if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { @@ -103064,16 +106754,39 @@ var ts; childContextNode = parent; } } - function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) { for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { var triviaItem = trivia_1[_i]; + var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); + switch (triviaItem.kind) { + case 3 /* MultiLineCommentTrivia */: + if (triviaInRange) { + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + } + indentNextTokenOrTrivia = false; + break; + case 2 /* SingleLineCommentTrivia */: + if (indentNextTokenOrTrivia && triviaInRange) { + indentSingleLine(triviaItem); + } + indentNextTokenOrTrivia = false; + break; + case 4 /* NewLineTrivia */: + indentNextTokenOrTrivia = true; + break; + } + } + return indentNextTokenOrTrivia; + } + function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) { + var triviaItem = trivia_2[_i]; if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); } } } - // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAction = 0 /* None */; @@ -103245,7 +106958,10 @@ var ts; * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - var startPosition = previousRange ? previousRange.end : originalRange.pos; + if (!previousRange) { + return; + } + var startPosition = previousRange.end; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); @@ -103345,41 +107061,46 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 195 /* ArrowFunction */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 197 /* ArrowFunction */: if (node.typeParameters === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } else if (node.parameters === list) { - return 19 /* OpenParenToken */; + return 20 /* OpenParenToken */; } break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: if (node.typeArguments === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } else if (node.arguments === list) { - return 19 /* OpenParenToken */; + return 20 /* OpenParenToken */; } break; - case 162 /* TypeReference */: + case 164 /* TypeReference */: if (node.typeArguments === list) { - return 27 /* LessThanToken */; + return 28 /* LessThanToken */; } + break; + case 168 /* TypeLiteral */: + return 18 /* OpenBraceToken */; } return 0 /* Unknown */; } function getCloseTokenForOpenToken(kind) { switch (kind) { - case 19 /* OpenParenToken */: - return 20 /* CloseParenToken */; - case 27 /* LessThanToken */: - return 29 /* GreaterThanToken */; + case 20 /* OpenParenToken */: + return 21 /* CloseParenToken */; + case 28 /* LessThanToken */: + return 30 /* GreaterThanToken */; + case 18 /* OpenBraceToken */: + return 19 /* CloseBraceToken */; } return 0 /* Unknown */; } @@ -103484,13 +107205,18 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 202 /* BinaryExpression */) { + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 204 /* 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 */) { return actualIndentation; } } + var containerList = getListByPosition(position, precedingToken.parent, sourceFile); + // use list position if the preceding token is before any list items + if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) { + return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217 + } return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); } SmartIndenter.getIndentation = getIndentation; @@ -103501,12 +107227,12 @@ var ts; if (previousLine <= commentStartLine) { return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); } - var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); - var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; if (column === 0) { return column; } - var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; } function getBlockIndent(sourceFile, position, options) { @@ -103539,14 +107265,13 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 } // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); + // do not consider parent-child line sharing yet: + // function foo(a + // | preceding node 'a' does share line with its parent but indentation is expected + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } - actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); - if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; // TODO: GH#18217 - } previous = current; current = current.parent; } @@ -103573,23 +107298,17 @@ var ts; var start = current.getStart(sourceFile); useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; } - if (useActualIndentation) { - // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); - if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + indentationDelta; - } - } var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { - // try to fetch actual indentation for current node from source text - var actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); + // check if current node is a list item - if yes, take indentation from it + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } - actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + // try to fetch actual indentation for current node from source text + actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -103640,7 +107359,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.isStatementButNotDeclaration(current)) && - (parent.kind === 277 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -103657,11 +107376,11 @@ var ts; if (!nextToken) { return 0 /* Unknown */; } - if (nextToken.kind === 17 /* OpenBraceToken */) { + if (nextToken.kind === 18 /* OpenBraceToken */) { // open braces are always indented at the parent level return 1 /* OpenBrace */; } - else if (nextToken.kind === 18 /* CloseBraceToken */) { + else if (nextToken.kind === 19 /* CloseBraceToken */) { // close braces are indented at the parent level if they are located on the same line with cursor // this means that if new line will be added at $ position, this case will be indented // class A { @@ -103688,8 +107407,8 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 220 /* IfStatement */ && parent.elseStatement === child) { - var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile); + if (parent.kind === 222 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 83 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; @@ -103697,103 +107416,87 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; - function getListIfStartEndIsInListRange(list, start, end) { - return list && ts.rangeContainsStartEnd(list, start, end) ? list : undefined; - } function getContainingList(node, sourceFile) { - if (node.parent) { - var end = node.end; - switch (node.parent.kind) { - case 162 /* TypeReference */: - return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); - case 186 /* ObjectLiteralExpression */: - return node.parent.properties; - case 185 /* ArrayLiteralExpression */: - return node.parent.elements; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 155 /* Constructor */: - case 164 /* ConstructorType */: - case 159 /* ConstructSignature */: { - var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || - getListIfStartEndIsInListRange(node.parent.parameters, start, end); - } - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: { - var typeParameters = node.parent.typeParameters; - return getListIfStartEndIsInListRange(typeParameters, node.getStart(sourceFile), end); - } - case 190 /* NewExpression */: - case 189 /* CallExpression */: { - var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || - getListIfStartEndIsInListRange(node.parent.arguments, start, end); - } - case 236 /* VariableDeclarationList */: - return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); - case 250 /* NamedImports */: - case 254 /* NamedExports */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); - } - } - return undefined; + return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile); } SmartIndenter.getContainingList = getContainingList; - function getActualIndentationForListItem(node, sourceFile, options) { + function getListByPosition(pos, node, sourceFile) { + return node && getListByRange(pos, pos, node, sourceFile); + } + function getListByRange(start, end, node, sourceFile) { + switch (node.kind) { + case 164 /* TypeReference */: + return getList(node.typeArguments); + case 188 /* ObjectLiteralExpression */: + return getList(node.properties); + case 187 /* ArrayLiteralExpression */: + return getList(node.elements); + case 168 /* TypeLiteral */: + return getList(node.members); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 157 /* Constructor */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: + return getList(node.typeParameters) || getList(node.parameters); + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + return getList(node.typeParameters); + case 192 /* NewExpression */: + case 191 /* CallExpression */: + return getList(node.typeArguments) || getList(node.arguments); + case 238 /* VariableDeclarationList */: + return getList(node.declarations); + case 252 /* NamedImports */: + case 256 /* NamedExports */: + return getList(node.elements); + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return getList(node.elements); + } + function getList(list) { + return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined; + } + } + function getVisualListRange(node, list, sourceFile) { + var children = node.getChildren(sourceFile); + for (var i = 1; i < children.length - 1; i++) { + if (children[i].pos === list.pos && children[i].end === list.end) { + return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) }; + } + } + return list; + } + function getActualIndentationForListStartLine(list, sourceFile, options) { + if (!list) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); + } + function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { + if (node.parent && node.parent.kind === 238 /* VariableDeclarationList */) { + // VariableDeclarationList has no wrapping tokens + return -1 /* Unknown */; + } var containingList = getContainingList(node, sourceFile); if (containingList) { var index = containingList.indexOf(node); if (index !== -1) { - return deriveActualIndentationFromList(containingList, index, sourceFile, options); - } - } - return -1 /* Unknown */; - } - function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { - // actual indentation should not be used when: - // - node is close parenthesis - this is the end of the expression - if (node.kind === 20 /* CloseParenToken */) { - return -1 /* Unknown */; - } - if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { - var fullCallOrNewExpression = node.parent.expression; - var startingExpression = getStartingExpression(fullCallOrNewExpression); - if (fullCallOrNewExpression === startingExpression) { - return -1 /* Unknown */; - } - var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); - var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); - if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { - return -1 /* Unknown */; - } - return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); - } - return -1 /* Unknown */; - function getStartingExpression(node) { - while (true) { - switch (node.kind) { - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - node = node.expression; - break; - default: - return node; + var result = deriveActualIndentationFromList(containingList, index, sourceFile, options); + if (result !== -1 /* Unknown */) { + return result; } } + return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217 } + return -1 /* Unknown */; } function deriveActualIndentationFromList(list, index, sourceFile, options) { ts.Debug.assert(index >= 0 && index < list.length); @@ -103802,7 +107505,7 @@ var ts; // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for (var i = index - 1; i >= 0; i--) { - if (list[i].kind === 26 /* CommaToken */) { + if (list[i].kind === 27 /* CommaToken */) { continue; } // skip list items that ends on the same line with the current list element @@ -103851,83 +107554,83 @@ var ts; function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 219 /* ExpressionStatement */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 185 /* ArrayLiteralExpression */: - case 216 /* Block */: - case 243 /* ModuleBlock */: - case 186 /* ObjectLiteralExpression */: - case 166 /* TypeLiteral */: - case 179 /* MappedType */: - case 168 /* TupleType */: - case 244 /* CaseBlock */: - case 270 /* DefaultClause */: - case 269 /* CaseClause */: - case 193 /* ParenthesizedExpression */: - case 187 /* PropertyAccessExpression */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 217 /* VariableStatement */: - case 252 /* ExportAssignment */: - case 228 /* ReturnStatement */: - case 203 /* ConditionalExpression */: - case 183 /* ArrayBindingPattern */: - case 182 /* ObjectBindingPattern */: - case 260 /* JsxOpeningElement */: - case 263 /* JsxOpeningFragment */: - case 259 /* JsxSelfClosingElement */: - case 268 /* JsxExpression */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 149 /* Parameter */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 175 /* ParenthesizedType */: - case 191 /* TaggedTemplateExpression */: - case 199 /* AwaitExpression */: - case 254 /* NamedExports */: - case 250 /* NamedImports */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 152 /* PropertyDeclaration */: + case 221 /* ExpressionStatement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 187 /* ArrayLiteralExpression */: + case 218 /* Block */: + case 245 /* ModuleBlock */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 181 /* MappedType */: + case 170 /* TupleType */: + case 246 /* CaseBlock */: + case 272 /* DefaultClause */: + case 271 /* CaseClause */: + case 195 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 219 /* VariableStatement */: + case 254 /* ExportAssignment */: + case 230 /* ReturnStatement */: + case 205 /* ConditionalExpression */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: + case 261 /* JsxSelfClosingElement */: + case 270 /* JsxExpression */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 151 /* Parameter */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 177 /* ParenthesizedType */: + case 193 /* TaggedTemplateExpression */: + case 201 /* AwaitExpression */: + case 256 /* NamedExports */: + case 252 /* NamedImports */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 154 /* PropertyDeclaration */: return true; - case 235 /* VariableDeclaration */: - case 273 /* PropertyAssignment */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 186 /* ObjectLiteralExpression */) { // TODO: GH#18217 + case 237 /* VariableDeclaration */: + case 275 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 188 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } return true; - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 220 /* IfStatement */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 195 /* ArrowFunction */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return childKind !== 216 /* Block */; - case 253 /* ExportDeclaration */: - return childKind !== 254 /* NamedExports */; - case 247 /* ImportDeclaration */: - return childKind !== 248 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 250 /* NamedImports */); - case 258 /* JsxElement */: - return childKind !== 261 /* JsxClosingElement */; - case 262 /* JsxFragment */: - return childKind !== 264 /* JsxClosingFragment */; - case 172 /* IntersectionType */: - case 171 /* UnionType */: - if (childKind === 166 /* TypeLiteral */) { + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 222 /* IfStatement */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return childKind !== 218 /* Block */; + case 255 /* ExportDeclaration */: + return childKind !== 256 /* NamedExports */; + case 249 /* ImportDeclaration */: + return childKind !== 250 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 252 /* NamedImports */); + case 260 /* JsxElement */: + return childKind !== 263 /* JsxClosingElement */; + case 264 /* JsxFragment */: + return childKind !== 266 /* JsxClosingFragment */; + case 174 /* IntersectionType */: + case 173 /* UnionType */: + if (childKind === 168 /* TypeLiteral */) { return false; } // falls through @@ -103938,11 +107641,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: - return parent.kind !== 216 /* Block */; + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + return parent.kind !== 218 /* Block */; default: return false; } @@ -104070,7 +107773,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 186 /* ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 188 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -104099,7 +107802,6 @@ var ts; }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); - return this; }; ChangeTracker.prototype.delete = function (sourceFile, node) { this.deletedNodes.push({ sourceFile: sourceFile, node: node }); @@ -104112,7 +107814,6 @@ var ts; var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - return this; }; ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { if (options === void 0) { options = {}; } @@ -104123,11 +107824,10 @@ var ts; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); - return this; }; ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } @@ -104136,31 +107836,33 @@ var ts; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); - return this; }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + }; + ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) { + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } - return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); - return next && next.kind === 26 /* CommaToken */ ? next : undefined; + return next && next.kind === 27 /* CommaToken */ ? next : undefined; }; ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); - return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); + this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -104175,7 +107877,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -104190,17 +107900,32 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) { + var fnStart = node.getStart(sourceFile); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsdoc = _a[_i]; + this.deleteRange(sourceFile, { + pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + }); + } + } + var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); + var indent = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { var endNode; if (ts.isFunctionLike(node)) { - endNode = ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile); + endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) return; // Function missing parentheses, give up @@ -104209,13 +107934,13 @@ var ts; } } else { - endNode = node.kind !== 235 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + endNode = node.kind !== 237 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter - var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); }; ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { @@ -104256,30 +107981,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +108034,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104314,18 +108046,18 @@ var ts; }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - case 235 /* VariableDeclaration */: - case 9 /* StringLiteral */: - case 71 /* Identifier */: + case 237 /* VariableDeclaration */: + case 10 /* StringLiteral */: + case 72 /* Identifier */: return { prefix: ", " }; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return { suffix: "," + this.newLineCharacter }; - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: return { prefix: " " }; - case 149 /* Parameter */: + case 151 /* Parameter */: return {}; default: ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it @@ -104334,28 +108066,28 @@ var ts; }; ChangeTracker.prototype.insertName = function (sourceFile, node, name) { ts.Debug.assert(!node.name); - if (node.kind === 195 /* ArrowFunction */) { - var arrow = ts.findChildOfKind(node, 36 /* EqualsGreaterThanToken */, sourceFile); - var lparen = ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile); + if (node.kind === 197 /* ArrowFunction */) { + var arrow = ts.findChildOfKind(node, 37 /* EqualsGreaterThanToken */, sourceFile); + var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); if (lparen) { // `() => {}` --> `function f() {}` - this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(89 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(90 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); deleteNode(this, sourceFile, arrow); } else { // `x => {}` -> `function f(x) {}` this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` - this.replaceRange(sourceFile, arrow, ts.createToken(20 /* CloseParenToken */)); + this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */)); } - if (node.body.kind !== 216 /* Block */) { + if (node.body.kind !== 218 /* Block */) { // `() => 0` => `function f() { return 0; }` - this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(17 /* OpenBraceToken */), ts.createToken(96 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); - this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(25 /* SemicolonToken */), ts.createToken(18 /* CloseBraceToken */)], { joiner: " " }); + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(97 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); + this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " }); } } else { - var pos = ts.findChildOfKind(node, node.kind === 194 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end; + var pos = ts.findChildOfKind(node, node.kind === 196 /* FunctionExpression */ ? 90 /* FunctionKeyword */ : 76 /* ClassKeyword */, sourceFile).end; this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } }; @@ -104371,11 +108103,11 @@ var ts; if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } if (!containingList) { ts.Debug.fail("node is not a list element"); - return this; + return; } var index = ts.indexOfNode(containingList, after); if (index < 0) { - return this; + return; } var end = after.getEnd(); if (index !== containingList.length - 1) { @@ -104427,7 +108159,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104443,12 +108175,12 @@ var ts; // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise // i.e. var x = 1 // this is x // | new element will be inserted at this position - separator = 26 /* CommaToken */; + separator = 27 /* CommaToken */; } else { // element has more than one element, pick separator from the list var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile); - separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 26 /* CommaToken */; + separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */; // determine if list is multiline by checking lines of after element and element that precedes it. var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile); multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition; @@ -104459,7 +108191,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +108199,28 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } - return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; - var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var _loop_17 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +108233,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_17(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +108272,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { - return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; + function getClassOrObjectBraceEnds(cls, sourceFile) { + return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +108290,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +108307,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes) + newLineCharacter; + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,9 +108356,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -104698,6 +108441,9 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeComment = function (s) { + this.writer.writeComment(s); + }; Writer.prototype.writeKeyword = function (s) { this.writer.writeKeyword(s); this.setLastNonTriviaPosition(s, /*force*/ false); @@ -104710,6 +108456,10 @@ var ts; this.writer.writePunctuation(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeTrailingSemicolon = function (s) { + this.writer.writeTrailingSemicolon(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; Writer.prototype.writeParameter = function (s) { this.writer.writeParameter(s); this.setLastNonTriviaPosition(s, /*force*/ false); @@ -104730,9 +108480,6 @@ var ts; this.writer.writeSymbol(s, sym); this.setLastNonTriviaPosition(s, /*force*/ false); }; - Writer.prototype.writeTextOfNode = function (text, node) { - this.writer.writeTextOfNode(text, node); - }; Writer.prototype.writeLine = function () { this.writer.writeLine(); }; @@ -104774,10 +108521,25 @@ var ts; }; return Writer; }()); - function getInsertionPositionAtSourceFileTop(_a) { - var text = _a.text; - var shebang = ts.getShebang(text); + function getInsertionPositionAtSourceFileTop(sourceFile) { + var lastPrologue; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + if (ts.isPrologueDirective(node)) { + lastPrologue = node; + } + else { + break; + } + } var position = 0; + var text = sourceFile.text; + if (lastPrologue) { + position = lastPrologue.end; + advancePastLineBreak(); + return position; + } + var shebang = ts.getShebang(text); if (shebang !== undefined) { position = shebang.length; advancePastLineBreak(); @@ -104793,8 +108555,8 @@ var ts; ranges = ranges.slice(1); } // As well as any triple slash references - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; + for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) { + var range = ranges_1[_b]; if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { position = range.end; advancePastLineBreak(); @@ -104816,45 +108578,40 @@ var ts; } } function isValidLocationToAddComment(sourceFile, position) { - return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position); } textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; function needSemicolonBetween(a, b) { - return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 147 /* ComputedPropertyName */ + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 149 /* ComputedPropertyName */ || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` } var deleteDeclaration; (function (deleteDeclaration_1) { function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { switch (node.kind) { - case 149 /* Parameter */: { + case 151 /* Parameter */: { var oldFunction = node.parent; - if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + if (ts.isArrowFunction(oldFunction) && + oldFunction.parameters.length === 1 && + !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the // case if the parameter is simply removed (e.g. in `x => 1`). - var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, - /*parameters*/ undefined, // TODO: GH#18217 - oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); - // Drop leading and trailing trivia of the new function because we're only going - // to replace the span (vs the full span) of the old function - the old leading - // and trailing trivia will remain. - ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction); + changes.replaceNodeWithText(sourceFile, node, "()"); } else { deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; } - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: deleteNode(changes, sourceFile, node, // For first import, leave header comment in place node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: var pattern = node.parent; - var preserveComma = pattern.kind === 183 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + var preserveComma = pattern.kind === 185 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); if (preserveComma) { deleteNode(changes, sourceFile, node); } @@ -104862,13 +108619,13 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { deleteImportBinding(changes, sourceFile, namedImports); @@ -104877,7 +108634,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; default: @@ -104888,7 +108645,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } else { - deleteNode(changes, sourceFile, node, node.kind === 25 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); } } } @@ -104902,7 +108659,7 @@ var ts; // import |d,| * as ns from './file' var start = importClause.name.getStart(sourceFile); var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { + if (nextToken && nextToken.kind === 27 /* CommaToken */) { // shift first non-whitespace position after comma to the start position of the node var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); changes.deleteRange(sourceFile, { pos: start, end: end }); @@ -104924,15 +108681,15 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(node, 247 /* ImportDeclaration */); + var importDecl = ts.getAncestor(node, 249 /* ImportDeclaration */); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { var parent = node.parent; - if (parent.kind === 272 /* CatchClause */) { + if (parent.kind === 274 /* CatchClause */) { // TODO: There's currently no unused diagnostic for this, could be a suggestion - changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 19 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 20 /* CloseParenToken */, sourceFile)); + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); return; } if (parent.declarations.length !== 1) { @@ -104941,14 +108698,14 @@ var ts; } var gp = parent.parent; switch (gp.kind) { - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: deleteNode(changes, sourceFile, parent); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: deleteNode(changes, sourceFile, gp); break; default: @@ -105093,6 +108850,32 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addConvertToUnknownForNonOverlappingTypes"; + var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var assertion = ts.Debug.assertDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); })); + var replacement = ts.isAsExpression(assertion) + ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(143 /* UnknownKeyword */)) + : ts.createTypeAssertion(ts.createKeywordTypeNode(143 /* UnknownKeyword */), assertion.expression); + changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -105160,9 +108943,9 @@ var ts; if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } - var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile); if (needParens) - changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(19 /* OpenParenToken */)); + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */)); for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { var param = _a[_i]; if (!param.type) { @@ -105172,7 +108955,7 @@ var ts; } } if (needParens) - changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(20 /* CloseParenToken */)); + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */)); if (!decl.type) { var returnType = ts.getJSDocReturnType(decl); if (returnType) @@ -105187,26 +108970,26 @@ var ts; } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 235 /* VariableDeclaration */ || - node.kind === 151 /* PropertySignature */ || - node.kind === 152 /* PropertyDeclaration */; + node.kind === 237 /* VariableDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 154 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 285 /* JSDocNonNullableType */: + case 287 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return transformJSDocFunctionType(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return transformJSDocTypeReference(node); default: var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 @@ -105228,9 +109011,9 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 288 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); - var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; + var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); } function transformJSDocTypeReference(node) { @@ -105268,8 +109051,8 @@ var ts; var index = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s", - /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []), + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 135 /* NumberKeyword */ ? "number" : "string", []), /*initializer*/ undefined); var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); ts.setEmitFlags(indexSignature, 1 /* SingleLine */); @@ -105279,6 +109062,784 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var token = ts.getTokenAtPosition(sourceFile, start); + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var markSeen = ts.nodeSeenTracker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + }); + }, + }); + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; + default: + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode) { + switch (errorCode) { + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 72 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 100 /* ThisKeyword */) { + return undefined; + } + var parent = token.parent; + errorCode = mapSuggestionDiagnostic(errorCode); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags + var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ ""); + addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + } + return parent; + } + return undefined; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + return symbol.valueDeclaration; + } + return undefined; + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + return param; + } + return undefined; + // Get Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: + case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + return containingFunction; + } + return undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + return containingFunction; + } + return undefined; + default: + return ts.Debug.fail(String(errorCode)); + } + } + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + } + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + return true; + case 196 /* FunctionExpression */: + var parent = declaration.parent; + return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) || !!declaration.name; + } + return false; + } + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return; + } + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } + } + } + } + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } + } + } + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) { + var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; + if (!parent) { + return; + } + var typeExpression = ts.createJSDocTypeExpression(typeNode); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } + } + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + var paramTags = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + // only infer parameters that have (1) no type and (2) an accessible inferred type + if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name)) + return; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + var name = ts.getSynthesizedClone(param.name); + ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */); + return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), ""); + }); + addJSDocTags(changes, sourceFile, signature, paramTags); + } + function addJSDocTags(changes, sourceFile, parent, newTags) { + var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags))); + changes.insertJsdocCommentBefore(sourceFile, parent, tag); + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 299 /* JSDocParameterTag */: { + var oldParam = oldTag; + var newParam = newTag; + return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + : undefined; + } + case 300 /* JSDocReturnTag */: + return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); + } + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } + }); + return typeIsAccessible ? res : undefined; + } + function getReferences(token, program, cancellationToken) { + // Position shouldn't matter since token is not a SourceFile. + return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + }); + } + function inferTypeForVariableFromUsage(token, program, cancellationToken) { + var references = getReferences(token, program, cancellationToken); + var checker = program.getTypeChecker(); + var types = InferFromReference.inferTypesFromReferences(references, checker, cancellationToken); + return InferFromReference.unifyFromContext(types, checker); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + var searchToken; + switch (containingFunction.kind) { + case 157 /* Constructor */: + searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); + break; + case 196 /* FunctionExpression */: + var parent = containingFunction.parent; + searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + searchToken = containingFunction.name; + break; + } + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypesFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return inferFromContext(usageContext, checker); + } + InferFromReference.inferTypesFromReferences = inferTypesFromReferences; + function inferTypeForParametersFromReferences(references, declaration, program, cancellationToken) { + var checker = program.getTypeChecker(); + if (references.length === 0) { + return undefined; + } + if (!declaration.parameters) { + return undefined; + } + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []); + return declaration.parameters.map(function (parameter, parameterIndex) { + var types = []; + var isRest = ts.isRestParameter(parameter); + var isOptional = false; + for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { + var callContext = callContexts_1[_i]; + if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); + types.push(checker.getUndefinedType()); + } + else if (isRest) { + for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + } + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + if (ts.isIdentifier(parameter.name)) { + var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken); + types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); + } + var type = unifyFromContext(types, checker); + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; + }); + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 203 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 202 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 204 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 191 /* CallExpression */: + case 192 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 189 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 190 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + case 237 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + usageContext.isNumber = true; + break; + case 38 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + // case SyntaxKind.ExclamationToken: + // no inferences here; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 41 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: + // ShiftOperator + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 49 /* AmpersandToken */: + case 50 /* BarToken */: + case 51 /* CaretToken */: + // CompoundAssignmentOperator + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 70 /* BarEqualsToken */: + case 71 /* CaretEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 39 /* MinusToken */: + // RelationalOperator + case 28 /* LessThanToken */: + case 31 /* LessThanEqualsToken */: + case 30 /* GreaterThanToken */: + case 32 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 60 /* PlusEqualsToken */: + case 38 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 1056 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 296 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 132 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 59 /* EqualsToken */: + case 33 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 93 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 55 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 237 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + case 94 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 191 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent.argumentExpression); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 296 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function removeLowPriorityInferences(inferences, priorities) { + var toRemove = []; + for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) { + var i = inferences_2[_i]; + for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) { + var _b = priorities_1[_a], high = _b.high, low = _b.low; + if (high(i)) { + ts.Debug.assert(!low(i)); + toRemove.push(low); + } + } + } + return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); }); + } + function unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + // 1. string or number individually override string | number + // 2. non-any, non-void overrides any or void + // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types + var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); + var priorities = [ + { + high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); }, + low: function (t) { return t === stringNumber; } + }, + { + high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); }, + low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); } + }, + { + high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); }, + low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); } + } + ]; + var good = removeLowPriorityInferences(inferences, priorities); + var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + if (anons.length) { + good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + good.push(unifyAnonymousTypes(anons, checker)); + } + return checker.getWidenedType(checker.getUnionType(good)); + } + InferFromReference.unifyFromContext = unifyFromContext; + function unifyAnonymousTypes(anons, checker) { + if (anons.length === 1) { + return anons[0]; + } + var calls = []; + var constructs = []; + var stringIndices = []; + var numberIndices = []; + var stringIndexReadonly = false; + var numberIndexReadonly = false; + var props = ts.createMultiMap(); + for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) { + var anon = anons_1[_i]; + for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { + var p = _b[_a]; + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); + constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } + } + var members = ts.mapEntries(props, function (name, types) { + var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; + var s = checker.createSymbol(4 /* Property */ | isOptional, name); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + function inferFromContext(usageContext, checker) { + var types = []; + if (usageContext.isNumber) { + types.push(checker.getNumberType()); + } + if (usageContext.isString) { + types.push(checker.getStringType()); + } + if (usageContext.isNumberOrString) { + types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); + } + types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 + var types_19 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + types_19.push(checker.createPromiseType(types_19.length ? checker.getUnionType(types_19, 2 /* Subtype */) : checker.getAnyType())); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker))); + } + if (usageContext.numberIndexContext) { + types.push(checker.createArrayType(recur(usageContext.numberIndexContext))); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { + var members_6 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = recur(context); + members_6.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); + } + types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 + } + return types; + function recur(innerContext) { + return unifyFromContext(inferFromContext(innerContext, checker), checker); + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = unifyFromContext(inferFromContext(callContext.returnType, checker), checker, checker.getVoidType()); + // TODO: GH#18217 + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return !!usageContext && !!usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -105303,12 +109864,12 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: precedingNode = ctorDeclaration; changes.delete(sourceFile, ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: precedingNode = ctorDeclaration.parent.parent; newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { @@ -105340,7 +109901,7 @@ var ts; // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); + var memberElement = createClassElement(member, [ts.createToken(116 /* StaticKeyword */)]); if (memberElement) { memberElements.push(memberElement); } @@ -105363,7 +109924,7 @@ var ts; return; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 219 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 221 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentBinaryExpression.right) { @@ -105371,27 +109932,27 @@ var ts; /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 194 /* FunctionExpression */: { + case 196 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); ts.copyComments(assignmentBinaryExpression, method, sourceFile); return method; } - case 195 /* ArrowFunction */: { + case 197 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 216 /* Block */) { + if (arrowFunctionBody.kind === 218 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] else { bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); } - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); ts.copyComments(assignmentBinaryExpression, method, sourceFile); @@ -105399,7 +109960,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105412,17 +109973,17 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 194 /* FunctionExpression */) { + if (!initializer || initializer.kind !== 196 /* FunctionExpression */) { return undefined; } - if (node.name.kind !== 71 /* Identifier */) { + if (node.name.kind !== 72 /* Identifier */) { return undefined; } var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */); + var modifiers = getModifierKindFromSource(precedingNode, 85 /* ExportKeyword */); var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place @@ -105433,7 +109994,7 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); } - var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */); + var modifiers = getModifierKindFromSource(node, 85 /* ExportKeyword */); var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place @@ -105452,59 +110013,73 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); - var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 121 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_19(statement); } } + function getReturnStatementsWithPromiseHandlers(body) { + var res = []; + ts.forEachReturnStatement(body, function (ret) { + if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + res.push(ret); + }); + return res; + } // Returns the identifiers that are never reassigned in the refactor function getConstIdentifiers(synthNamesMap) { var constIdentifiers = []; @@ -105549,7 +110124,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +110138,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +110152,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +110178,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +110201,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +110211,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,7 +110245,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105670,17 +110261,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +110288,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +110304,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,100 +110317,134 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 96 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 72 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; - if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } + if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; - var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); + var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105837,12 +110465,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +110472,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105912,10 +110532,10 @@ var ts; } var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); } @@ -105941,7 +110561,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -105961,29 +110581,29 @@ var ts; sourceFile.forEachChild(function recur(node) { if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { var parent = node.parent; - cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 59 /* EqualsToken */); } node.forEachChild(recur); }); } function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 219 /* ExpressionStatement */: { + case 221 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 189 /* CallExpression */: { + case 191 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var operatorToken = expression.operatorToken; - return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); + return operatorToken.kind === 59 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); } } } @@ -106023,8 +110643,8 @@ var ts; /** Converts `const name = require("moduleSpecifier").propertyName` */ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: { + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ @@ -106032,7 +110652,7 @@ var ts; makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } - case 71 /* Identifier */: + case 72 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; default: @@ -106058,7 +110678,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106075,16 +110695,16 @@ var ts; function tryChangeModuleExportsObject(object) { var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. - case 274 /* ShorthandPropertyAssignment */: - case 275 /* SpreadAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 277 /* SpreadAssignment */: return undefined; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); - case 154 /* MethodDeclaration */: - return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); + case 156 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(85 /* ExportKeyword */)], prop); default: ts.Debug.assertNever(prop); } @@ -106133,23 +110753,23 @@ var ts; var name = left.name.text; if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) { // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. - changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(84 /* ExportKeyword */), { suffix: " " }); + changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(85 /* ExportKeyword */), { suffix: " " }); if (!right.name) changes.insertName(sourceFile, right, name); - var semi = ts.findChildOfKind(parent, 25 /* SemicolonToken */, sourceFile); + var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile); if (semi) changes.delete(sourceFile, semi); } else { // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` - changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 23 /* DotToken */, sourceFile), [ts.createToken(84 /* ExportKeyword */), ts.createToken(76 /* ConstKeyword */)], { joiner: " ", suffix: " " }); + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(85 /* ExportKeyword */), ts.createToken(77 /* ConstKeyword */)], { joiner: " ", suffix: " " }); } } // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node. function convertExportsDotXEquals_replaceNode(name, exported) { - var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + var modifiers = [ts.createToken(85 /* ExportKeyword */)]; switch (exported.kind) { - case 194 /* FunctionExpression */: { + case 196 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -106157,10 +110777,10 @@ var ts; } } // falls through - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported); default: @@ -106178,7 +110798,7 @@ var ts; */ function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: { + case 184 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined @@ -106189,7 +110809,7 @@ var ts; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 183 /* ArrayBindingPattern */: { + case 185 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; @@ -106200,7 +110820,7 @@ var ts; makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } - case 71 /* Identifier */: + case 72 /* Identifier */: return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); default: return ts.Debug.assertNever(name); @@ -106272,11 +110892,11 @@ var ts; function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return parent.name !== node; - case 184 /* BindingElement */: + case 186 /* BindingElement */: return parent.propertyName !== node; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -106544,33 +111164,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106608,21 +111235,21 @@ var ts; function tryAddToExistingImport(existingImports) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind !== 247 /* ImportDeclaration */) + if (declaration.kind !== 249 /* ImportDeclaration */) return undefined; var importClause = declaration.importClause; if (!importClause) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; - return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */) + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 252 /* NamedImports */) ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } : undefined; }); } function getNamespaceImportName(declaration) { - if (declaration.kind === 247 /* ImportDeclaration */) { + if (declaration.kind === 249 /* ImportDeclaration */) { var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 249 /* NamespaceImport */ ? namedBindings.name : undefined; + return namedBindings && namedBindings.kind === 251 /* NamespaceImport */ ? namedBindings.name : undefined; } else { return declaration.name; @@ -106631,24 +111258,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) + return (i.kind === 249 /* ImportDeclaration */ || i.kind === 248 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return ts.sort(choicesForEachExportingModule, function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106656,9 +111283,9 @@ var ts; } function newImportInfoFromExistingSpecifier(_a) { var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 247 /* ImportDeclaration */ + var expression = declaration.kind === 249 /* ImportDeclaration */ ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 257 /* ExternalModuleReference */ + : declaration.moduleReference.kind === 259 /* ExternalModuleReference */ ? declaration.moduleReference.expression : undefined; return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; @@ -106690,7 +111317,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106738,17 +111365,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +111381,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +111404,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -106975,12 +111613,12 @@ var ts; var checker = context.program.getTypeChecker(); var suggestion; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71 /* Identifier */); + ts.Debug.assert(node.kind === 72 /* Identifier */); var containingType = checker.getTypeAtLocation(node.parent.expression); suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); } else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71 /* Identifier */); + ts.Debug.assert(node.kind === 72 /* Identifier */); var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { @@ -107009,10 +111647,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107035,6 +111673,9 @@ var ts; var errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, + ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code ]; var fixId = "addMissingMember"; codefix.registerCodeFix({ @@ -107051,7 +111692,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +111721,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_20 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +111748,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_20(info); } }); })); @@ -107151,7 +111792,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,14 +111802,14 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { - if (classDeclaration.kind === 207 /* ClassExpression */) { + if (classDeclaration.kind === 209 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -107194,13 +111835,17 @@ var ts; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 202 /* BinaryExpression */) { + if (token.parent.parent.kind === 204 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } - return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); + else { + var contextualType = checker.getContextualType(token.parent); + typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + } + return typeNode || ts.createKeywordTypeNode(120 /* AnyKeyword */); } function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); @@ -107209,7 +111854,7 @@ var ts; function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); var lastProp = getNodeToInsertPropertyAfter(classDeclaration); @@ -107233,7 +111878,7 @@ var ts; } function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. - var stringTypeNode = ts.createKeywordTypeNode(137 /* StringKeyword */); + var stringTypeNode = ts.createKeywordTypeNode(138 /* StringKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -107253,7 +111898,7 @@ var ts; } function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); - var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */); + var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); } @@ -107269,7 +111914,7 @@ var ts; */ var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { var type = checker.getTypeAtLocation(member); - return !!(type && type.flags & 68 /* StringLike */); + return !!(type && type.flags & 132 /* StringLike */); }); var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); @@ -107281,7 +111926,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +111938,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -107406,7 +112163,7 @@ var ts; } function getNodes(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - if (token.kind !== 99 /* ThisKeyword */) + if (token.kind !== 100 /* ThisKeyword */) return undefined; var constructor = ts.getContainingFunction(token); var superCall = findSuperCall(constructor.body); @@ -107445,7 +112202,7 @@ var ts; }); function getNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */); + ts.Debug.assert(token.kind === 124 /* ConstructorKeyword */); return token.parent; } function doChange(changes, sourceFile, ctr) { @@ -107483,17 +112240,17 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); var heritageClauses = ts.getContainingClass(token).heritageClauses; var extendsToken = heritageClauses[0].getFirstToken(); - return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + return extendsToken.kind === 86 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; } function doChanges(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); + changes.replaceNode(sourceFile, extendsToken, ts.createToken(109 /* ImplementsKeyword */)); // If there is already an implements clause, replace the implements keyword with a comma. if (heritageClauses.length === 2 && - heritageClauses[0].token === 85 /* ExtendsKeyword */ && - heritageClauses[1].token === 108 /* ImplementsKeyword */) { + heritageClauses[0].token === 86 /* ExtendsKeyword */ && + heritageClauses[1].token === 109 /* ImplementsKeyword */) { var implementsToken = heritageClauses[1].getFirstToken(); var implementsFullStart = implementsToken.getFullStart(); - changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(26 /* CommaToken */)); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */)); // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. // (Trailing because leading might be indentation, which is more sensitive.) var text = sourceFile.text; @@ -107577,7 +112334,7 @@ var ts; if (ts.isJSDocTemplateTag(token)) { return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; } - if (token.kind === 27 /* LessThanToken */) { + if (token.kind === 28 /* LessThanToken */) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; } @@ -107597,7 +112354,7 @@ var ts; return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; } var result = []; - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); @@ -107629,7 +112386,7 @@ var ts; tryPrefixDeclaration(changes, diag.code, sourceFile, token); break; case fixIdDelete: { - if (token.kind === 126 /* InferKeyword */) + if (token.kind === 127 /* InferKeyword */) break; // Can't delete var importDecl = tryGetFullImport(token); if (importDecl) { @@ -107638,7 +112395,7 @@ var ts; else if (ts.isJSDocTemplateTag(token)) { changes.delete(sourceFile, token); } - else if (token.kind === 27 /* LessThanToken */) { + else if (token.kind === 28 /* LessThanToken */) { deleteTypeParameters(changes, sourceFile, token); } else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && @@ -107648,7 +112405,7 @@ var ts; break; } case fixIdInfer: - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { changeInferToUnknown(changes, sourceFile, token); } break; @@ -107659,7 +112416,7 @@ var ts; }, }); function changeInferToUnknown(changes, sourceFile, token) { - changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(142 /* UnknownKeyword */)); + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(143 /* UnknownKeyword */)); } function createDeleteFix(changes, diag) { return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); @@ -107669,13 +112426,13 @@ var ts; } // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(token) { - return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; + return token.kind === 92 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; } function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { - if (token.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) + if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) return false; var decl = token.parent.parent; - if (decl.kind === 149 /* Parameter */) { + if (decl.kind === 151 /* Parameter */) { tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); } else { @@ -107686,7 +112443,7 @@ var ts; function tryDeleteFullVariableStatement(sourceFile, token, changes) { var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { - changes.delete(sourceFile, declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList); + changes.delete(sourceFile, declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList); return true; } return false; @@ -107695,7 +112452,7 @@ var ts; // Don't offer to prefix a property. if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) return; - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; } if (ts.isIdentifier(token) && canPrefix(token)) { @@ -107704,14 +112461,14 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 149 /* Parameter */: - case 148 /* TypeParameter */: + case 151 /* Parameter */: + case 150 /* TypeParameter */: return true; - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: return true; } } @@ -107725,9 +112482,9 @@ var ts; } function deleteAssignments(changes, sourceFile, token, checker) { ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { - if (ref.parent.kind === 187 /* PropertyAccessExpression */) + if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent; - if (ref.parent.kind === 202 /* BinaryExpression */ && ref.parent.parent.kind === 219 /* ExpressionStatement */) { + if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) { changes.delete(sourceFile, ref.parent.parent); } }); @@ -107743,33 +112500,41 @@ var ts; } function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { if (mayDeleteParameter(p, checker, isFixAll)) { - changes.delete(sourceFile, p); - deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + if (p.modifiers && p.modifiers.length > 0 + && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + p.modifiers.forEach(function (modifier) { + changes.deleteModifier(sourceFile, modifier); + }); + } + else { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + } } } function mayDeleteParameter(p, checker, isFixAll) { var parent = p.parent; switch (parent.kind) { - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // Don't remove a parameter if this overrides something. var symbol = checker.getSymbolAtLocation(parent.name); if (ts.isMemberSymbolInBaseType(symbol, checker)) return false; // falls through - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: return true; - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: { // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. var parameters = parent.parameters; var index = parameters.indexOf(p); ts.Debug.assert(index !== -1); return isFixAll - ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 71 /* Identifier */ && !p.symbol.isReferenced; }) + ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 72 /* Identifier */ && !p.symbol.isReferenced; }) : index === parameters.length - 1; } - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: // Setter must have a parameter return false; default: @@ -107809,7 +112574,7 @@ var ts; var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { switch (container.kind) { - case 220 /* IfStatement */: + case 222 /* IfStatement */: if (container.elseStatement) { if (ts.isBlock(statement.parent)) { break; @@ -107820,8 +112585,8 @@ var ts; return; } // falls through - case 222 /* WhileStatement */: - case 223 /* ForStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: changes.delete(sourceFile, container); return; } @@ -107870,7 +112635,7 @@ var ts; var statementPos = labeledStatement.statement.getStart(sourceFile); // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos - : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 57 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); changes.deleteRange(sourceFile, { pos: pos, end: end }); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -107894,10 +112659,10 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 284 /* JSDocNullableType */) { + if (typeNode.kind === 286 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - actions.push(fix(checker.getNullableType(type, 8192 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); + actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; function fix(type, fixId, fixAllDescription) { @@ -107914,7 +112679,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 284 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type; + var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -107931,22 +112696,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 210 /* AsExpression */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 237 /* FunctionDeclaration */: - case 156 /* GetAccessor */: - case 160 /* IndexSignature */: - case 179 /* MappedType */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 157 /* SetAccessor */: - case 240 /* TypeAliasDeclaration */: - case 192 /* TypeAssertionExpression */: - case 235 /* VariableDeclaration */: + case 212 /* AsExpression */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 239 /* FunctionDeclaration */: + case 158 /* GetAccessor */: + case 162 /* IndexSignature */: + case 181 /* MappedType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 194 /* TypeAssertionExpression */: + case 237 /* VariableDeclaration */: return true; default: return false; @@ -108000,15 +112765,15 @@ var ts; } var insertBefore; switch (containingFunction.kind) { - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 90 /* FunctionKeyword */, sourceFile); break; - case 195 /* ArrowFunction */: - insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + case 197 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: return; @@ -108022,11 +112787,11 @@ var ts; var insertBefore = _a.insertBefore, returnType = _a.returnType; if (returnType) { var entityName = ts.getEntityNameFromTypeNode(returnType); - if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") { + if (!entityName || entityName.kind !== 72 /* Identifier */ || entityName.text !== "Promise") { changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); } } - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore); + changes.insertModifierBefore(sourceFile, 121 /* AsyncKeyword */, insertBefore); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -108045,7 +112810,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108116,17 +112881,17 @@ var ts; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 151 /* PropertySignature */: - case 152 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 153 /* PropertySignature */: + case 154 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); out(ts.createProperty( - /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, + /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 153 /* MethodSignature */: - case 154 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 156 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -108144,8 +112909,8 @@ var ts; outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } - for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { - var signature = signatures_8[_i]; + for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) { + var signature = signatures_7[_i]; // Need to ensure nodes are fresh each time so they can have different positions. outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); } @@ -108166,43 +112931,40 @@ var ts; } } function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 154 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); if (!signatureDeclaration) { return undefined; } signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; signatureDeclaration.name = name; - signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; + signatureDeclaration.questionToken = optional ? ts.createToken(56 /* QuestionToken */) : undefined; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, - /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(39 /* AsteriskToken */) : undefined, methodName, + /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(40 /* AsteriskToken */) : undefined, methodName, /*questionToken*/ undefined, /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108213,8 +112975,8 @@ var ts; /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || "arg" + i, - /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, - /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(119 /* AnyKeyword */), + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(120 /* AnyKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -108228,8 +112990,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { - var sig = signatures_9[_i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var sig = signatures_8[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -108242,11 +113004,11 @@ var ts; var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { - var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); + var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(120 /* AnyKeyword */)); var restParameter = ts.createParameter( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", - /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, anyArrayType, + /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", + /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(56 /* QuestionToken */) : undefined, anyArrayType, /*initializer*/ undefined); parameters.push(restParameter); } @@ -108257,7 +113019,7 @@ var ts; function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { return ts.createMethod( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); + /*asteriskToken*/ undefined, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); } function createStubbedMethodBody(preferences) { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), @@ -108266,10 +113028,10 @@ var ts; } function createVisibilityModifier(flags) { if (flags & 4 /* Public */) { - return ts.createToken(114 /* PublicKeyword */); + return ts.createToken(115 /* PublicKeyword */); } else if (flags & 16 /* Protected */) { - return ts.createToken(113 /* ProtectedKeyword */); + return ts.createToken(114 /* ProtectedKeyword */); } return undefined; } @@ -108277,561 +113039,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - var codefix; - (function (codefix) { - var fixId = "inferFromUsage"; - var errorCodes = [ - // Variable declarations - ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, - ]; - codefix.registerCodeFix({ - errorCodes: errorCodes, - getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } - var token = ts.getTokenAtPosition(sourceFile, start); - var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); - var name = declaration && ts.getNameOfDeclaration(declaration); - return !name || changes.length === 0 ? undefined - : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; - }, - fixIds: [fixId], - getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; - var markSeen = ts.nodeSeenTracker(); - return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); - }); - }, - }); - function getDiagnostic(errorCode, token) { - switch (errorCode) { - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return ts.Diagnostics.Infer_parameter_types_from_usage; - default: - return ts.Diagnostics.Infer_type_of_0_from_usage; - } - } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { - return undefined; - } - var parent = token.parent; - switch (errorCode) { - // Variable and Property declarations - case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: - case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); - return parent; - } - return undefined; - case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { - var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); - return symbol.valueDeclaration; - } - return undefined; - } - } - var containingFunction = ts.getContainingFunction(token); - if (containingFunction === undefined) { - return undefined; - } - switch (errorCode) { - // Parameter declarations - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); - return containingFunction; - } - // falls through - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (markSeen(containingFunction)) { - var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); - return param; - } - return undefined; - // Get Accessor declarations - case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: - case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); - return containingFunction; - } - return undefined; - // Set Accessor declarations - case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); - return containingFunction; - } - return undefined; - default: - return ts.Debug.fail(String(errorCode)); - } - } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { - if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); - } - } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - return true; - case 194 /* FunctionExpression */: - return !!declaration.name; - } - return false; - } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return; - } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; - } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); - } - }); - } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { - var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); - if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || - inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); - } - } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); - } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { - var typeIsAccessible = true; - var notAccessible = function () { typeIsAccessible = false; }; - var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { - trackSymbol: function (symbol, declaration, meaning) { - // TODO: GH#18217 - typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; - }, - reportInaccessibleThisError: notAccessible, - reportPrivateInBaseOfClassExpression: notAccessible, - reportInaccessibleUniqueSymbolError: notAccessible, - }); - return typeIsAccessible ? res : undefined; - } - function getReferences(token, program, cancellationToken) { - // Position shouldn't matter since token is not a SourceFile. - return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; - }); - } - function inferTypeForVariableFromUsage(token, program, cancellationToken) { - return InferFromReference.inferTypeFromReferences(getReferences(token, program, cancellationToken), program.getTypeChecker(), cancellationToken); - } - function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { - switch (containingFunction.kind) { - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - var isConstructor = containingFunction.kind === 155 /* Constructor */; - var searchToken = isConstructor ? - ts.findChildOfKind(containingFunction, 123 /* ConstructorKeyword */, sourceFile) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); - } - } - } - var InferFromReference; - (function (InferFromReference) { - function inferTypeFromReferences(references, checker, cancellationToken) { - var usageContext = {}; - for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { - var reference = references_1[_i]; - cancellationToken.throwIfCancellationRequested(); - inferTypeFromContext(reference, checker, usageContext); - } - return getTypeFromUsageContext(usageContext, checker); - } - InferFromReference.inferTypeFromReferences = inferTypeFromReferences; - function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { - if (references.length === 0) { - return undefined; - } - if (!declaration.parameters) { - return undefined; - } - var usageContext = {}; - for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { - var reference = references_2[_i]; - cancellationToken.throwIfCancellationRequested(); - inferTypeFromContext(reference, checker, usageContext); - } - var isConstructor = declaration.kind === 155 /* Constructor */; - var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; - return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { - var types = []; - var isRest = ts.isRestParameter(parameter); - for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { - var callContext = callContexts_1[_i]; - if (callContext.argumentTypes.length <= parameterIndex) { - continue; - } - if (isRest) { - for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); - } - } - else { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); - } - } - if (!types.length) { - return undefined; - } - var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; - }); - } - InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; - function inferTypeFromContext(node, checker, usageContext) { - while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { - node = node.parent; - } - switch (node.parent.kind) { - case 201 /* PostfixUnaryExpression */: - usageContext.isNumber = true; - break; - case 200 /* PrefixUnaryExpression */: - inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); - break; - case 202 /* BinaryExpression */: - inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); - break; - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); - break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: - if (node.parent.expression === node) { - inferTypeFromCallExpressionContext(node.parent, checker, usageContext); - } - else { - inferTypeFromContextualType(node, checker, usageContext); - } - break; - case 187 /* PropertyAccessExpression */: - inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); - break; - case 188 /* ElementAccessExpression */: - inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); - break; - case 235 /* VariableDeclaration */: { - var _a = node.parent, name = _a.name, initializer = _a.initializer; - if (node === name) { - if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. - addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); - } - break; - } - } - // falls through - default: - return inferTypeFromContextualType(node, checker, usageContext); - } - } - function inferTypeFromContextualType(node, checker, usageContext) { - if (ts.isExpressionNode(node)) { - addCandidateType(usageContext, checker.getContextualType(node)); - } - } - function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { - switch (node.operator) { - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - usageContext.isNumber = true; - break; - case 37 /* PlusToken */: - usageContext.isNumberOrString = true; - break; - // case SyntaxKind.ExclamationToken: - // no inferences here; - } - } - function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { - switch (parent.operatorToken.kind) { - // ExponentiationOperator - case 40 /* AsteriskAsteriskToken */: - // MultiplicativeOperator - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - // ShiftOperator - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - // BitwiseOperator - case 48 /* AmpersandToken */: - case 49 /* BarToken */: - case 50 /* CaretToken */: - // CompoundAssignmentOperator - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 69 /* BarEqualsToken */: - case 70 /* CaretEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - // AdditiveOperator - case 38 /* MinusToken */: - // RelationalOperator - case 27 /* LessThanToken */: - case 30 /* LessThanEqualsToken */: - case 29 /* GreaterThanToken */: - case 31 /* GreaterThanEqualsToken */: - var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (operandType.flags & 544 /* EnumLike */) { - addCandidateType(usageContext, operandType); - } - else { - usageContext.isNumber = true; - } - break; - case 59 /* PlusEqualsToken */: - case 37 /* PlusToken */: - var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (otherOperandType.flags & 544 /* EnumLike */) { - addCandidateType(usageContext, otherOperandType); - } - else if (otherOperandType.flags & 168 /* NumberLike */) { - usageContext.isNumber = true; - } - else if (otherOperandType.flags & 68 /* StringLike */) { - usageContext.isString = true; - } - else { - usageContext.isNumberOrString = true; - } - break; - // AssignmentOperators - case 58 /* EqualsToken */: - case 32 /* EqualsEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); - break; - case 92 /* InKeyword */: - if (node === parent.left) { - usageContext.isString = true; - } - break; - // LogicalOperator - case 54 /* BarBarToken */: - if (node === parent.left && - (node.parent.parent.kind === 235 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { - // var x = x || {}; - // TODO: use getFalsyflagsOfType - addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); - } - break; - case 53 /* AmpersandAmpersandToken */: - case 26 /* CommaToken */: - case 93 /* InstanceOfKeyword */: - // nothing to infer here - break; - } - } - function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { - addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); - } - function inferTypeFromCallExpressionContext(parent, checker, usageContext) { - var callContext = { - argumentTypes: [], - returnType: {} - }; - if (parent.arguments) { - for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); - } - } - inferTypeFromContext(parent, checker, callContext.returnType); - if (parent.kind === 189 /* CallExpression */) { - (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); - } - else { - (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); - } - } - function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { - var name = ts.escapeLeadingUnderscores(parent.name.text); - if (!usageContext.properties) { - usageContext.properties = ts.createUnderscoreEscapedMap(); - } - var propertyUsageContext = usageContext.properties.get(name) || {}; - inferTypeFromContext(parent, checker, propertyUsageContext); - usageContext.properties.set(name, propertyUsageContext); - } - function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { - if (node === parent.argumentExpression) { - usageContext.isNumberOrString = true; - return; - } - else { - var indexType = checker.getTypeAtLocation(parent.argumentExpression); - var indexUsageContext = {}; - inferTypeFromContext(parent, checker, indexUsageContext); - if (indexType.flags & 168 /* NumberLike */) { - usageContext.numberIndexContext = indexUsageContext; - } - else { - usageContext.stringIndexContext = indexUsageContext; - } - } - } - function getTypeFromUsageContext(usageContext, checker) { - if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { - return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); - } - else if (usageContext.isNumber) { - return checker.getNumberType(); - } - else if (usageContext.isString) { - return checker.getStringType(); - } - else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); - } - else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { - var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 - var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); - return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); - } - else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { - return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); - } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { - var members_6 = ts.createUnderscoreEscapedMap(); - var callSignatures = []; - var constructSignatures = []; - var stringIndexInfo = void 0; - var numberIndexInfo = void 0; - if (usageContext.properties) { - usageContext.properties.forEach(function (context, name) { - var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); - members_6.set(name, symbol); - }); - } - if (usageContext.callContexts) { - for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { - var callContext = _a[_i]; - callSignatures.push(getSignatureFromCallContext(callContext, checker)); - } - } - if (usageContext.constructContexts) { - for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { - var constructContext = _c[_b]; - constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); - } - } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } - if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 - } - else { - return undefined; - } - } - function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { - var types = []; - if (callContexts) { - for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { - var callContext = callContexts_2[_i]; - if (callContext.argumentTypes.length > parameterIndex) { - if (isRestParameter) { - types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); - } - else { - types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); - } - } - } - } - if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRestParameter ? checker.createArrayType(type) : type; - } - return undefined; - } - function getSignatureFromCallContext(callContext, checker) { - var parameters = []; - for (var i = 0; i < callContext.argumentTypes.length; i++) { - var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); - symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); - parameters.push(symbol); - } - var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); - // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - } - function addCandidateType(context, type) { - if (type && !(type.flags & 1 /* Any */) && !(type.flags & 32768 /* Never */)) { - (context.candidateTypes || (context.candidateTypes = [])).push(type); - } - } - function hasCallContext(usageContext) { - return !!usageContext && !!usageContext.callContexts; - } - })(InferFromReference || (InferFromReference = {})); - })(codefix = ts.codefix || (ts.codefix = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var codefix; (function (codefix) { @@ -108864,7 +113071,7 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 189 /* CallExpression */ : 190 /* NewExpression */; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 191 /* CallExpression */ : 192 /* NewExpression */; var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); if (!node) { return []; @@ -108975,7 +113182,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { - var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(52 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, propertyDeclaration) { @@ -108983,7 +113190,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { - var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + var undefinedTypeNode = ts.createKeywordTypeNode(141 /* UndefinedKeyword */); var type = propertyDeclaration.type; // TODO: GH#18217 var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); @@ -109004,8 +113211,8 @@ var ts; return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 } function getDefaultValueFromType(checker, type) { - if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + if (type.flags & 512 /* BooleanLiteral */) { + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109029,6 +113236,234 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, 0 /* ExportEquals */); + } + ts.generateTypesForModule = generateTypesForModule; + function generateTypesForGlobal(name, globalValue, formatSettings) { + return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, 3 /* Global */); + } + ts.generateTypesForGlobal = generateTypesForGlobal; + function generateTypesForModuleOrGlobal(name, globalValue, formatSettings, outputKind) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, globalValue), formatSettings, outputKind); + } + /* @internal */ + function valueInfoToDeclarationFileText(valueInfo, formatSettings, outputKind) { + if (outputKind === void 0) { outputKind = 0 /* ExportEquals */; } + return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + OutputKind[OutputKind["Global"] = 3] = "Global"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(85 /* ExportKeyword */), ts.createModifier(80 /* DefaultKeyword */)] + : kind === 3 /* Global */ || kind === 0 /* ExportEquals */ ? [ts.createModifier(125 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(85 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members, hasNontrivialPrototype = info.hasNontrivialPrototype; + if (!hasNontrivialPrototype) { + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var protoOrInstanceMembers = ts.createMap(); + if (typeof fnAst === "object") + getConstructorFunctionInstanceProperties(fnAst, protoOrInstanceMembers); + for (var _i = 0, prototypeMembers_1 = prototypeMembers; _i < prototypeMembers_1.length; _i++) { + var p = prototypeMembers_1[_i]; + // ignore non-functions on the prototype + if (p.kind === 2 /* FunctionOrClass */) { + var m = tryGetMethod(p); + if (m) { + protoOrInstanceMembers.set(p.name, m); + } + } + } + var classStaticMembers = protoOrInstanceMembers.size !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(116 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(116 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + break; + default: + ts.Debug.assertNever(info); + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), ts.arrayFrom(protoOrInstanceMembers.values()))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 157 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + function toPropertyName(name) { + return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name); + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst, members) { + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { + var name_6 = node.left.name.text; + if (!ts.isJsPrivate(name_6)) { + ts.getOrUpdate(members, name_6, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_6, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + } + } + }); + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 200 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(106 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -109125,8 +113560,8 @@ var ts; }); function getImportTypeNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 91 /* ImportKeyword */); - ts.Debug.assert(token.parent.kind === 181 /* ImportType */); + ts.Debug.assert(token.kind === 92 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 183 /* ImportType */); return token.parent; } function doChange(changes, sourceFile, importType) { @@ -109178,7 +113613,7 @@ var ts; var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); var parameter = ts.first(indexSignature.parameters); var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); - var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(133 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ mappedIntersectionType ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); @@ -109198,7 +113633,7 @@ var ts; getAvailableActions: function (context) { var info = getInfo(context); if (!info) - return undefined; + return ts.emptyArray; var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; @@ -109225,16 +113660,16 @@ var ts; return undefined; } switch (exportNode.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: { + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: { var node = exportNode; return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { var vs = exportNode; // Must be `export const x = something;`. if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { @@ -109257,17 +113692,17 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 79 /* DefaultKeyword */))); + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 80 /* DefaultKeyword */))); } else { - var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* ExportKeyword */)); + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 85 /* ExportKeyword */)); switch (exportNode.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(79 /* DefaultKeyword */)); + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(80 /* DefaultKeyword */)); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { // We checked in `getInfo` that an initializer exists. @@ -109275,9 +113710,9 @@ var ts; break; } // falls through - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // `export type T = number;` -> `type T = number; export default T;` changes.deleteModifier(exportingSourceFile, exportKeyword); changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); @@ -109304,18 +113739,18 @@ var ts; function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { var parent = ref.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // `a.default` --> `a.foo` changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: { + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: { var spec = parent; // `default as foo` --> `foo`, `default as bar` --> `foo as bar` changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); break; } - case 248 /* ImportClause */: { + case 250 /* ImportClause */: { var clause = parent; ts.Debug.assert(clause.name === ref); var spec = makeImportSpecifier(exportName, ref.text); @@ -109324,7 +113759,7 @@ var ts; // `import foo from "./a";` --> `import { foo } from "./a";` changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); } - else if (namedBindings.kind === 249 /* NamespaceImport */) { + else if (namedBindings.kind === 251 /* NamespaceImport */) { // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; @@ -109345,36 +113780,33 @@ var ts; function changeNamedToDefaultImport(importingSourceFile, ref, changes) { var parent = ref.parent; switch (parent.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // `a.foo` --> `a.default` changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: { - var spec = parent; - if (spec.kind === 251 /* ImportSpecifier */) { - // `import { foo } from "./a";` --> `import foo from "./a";` - // `import { foo as bar } from "./a";` --> `import bar from "./a";` - var defaultImport = ts.createIdentifier(spec.name.text); - if (spec.parent.elements.length === 1) { - changes.replaceNode(importingSourceFile, spec.parent, defaultImport); - } - else { - changes.delete(importingSourceFile, spec); - changes.insertNodeBefore(importingSourceFile, spec.parent, defaultImport); - } + case 253 /* ImportSpecifier */: { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(parent.name.text); + if (parent.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent.parent, defaultImport); } else { - // `export { foo } from "./a";` --> `export { default as foo } from "./a";` - // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` - // `export { foo as default } from "./a";` --> `export { default } from "./a";` - // (Because `export foo from "./a";` isn't valid syntax.) - changes.replaceNode(importingSourceFile, spec, makeExportSpecifier("default", spec.name.text)); + changes.delete(importingSourceFile, parent); + changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport); } break; } + case 257 /* ExportSpecifier */: { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text)); + break; + } default: - ts.Debug.failBadSyntaxKind(parent); + ts.Debug.assertNever(parent); } } function makeImportSpecifier(propertyName, name) { @@ -109397,9 +113829,9 @@ var ts; getAvailableActions: function (context) { var i = getImportToConvert(context); if (!i) - return undefined; - var description = i.kind === 249 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; - var actionName = i.kind === 249 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return ts.emptyArray; + var description = i.kind === 251 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 251 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; }, getEditsForAction: function (context, actionName) { @@ -109421,7 +113853,7 @@ var ts; } function doChange(sourceFile, program, changes, toConvert) { var checker = program.getTypeChecker(); - if (toConvert.kind === 249 /* NamespaceImport */) { + if (toConvert.kind === 251 /* NamespaceImport */) { doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { @@ -109481,7 +113913,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_21 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +113932,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_21(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -109529,12 +113961,12 @@ var ts; var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { - return undefined; + return ts.emptyArray; } var extractions = getPossibleExtractions(targetRange, context); if (extractions === undefined) { // No extractions possible - return undefined; + return ts.emptyArray; } var functionActions = []; var usedFunctionNames = ts.createMap(); @@ -109590,7 +114022,7 @@ var ts; actions: constantActions }); } - return infos.length ? infos : undefined; + return infos.length ? infos : ts.emptyArray; } extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ @@ -109764,20 +114196,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 152 /* PropertyDeclaration */) { + if (current.kind === 154 /* PropertyDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 149 /* Parameter */) { + else if (current.kind === 151 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 155 /* Constructor */) { + if (ctorOrMethod.kind === 157 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 154 /* MethodDeclaration */) { + else if (current.kind === 156 /* MethodDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -109820,7 +114252,7 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 235 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 237 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! @@ -109832,13 +114264,13 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 189 /* CallExpression */) { + if (node.parent.kind === 191 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { @@ -109853,8 +114285,8 @@ var ts; } if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); @@ -109866,20 +114298,20 @@ var ts; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 220 /* IfStatement */: + case 222 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 216 /* Block */: - if (node.parent && node.parent.kind === 233 /* TryStatement */ && node.parent.finallyBlock === node) { + case 218 /* Block */: + if (node.parent && node.parent.kind === 235 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 269 /* CaseClause */: + case 271 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -109891,11 +114323,11 @@ var ts; break; } switch (node.kind) { - case 176 /* ThisType */: - case 99 /* ThisKeyword */: + case 178 /* ThisType */: + case 100 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -109903,8 +114335,8 @@ var ts; seenLabels.pop(); break; } - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: { var label = node.label; if (label) { @@ -109914,20 +114346,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 227 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -109981,7 +114413,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 149 /* Parameter */) { + if (current.kind === 151 /* Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -109992,7 +114424,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 277 /* SourceFile */) { + if (current.kind === 279 /* SourceFile */) { return scopes; } } @@ -110082,32 +114514,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: return "constructor"; - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : "anonymous function"; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return "arrow function"; - case 154 /* MethodDeclaration */: - return "method '" + scope.name.getText(); - case 156 /* GetAccessor */: + case 156 /* MethodDeclaration */: + return "method '" + scope.name.getText() + "'"; + case 158 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: throw ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 238 /* ClassDeclaration */ + return scope.kind === 240 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 243 /* ModuleBlock */ + return scope.kind === 245 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -110126,7 +114558,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110173,20 +114605,20 @@ var ts; var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files - var modifiers = isJS ? [] : [ts.createToken(112 /* PrivateKeyword */)]; + var modifiers = isJS ? [] : [ts.createToken(113 /* PrivateKeyword */)]; if (range.facts & RangeFacts.InStaticRegion) { - modifiers.push(ts.createToken(115 /* StaticKeyword */)); + modifiers.push(ts.createToken(116 /* StaticKeyword */)); } if (range.facts & RangeFacts.IsAsyncFunction) { - modifiers.push(ts.createToken(120 /* AsyncKeyword */)); + modifiers.push(ts.createToken(121 /* AsyncKeyword */)); } newFunction = ts.createMethod( - /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { newFunction = ts.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(121 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(40 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; @@ -110203,7 +114635,7 @@ var ts; var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference callArguments); if (range.facts & RangeFacts.IsGenerator) { - call = ts.createYield(ts.createToken(39 /* AsteriskToken */), call); + call = ts.createYield(ts.createToken(40 /* AsteriskToken */), call); } if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); @@ -110327,9 +114759,9 @@ var ts; while (ts.isParenthesizedTypeNode(withoutParens)) { withoutParens = withoutParens.type; } - return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 140 /* UndefinedKeyword */; }) + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 141 /* UndefinedKeyword */; }) ? clone - : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(140 /* UndefinedKeyword */)]); + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(141 /* UndefinedKeyword */)]); } } /** @@ -110342,7 +114774,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110352,11 +114784,11 @@ var ts; if (ts.isClassLike(scope)) { ts.Debug.assert(!isJS); // See CannotExtractToJSClass var modifiers = []; - modifiers.push(ts.createToken(112 /* PrivateKeyword */)); + modifiers.push(ts.createToken(113 /* PrivateKeyword */)); if (rangeFacts & RangeFacts.InStaticRegion) { - modifiers.push(ts.createToken(115 /* StaticKeyword */)); + modifiers.push(ts.createToken(116 /* StaticKeyword */)); } - modifiers.push(ts.createToken(132 /* ReadonlyKeyword */)); + modifiers.push(ts.createToken(133 /* ReadonlyKeyword */)); var newVariable = ts.createProperty( /*decorators*/ undefined, modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); @@ -110385,7 +114817,7 @@ var ts; var localReference = ts.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 219 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 221 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.createVariableStatement( @@ -110404,7 +114836,7 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 219 /* ExpressionStatement */) { + if (node.parent.kind === 221 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. changeTracker.delete(context.file, node.parent); } @@ -110491,7 +114923,7 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 228 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + if (!ignoreReturns && node.kind === 230 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { @@ -110661,7 +115093,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { + else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -110669,14 +115101,14 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 237 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 239 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +115164,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_22 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +115204,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_22(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -110985,30 +115417,30 @@ var ts; function isExtractableExpression(node) { var parent = node.parent; switch (parent.kind) { - case 276 /* EnumMember */: + case 278 /* EnumMember */: return false; } switch (node.kind) { - case 9 /* StringLiteral */: - return parent.kind !== 247 /* ImportDeclaration */ && - parent.kind !== 251 /* ImportSpecifier */; - case 206 /* SpreadElement */: - case 182 /* ObjectBindingPattern */: - case 184 /* BindingElement */: + case 10 /* StringLiteral */: + return parent.kind !== 249 /* ImportDeclaration */ && + parent.kind !== 253 /* ImportSpecifier */; + case 208 /* SpreadElement */: + case 184 /* ObjectBindingPattern */: + case 186 /* BindingElement */: return false; - case 71 /* Identifier */: - return parent.kind !== 184 /* BindingElement */ && - parent.kind !== 251 /* ImportSpecifier */ && - parent.kind !== 255 /* ExportSpecifier */; + case 72 /* Identifier */: + return parent.kind !== 186 /* BindingElement */ && + parent.kind !== 253 /* ImportSpecifier */ && + parent.kind !== 257 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 216 /* Block */: - case 277 /* SourceFile */: - case 243 /* ModuleBlock */: - case 269 /* CaseClause */: + case 218 /* Block */: + case 279 /* SourceFile */: + case 245 /* ModuleBlock */: + case 271 /* CaseClause */: return true; default: return false; @@ -111029,7 +115461,7 @@ var ts; refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!getConvertibleFieldAtPosition(context)) - return undefined; + return ts.emptyArray; return [{ name: actionName, description: actionDescription, @@ -111046,7 +115478,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111057,10 +115489,10 @@ var ts; var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; var accessorModifiers = isInClassLike ? !modifierFlags || modifierFlags & 8 /* Private */ - ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) + ? getModifiers(isJS, isStatic, 115 /* PublicKeyword */) : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined; - var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined; + var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 113 /* PrivateKeyword */) : undefined; updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); ts.suppressLeadingAndTrailingTrivia(getAccessor); @@ -111069,7 +115501,7 @@ var ts; // readonly modifier only existed in classLikeDeclaration var constructor = ts.getFirstConstructorWithBody(container); if (constructor) { - updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); } } else { @@ -111098,7 +115530,7 @@ var ts; return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); } function getModifiers(isJS, isStatic, accessModifier) { - var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined); + var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(116 /* StaticKeyword */) : undefined); return modifiers && ts.createNodeArray(modifiers); } function startsWithUnderscore(name) { @@ -111121,8 +115553,8 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), - container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent, - originalName: declaration.name, + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name.text, declaration: declaration, fieldName: fieldName, accessorName: accessorName, @@ -111173,22 +115605,23 @@ var ts; ? changeTracker.insertNodeAfterComma(file, declaration, accessor) : changeTracker.insertNodeAfter(file, declaration, accessor); } - function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) { + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { if (!constructor.body) return; - var file = context.file, program = context.program, cancellationToken = context.cancellationToken; - var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; - }); - ts.forEach(referenceEntries, function (entry) { - var parent = entry.parent; - var accessorName = ts.createIdentifier(fieldName.text); - var node = ts.isBinaryExpression(parent) - ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken) - : ts.isPropertyAccessExpression(parent) - ? ts.updatePropertyAccess(parent, parent.expression, accessorName) - : ts.Debug.fail("Unexpected write access token"); - changeTracker.replaceNode(file, parent, node); + constructor.body.forEachChild(function recur(node) { + if (ts.isElementAccessExpression(node) && + node.expression.kind === 100 /* ThisKeyword */ && + ts.isStringLiteral(node.argumentExpression) && + node.argumentExpression.text === originalName && + ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName)); + } + if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) { + changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName)); + } + if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(recur); + } }); } })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); @@ -111203,7 +115636,7 @@ var ts; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) - return undefined; + return ts.emptyArray; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; }, @@ -111265,11 +115698,11 @@ var ts; } function isPureImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return true; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return !ts.hasModifier(node, 1 /* Export */); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; @@ -111322,10 +115755,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_23 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_24 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,22 +115780,22 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_24(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_23(sourceFile); } } function getNamespaceLikeImport(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 249 /* NamespaceImport */ ? + case 249 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 251 /* NamespaceImport */ ? node.importClause.namedBindings.name : undefined; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node.name; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: return ts.Debug.assertNever(node); @@ -111393,20 +115826,20 @@ var ts; var newNamespaceId = ts.createIdentifier(newNamespaceName); var newModuleString = ts.createLiteral(newModuleSpecifier); switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); default: return ts.Debug.assertNever(node); } } function moduleSpecifierFromImport(i) { - return (i.kind === 247 /* ImportDeclaration */ ? i.moduleSpecifier - : i.kind === 246 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + return (i.kind === 249 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 248 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]); } function forEachImportInStatement(statement, cb) { @@ -111476,15 +115909,15 @@ var ts; } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { switch (importDecl.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); break; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: if (isUnused(importDecl.name)) { changes.delete(sourceFile, importDecl); } break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: @@ -111497,7 +115930,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 251 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -111509,7 +115942,7 @@ var ts; if (namedBindingsUnused) { changes.delete(sourceFile, namedBindings); } - else if (namedBindings.kind === 250 /* NamedImports */) { + else if (namedBindings.kind === 252 /* NamedImports */) { for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { var element = _b[_i]; if (isUnused(element.name)) @@ -111522,14 +115955,14 @@ var ts; function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { var name = varDecl.name; switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: if (isUnused(name)) { changes.delete(sourceFile, name); } break; - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: break; - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } @@ -111634,13 +116067,13 @@ var ts; // Below should all be utilities function isInImport(decl) { switch (decl.kind) { - case 246 /* ImportEqualsDeclaration */: - case 251 /* ImportSpecifier */: - case 248 /* ImportClause */: + case 248 /* ImportEqualsDeclaration */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: return true; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return isVariableDeclarationInImport(decl); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); default: return false; @@ -111652,7 +116085,7 @@ var ts; } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 247 /* ImportDeclaration */: { + case 249 /* ImportDeclaration */: { var clause = i.importClause; if (!clause) return undefined; @@ -111662,9 +116095,9 @@ var ts; ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) : undefined; } - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return keep(i.name) ? i : undefined; - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { var name = filterBindingName(i.name, keep); return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } @@ -111673,7 +116106,7 @@ var ts; } } function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 249 /* NamespaceImport */) { + if (namedBindings.kind === 251 /* NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : undefined; } else { @@ -111683,11 +116116,11 @@ var ts; } function filterBindingName(name, keep) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return keep(name) ? name : undefined; - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return name; - case 182 /* ObjectBindingPattern */: { + case 184 /* ObjectBindingPattern */: { // We can't handle nested destructurings or property names well here, so just copy them all. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; @@ -111744,13 +116177,13 @@ var ts; } function isNonVariableTopLevelDeclaration(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return true; default: return false; @@ -111758,29 +116191,47 @@ var ts; } function forEachTopLevelDeclaration(statement, cb) { switch (statement.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return cb(statement); - case 217 /* VariableStatement */: - return ts.forEach(statement.declarationList.declarations, cb); - case 219 /* ExpressionStatement */: { + case 219 /* VariableStatement */: + return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); + case 221 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } } } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 72 /* Identifier */: + return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); + default: + return ts.Debug.assertNever(name); + } + } function nameOfTopLevelDeclaration(d) { - return d.kind === 219 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + return ts.isExpressionStatement(d) ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); } function getTopLevelDeclarationStatement(d) { - return ts.isVariableDeclaration(d) ? d.parent.parent : d; + switch (d.kind) { + case 237 /* VariableDeclaration */: + return d.parent.parent; + case 186 /* BindingElement */: + return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); + default: + return d; + } } function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { if (isExported(sourceFile, decl, useEs6Exports)) @@ -111807,25 +116258,25 @@ var ts; return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); } function addEs6Export(d) { - var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers); + var modifiers = ts.concatenate([ts.createModifier(85 /* ExportKeyword */)], d.modifiers); switch (d.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.updateVariableStatement(d, modifiers, d.declarationList); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(d); @@ -111836,18 +116287,18 @@ var ts; } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: return [decl.name.text]; // TODO: GH#18217 - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.emptyArray; - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(decl); @@ -111855,7 +116306,7 @@ var ts; } /** Creates `exports.x = x;` */ function createExportAssignment(name) { - return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name))); + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 59 /* EqualsToken */, ts.createIdentifier(name))); } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); @@ -111877,7 +116328,7 @@ var ts; var file = context.file, startPosition = context.startPosition; var info = getConvertibleArrowFunctionAtPosition(file, startPosition); if (!info) - return undefined; + return ts.emptyArray; return [{ name: refactorName, description: refactorDescription, @@ -111919,7 +116370,7 @@ var ts; return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); } function getConvertibleArrowFunctionAtPosition(file, startPosition) { var node = ts.getTokenAtPosition(file, startPosition); @@ -111955,7 +116406,7 @@ var ts; ts.servicesVersion = "0.8"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : - kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : + kind === 72 /* Identifier */ ? new IdentifierObject(72 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; node.flags = parent.flags & 12679168 /* ContextFlags */; @@ -112028,8 +116479,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 303 /* LastJSDocNode */; }); - return child.kind < 146 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; }); + return child.kind < 148 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -112040,7 +116491,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 146 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 148 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -112086,7 +116537,7 @@ var ts; var token = ts.scanner.scan(); var textPos = ts.scanner.getTextPos(); if (textPos <= end) { - if (token === 71 /* Identifier */) { + if (token === 72 /* Identifier */) { ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); } nodes.push(createNode(token, pos, textPos, parent)); @@ -112098,7 +116549,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(304 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -112230,7 +116681,7 @@ var ts; }); return IdentifierObject; }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 71 /* Identifier */; + IdentifierObject.prototype.kind = 72 /* Identifier */; var TypeObject = /** @class */ (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -112276,25 +116727,25 @@ var ts; return this.checker.getDefaultFromTypeParameter(this); }; TypeObject.prototype.isUnion = function () { - return !!(this.flags & 262144 /* Union */); + return !!(this.flags & 1048576 /* Union */); }; TypeObject.prototype.isIntersection = function () { - return !!(this.flags & 524288 /* Intersection */); + return !!(this.flags & 2097152 /* Intersection */); }; TypeObject.prototype.isUnionOrIntersection = function () { - return !!(this.flags & 786432 /* UnionOrIntersection */); + return !!(this.flags & 3145728 /* UnionOrIntersection */); }; TypeObject.prototype.isLiteral = function () { - return !!(this.flags & 192 /* StringOrNumberLiteral */); + return !!(this.flags & 384 /* StringOrNumberLiteral */); }; TypeObject.prototype.isStringLiteral = function () { - return !!(this.flags & 64 /* StringLiteral */); + return !!(this.flags & 128 /* StringLiteral */); }; TypeObject.prototype.isNumberLiteral = function () { - return !!(this.flags & 128 /* NumberLiteral */); + return !!(this.flags & 256 /* NumberLiteral */); }; TypeObject.prototype.isTypeParameter = function () { - return !!(this.flags & 65536 /* TypeParameter */); + return !!(this.flags & 262144 /* TypeParameter */); }; TypeObject.prototype.isClassOrInterface = function () { return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */); @@ -112344,8 +116795,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112431,10 +116882,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -112454,31 +116905,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 255 /* ExportSpecifier */: - case 251 /* ImportSpecifier */: - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 166 /* TypeLiteral */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 257 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 168 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 149 /* Parameter */: + case 151 /* Parameter */: // Only consider parameter properties if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // falls through - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: { + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -112489,19 +116940,19 @@ var ts; } } // falls through - case 276 /* EnumMember */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 278 /* EnumMember */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: addDeclaration(node); break; - case 253 /* ExportDeclaration */: + case 255 /* 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 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -112513,7 +116964,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -112522,8 +116973,8 @@ var ts; } } break; - case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112835,7 +117286,7 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; }); + var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -112865,8 +117316,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +117355,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112911,11 +117367,11 @@ var ts; compilerHost.trace = function (message) { return host.trace(message); }; } if (host.resolveModuleNames) { - compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }; + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }; } if (host.resolveTypeReferenceDirectives) { - compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile) { - return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile); + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile, redirectedReference); }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); @@ -112924,7 +117380,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -112949,7 +117405,7 @@ var ts; // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -113039,7 +117495,7 @@ var ts; // 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); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +117538,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113106,15 +117562,15 @@ var ts; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { - case 71 /* Identifier */: - return !ts.isLabelName(node); - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + return !ts.isLabelName(node) && !ts.isTagName(node); + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` return !ts.isInComment(sourceFile, position); - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 97 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 98 /* SuperKeyword */: return true; default: return false; @@ -113152,7 +117608,7 @@ var ts; var normalizedFileName = ts.normalizePath(fileName); ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); synchronizeHostData(); - var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); }); + var sourceFilesToSearch = filesToSearch.map(getValidSourceFile); var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } @@ -113160,29 +117616,27 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position); - if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { + if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113223,16 +117677,16 @@ var ts; return undefined; } switch (node.kind) { - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: - case 9 /* StringLiteral */: - case 86 /* FalseKeyword */: - case 101 /* TrueKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 71 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: + case 10 /* StringLiteral */: + case 87 /* FalseKeyword */: + case 102 /* TrueKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 100 /* ThisKeyword */: + case 178 /* ThisType */: + case 72 /* Identifier */: break; // Cant create the text span default: @@ -113248,7 +117702,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 === 242 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 244 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -113310,10 +117764,10 @@ var ts; return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken); } var braceMatching = ts.createMapFromTemplate((_a = {}, - _a[17 /* OpenBraceToken */] = 18 /* CloseBraceToken */, - _a[19 /* OpenParenToken */] = 20 /* CloseParenToken */, - _a[21 /* OpenBracketToken */] = 22 /* CloseBracketToken */, - _a[29 /* GreaterThanToken */] = 27 /* LessThanToken */, + _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */, + _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */, + _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */, + _a[30 /* GreaterThanToken */] = 28 /* LessThanToken */, _a)); braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); function getBraceMatchingAtPosition(fileName, position) { @@ -113389,19 +117843,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -113441,7 +117907,7 @@ var ts; var token = ts.findPrecedingToken(position, sourceFile); if (!token) return undefined; - var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent + var element = token.kind === 30 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent : ts.isJsxText(token) ? token.parent : undefined; if (element && isUnclosedTag(element)) { return { newText: "" }; @@ -113679,7 +118145,7 @@ var ts; function initializeNameTable(sourceFile) { var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); sourceFile.forEachChild(function walk(node) { - if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { + if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { var text = ts.getEscapedTextOfIdentifierOrLiteral(node); nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } @@ -113700,7 +118166,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 257 /* ExternalModuleReference */ || + node.parent.kind === 259 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -113715,15 +118181,15 @@ var ts; ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; function getContainingObjectLiteralElementWorker(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 147 /* ComputedPropertyName */) { + if (node.parent.kind === 149 /* ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 186 /* ObjectLiteralExpression */ || node.parent.parent.kind === 266 /* JsxAttributes */) && + (node.parent.parent.kind === 188 /* ObjectLiteralExpression */ || node.parent.parent.kind === 268 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -113765,7 +118231,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 188 /* ElementAccessExpression */ && + node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -113845,144 +118311,144 @@ var ts; if (node) { var parent = node.parent; switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 235 /* VariableDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 237 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return spanInVariableDeclaration(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return spanInParameterDeclaration(node); - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return spanInBlock(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return spanInBlock(node.block); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 221 /* DoStatement */: + case 223 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 234 /* DebuggerStatement */: + case 236 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 220 /* IfStatement */: + case 222 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return spanInForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 233 /* TryStatement */: + case 235 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 184 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 186 /* BindingElement */: // span on complete node return textSpan(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 150 /* Decorator */: + case 152 /* Decorator */: return spanInNodeArray(parent.decorators); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return undefined; // Tokens: - case 25 /* SemicolonToken */: + case 26 /* SemicolonToken */: case 1 /* EndOfFileToken */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return spanInPreviousNode(node); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return spanInOpenBraceToken(node); - case 18 /* CloseBraceToken */: + case 19 /* CloseBraceToken */: return spanInCloseBraceToken(node); - case 22 /* CloseBracketToken */: + case 23 /* CloseBracketToken */: return spanInCloseBracketToken(node); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return spanInOpenParenToken(node); - case 20 /* CloseParenToken */: + case 21 /* CloseParenToken */: return spanInCloseParenToken(node); - case 56 /* ColonToken */: + case 57 /* ColonToken */: return spanInColonToken(node); - case 29 /* GreaterThanToken */: - case 27 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 28 /* LessThanToken */: return spanInGreaterThanOrLessThanToken(node); // Keywords: - case 106 /* WhileKeyword */: + case 107 /* WhileKeyword */: return spanInWhileKeyword(node); - case 82 /* ElseKeyword */: - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 83 /* ElseKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return spanInNextNode(node); - case 145 /* OfKeyword */: + case 147 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -113994,14 +118460,14 @@ var ts; // 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 === 71 /* Identifier */ || - node.kind === 206 /* SpreadElement */ || - node.kind === 273 /* PropertyAssignment */ || - node.kind === 274 /* ShorthandPropertyAssignment */) && + if ((node.kind === 72 /* Identifier */ || + node.kind === 208 /* SpreadElement */ || + node.kind === 275 /* PropertyAssignment */ || + node.kind === 276 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 202 /* BinaryExpression */) { + if (node.kind === 204 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -114010,35 +118476,35 @@ var ts; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); } - if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + if (operatorToken.kind === 59 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.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 (operatorToken.kind === 26 /* CommaToken */) { + if (operatorToken.kind === 27 /* CommaToken */) { return spanInNode(left); } } if (ts.isExpressionNode(node)) { switch (parent.kind) { - case 221 /* DoStatement */: + case 223 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 150 /* Decorator */: + case 152 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: return textSpan(node); - case 202 /* BinaryExpression */: - if (node.parent.operatorToken.kind === 26 /* CommaToken */) { + case 204 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 27 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -114047,21 +118513,21 @@ var ts; } } switch (node.parent.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: { + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -114069,7 +118535,7 @@ var ts; } break; } - case 202 /* BinaryExpression */: { + case 204 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -114099,7 +118565,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 224 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 226 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } var parent = variableDeclaration.parent; @@ -114111,7 +118577,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - parent.parent.kind === 225 /* ForOfStatement */) { + parent.parent.kind === 227 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -114152,7 +118618,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 238 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */); + (functionDeclaration.parent.kind === 240 /* ClassDeclaration */ && functionDeclaration.kind !== 157 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -114175,26 +118641,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // falls through // Set on parent if on same line otherwise on first statement - case 222 /* WhileStatement */: - case 220 /* IfStatement */: - case 224 /* ForInStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 226 /* 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 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 227 /* 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(forLikeStatement) { - if (forLikeStatement.initializer.kind === 236 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 238 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -114219,21 +118685,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 184 /* BindingElement */) { + if (bindingPattern.parent.kind === 186 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 183 /* ArrayBindingPattern */ && node.kind !== 182 /* ObjectBindingPattern */); - var elements = node.kind === 185 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 185 /* ArrayBindingPattern */ && node.kind !== 184 /* ObjectBindingPattern */); + var elements = node.kind === 187 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 210 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -114241,18 +118707,18 @@ var ts; // 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 === 202 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 204 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -114260,25 +118726,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 241 /* EnumDeclaration */: - case 238 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 216 /* Block */: + case 218 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 272 /* CatchClause */: + case 274 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -114286,7 +118752,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 182 /* ObjectBindingPattern */: + case 184 /* 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); @@ -114302,7 +118768,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 183 /* ArrayBindingPattern */: + case 185 /* 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); @@ -114317,12 +118783,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 221 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 189 /* CallExpression */ || - node.parent.kind === 190 /* NewExpression */) { + if (node.parent.kind === 223 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 191 /* CallExpression */ || + node.parent.kind === 192 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 193 /* ParenthesizedExpression */) { + if (node.parent.kind === 195 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -114331,21 +118797,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 193 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 195 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -114355,20 +118821,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 273 /* PropertyAssignment */ || - node.parent.kind === 149 /* Parameter */) { + node.parent.kind === 275 /* PropertyAssignment */ || + node.parent.kind === 151 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 192 /* TypeAssertionExpression */) { + if (node.parent.kind === 194 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 221 /* DoStatement */) { + if (node.parent.kind === 223 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -114376,7 +118842,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 225 /* ForOfStatement */) { + if (node.parent.kind === 227 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -114474,7 +118940,7 @@ var ts; var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; // TODO: GH#18217 + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -114484,7 +118950,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); }; } } @@ -114593,9 +119059,15 @@ var ts; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } + else { + this.directoryExists = undefined; // TODO: GH#18217 + } if ("realpath" in this.shimHost) { this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 } + else { + this.realpath = undefined; // TODO: GH#18217 + } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index dd81fe55ced..f3a4bfc0f58 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -21,7 +21,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -86,7 +86,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -101,6 +101,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -490,10 +491,33 @@ var ts; return result; } ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ function flatMap(array, mapfn) { var result; if (array) { - result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || ts.emptyArray; + } + ts.flatMap = flatMap; + function flatMapToMutable(array, mapfn) { + var result = []; + if (array) { for (var i = 0; i < array.length; i++) { var v = mapfn(array[i], i); if (v) { @@ -508,7 +532,7 @@ var ts; } return result; } - ts.flatMap = flatMap; + ts.flatMapToMutable = flatMapToMutable; function flatMapIterator(iter, mapfn) { var first = iter.next(); if (first.done) { @@ -729,19 +753,25 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) - return []; + return ts.emptyArray; var last = array[0]; var deduplicated = [last]; for (var i = 1; i < array.length; i++) { @@ -772,7 +802,7 @@ var ts; } ts.insertSorted = insertSorted; function sortAndDeduplicate(array, comparer, equalityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); } ts.sortAndDeduplicate = sortAndDeduplicate; function arrayIsEqualTo(array1, array2, equalityComparer) { @@ -784,7 +814,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -925,7 +955,7 @@ var ts; * Returns a new sorted array. */ function sort(array, comparer) { - return array.slice().sort(comparer); + return (array.length === 0 ? array : array.slice().sort(comparer)); } ts.sort = sort; function arrayIterator(array) { @@ -1031,12 +1061,25 @@ var ts; * @param offset An offset into `array` at which to start the search. */ function binarySearch(array, value, keySelector, keyComparer, offset) { - if (!array || array.length === 0) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + ts.binarySearch = binarySearch; + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { return -1; } var low = offset || 0; var high = array.length - 1; - var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); var midKey = keySelector(array[middle]); @@ -1053,7 +1096,7 @@ var ts; } return ~low; } - ts.binarySearch = binarySearch; + ts.binarySearchKey = binarySearchKey; function reduceLeft(array, f, initial, start, count) { if (array && array.length > 0) { var size = array.length; @@ -1161,7 +1204,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1281,6 +1324,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1445,7 +1492,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1948,6 +1997,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -1967,6 +2020,33 @@ var ts; var counts; var marks; var measures; + function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; + } + performance.createTimerIf = createTimerIf; + function createTimer(measureName, startMarkName, endMarkName) { + var enterCount = 0; + return { + enter: enter, + exit: exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + ts.Debug.fail("enter/exit count does not match."); + } + } + } + performance.createTimer = createTimer; + performance.nullTimer = { enter: ts.noop, exit: ts.noop }; /** * Marks a performance event. * @@ -2042,6 +2122,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2061,368 +2501,370 @@ var ts; SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; // Literals SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; - SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; - SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; // Pseudo-literals - SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; + SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail"; // Punctuation - SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken"; // Assignments - SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken"; // Identifiers - SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; + SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier"; // Reserved words - SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword"; // Strict mode reserved words - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword"; // Contextual keywords - SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; - SyntaxKind[SyntaxKind["InferKeyword"] = 126] = "InferKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 127] = "IsKeyword"; - SyntaxKind[SyntaxKind["KeyOfKeyword"] = 128] = "KeyOfKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 129] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 130] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 131] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 132] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 133] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 134] = "NumberKeyword"; - SyntaxKind[SyntaxKind["ObjectKeyword"] = 135] = "ObjectKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 136] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 137] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 138] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword"; - SyntaxKind[SyntaxKind["UnknownKeyword"] = 142] = "UnknownKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 143] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 144] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 145] = "OfKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 146] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 147] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 148] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 149] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 150] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 151] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 152] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 153] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 154] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 155] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 156] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 157] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 158] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 159] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 160] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 161] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 162] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 163] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 164] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 165] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 166] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 167] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 168] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 169] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 170] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 171] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 172] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 173] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 174] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 175] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 176] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 177] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 178] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 179] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 180] = "LiteralType"; - SyntaxKind[SyntaxKind["ImportType"] = 181] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 182] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 183] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 184] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 185] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 186] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 187] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 188] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 189] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 190] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 191] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 192] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 193] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 194] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 195] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 196] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 197] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 198] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 199] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 200] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 201] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 202] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 203] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 204] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 205] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 206] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 207] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 208] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 209] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 210] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 211] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 212] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 213] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 214] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 215] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 216] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 217] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 218] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 219] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 220] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 221] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 222] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 223] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 224] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 225] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 226] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 227] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 228] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 229] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 230] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 231] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 232] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 233] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 234] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 235] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 236] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 237] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 238] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 239] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 240] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 241] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 242] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 243] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 244] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 245] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 246] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 247] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 248] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 249] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 250] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 251] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 252] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 253] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 254] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 255] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 256] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 218] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 257] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 258] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 259] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 260] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 261] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 262] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 263] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 264] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 265] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 266] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 267] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 268] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 269] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 270] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 271] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 272] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 273] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 274] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 275] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 276] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 277] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 278] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 279] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 280] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 281] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 282] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 283] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 284] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 285] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 286] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 287] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 288] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 289] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 290] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 291] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 292] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 310] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; // Markers - SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 145] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 161] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 181] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 145] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode"; - /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -2622,7 +3064,10 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; + // Errors (cont.) + NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors"; // State NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; @@ -2678,6 +3123,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2709,14 +3156,15 @@ var ts; // of a type, such as the global `Promise` type in lib.d.ts). TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature"; // with call signatures. - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var SymbolFlags; (function (SymbolFlags) { @@ -2747,38 +3195,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2853,14 +3301,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2870,29 +3319,27 @@ var ts; TypeFlags[TypeFlags["Number"] = 8] = "Number"; TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 64] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 128] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 256] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 512] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 1024] = "ESSymbol"; - TypeFlags[TypeFlags["UniqueESSymbol"] = 2048] = "UniqueESSymbol"; - TypeFlags[TypeFlags["Void"] = 4096] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 8192] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 16384] = "Null"; - TypeFlags[TypeFlags["Never"] = 32768] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 65536] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 131072] = "Object"; - TypeFlags[TypeFlags["Union"] = 262144] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 524288] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 1048576] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 2097152] = "IndexedAccess"; - TypeFlags[TypeFlags["Conditional"] = 4194304] = "Conditional"; - TypeFlags[TypeFlags["Substitution"] = 8388608] = "Substitution"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; - /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; - /* @internal */ - TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes"; + TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt"; + TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 16384] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 65536] = "Null"; + TypeFlags[TypeFlags["Never"] = 131072] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 524288] = "Object"; + TypeFlags[TypeFlags["Union"] = 1048576] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 4194304] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; /* @internal */ TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ @@ -2902,40 +3349,41 @@ var ts; /* @internal */ TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 24576] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 448] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 27072] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 192] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 2944] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 2240] = "StringOrNumberLiteralOrUnique"; + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 29120] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 29148] = "PossiblyFalsy"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 16839967] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 32764] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 68] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 168] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 272] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 544] = "EnumLike"; - TypeFlags[TypeFlags["ESSymbolLike"] = 3072] = "ESSymbolLike"; - TypeFlags[TypeFlags["VoidLike"] = 12288] = "VoidLike"; + TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike"; + TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; /* @internal */ - TypeFlags[TypeFlags["DisjointDomains"] = 16809468] = "DisjointDomains"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 786432] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 917504] = "StructuredType"; - TypeFlags[TypeFlags["TypeVariable"] = 2162688] = "TypeVariable"; - TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 14745600] = "InstantiableNonPrimitive"; - TypeFlags[TypeFlags["InstantiablePrimitive"] = 1048576] = "InstantiablePrimitive"; - TypeFlags[TypeFlags["Instantiable"] = 15794176] = "Instantiable"; - TypeFlags[TypeFlags["StructuredOrInstantiable"] = 16711680] = "StructuredOrInstantiable"; + TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion"; + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ @@ -2970,6 +3418,7 @@ var ts; ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -2981,6 +3430,13 @@ var ts; Variance[Variance["Bivariant"] = 3] = "Bivariant"; Variance[Variance["Independent"] = 4] = "Independent"; })(Variance = ts.Variance || (ts.Variance = {})); + /* @internal */ + var JsxReferenceKind; + (function (JsxReferenceKind) { + JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component"; + JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function"; + JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed"; + })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {})); var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; @@ -3006,9 +3462,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3027,22 +3482,31 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue"; + // Object.defineProperty(exports || module.exports, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports"; + // Object.defineProperty(Foo.prototype, 'name', ...); + AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3279,25 +3743,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3316,25 +3776,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3414,6 +3873,7 @@ var ts; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; + EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); var ListFormat; (function (ListFormat) { @@ -3428,64 +3888,66 @@ var ts; ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma"; // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + ListFormat[ListFormat["Indented"] = 128] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings"; // Brackets/Braces - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + ListFormat[ListFormat["Braces"] = 1024] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 49152] = "Optional"; // Other - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; + ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters"; + ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment"; })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); /* @internal */ var PragmaKindFlags; @@ -3578,20 +4040,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3809,17 +4257,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4140,11 +4592,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4755,7 +5208,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4794,6 +5247,11 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4806,7 +5264,7 @@ var ts; An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), - An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), @@ -4850,14 +5308,14 @@ var ts; Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), @@ -4913,7 +5371,7 @@ var ts; Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), - A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), @@ -4996,7 +5454,7 @@ var ts; _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), - Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), @@ -5027,7 +5485,7 @@ var ts; Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), @@ -5037,7 +5495,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5065,6 +5522,15 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5156,6 +5622,15 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5269,7 +5744,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5363,7 +5840,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5461,6 +5938,18 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5491,9 +5980,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5501,6 +5990,7 @@ var ts; _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), @@ -5528,6 +6018,15 @@ var ts; If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5558,6 +6057,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5622,6 +6122,7 @@ var ts; Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), + Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -5686,150 +6187,108 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { - return token >= 71 /* Identifier */; + return token >= 72 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; /* @internal */ function tokenIsIdentifierOrKeywordOrGreaterThan(token) { - return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 118 /* AbstractKeyword */, + any: 120 /* AnyKeyword */, + as: 119 /* AsKeyword */, + bigint: 146 /* BigIntKeyword */, + boolean: 123 /* BooleanKeyword */, + break: 73 /* BreakKeyword */, + case: 74 /* CaseKeyword */, + catch: 75 /* CatchKeyword */, + class: 76 /* ClassKeyword */, + continue: 78 /* ContinueKeyword */, + const: 77 /* ConstKeyword */ + }, + _a["" + "constructor"] = 124 /* ConstructorKeyword */, + _a.debugger = 79 /* DebuggerKeyword */, + _a.declare = 125 /* DeclareKeyword */, + _a.default = 80 /* DefaultKeyword */, + _a.delete = 81 /* DeleteKeyword */, + _a.do = 82 /* DoKeyword */, + _a.else = 83 /* ElseKeyword */, + _a.enum = 84 /* EnumKeyword */, + _a.export = 85 /* ExportKeyword */, + _a.extends = 86 /* ExtendsKeyword */, + _a.false = 87 /* FalseKeyword */, + _a.finally = 88 /* FinallyKeyword */, + _a.for = 89 /* ForKeyword */, + _a.from = 144 /* FromKeyword */, + _a.function = 90 /* FunctionKeyword */, + _a.get = 126 /* GetKeyword */, + _a.if = 91 /* IfKeyword */, + _a.implements = 109 /* ImplementsKeyword */, + _a.import = 92 /* ImportKeyword */, + _a.in = 93 /* InKeyword */, + _a.infer = 127 /* InferKeyword */, + _a.instanceof = 94 /* InstanceOfKeyword */, + _a.interface = 110 /* InterfaceKeyword */, + _a.is = 128 /* IsKeyword */, + _a.keyof = 129 /* KeyOfKeyword */, + _a.let = 111 /* LetKeyword */, + _a.module = 130 /* ModuleKeyword */, + _a.namespace = 131 /* NamespaceKeyword */, + _a.never = 132 /* NeverKeyword */, + _a.new = 95 /* NewKeyword */, + _a.null = 96 /* NullKeyword */, + _a.number = 135 /* NumberKeyword */, + _a.object = 136 /* ObjectKeyword */, + _a.package = 112 /* PackageKeyword */, + _a.private = 113 /* PrivateKeyword */, + _a.protected = 114 /* ProtectedKeyword */, + _a.public = 115 /* PublicKeyword */, + _a.readonly = 133 /* ReadonlyKeyword */, + _a.require = 134 /* RequireKeyword */, + _a.global = 145 /* GlobalKeyword */, + _a.return = 97 /* ReturnKeyword */, + _a.set = 137 /* SetKeyword */, + _a.static = 116 /* StaticKeyword */, + _a.string = 138 /* StringKeyword */, + _a.super = 98 /* SuperKeyword */, + _a.switch = 99 /* SwitchKeyword */, + _a.symbol = 139 /* SymbolKeyword */, + _a.this = 100 /* ThisKeyword */, + _a.throw = 101 /* ThrowKeyword */, + _a.true = 102 /* TrueKeyword */, + _a.try = 103 /* TryKeyword */, + _a.type = 140 /* TypeKeyword */, + _a.typeof = 104 /* TypeOfKeyword */, + _a.undefined = 141 /* UndefinedKeyword */, + _a.unique = 142 /* UniqueKeyword */, + _a.unknown = 143 /* UnknownKeyword */, + _a.var = 105 /* VarKeyword */, + _a.void = 106 /* VoidKeyword */, + _a.while = 107 /* WhileKeyword */, + _a.with = 108 /* WithKeyword */, + _a.yield = 117 /* YieldKeyword */, + _a.async = 121 /* AsyncKeyword */, + _a.await = 122 /* AwaitKeyword */, + _a.of = 147 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, ">": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -5964,11 +6423,28 @@ var ts; } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { + function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); + } + ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { - ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + } } var res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } if (line < lineStarts.length - 1) { ts.Debug.assert(res < lineStarts[line + 1]); } @@ -6407,6 +6883,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6417,8 +6894,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, - isIdentifier: function () { return token === 71 /* Identifier */ || token > 107 /* LastReservedWord */; }, - isReservedWord: function () { return token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */; }, + isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; }, isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, @@ -6436,6 +6913,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6511,18 +6989,29 @@ var ts; end = pos; } } + var result; if (tokenFlags & 512 /* ContainsSeparator */) { - var result = mainFragment; + result = mainFragment; if (decimalFragment) { result += "." + decimalFragment; } if (scientificFragment) { result += scientificFragment; } - return "" + +result; } else { - return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + return { + type: 8 /* NumericLiteral */, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type: type, value: tokenValue }; } } function scanOctalDigits() { @@ -6537,21 +7026,21 @@ var ts; * returning -1 if the given number is unavailable. */ function scanExactNumberOfHexDigits(count, canHaveSeparators) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; } /** * Scans as many hexadecimal digits as are available in the text, - * returning -1 if the given number of digits was unavailable. + * returning "" if the given number of digits was unavailable. */ function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { - var digits = 0; - var value = 0; + var valueChars = []; var allowSeparator = false; var isPreviousTokenSeparator = false; - while (digits < minCount || scanAsManyAsPossible) { + while (valueChars.length < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); if (canHaveSeparators && ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; @@ -6569,29 +7058,24 @@ var ts; continue; } allowSeparator = canHaveSeparators; - if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { - value = value * 16 + ch - 48 /* _0 */; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase } - else if (ch >= 65 /* A */ && ch <= 70 /* F */) { - value = value * 16 + ch - 65 /* A */ + 10; - } - else if (ch >= 97 /* a */ && ch <= 102 /* f */) { - value = value * 16 + ch - 97 /* a */ + 10; - } - else { + else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) || + (ch >= 97 /* a */ && ch <= 102 /* f */))) { break; } + valueChars.push(ch); pos++; - digits++; isPreviousTokenSeparator = false; } - if (digits < minCount) { - value = -1; + if (valueChars.length < minCount) { + valueChars = []; } if (text.charCodeAt(pos - 1) === 95 /* _ */) { error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } - return value; + return String.fromCharCode.apply(String, valueChars); } function scanString(jsxAttributeString) { if (jsxAttributeString === void 0) { jsxAttributeString = false; } @@ -6643,7 +7127,7 @@ var ts; contents += text.substring(start, pos); tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; break; } var currChar = text.charCodeAt(pos); @@ -6651,14 +7135,14 @@ var ts; if (currChar === 96 /* backtick */) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; + resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */; break; } // '${' if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 14 /* TemplateHead */ : 15 /* TemplateMiddle */; + resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */; break; } // Escape character @@ -6751,7 +7235,8 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; var isInvalidExtendedEscape = false; // Validate the value of the digit if (escapedValue < 0) { @@ -6833,20 +7318,18 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } - return token = 71 /* Identifier */; + return token = 72 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); - var value = 0; + var value = ""; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. - var numberOfDigits = 0; var separatorAllowed = false; var isPreviousTokenSeparator = false; while (true) { @@ -6868,29 +7351,45 @@ var ts; continue; } separatorAllowed = true; - var valueOfCh = ch - 48 /* _0 */; - if (!isDigit(ch) || valueOfCh >= base) { + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { break; } - value = value * base + valueOfCh; + value += text[pos]; pos++; - numberOfDigits++; isPreviousTokenSeparator = false; } - // Invalid binaryIntegerLiteral or octalIntegerLiteral - if (numberOfDigits === 0) { - return -1; - } if (text.charCodeAt(pos - 1) === 95 /* _ */) { // Literal ends with underscore - not allowed error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); - return value; } return value; } + function checkBigIntSuffix() { + if (text.charCodeAt(pos) === 110 /* n */) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = ts.parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 9 /* BigIntLiteral */; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + var numericValue = tokenFlags & 128 /* BinarySpecifier */ + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & 256 /* OctalSpecifier */ + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return 8 /* NumericLiteral */; + } + } function scan() { + var _a; startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6929,6 +7428,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6942,82 +7459,87 @@ var ts; case 33 /* exclamation */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 35 /* ExclamationEqualsEqualsToken */; + return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */; } - return pos += 2, token = 33 /* ExclamationEqualsToken */; + return pos += 2, token = 34 /* ExclamationEqualsToken */; } pos++; - return token = 51 /* ExclamationToken */; + return token = 52 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); - return token = 9 /* StringLiteral */; + return token = 10 /* StringLiteral */; case 96 /* backtick */: return token = scanTemplateAndSetTokenValue(); case 37 /* percent */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 64 /* PercentEqualsToken */; + return pos += 2, token = 65 /* PercentEqualsToken */; } pos++; - return token = 42 /* PercentToken */; + return token = 43 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { - return pos += 2, token = 53 /* AmpersandAmpersandToken */; + return pos += 2, token = 54 /* AmpersandAmpersandToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 68 /* AmpersandEqualsToken */; + return pos += 2, token = 69 /* AmpersandEqualsToken */; } pos++; - return token = 48 /* AmpersandToken */; + return token = 49 /* AmpersandToken */; case 40 /* openParen */: pos++; - return token = 19 /* OpenParenToken */; + return token = 20 /* OpenParenToken */; case 41 /* closeParen */: pos++; - return token = 20 /* CloseParenToken */; + return token = 21 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 61 /* AsteriskEqualsToken */; + return pos += 2, token = 62 /* AsteriskEqualsToken */; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 62 /* AsteriskAsteriskEqualsToken */; + return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */; } - return pos += 2, token = 40 /* AsteriskAsteriskToken */; + return pos += 2, token = 41 /* AsteriskAsteriskToken */; } pos++; - return token = 39 /* AsteriskToken */; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } + return token = 40 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { - return pos += 2, token = 43 /* PlusPlusToken */; + return pos += 2, token = 44 /* PlusPlusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 59 /* PlusEqualsToken */; + return pos += 2, token = 60 /* PlusEqualsToken */; } pos++; - return token = 37 /* PlusToken */; + return token = 38 /* PlusToken */; case 44 /* comma */: pos++; - return token = 26 /* CommaToken */; + return token = 27 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { - return pos += 2, token = 44 /* MinusMinusToken */; + return pos += 2, token = 45 /* MinusMinusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 60 /* MinusEqualsToken */; + return pos += 2, token = 61 /* MinusEqualsToken */; } pos++; - return token = 38 /* MinusToken */; + return token = 39 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber(); + tokenValue = scanNumber().value; return token = 8 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { - return pos += 3, token = 24 /* DotDotDotToken */; + return pos += 3, token = 25 /* DotDotDotToken */; } pos++; - return token = 23 /* DotToken */; + return token = 24 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -7068,43 +7590,43 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 63 /* SlashEqualsToken */; + return pos += 2, token = 64 /* SlashEqualsToken */; } pos++; - return token = 41 /* SlashToken */; + return token = 42 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); - if (value < 0) { + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { error(ts.Diagnostics.Hexadecimal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0x" + tokenValue; tokenFlags |= 64 /* HexSpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 2); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { error(ts.Diagnostics.Binary_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0b" + tokenValue; tokenFlags |= 128 /* BinarySpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 8); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { error(ts.Diagnostics.Octal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0o" + tokenValue; tokenFlags |= 256 /* OctalSpecifier */; - return token = 8 /* NumericLiteral */; + return token = checkBigIntSuffix(); } // Try to parse as an octal if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { @@ -7125,14 +7647,14 @@ var ts; case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - tokenValue = scanNumber(); - return token = 8 /* NumericLiteral */; + (_a = scanNumber(), token = _a.type, tokenValue = _a.value); + return token; case 58 /* colon */: pos++; - return token = 56 /* ColonToken */; + return token = 57 /* ColonToken */; case 59 /* semicolon */: pos++; - return token = 25 /* SemicolonToken */; + return token = 26 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7145,20 +7667,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 65 /* LessThanLessThanEqualsToken */; + return pos += 3, token = 66 /* LessThanLessThanEqualsToken */; } - return pos += 2, token = 45 /* LessThanLessThanToken */; + return pos += 2, token = 46 /* LessThanLessThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 30 /* LessThanEqualsToken */; + return pos += 2, token = 31 /* LessThanEqualsToken */; } if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */) { - return pos += 2, token = 28 /* LessThanSlashToken */; + return pos += 2, token = 29 /* LessThanSlashToken */; } pos++; - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7171,15 +7693,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 34 /* EqualsEqualsEqualsToken */; + return pos += 3, token = 35 /* EqualsEqualsEqualsToken */; } - return pos += 2, token = 32 /* EqualsEqualsToken */; + return pos += 2, token = 33 /* EqualsEqualsToken */; } if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { - return pos += 2, token = 36 /* EqualsGreaterThanToken */; + return pos += 2, token = 37 /* EqualsGreaterThanToken */; } pos++; - return token = 58 /* EqualsToken */; + return token = 59 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7191,25 +7713,25 @@ var ts; } } pos++; - return token = 29 /* GreaterThanToken */; + return token = 30 /* GreaterThanToken */; case 63 /* question */: pos++; - return token = 55 /* QuestionToken */; + return token = 56 /* QuestionToken */; case 91 /* openBracket */: pos++; - return token = 21 /* OpenBracketToken */; + return token = 22 /* OpenBracketToken */; case 93 /* closeBracket */: pos++; - return token = 22 /* CloseBracketToken */; + return token = 23 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 70 /* CaretEqualsToken */; + return pos += 2, token = 71 /* CaretEqualsToken */; } pos++; - return token = 50 /* CaretToken */; + return token = 51 /* CaretToken */; case 123 /* openBrace */: pos++; - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; case 124 /* bar */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -7221,22 +7743,22 @@ var ts; } } if (text.charCodeAt(pos + 1) === 124 /* bar */) { - return pos += 2, token = 54 /* BarBarToken */; + return pos += 2, token = 55 /* BarBarToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 69 /* BarEqualsToken */; + return pos += 2, token = 70 /* BarEqualsToken */; } pos++; - return token = 49 /* BarToken */; + return token = 50 /* BarToken */; case 125 /* closeBrace */: pos++; - return token = 18 /* CloseBraceToken */; + return token = 19 /* CloseBraceToken */; case 126 /* tilde */: pos++; - return token = 52 /* TildeToken */; + return token = 53 /* TildeToken */; case 64 /* at */: pos++; - return token = 57 /* AtToken */; + return token = 58 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -7274,29 +7796,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 29 /* GreaterThanToken */) { + if (token === 30 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } - return pos += 2, token = 47 /* GreaterThanGreaterThanGreaterThanToken */; + return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 66 /* GreaterThanGreaterThanEqualsToken */; + return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */; } pos++; - return token = 46 /* GreaterThanGreaterThanToken */; + return token = 47 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { pos++; - return token = 31 /* GreaterThanEqualsToken */; + return token = 32 /* GreaterThanEqualsToken */; } } return token; } function reScanSlashToken() { - if (token === 41 /* SlashToken */ || token === 63 /* SlashEqualsToken */) { + if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -7341,7 +7863,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12 /* RegularExpressionLiteral */; + token = 13 /* RegularExpressionLiteral */; } return token; } @@ -7349,7 +7871,7 @@ var ts; * Unconditionally back up and scan a template expression portion. */ function reScanTemplateToken() { - ts.Debug.assert(token === 18 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -7366,14 +7888,14 @@ var ts; if (char === 60 /* lessThan */) { if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; - return token = 28 /* LessThanSlashToken */; + return token = 29 /* LessThanSlashToken */; } pos++; - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; } if (char === 123 /* openBrace */) { pos++; - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; } // First non-whitespace character on this line. var firstNonWhitespace = 0; @@ -7405,7 +7927,7 @@ var ts; } pos++; } - return firstNonWhitespace === -1 ? 11 /* JsxTextAllWhiteSpaces */ : 10 /* JsxText */; + return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -7431,7 +7953,7 @@ var ts; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(/*jsxAttributeString*/ true); - return token = 9 /* StringLiteral */; + return token = 10 /* StringLiteral */; default: // If this scans anything other than `{`, it's a parse error. return scan(); @@ -7455,43 +7977,43 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - return token = 57 /* AtToken */; + return token = 58 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - return token = 39 /* AsteriskToken */; + return token = 40 /* AsteriskToken */; case 123 /* openBrace */: - return token = 17 /* OpenBraceToken */; + return token = 18 /* OpenBraceToken */; case 125 /* closeBrace */: - return token = 18 /* CloseBraceToken */; + return token = 19 /* CloseBraceToken */; case 91 /* openBracket */: - return token = 21 /* OpenBracketToken */; + return token = 22 /* OpenBracketToken */; case 93 /* closeBracket */: - return token = 22 /* CloseBracketToken */; + return token = 23 /* CloseBracketToken */; case 60 /* lessThan */: - return token = 27 /* LessThanToken */; + return token = 28 /* LessThanToken */; case 61 /* equals */: - return token = 58 /* EqualsToken */; + return token = 59 /* EqualsToken */; case 44 /* comma */: - return token = 26 /* CommaToken */; + return token = 27 /* CommaToken */; case 46 /* dot */: - return token = 23 /* DotToken */; + return token = 24 /* DotToken */; case 96 /* backtick */: while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { pos++; } tokenValue = text.substring(tokenPos + 1, pos); pos++; - return token = 13 /* NoSubstitutionTemplateLiteral */; + return token = 14 /* NoSubstitutionTemplateLiteral */; } if (isIdentifierStart(ch, 6 /* Latest */)) { while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7568,10 +8090,12 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); -/** Non-internal stuff goes here */ var ts; (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -7588,7 +8112,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7635,7 +8158,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -7644,7 +8166,9 @@ var ts; writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, - writeSymbol: writeText, + writeSymbol: function (s, _) { return writeText(s); }, + writeTrailingSemicolon: writeText, + writeComment: writeText, getTextPos: function () { return str.length; }, getLine: function () { return 0; }, getColumn: function () { return 0; }, @@ -7670,22 +8194,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7790,6 +8301,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -7850,7 +8367,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 277 /* SourceFile */) { + while (node && node.kind !== 279 /* SourceFile */) { node = node.parent; } return node; @@ -7858,11 +8375,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 216 /* Block */: - case 244 /* CaseBlock */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return true; } return false; @@ -7996,7 +8513,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8014,12 +8531,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8046,35 +8571,37 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { + if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) || + ts.isBigIntLiteral(node))) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (node.singleQuote) { return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; } else { return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; } - case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return "`" + escapeText(node.text, 96 /* backtick */) + "`"; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: // tslint:disable-next-line no-invalid-template-strings return "`" + escapeText(node.text, 96 /* backtick */) + "${"; - case 15 /* TemplateMiddle */: + case 16 /* TemplateMiddle */: // tslint:disable-next-line no-invalid-template-strings return "}" + escapeText(node.text, 96 /* backtick */) + "${"; - case 16 /* TemplateTail */: + case 17 /* TemplateTail */: return "}" + escapeText(node.text, 96 /* backtick */) + "`"; case 8 /* NumericLiteral */: - case 12 /* RegularExpressionLiteral */: + case 9 /* BigIntLiteral */: + case 13 /* RegularExpressionLiteral */: return node.text; } return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -8097,15 +8624,15 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 235 /* VariableDeclaration */ && node.parent.kind === 272 /* CatchClause */; + return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { - return ts.isModuleDeclaration(node) && node.name.kind === 9 /* StringLiteral */; + return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */; } ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { @@ -8129,11 +8656,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 242 /* ModuleDeclaration */ && (!node.body); + return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 277 /* SourceFile */ || - node.kind === 242 /* ModuleDeclaration */ || + return node.kind === 279 /* SourceFile */ || + node.kind === 244 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -8150,9 +8677,9 @@ var ts; // - 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 switch (node.parent.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.isExternalModule(node.parent); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; @@ -8168,22 +8695,22 @@ var ts; ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 277 /* SourceFile */: - case 244 /* CaseBlock */: - case 272 /* CatchClause */: - case 242 /* ModuleDeclaration */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 274 /* CatchClause */: + case 244 /* ModuleDeclaration */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; - case 216 /* Block */: + case 218 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -8193,9 +8720,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: - case 291 /* JSDocSignature */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 293 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -8205,25 +8732,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 287 /* JSDocFunctionType */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; default: ts.assertType(node); @@ -8233,8 +8760,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: return true; default: return false; @@ -8243,15 +8770,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 217 /* VariableStatement */: - case 238 /* ClassDeclaration */: - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 219 /* VariableStatement */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: return true; default: return false; @@ -8281,12 +8808,13 @@ var ts; ts.getNameFromIndexInfo = getNameFromIndexInfo; function getTextOfPropertyName(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return name.escapedText; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: return ts.Debug.assertNever(name); @@ -8295,11 +8823,11 @@ var ts; ts.getTextOfPropertyName = getTextOfPropertyName; function entityNameToString(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); default: throw ts.Debug.assertNever(name); @@ -8344,7 +8872,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 216 /* Block */) { + if (node.body && node.body.kind === 218 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -8358,7 +8886,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 277 /* SourceFile */: + case 279 /* 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 @@ -8367,25 +8895,25 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 240 /* TypeAliasDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 242 /* TypeAliasDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: errorNode = node.name; break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -8421,6 +8949,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8430,11 +8962,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 189 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; + return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 189 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { @@ -8442,20 +8974,20 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 219 /* ExpressionStatement */ - && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 221 /* ExpressionStatement */ + && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return node.kind !== 10 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 149 /* Parameter */ || - node.kind === 148 /* TypeParameter */ || - node.kind === 194 /* FunctionExpression */ || - node.kind === 195 /* ArrowFunction */ || - node.kind === 193 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 151 /* Parameter */ || + node.kind === 150 /* TypeParameter */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 197 /* ArrowFunction */ || + node.kind === 195 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -8471,46 +9003,48 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 181 /* LastTypeNode */) { + if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) { return true; } switch (node.kind) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 134 /* NumberKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 140 /* UndefinedKeyword */: - case 131 /* NeverKeyword */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: return true; - case 105 /* VoidKeyword */: - return node.parent.kind !== 198 /* VoidExpression */; - case 209 /* ExpressionWithTypeArguments */: + case 106 /* VoidKeyword */: + return node.parent.kind !== 200 /* VoidExpression */; + case 211 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 148 /* TypeParameter */: - return node.parent.kind === 179 /* MappedType */ || node.parent.kind === 174 /* InferType */; + case 150 /* TypeParameter */: + return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container - case 71 /* Identifier */: + case 72 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 189 /* 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 === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 187 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 146 /* QualifiedName */: - case 187 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: { + case 148 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + case 100 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 165 /* TypeQuery */) { + if (parent.kind === 167 /* TypeQuery */) { return false; } - if (parent.kind === 181 /* ImportType */) { + if (parent.kind === 183 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -8519,40 +9053,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 181 /* LastTypeNode */) { + if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return node === parent.constraint; - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return node === parent.constraint; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 149 /* Parameter */: - case 235 /* VariableDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: return node === parent.type; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return node === parent.type; - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return node === parent.type; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return node === parent.type; - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -8577,23 +9111,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitor(node); - case 244 /* CaseBlock */: - case 216 /* Block */: - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 229 /* WithStatement */: - case 230 /* SwitchStatement */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 231 /* LabeledStatement */: - case 233 /* TryStatement */: - case 272 /* CatchClause */: + case 246 /* CaseBlock */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -8603,26 +9137,26 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 241 /* EnumDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 243 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* 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. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 147 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 149 /* 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(node.name.expression); @@ -8645,10 +9179,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 167 /* ArrayType */) { + if (node && node.kind === 169 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 162 /* TypeReference */) { + else if (node && node.kind === 164 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -8658,12 +9192,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 166 /* TypeLiteral */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 168 /* TypeLiteral */: return node.members; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return node.properties; } } @@ -8671,14 +9205,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 184 /* BindingElement */: - case 276 /* EnumMember */: - case 149 /* Parameter */: - case 273 /* PropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 274 /* ShorthandPropertyAssignment */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 278 /* EnumMember */: + case 151 /* Parameter */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 276 /* ShorthandPropertyAssignment */: + case 237 /* VariableDeclaration */: return true; } } @@ -8690,8 +9224,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 236 /* VariableDeclarationList */ - && node.parent.parent.kind === 217 /* VariableStatement */; + return node.parent.kind === 238 /* VariableDeclarationList */ + && node.parent.parent.kind === 219 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -8702,13 +9236,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return true; } return false; @@ -8719,7 +9253,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 231 /* LabeledStatement */) { + if (node.statement.kind !== 233 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -8727,17 +9261,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 216 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 186 /* ObjectLiteralExpression */; + return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 154 /* MethodDeclaration */ && - (node.parent.kind === 186 /* ObjectLiteralExpression */ || - node.parent.kind === 207 /* ClassExpression */); + return node.kind === 156 /* MethodDeclaration */ && + (node.parent.kind === 188 /* ObjectLiteralExpression */ || + node.parent.kind === 209 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -8750,7 +9284,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 273 /* PropertyAssignment */) { + if (property.kind === 275 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -8787,14 +9321,14 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 277 /* SourceFile */); + ts.Debug.assert(node.kind !== 279 /* SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* 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 @@ -8809,9 +9343,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8822,26 +9356,26 @@ var ts; node = node.parent; } break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 242 /* ModuleDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 241 /* EnumDeclaration */: - case 277 /* SourceFile */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 244 /* ModuleDeclaration */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 243 /* EnumDeclaration */: + case 279 /* SourceFile */: return node; } } @@ -8851,9 +9385,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: return container; } } @@ -8875,27 +9409,27 @@ var ts; return node; } switch (node.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: node = node.parent; break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return node; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8911,14 +9445,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 194 /* FunctionExpression */ || func.kind === 195 /* ArrowFunction */) { + if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 193 /* ParenthesizedExpression */) { + while (parent.kind === 195 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 189 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -8929,8 +9463,8 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) - && node.expression.kind === 97 /* SuperKeyword */; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 98 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; /** @@ -8938,20 +9472,20 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) - && node.expression.kind === 99 /* ThisKeyword */; + return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */) + && node.expression.kind === 100 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; - case 71 /* Identifier */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 148 /* QualifiedName */: return node; } return undefined; @@ -8959,10 +9493,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return node.tag; - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -8971,25 +9505,25 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: // classes are valid targets return true; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 238 /* ClassDeclaration */; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: + return parent.kind === 240 /* ClassDeclaration */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 238 /* ClassDeclaration */; - case 149 /* Parameter */: + && parent.kind === 240 /* ClassDeclaration */; + case 151 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 155 /* Constructor */ - || parent.kind === 154 /* MethodDeclaration */ - || parent.kind === 157 /* SetAccessor */) - && grandparent.kind === 238 /* ClassDeclaration */; + && (parent.kind === 157 /* Constructor */ + || parent.kind === 156 /* MethodDeclaration */ + || parent.kind === 159 /* SetAccessor */) + && grandparent.kind === 240 /* ClassDeclaration */; } return false; } @@ -9005,10 +9539,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 154 /* MethodDeclaration */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 159 /* SetAccessor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -9017,9 +9551,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 260 /* JsxOpeningElement */ || - parent.kind === 259 /* JsxSelfClosingElement */ || - parent.kind === 261 /* JsxClosingElement */) { + if (parent.kind === 262 /* JsxOpeningElement */ || + parent.kind === 261 /* JsxSelfClosingElement */ || + parent.kind === 263 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -9027,56 +9561,57 @@ var ts; ts.isJSXTagName = isJSXTagName; function isExpressionNode(node) { switch (node.kind) { - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 12 /* RegularExpressionLiteral */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 191 /* TaggedTemplateExpression */: - case 210 /* AsExpression */: - case 192 /* TypeAssertionExpression */: - case 211 /* NonNullExpression */: - case 193 /* ParenthesizedExpression */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: - case 195 /* ArrowFunction */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: - case 202 /* BinaryExpression */: - case 203 /* ConditionalExpression */: - case 206 /* SpreadElement */: - case 204 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 208 /* OmittedExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 205 /* YieldExpression */: - case 199 /* AwaitExpression */: - case 212 /* MetaProperty */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 13 /* RegularExpressionLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 212 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 204 /* BinaryExpression */: + case 205 /* ConditionalExpression */: + case 208 /* SpreadElement */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 210 /* OmittedExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 207 /* YieldExpression */: + case 201 /* AwaitExpression */: + case 214 /* MetaProperty */: return true; - case 146 /* QualifiedName */: - while (node.parent.kind === 146 /* QualifiedName */) { + case 148 /* QualifiedName */: + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node); - case 71 /* Identifier */: - if (node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node)) { + return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node); + case 72 /* Identifier */: + if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 99 /* ThisKeyword */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 100 /* ThisKeyword */: return isInExpressionContext(node); default: return false; @@ -9086,49 +9621,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 276 /* EnumMember */: - case 273 /* PropertyAssignment */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 186 /* BindingElement */: return parent.initializer === node; - case 219 /* ExpressionStatement */: - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 228 /* ReturnStatement */: - case 229 /* WithStatement */: - case 230 /* SwitchStatement */: - case 269 /* CaseClause */: - case 232 /* ThrowStatement */: + case 221 /* ExpressionStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 230 /* ReturnStatement */: + case 231 /* WithStatement */: + case 232 /* SwitchStatement */: + case 271 /* CaseClause */: + case 234 /* ThrowStatement */: return parent.expression === node; - case 223 /* ForStatement */: + case 225 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 236 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 236 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) || forInStatement.expression === node; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return node === parent.expression; - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return node === parent.expression; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return node === parent.expression; - case 150 /* Decorator */: - case 268 /* JsxExpression */: - case 267 /* JsxSpreadAttribute */: - case 275 /* SpreadAssignment */: + case 152 /* Decorator */: + case 270 /* JsxExpression */: + case 269 /* JsxSpreadAttribute */: + case 277 /* SpreadAssignment */: return true; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -9136,7 +9671,7 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */; + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -9145,21 +9680,21 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; + return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9173,15 +9708,15 @@ var ts; ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && - (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */); + (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { - if (callExpression.kind !== 189 /* CallExpression */) { + if (callExpression.kind !== 191 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 /* Identifier */ || expression.escapedText !== "require") { + if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") { return false; } if (args.length !== 1) { @@ -9199,29 +9734,29 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; decl = node.parent; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.right === node) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) { name = node.parent.left; decl = name; } - else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54 /* BarBarToken */) { + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) { if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { name = node.parent.parent.name; decl = node.parent.parent; } - else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.parent.right === node.parent) { + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) { name = node.parent.parent.left; decl = name; } @@ -9229,42 +9764,55 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && - ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && + if (isInJSFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; } return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function hasExpandoValueProperty(node, isPrototypeAssignment) { + return ts.forEach(node.properties, function (p) { return ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment); }); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { - if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { + function getAssignedExpandoInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9273,47 +9821,47 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 194 /* FunctionExpression */ || - initializer.kind === 207 /* ClassExpression */ || - initializer.kind === 195 /* ArrowFunction */) { + if (initializer.kind === 196 /* FunctionExpression */ || + initializer.kind === 209 /* ClassExpression */ || + initializer.kind === 197 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : - ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { - var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; - if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) { return parent.left; } } @@ -9321,7 +9869,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9336,7 +9884,7 @@ var ts; return name.escapedText === initializer.escapedText; } if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { - return (initializer.expression.kind === 99 /* ThisKeyword */ || + return (initializer.expression.kind === 100 /* ThisKeyword */ || ts.isIdentifier(initializer.expression) && (initializer.expression.escapedText === "window" || initializer.expression.escapedText === "self" || @@ -9365,13 +9913,36 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { - if (expr.operatorToken.kind !== 58 /* EqualsToken */ || + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function isBindableObjectDefinePropertyCall(expr) { + return ts.length(expr.arguments) === 3 && + ts.isPropertyAccessExpression(expr.expression) && + ts.isIdentifier(expr.expression.expression) && + ts.idText(expr.expression.expression) === "Object" && + ts.idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; + function getAssignmentDeclarationKindWorker(expr) { + if (ts.isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + var entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 59 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } @@ -9380,13 +9951,13 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { - if (lhs.expression.kind === 99 /* ThisKeyword */) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 100 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + else if (isModuleExportsPropertyAccessExpression(lhs)) { // module.exports = expr return 2 /* ModuleExports */; } @@ -9411,7 +9982,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9420,12 +9991,12 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && - expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && + return isInJSFile(expr) && + expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; @@ -9434,7 +10005,7 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { @@ -9443,14 +10014,14 @@ var ts; ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return node.parent; - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return node.parent.parent; - case 189 /* CallExpression */: - return node.parent; - case 180 /* LiteralType */: + case 191 /* CallExpression */: + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; + case 182 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -9460,12 +10031,12 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return node.moduleSpecifier; - case 246 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 257 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 181 /* ImportType */: + case 248 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 183 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; default: return ts.Debug.assertNever(node); @@ -9474,11 +10045,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return undefined; default: return ts.Debug.assertNever(node); @@ -9486,19 +10057,19 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 247 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 149 /* Parameter */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 274 /* ShorthandPropertyAssignment */: - case 273 /* PropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 151 /* Parameter */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 276 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -9506,14 +10077,13 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 287 /* JSDocFunctionType */ && - node.parameters.length > 0 && - node.parameters[0].name && - node.parameters[0].name.escapedText === "new"; + var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; + var name = ts.tryCast(param && param.name, ts.isIdentifier); + return !!name && name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -9523,27 +10093,27 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 /* EqualsToken */ + node.expression.operatorToken.kind === 59 /* EqualsToken */ ? node.expression.right : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 /* BarBarToken */ + node.expression.right.operatorToken.kind === 55 /* BarBarToken */ ? node.expression.right.right : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return node.initializer; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return node.initializer; } } @@ -9553,7 +10123,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 242 /* ModuleDeclaration */ + node.body.kind === 244 /* ModuleDeclaration */ ? node.body : undefined; } @@ -9568,10 +10138,14 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.addRange(result, node.jsDoc); } - if (node.kind === 149 /* Parameter */) { + if (node.kind === 151 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 150 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9579,11 +10153,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 273 /* PropertyAssignment */ || - parent.kind === 152 /* PropertyDeclaration */ || - parent.kind === 219 /* ExpressionStatement */ && node.kind === 187 /* PropertyAccessExpression */ || + if (parent.kind === 275 /* PropertyAssignment */ || + parent.kind === 154 /* PropertyDeclaration */ || + parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ || getNestedModuleDeclaration(parent) || - ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */) { + ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) { return parent; } // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. @@ -9594,7 +10168,7 @@ var ts; // var x = function(name) { return name.length; } else if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node || - ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */)) { + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) { return parent.parent; } else if (parent.parent && parent.parent.parent && @@ -9617,7 +10191,7 @@ var ts; if (!decl) { return undefined; } - var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; @@ -9652,7 +10226,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 288 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9665,31 +10239,31 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? - binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; - return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 193 /* ParenthesizedExpression */: - case 185 /* ArrayLiteralExpression */: - case 206 /* SpreadElement */: - case 211 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 187 /* ArrayLiteralExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: node = parent; break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -9716,22 +10290,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 216 /* Block */: - case 217 /* VariableStatement */: - case 229 /* WithStatement */: - case 220 /* IfStatement */: - case 230 /* SwitchStatement */: - case 244 /* CaseBlock */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 231 /* LabeledStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 233 /* TryStatement */: - case 272 /* CatchClause */: + case 218 /* Block */: + case 219 /* VariableStatement */: + case 231 /* WithStatement */: + case 222 /* IfStatement */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 233 /* LabeledStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 235 /* TryStatement */: + case 274 /* CatchClause */: return true; } return false; @@ -9748,27 +10322,33 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 175 /* ParenthesizedType */); + return walkUp(node, 177 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 193 /* ParenthesizedExpression */); + return walkUp(node, 195 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function skipParentheses(node) { - while (node.kind === 193 /* ParenthesizedExpression */) { + while (node.kind === 195 /* ParenthesizedExpression */) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 195 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { + if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 196 /* DeleteExpression */; + return node && node.kind === 198 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -9786,35 +10366,39 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 10 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 72 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { - return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 147 /* ComputedPropertyName */ && + return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 149 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -9822,32 +10406,32 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 276 /* EnumMember */: - case 273 /* PropertyAssignment */: - case 187 /* PropertyAccessExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 278 /* EnumMember */: + case 275 /* PropertyAssignment */: + case 189 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: // Name on right hand side of dot in a type query or type reference if (parent.right === node) { - while (parent.kind === 146 /* QualifiedName */) { + while (parent.kind === 148 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 165 /* TypeQuery */ || parent.kind === 162 /* TypeReference */; + return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */; } return false; - case 184 /* BindingElement */: - case 251 /* ImportSpecifier */: + case 186 /* BindingElement */: + case 253 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 255 /* ExportSpecifier */: - case 265 /* JsxAttribute */: + case 257 /* ExportSpecifier */: + case 267 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -9862,15 +10446,16 @@ var ts; // export { x as } from ... // export = // export default + // module.exports = function isAliasSymbolDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */ || - node.kind === 245 /* NamespaceExportDeclaration */ || - node.kind === 248 /* ImportClause */ && !!node.name || - node.kind === 249 /* NamespaceImport */ || - node.kind === 251 /* ImportSpecifier */ || - node.kind === 255 /* ExportSpecifier */ || - node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + return node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 247 /* NamespaceExportDeclaration */ || + node.kind === 250 /* ImportClause */ && !!node.name || + node.kind === 251 /* NamespaceImport */ || + node.kind === 253 /* ImportSpecifier */ || + node.kind === 257 /* ExportSpecifier */ || + node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9879,7 +10464,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -9890,12 +10475,12 @@ var ts; } ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; function getClassExtendsHeritageElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; @@ -9907,7 +10492,7 @@ var ts; } ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -9941,11 +10526,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 72 /* FirstKeyword */ <= token && token <= 145 /* LastKeyword */; + return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 117 /* FirstContextualKeyword */ <= token && token <= 145 /* LastContextualKeyword */; + return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -9957,6 +10542,11 @@ var ts; return token !== undefined && isNonContextualKeyword(token); } ts.isStringANonContextualKeyword = isStringANonContextualKeyword; + function isIdentifierANonContextualKeyword(_a) { + var originalKeywordKind = _a.originalKeywordKind; + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword; function isTrivia(token) { return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; } @@ -9975,14 +10565,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 156 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: if (hasModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -9996,10 +10586,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256 /* Async */); @@ -10024,7 +10614,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 147 /* ComputedPropertyName */ && + return name.kind === 149 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -10040,12 +10630,12 @@ var ts; ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return name.escapedText; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); @@ -10061,9 +10651,9 @@ var ts; ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: return true; default: @@ -10072,11 +10662,11 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? ts.idText(node) : node.text; + return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -10091,7 +10681,7 @@ var ts; * Includes the word "Symbol" with unicode escapes */ function isESSymbolIdentifier(node) { - return node.kind === 71 /* Identifier */ && node.escapedText === "Symbol"; + return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { @@ -10100,11 +10690,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 149 /* Parameter */; + return root.kind === 151 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 184 /* BindingElement */) { + while (node.kind === 186 /* BindingElement */) { node = node.parent.parent; } return node; @@ -10112,15 +10702,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 155 /* Constructor */ - || kind === 194 /* FunctionExpression */ - || kind === 237 /* FunctionDeclaration */ - || kind === 195 /* ArrowFunction */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 242 /* ModuleDeclaration */ - || kind === 277 /* SourceFile */; + return kind === 157 /* Constructor */ + || kind === 196 /* FunctionExpression */ + || kind === 239 /* FunctionDeclaration */ + || kind === 197 /* ArrowFunction */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 244 /* ModuleDeclaration */ + || kind === 279 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -10139,38 +10729,38 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 190 /* NewExpression */: + case 192 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 200 /* PrefixUnaryExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 199 /* AwaitExpression */: - case 203 /* ConditionalExpression */: - case 205 /* YieldExpression */: + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: return 1 /* Right */; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (operator) { - case 40 /* AsteriskAsteriskToken */: - case 58 /* EqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 69 /* BarEqualsToken */: + case 41 /* AsteriskAsteriskToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: return 1 /* Right */; } } @@ -10179,15 +10769,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 202 /* BinaryExpression */) { + if (expression.kind === 204 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 200 /* PrefixUnaryExpression */ || expression.kind === 201 /* PostfixUnaryExpression */) { + else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -10197,116 +10787,116 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return 0; - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return 1; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return 2; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return 4; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (operatorKind) { - case 26 /* CommaToken */: + case 27 /* CommaToken */: return 0; - case 58 /* EqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 69 /* BarEqualsToken */: + case 59 /* EqualsToken */: + case 60 /* PlusEqualsToken */: + case 61 /* MinusEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: + case 64 /* SlashEqualsToken */: + case 65 /* PercentEqualsToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 69 /* AmpersandEqualsToken */: + case 71 /* CaretEqualsToken */: + case 70 /* BarEqualsToken */: return 3; default: return getBinaryOperatorPrecedence(operatorKind); } - case 200 /* PrefixUnaryExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 196 /* DeleteExpression */: - case 199 /* AwaitExpression */: + case 202 /* PrefixUnaryExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 198 /* DeleteExpression */: + case 201 /* AwaitExpression */: return 16; - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return 17; - case 189 /* CallExpression */: + case 191 /* CallExpression */: return 18; - case 190 /* NewExpression */: + case 192 /* NewExpression */: return hasArguments ? 19 : 18; - case 191 /* TaggedTemplateExpression */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 193 /* TaggedTemplateExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return 19; - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 71 /* Identifier */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 72 /* Identifier */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 207 /* ClassExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 193 /* ParenthesizedExpression */: - case 208 /* OmittedExpression */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 195 /* ParenthesizedExpression */: + case 210 /* OmittedExpression */: return 20; default: return -1; } } ts.getOperatorPrecedence = getOperatorPrecedence; - /* @internal */ function getBinaryOperatorPrecedence(kind) { switch (kind) { - case 54 /* BarBarToken */: + case 55 /* BarBarToken */: return 5; - case 53 /* AmpersandAmpersandToken */: + case 54 /* AmpersandAmpersandToken */: return 6; - case 49 /* BarToken */: + case 50 /* BarToken */: return 7; - case 50 /* CaretToken */: + case 51 /* CaretToken */: return 8; - case 48 /* AmpersandToken */: + case 49 /* AmpersandToken */: return 9; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: return 10; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: + case 94 /* InstanceOfKeyword */: + case 93 /* InKeyword */: + case 119 /* AsKeyword */: return 11; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 46 /* LessThanLessThanToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return 12; - case 37 /* PlusToken */: - case 38 /* MinusToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: return 13; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: + case 40 /* AsteriskToken */: + case 42 /* SlashToken */: + case 43 /* PercentToken */: return 14; - case 40 /* AsteriskAsteriskToken */: + case 41 /* AsteriskAsteriskToken */: return 15; } // -1 is lower than all other precedences. Returning it will cause binary expression @@ -10374,7 +10964,7 @@ var ts; if (fileName) { return fileDiagnostics.get(fileName) || []; } - var fileDiags = ts.flatMap(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); + var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); }); if (!nonFileDiagnostics.length) { return fileDiags; } @@ -10432,7 +11022,7 @@ var ts; } function isIntrinsicJsxName(name) { var ch = name.charCodeAt(0); - return (ch >= 97 /* a */ && ch <= 122 /* z */) || name.indexOf("-") > -1; + return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-"); } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -10515,16 +11105,10 @@ var ts; lineStart = true; } } - function writeTextOfNode(text, node) { - var s = getTextOfNodeFromSourceText(text, node); - write(s); - updateLineCountAndPosFor(s); - } reset(); return { write: write, rawWrite: rawWrite, - writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, increaseIndent: function () { indent++; }, @@ -10547,10 +11131,77 @@ var ts; writePunctuation: write, writeSpace: write, writeStringLiteral: write, - writeSymbol: write + writeSymbol: function (s, _) { return write(s); }, + writeTrailingSemicolon: write, + writeComment: write }; } ts.createTextWriter = createTextWriter; + function getTrailingSemicolonOmittingWriter(writer) { + var pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return __assign({}, writer, { writeTrailingSemicolon: function () { + pendingTrailingSemicolon = true; + }, + writeLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral: function (s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol: function (s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation: function (s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword: function (s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator: function (s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter: function (s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace: function (s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty: function (s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment: function (s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine: function () { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent: function () { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }); + } + ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter; function getResolvedExternalModuleName(host, file, referenceFile) { return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } @@ -10613,7 +11264,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10627,7 +11278,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10686,11 +11337,11 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { - return id.originalKeywordKind === 99 /* ThisKeyword */; + return id.originalKeywordKind === 100 /* ThisKeyword */; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { @@ -10701,10 +11352,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 156 /* GetAccessor */) { + if (accessor.kind === 158 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 157 /* SetAccessor */) { + else if (accessor.kind === 159 /* SetAccessor */) { setAccessor = accessor; } else { @@ -10724,10 +11375,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 156 /* GetAccessor */ && !getAccessor) { + if (member.kind === 158 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 157 /* SetAccessor */ && !setAccessor) { + if (member.kind === 159 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -10748,7 +11399,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10764,7 +11415,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -10773,7 +11424,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 289 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -10807,13 +11458,13 @@ var ts; function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { if (comments && comments.length > 0) { if (leadingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } var emitInterveningSeparator = false; for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { var comment = comments_1[_i]; if (emitInterveningSeparator) { - writer.write(" "); + writer.writeSpace(" "); emitInterveningSeparator = false; } writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); @@ -10825,7 +11476,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -10943,7 +11594,7 @@ var ts; } else { // Single line comment of style //.... - writer.write(text.substring(commentPos, commentEnd)); + writer.writeComment(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; @@ -10952,14 +11603,14 @@ var ts; var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { // trimmed forward and ending spaces text - writer.write(currentLineText); + writer.writeComment(currentLineText); if (end !== commentEnd) { writer.writeLine(); } } else { // Empty string - make sure we write empty line - writer.writeLiteral(newLine); + writer.rawWrite(newLine); } } function calculateIndent(text, pos, end) { @@ -11013,7 +11664,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4 /* NestedNamespace */ || (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace)) { + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* Export */; } return flags; @@ -11021,44 +11672,49 @@ var ts; ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { - case 115 /* StaticKeyword */: return 32 /* Static */; - case 114 /* PublicKeyword */: return 4 /* Public */; - case 113 /* ProtectedKeyword */: return 16 /* Protected */; - case 112 /* PrivateKeyword */: return 8 /* Private */; - case 117 /* AbstractKeyword */: return 128 /* Abstract */; - case 84 /* ExportKeyword */: return 1 /* Export */; - case 124 /* DeclareKeyword */: return 2 /* Ambient */; - case 76 /* ConstKeyword */: return 2048 /* Const */; - case 79 /* DefaultKeyword */: return 512 /* Default */; - case 120 /* AsyncKeyword */: return 256 /* Async */; - case 132 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 116 /* StaticKeyword */: return 32 /* Static */; + case 115 /* PublicKeyword */: return 4 /* Public */; + case 114 /* ProtectedKeyword */: return 16 /* Protected */; + case 113 /* PrivateKeyword */: return 8 /* Private */; + case 118 /* AbstractKeyword */: return 128 /* Abstract */; + case 85 /* ExportKeyword */: return 1 /* Export */; + case 125 /* DeclareKeyword */: return 2 /* Ambient */; + case 77 /* ConstKeyword */: return 2048 /* Const */; + case 80 /* DefaultKeyword */: return 512 /* Default */; + case 121 /* AsyncKeyword */: return 256 /* Async */; + case 133 /* ReadonlyKeyword */: return 64 /* Readonly */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 54 /* BarBarToken */ - || token === 53 /* AmpersandAmpersandToken */ - || token === 51 /* ExclamationToken */; + return token === 55 /* BarBarToken */ + || token === 54 /* AmpersandAmpersandToken */ + || token === 52 /* ExclamationToken */; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 58 /* FirstAssignment */ && token <= 70 /* LastAssignment */; + return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment - ? node.operatorToken.kind === 58 /* EqualsToken */ + ? node.operatorToken.kind === 59 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) && ts.isLeftHandSideExpression(node.left); } @@ -11066,8 +11722,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 186 /* ObjectLiteralExpression */ - || kind === 185 /* ArrayLiteralExpression */; + return kind === 188 /* ObjectLiteralExpression */ + || kind === 187 /* ArrayLiteralExpression */; } return false; } @@ -11076,17 +11732,8 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; function isPropertyAccessEntityNameExpression(node) { @@ -11098,17 +11745,17 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 186 /* ObjectLiteralExpression */ && + return expression.kind === 188 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 185 /* ArrayLiteralExpression */ && + return expression.kind === 187 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -11120,10 +11767,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * 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. @@ -11262,6 +11909,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11352,6 +12021,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11449,8 +12120,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 241 /* EnumDeclaration */: - case 242 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -11527,23 +12198,47 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 201 /* PostfixUnaryExpression */: - case 200 /* PrefixUnaryExpression */: + case 195 /* ParenthesizedExpression */: + return accessKind(parent); + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: var operator = parent.operator; - return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 202 /* BinaryExpression */: + return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 204 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? - operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 275 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 276 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 187 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11634,7 +12329,7 @@ var ts; } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { - return type.flags & 131072 /* Object */ ? type.objectFlags : 0; + return type.flags & 524288 /* Object */ ? type.objectFlags : 0; } ts.getObjectFlags = getObjectFlags; function typeHasCallOrConstructSignatures(type, checker) { @@ -11685,6 +12380,31 @@ var ts; return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; + function isTypeNodeKind(kind) { + return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) + || kind === 120 /* AnyKeyword */ + || kind === 143 /* UnknownKeyword */ + || kind === 135 /* NumberKeyword */ + || kind === 146 /* BigIntKeyword */ + || kind === 136 /* ObjectKeyword */ + || kind === 123 /* BooleanKeyword */ + || kind === 138 /* StringKeyword */ + || kind === 139 /* SymbolKeyword */ + || kind === 100 /* ThisKeyword */ + || kind === 106 /* VoidKeyword */ + || kind === 141 /* UndefinedKeyword */ + || kind === 96 /* NullKeyword */ + || kind === 132 /* NeverKeyword */ + || kind === 211 /* ExpressionWithTypeArguments */ + || kind === 284 /* JSDocAllType */ + || kind === 285 /* JSDocUnknownType */ + || kind === 286 /* JSDocNullableType */ + || kind === 287 /* JSDocNonNullableType */ + || kind === 288 /* JSDocOptionalType */ + || kind === 289 /* JSDocFunctionType */ + || kind === 290 /* JSDocVariadicType */; + } + ts.isTypeNodeKind = isTypeNodeKind; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11769,13 +12489,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -11912,9 +12625,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 148 /* TypeParameter */) { + if (d && d.kind === 150 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 239 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) { return current; } } @@ -11922,7 +12635,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 155 /* Constructor */; + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11952,14 +12665,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 235 /* VariableDeclaration */) { + if (node.kind === 237 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 236 /* VariableDeclarationList */) { + if (node && node.kind === 238 /* VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 217 /* VariableStatement */) { + if (node && node.kind === 219 /* VariableStatement */) { flags |= getFlags(node); } return flags; @@ -12103,38 +12816,34 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; - case 219 /* ExpressionStatement */: + break; + case 221 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return expr.name; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; - case 193 /* ParenthesizedExpression */: { + break; + case 195 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 231 /* LabeledStatement */: { + case 233 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12153,31 +12862,36 @@ var ts; /** @internal */ function getNonAssignedNameOfDeclaration(declaration) { switch (declaration.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return declaration; - case 303 /* JSDocPropertyTag */: - case 297 /* JSDocParameterTag */: { + case 305 /* JSDocPropertyTag */: + case 299 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 146 /* QualifiedName */) { + if (name.kind === 148 /* QualifiedName */) { return name.right; } break; } - case 202 /* BinaryExpression */: { + case 191 /* CallExpression */: + case 204 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: case 3 /* PrototypeProperty */: return expr.left.name; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr.arguments[1]; default: return undefined; } } - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 252 /* ExportAssignment */: { + case 254 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } @@ -12211,15 +12925,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12240,6 +12953,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12363,10 +13093,23 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -12384,684 +13127,688 @@ var ts; return node.kind === 8 /* NumericLiteral */; } ts.isNumericLiteral = isNumericLiteral; + function isBigIntLiteral(node) { + return node.kind === 9 /* BigIntLiteral */; + } + ts.isBigIntLiteral = isBigIntLiteral; function isStringLiteral(node) { - return node.kind === 9 /* StringLiteral */; + return node.kind === 10 /* StringLiteral */; } ts.isStringLiteral = isStringLiteral; function isJsxText(node) { - return node.kind === 10 /* JsxText */; + return node.kind === 11 /* JsxText */; } ts.isJsxText = isJsxText; function isRegularExpressionLiteral(node) { - return node.kind === 12 /* RegularExpressionLiteral */; + return node.kind === 13 /* RegularExpressionLiteral */; } ts.isRegularExpressionLiteral = isRegularExpressionLiteral; function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13 /* NoSubstitutionTemplateLiteral */; + return node.kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; // Pseudo-literals function isTemplateHead(node) { - return node.kind === 14 /* TemplateHead */; + return node.kind === 15 /* TemplateHead */; } ts.isTemplateHead = isTemplateHead; function isTemplateMiddle(node) { - return node.kind === 15 /* TemplateMiddle */; + return node.kind === 16 /* TemplateMiddle */; } ts.isTemplateMiddle = isTemplateMiddle; function isTemplateTail(node) { - return node.kind === 16 /* TemplateTail */; + return node.kind === 17 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; function isIdentifier(node) { - return node.kind === 71 /* Identifier */; + return node.kind === 72 /* Identifier */; } ts.isIdentifier = isIdentifier; // Names function isQualifiedName(node) { - return node.kind === 146 /* QualifiedName */; + return node.kind === 148 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 147 /* ComputedPropertyName */; + return node.kind === 149 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 148 /* TypeParameter */; + return node.kind === 150 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 149 /* Parameter */; + return node.kind === 151 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 150 /* Decorator */; + return node.kind === 152 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 151 /* PropertySignature */; + return node.kind === 153 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 152 /* PropertyDeclaration */; + return node.kind === 154 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 153 /* MethodSignature */; + return node.kind === 155 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 154 /* MethodDeclaration */; + return node.kind === 156 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 155 /* Constructor */; + return node.kind === 157 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 156 /* GetAccessor */; + return node.kind === 158 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 157 /* SetAccessor */; + return node.kind === 159 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 158 /* CallSignature */; + return node.kind === 160 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 159 /* ConstructSignature */; + return node.kind === 161 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 160 /* IndexSignature */; + return node.kind === 162 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 157 /* SetAccessor */ || node.kind === 156 /* GetAccessor */; + return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 161 /* TypePredicate */; + return node.kind === 163 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 162 /* TypeReference */; + return node.kind === 164 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 163 /* FunctionType */; + return node.kind === 165 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 164 /* ConstructorType */; + return node.kind === 166 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 165 /* TypeQuery */; + return node.kind === 167 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 166 /* TypeLiteral */; + return node.kind === 168 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 167 /* ArrayType */; + return node.kind === 169 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 168 /* TupleType */; + return node.kind === 170 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 171 /* UnionType */; + return node.kind === 173 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 172 /* IntersectionType */; + return node.kind === 174 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 173 /* ConditionalType */; + return node.kind === 175 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 174 /* InferType */; + return node.kind === 176 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 175 /* ParenthesizedType */; + return node.kind === 177 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 176 /* ThisType */; + return node.kind === 178 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 177 /* TypeOperator */; + return node.kind === 179 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 178 /* IndexedAccessType */; + return node.kind === 180 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 179 /* MappedType */; + return node.kind === 181 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 180 /* LiteralType */; + return node.kind === 182 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 181 /* ImportType */; + return node.kind === 183 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 182 /* ObjectBindingPattern */; + return node.kind === 184 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 183 /* ArrayBindingPattern */; + return node.kind === 185 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 184 /* BindingElement */; + return node.kind === 186 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 185 /* ArrayLiteralExpression */; + return node.kind === 187 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 186 /* ObjectLiteralExpression */; + return node.kind === 188 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 187 /* PropertyAccessExpression */; + return node.kind === 189 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 188 /* ElementAccessExpression */; + return node.kind === 190 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 189 /* CallExpression */; + return node.kind === 191 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 190 /* NewExpression */; + return node.kind === 192 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 191 /* TaggedTemplateExpression */; + return node.kind === 193 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 192 /* TypeAssertionExpression */; + return node.kind === 194 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 193 /* ParenthesizedExpression */; + return node.kind === 195 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 306 /* PartiallyEmittedExpression */) { + while (node.kind === 308 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 194 /* FunctionExpression */; + return node.kind === 196 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 195 /* ArrowFunction */; + return node.kind === 197 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 196 /* DeleteExpression */; + return node.kind === 198 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 197 /* TypeOfExpression */; + return node.kind === 199 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 198 /* VoidExpression */; + return node.kind === 200 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 199 /* AwaitExpression */; + return node.kind === 201 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 200 /* PrefixUnaryExpression */; + return node.kind === 202 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 201 /* PostfixUnaryExpression */; + return node.kind === 203 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 202 /* BinaryExpression */; + return node.kind === 204 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 203 /* ConditionalExpression */; + return node.kind === 205 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 204 /* TemplateExpression */; + return node.kind === 206 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 205 /* YieldExpression */; + return node.kind === 207 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 206 /* SpreadElement */; + return node.kind === 208 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 207 /* ClassExpression */; + return node.kind === 209 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 208 /* OmittedExpression */; + return node.kind === 210 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */; + return node.kind === 211 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 210 /* AsExpression */; + return node.kind === 212 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 211 /* NonNullExpression */; + return node.kind === 213 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 212 /* MetaProperty */; + return node.kind === 214 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; // Misc function isTemplateSpan(node) { - return node.kind === 214 /* TemplateSpan */; + return node.kind === 216 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 215 /* SemicolonClassElement */; + return node.kind === 217 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Block function isBlock(node) { - return node.kind === 216 /* Block */; + return node.kind === 218 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 217 /* VariableStatement */; + return node.kind === 219 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 218 /* EmptyStatement */; + return node.kind === 220 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 219 /* ExpressionStatement */; + return node.kind === 221 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 220 /* IfStatement */; + return node.kind === 222 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 221 /* DoStatement */; + return node.kind === 223 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 222 /* WhileStatement */; + return node.kind === 224 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 223 /* ForStatement */; + return node.kind === 225 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 224 /* ForInStatement */; + return node.kind === 226 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 225 /* ForOfStatement */; + return node.kind === 227 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 226 /* ContinueStatement */; + return node.kind === 228 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 227 /* BreakStatement */; + return node.kind === 229 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isBreakOrContinueStatement(node) { - return node.kind === 227 /* BreakStatement */ || node.kind === 226 /* ContinueStatement */; + return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 228 /* ReturnStatement */; + return node.kind === 230 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 229 /* WithStatement */; + return node.kind === 231 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 230 /* SwitchStatement */; + return node.kind === 232 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 231 /* LabeledStatement */; + return node.kind === 233 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 232 /* ThrowStatement */; + return node.kind === 234 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 233 /* TryStatement */; + return node.kind === 235 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 234 /* DebuggerStatement */; + return node.kind === 236 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 235 /* VariableDeclaration */; + return node.kind === 237 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 236 /* VariableDeclarationList */; + return node.kind === 238 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 237 /* FunctionDeclaration */; + return node.kind === 239 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 238 /* ClassDeclaration */; + return node.kind === 240 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 239 /* InterfaceDeclaration */; + return node.kind === 241 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 240 /* TypeAliasDeclaration */; + return node.kind === 242 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 241 /* EnumDeclaration */; + return node.kind === 243 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */; + return node.kind === 244 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 243 /* ModuleBlock */; + return node.kind === 245 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 244 /* CaseBlock */; + return node.kind === 246 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 245 /* NamespaceExportDeclaration */; + return node.kind === 247 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 246 /* ImportEqualsDeclaration */; + return node.kind === 248 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 247 /* ImportDeclaration */; + return node.kind === 249 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 248 /* ImportClause */; + return node.kind === 250 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 249 /* NamespaceImport */; + return node.kind === 251 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 250 /* NamedImports */; + return node.kind === 252 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 251 /* ImportSpecifier */; + return node.kind === 253 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 252 /* ExportAssignment */; + return node.kind === 254 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 253 /* ExportDeclaration */; + return node.kind === 255 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 254 /* NamedExports */; + return node.kind === 256 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 255 /* ExportSpecifier */; + return node.kind === 257 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 256 /* MissingDeclaration */; + return node.kind === 258 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; // Module References function isExternalModuleReference(node) { - return node.kind === 257 /* ExternalModuleReference */; + return node.kind === 259 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 258 /* JsxElement */; + return node.kind === 260 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 259 /* JsxSelfClosingElement */; + return node.kind === 261 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 260 /* JsxOpeningElement */; + return node.kind === 262 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 261 /* JsxClosingElement */; + return node.kind === 263 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 262 /* JsxFragment */; + return node.kind === 264 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 263 /* JsxOpeningFragment */; + return node.kind === 265 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 264 /* JsxClosingFragment */; + return node.kind === 266 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 265 /* JsxAttribute */; + return node.kind === 267 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 266 /* JsxAttributes */; + return node.kind === 268 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 267 /* JsxSpreadAttribute */; + return node.kind === 269 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 268 /* JsxExpression */; + return node.kind === 270 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 269 /* CaseClause */; + return node.kind === 271 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 270 /* DefaultClause */; + return node.kind === 272 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 271 /* HeritageClause */; + return node.kind === 273 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 272 /* CatchClause */; + return node.kind === 274 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 273 /* PropertyAssignment */; + return node.kind === 275 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 274 /* ShorthandPropertyAssignment */; + return node.kind === 276 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 275 /* SpreadAssignment */; + return node.kind === 277 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 276 /* EnumMember */; + return node.kind === 278 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 277 /* SourceFile */; + return node.kind === 279 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 278 /* Bundle */; + return node.kind === 280 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 279 /* UnparsedSource */; + return node.kind === 281 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 281 /* JSDocTypeExpression */; + return node.kind === 283 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 282 /* JSDocAllType */; + return node.kind === 284 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 283 /* JSDocUnknownType */; + return node.kind === 285 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 284 /* JSDocNullableType */; + return node.kind === 286 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 285 /* JSDocNonNullableType */; + return node.kind === 287 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 286 /* JSDocOptionalType */; + return node.kind === 288 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 287 /* JSDocFunctionType */; + return node.kind === 289 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 288 /* JSDocVariadicType */; + return node.kind === 290 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 289 /* JSDocComment */; + return node.kind === 291 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 293 /* JSDocAugmentsTag */; + return node.kind === 295 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 294 /* JSDocClassTag */; + return node.kind === 296 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocEnumTag(node) { - return node.kind === 296 /* JSDocEnumTag */; + return node.kind === 298 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 299 /* JSDocThisTag */; + return node.kind === 301 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 297 /* JSDocParameterTag */; + return node.kind === 299 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 298 /* JSDocReturnTag */; + return node.kind === 300 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 300 /* JSDocTypeTag */; + return node.kind === 302 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 301 /* JSDocTemplateTag */; + return node.kind === 303 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 302 /* JSDocTypedefTag */; + return node.kind === 304 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 303 /* JSDocPropertyTag */; + return node.kind === 305 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */; + return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 290 /* JSDocTypeLiteral */; + return node.kind === 292 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocCallbackTag(node) { - return node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 297 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocSignature(node) { - return node.kind === 291 /* JSDocSignature */; + return node.kind === 293 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); @@ -13072,7 +13819,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 304 /* SyntaxList */; + return n.kind === 306 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13082,7 +13829,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 146 /* FirstNode */; + return kind >= 148 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13091,7 +13838,7 @@ var ts; * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 145 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */; } ts.isToken = isToken; // Node Arrays @@ -13103,7 +13850,7 @@ var ts; // Literals /* @internal */ function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */; + return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */; } ts.isLiteralKind = isLiteralKind; function isLiteralExpression(node) { @@ -13113,7 +13860,7 @@ var ts; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { - return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; + return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isTemplateLiteralToken(node) { @@ -13122,12 +13869,16 @@ var ts; ts.isTemplateLiteralToken = isTemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node) { var kind = node.kind; - return kind === 15 /* TemplateMiddle */ - || kind === 16 /* TemplateTail */; + return kind === 16 /* TemplateMiddle */ + || kind === 17 /* TemplateTail */; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isImportOrExportSpecifier(node) { + return ts.isImportSpecifier(node) || ts.isExportSpecifier(node); + } + ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isStringTextContainingNode(node) { - return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -13140,17 +13891,17 @@ var ts; /* @internal */ function isModifierKind(token) { switch (token) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 79 /* DefaultKeyword */: - case 84 /* ExportKeyword */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 115 /* StaticKeyword */: + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 80 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 116 /* StaticKeyword */: return true; } return false; @@ -13163,7 +13914,7 @@ var ts; ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */; + return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -13172,23 +13923,23 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 146 /* QualifiedName */ - || kind === 71 /* Identifier */; + return kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 9 /* StringLiteral */ + return kind === 72 /* Identifier */ + || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 147 /* ComputedPropertyName */; + || kind === 149 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 182 /* ObjectBindingPattern */ - || kind === 183 /* ArrayBindingPattern */; + return kind === 72 /* Identifier */ + || kind === 184 /* ObjectBindingPattern */ + || kind === 185 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -13203,13 +13954,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; default: return false; @@ -13218,14 +13969,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 163 /* FunctionType */: - case 287 /* JSDocFunctionType */: - case 164 /* ConstructorType */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 166 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -13240,29 +13991,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 155 /* Constructor */ - || kind === 152 /* PropertyDeclaration */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 160 /* IndexSignature */ - || kind === 215 /* SemicolonClassElement */; + return kind === 157 /* Constructor */ + || kind === 154 /* PropertyDeclaration */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 162 /* IndexSignature */ + || kind === 217 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */); + return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */); + return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return true; default: return false; @@ -13272,11 +14023,11 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 159 /* ConstructSignature */ - || kind === 158 /* CallSignature */ - || kind === 151 /* PropertySignature */ - || kind === 153 /* MethodSignature */ - || kind === 160 /* IndexSignature */; + return kind === 161 /* ConstructSignature */ + || kind === 160 /* CallSignature */ + || kind === 153 /* PropertySignature */ + || kind === 155 /* MethodSignature */ + || kind === 162 /* IndexSignature */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -13285,51 +14036,28 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 273 /* PropertyAssignment */ - || kind === 274 /* ShorthandPropertyAssignment */ - || kind === 275 /* SpreadAssignment */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 275 /* PropertyAssignment */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 277 /* SpreadAssignment */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type - function isTypeNodeKind(kind) { - return (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) - || kind === 119 /* AnyKeyword */ - || kind === 142 /* UnknownKeyword */ - || kind === 134 /* NumberKeyword */ - || kind === 135 /* ObjectKeyword */ - || kind === 122 /* BooleanKeyword */ - || kind === 137 /* StringKeyword */ - || kind === 138 /* SymbolKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 105 /* VoidKeyword */ - || kind === 140 /* UndefinedKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 131 /* NeverKeyword */ - || kind === 209 /* ExpressionWithTypeArguments */ - || kind === 282 /* JSDocAllType */ - || kind === 283 /* JSDocUnknownType */ - || kind === 284 /* JSDocNullableType */ - || kind === 285 /* JSDocNonNullableType */ - || kind === 286 /* JSDocOptionalType */ - || kind === 287 /* JSDocFunctionType */ - || kind === 288 /* JSDocVariadicType */; - } /** * Node test that determines whether a node is a valid type node. * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* * of a TypeNode. */ function isTypeNode(node) { - return isTypeNodeKind(node.kind); + return ts.isTypeNodeKind(node.kind); } ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return true; } return false; @@ -13340,8 +14068,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 183 /* ArrayBindingPattern */ - || kind === 182 /* ObjectBindingPattern */; + return kind === 185 /* ArrayBindingPattern */ + || kind === 184 /* ObjectBindingPattern */; } return false; } @@ -13349,15 +14077,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 185 /* ArrayLiteralExpression */ - || kind === 186 /* ObjectLiteralExpression */; + return kind === 187 /* ArrayLiteralExpression */ + || kind === 188 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 184 /* BindingElement */ - || kind === 208 /* OmittedExpression */; + return kind === 186 /* BindingElement */ + || kind === 210 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -13366,9 +14094,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: return true; } return false; @@ -13389,8 +14117,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 182 /* ObjectBindingPattern */: - case 186 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: return true; } return false; @@ -13402,8 +14130,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: return true; } return false; @@ -13412,26 +14140,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 187 /* PropertyAccessExpression */ - || kind === 146 /* QualifiedName */ - || kind === 181 /* ImportType */; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */ + || kind === 183 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 187 /* PropertyAccessExpression */ - || kind === 146 /* QualifiedName */; + return kind === 189 /* PropertyAccessExpression */ + || kind === 148 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 191 /* TaggedTemplateExpression */: - case 150 /* Decorator */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 193 /* TaggedTemplateExpression */: + case 152 /* Decorator */: return true; default: return false; @@ -13439,13 +14167,13 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 189 /* CallExpression */ || node.kind === 190 /* NewExpression */; + return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 204 /* TemplateExpression */ - || kind === 13 /* NoSubstitutionTemplateLiteral */; + return kind === 206 /* TemplateExpression */ + || kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; /* @internal */ @@ -13455,33 +14183,34 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - case 190 /* NewExpression */: - case 189 /* CallExpression */: - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 262 /* JsxFragment */: - case 191 /* TaggedTemplateExpression */: - case 185 /* ArrayLiteralExpression */: - case 193 /* ParenthesizedExpression */: - case 186 /* ObjectLiteralExpression */: - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: - case 71 /* Identifier */: - case 12 /* RegularExpressionLiteral */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 192 /* NewExpression */: + case 191 /* CallExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + case 193 /* TaggedTemplateExpression */: + case 187 /* ArrayLiteralExpression */: + case 195 /* ParenthesizedExpression */: + case 188 /* ObjectLiteralExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 72 /* Identifier */: + case 13 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* TemplateExpression */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 101 /* TrueKeyword */: - case 97 /* SuperKeyword */: - case 211 /* NonNullExpression */: - case 212 /* MetaProperty */: - case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 206 /* TemplateExpression */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 102 /* TrueKeyword */: + case 98 /* SuperKeyword */: + case 213 /* NonNullExpression */: + case 214 /* MetaProperty */: + case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: return false; @@ -13494,13 +14223,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 199 /* AwaitExpression */: - case 192 /* TypeAssertionExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 194 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13509,11 +14238,11 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return true; - case 200 /* PrefixUnaryExpression */: - return expr.operator === 43 /* PlusPlusToken */ || - expr.operator === 44 /* MinusMinusToken */; + case 202 /* PrefixUnaryExpression */: + return expr.operator === 44 /* PlusPlusToken */ || + expr.operator === 45 /* MinusMinusToken */; default: return false; } @@ -13530,15 +14259,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 203 /* ConditionalExpression */: - case 205 /* YieldExpression */: - case 195 /* ArrowFunction */: - case 202 /* BinaryExpression */: - case 206 /* SpreadElement */: - case 210 /* AsExpression */: - case 208 /* OmittedExpression */: - case 307 /* CommaListExpression */: - case 306 /* PartiallyEmittedExpression */: + case 205 /* ConditionalExpression */: + case 207 /* YieldExpression */: + case 197 /* ArrowFunction */: + case 204 /* BinaryExpression */: + case 208 /* SpreadElement */: + case 212 /* AsExpression */: + case 210 /* OmittedExpression */: + case 309 /* CommaListExpression */: + case 308 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13546,18 +14275,18 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 192 /* TypeAssertionExpression */ - || kind === 210 /* AsExpression */; + return kind === 194 /* TypeAssertionExpression */ + || kind === 212 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 306 /* PartiallyEmittedExpression */; + return node.kind === 308 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 305 /* NotEmittedStatement */; + return node.kind === 307 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13568,13 +14297,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return true; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13582,7 +14311,7 @@ var ts; ts.isIterationStatement = isIterationStatement; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 224 /* ForInStatement */ || node.kind === 225 /* ForOfStatement */; + return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13606,113 +14335,113 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 243 /* ModuleBlock */ - || kind === 242 /* ModuleDeclaration */ - || kind === 71 /* Identifier */; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */ + || kind === 72 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 243 /* ModuleBlock */ - || kind === 242 /* ModuleDeclaration */; + return kind === 245 /* ModuleBlock */ + || kind === 244 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 242 /* ModuleDeclaration */; + return kind === 72 /* Identifier */ + || kind === 244 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 250 /* NamedImports */ - || kind === 249 /* NamespaceImport */; + return kind === 252 /* NamedImports */ + || kind === 251 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 242 /* ModuleDeclaration */ || node.kind === 241 /* EnumDeclaration */; + return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 195 /* ArrowFunction */ - || kind === 184 /* BindingElement */ - || kind === 238 /* ClassDeclaration */ - || kind === 207 /* ClassExpression */ - || kind === 155 /* Constructor */ - || kind === 241 /* EnumDeclaration */ - || kind === 276 /* EnumMember */ - || kind === 255 /* ExportSpecifier */ - || kind === 237 /* FunctionDeclaration */ - || kind === 194 /* FunctionExpression */ - || kind === 156 /* GetAccessor */ - || kind === 248 /* ImportClause */ - || kind === 246 /* ImportEqualsDeclaration */ - || kind === 251 /* ImportSpecifier */ - || kind === 239 /* InterfaceDeclaration */ - || kind === 265 /* JsxAttribute */ - || kind === 154 /* MethodDeclaration */ - || kind === 153 /* MethodSignature */ - || kind === 242 /* ModuleDeclaration */ - || kind === 245 /* NamespaceExportDeclaration */ - || kind === 249 /* NamespaceImport */ - || kind === 149 /* Parameter */ - || kind === 273 /* PropertyAssignment */ - || kind === 152 /* PropertyDeclaration */ - || kind === 151 /* PropertySignature */ - || kind === 157 /* SetAccessor */ - || kind === 274 /* ShorthandPropertyAssignment */ - || kind === 240 /* TypeAliasDeclaration */ - || kind === 148 /* TypeParameter */ - || kind === 235 /* VariableDeclaration */ - || kind === 302 /* JSDocTypedefTag */ - || kind === 295 /* JSDocCallbackTag */ - || kind === 303 /* JSDocPropertyTag */; + return kind === 197 /* ArrowFunction */ + || kind === 186 /* BindingElement */ + || kind === 240 /* ClassDeclaration */ + || kind === 209 /* ClassExpression */ + || kind === 157 /* Constructor */ + || kind === 243 /* EnumDeclaration */ + || kind === 278 /* EnumMember */ + || kind === 257 /* ExportSpecifier */ + || kind === 239 /* FunctionDeclaration */ + || kind === 196 /* FunctionExpression */ + || kind === 158 /* GetAccessor */ + || kind === 250 /* ImportClause */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 253 /* ImportSpecifier */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 267 /* JsxAttribute */ + || kind === 156 /* MethodDeclaration */ + || kind === 155 /* MethodSignature */ + || kind === 244 /* ModuleDeclaration */ + || kind === 247 /* NamespaceExportDeclaration */ + || kind === 251 /* NamespaceImport */ + || kind === 151 /* Parameter */ + || kind === 275 /* PropertyAssignment */ + || kind === 154 /* PropertyDeclaration */ + || kind === 153 /* PropertySignature */ + || kind === 159 /* SetAccessor */ + || kind === 276 /* ShorthandPropertyAssignment */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 150 /* TypeParameter */ + || kind === 237 /* VariableDeclaration */ + || kind === 304 /* JSDocTypedefTag */ + || kind === 297 /* JSDocCallbackTag */ + || kind === 305 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 237 /* FunctionDeclaration */ - || kind === 256 /* MissingDeclaration */ - || kind === 238 /* ClassDeclaration */ - || kind === 239 /* InterfaceDeclaration */ - || kind === 240 /* TypeAliasDeclaration */ - || kind === 241 /* EnumDeclaration */ - || kind === 242 /* ModuleDeclaration */ - || kind === 247 /* ImportDeclaration */ - || kind === 246 /* ImportEqualsDeclaration */ - || kind === 253 /* ExportDeclaration */ - || kind === 252 /* ExportAssignment */ - || kind === 245 /* NamespaceExportDeclaration */; + return kind === 239 /* FunctionDeclaration */ + || kind === 258 /* MissingDeclaration */ + || kind === 240 /* ClassDeclaration */ + || kind === 241 /* InterfaceDeclaration */ + || kind === 242 /* TypeAliasDeclaration */ + || kind === 243 /* EnumDeclaration */ + || kind === 244 /* ModuleDeclaration */ + || kind === 249 /* ImportDeclaration */ + || kind === 248 /* ImportEqualsDeclaration */ + || kind === 255 /* ExportDeclaration */ + || kind === 254 /* ExportAssignment */ + || kind === 247 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 227 /* BreakStatement */ - || kind === 226 /* ContinueStatement */ - || kind === 234 /* DebuggerStatement */ - || kind === 221 /* DoStatement */ - || kind === 219 /* ExpressionStatement */ - || kind === 218 /* EmptyStatement */ - || kind === 224 /* ForInStatement */ - || kind === 225 /* ForOfStatement */ - || kind === 223 /* ForStatement */ - || kind === 220 /* IfStatement */ - || kind === 231 /* LabeledStatement */ - || kind === 228 /* ReturnStatement */ - || kind === 230 /* SwitchStatement */ - || kind === 232 /* ThrowStatement */ - || kind === 233 /* TryStatement */ - || kind === 217 /* VariableStatement */ - || kind === 222 /* WhileStatement */ - || kind === 229 /* WithStatement */ - || kind === 305 /* NotEmittedStatement */ - || kind === 309 /* EndOfDeclarationMarker */ - || kind === 308 /* MergeDeclarationMarker */; + return kind === 229 /* BreakStatement */ + || kind === 228 /* ContinueStatement */ + || kind === 236 /* DebuggerStatement */ + || kind === 223 /* DoStatement */ + || kind === 221 /* ExpressionStatement */ + || kind === 220 /* EmptyStatement */ + || kind === 226 /* ForInStatement */ + || kind === 227 /* ForOfStatement */ + || kind === 225 /* ForStatement */ + || kind === 222 /* IfStatement */ + || kind === 233 /* LabeledStatement */ + || kind === 230 /* ReturnStatement */ + || kind === 232 /* SwitchStatement */ + || kind === 234 /* ThrowStatement */ + || kind === 235 /* TryStatement */ + || kind === 219 /* VariableStatement */ + || kind === 224 /* WhileStatement */ + || kind === 231 /* WithStatement */ + || kind === 307 /* NotEmittedStatement */ + || kind === 311 /* EndOfDeclarationMarker */ + || kind === 310 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + if (node.kind === 150 /* TypeParameter */) { + return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -13739,10 +14468,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 216 /* Block */) + if (node.kind !== 218 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 233 /* TryStatement */ || node.parent.kind === 272 /* CatchClause */) { + if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) { return false; } } @@ -13752,81 +14481,81 @@ var ts; /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 257 /* ExternalModuleReference */ - || kind === 146 /* QualifiedName */ - || kind === 71 /* Identifier */; + return kind === 259 /* ExternalModuleReference */ + || kind === 148 /* QualifiedName */ + || kind === 72 /* Identifier */; } ts.isModuleReference = isModuleReference; // JSX /* @internal */ function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 99 /* ThisKeyword */ - || kind === 71 /* Identifier */ - || kind === 187 /* PropertyAccessExpression */; + return kind === 100 /* ThisKeyword */ + || kind === 72 /* Identifier */ + || kind === 189 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 258 /* JsxElement */ - || kind === 268 /* JsxExpression */ - || kind === 259 /* JsxSelfClosingElement */ - || kind === 10 /* JsxText */ - || kind === 262 /* JsxFragment */; + return kind === 260 /* JsxElement */ + || kind === 270 /* JsxExpression */ + || kind === 261 /* JsxSelfClosingElement */ + || kind === 11 /* JsxText */ + || kind === 264 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 265 /* JsxAttribute */ - || kind === 267 /* JsxSpreadAttribute */; + return kind === 267 /* JsxAttribute */ + || kind === 269 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 268 /* JsxExpression */; + return kind === 10 /* StringLiteral */ + || kind === 270 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 260 /* JsxOpeningElement */ - || kind === 259 /* JsxSelfClosingElement */; + return kind === 262 /* JsxOpeningElement */ + || kind === 261 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 269 /* CaseClause */ - || kind === 270 /* DefaultClause */; + return kind === 271 /* CaseClause */ + || kind === 272 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */; + return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 289 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */; + return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 157 /* SetAccessor */; + return node.kind === 159 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 156 /* GetAccessor */; + return node.kind === 158 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -13856,12 +14585,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 162 /* TypeReference */ || node.kind === 209 /* ExpressionWithTypeArguments */; + return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13890,15 +14619,14 @@ var ts; } ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { - return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; + return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isStringLiteralLike = isStringLiteralLike; })(ts || (ts = {})); /* @internal */ (function (ts) { - /** @internal */ function isNamedImportsOrExports(node) { - return node.kind === 250 /* NamedImports */ || node.kind === 254 /* NamedExports */; + return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function Symbol(flags, name) { @@ -13943,10 +14671,9 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - /* @internal */ function formatStringFromArgs(text, args, baseIndex) { if (baseIndex === void 0) { baseIndex = 0; } - return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); }); + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; function getLocaleSpecificMessage(message) { @@ -13975,7 +14702,6 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; - /* @internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -14000,7 +14726,6 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; - /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -14037,14 +14762,12 @@ var ts; function getDiagnosticFilePath(diagnostic) { return diagnostic.file ? diagnostic.file.path : undefined; } - /* @internal */ function compareDiagnostics(d1, d2) { return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || 0 /* EqualTo */; } ts.compareDiagnostics = compareDiagnostics; - /* @internal */ function compareDiagnosticsSkipRelatedInformation(d1, d2) { return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || ts.compareValues(d1.start, d2.start) || @@ -14105,6 +14828,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14121,9 +14856,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14135,13 +14869,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14336,7 +15071,6 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; - /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -14414,8 +15148,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14637,6 +15369,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14697,6 +15436,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14923,36 +15663,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15080,14 +15841,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15258,6 +16019,98 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + function parsePseudoBigInt(stringValue) { + var log2Base; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: // 0b or 0B + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: // 0o or 0O + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + var nIndex = stringValue.length - 1; + // Skip leading 0s + var nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + // Omit leading "0b", "0o", or "0x", and trailing "n" + var startIndex = 2, endIndex = stringValue.length - 1; + var bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + var segment = bitOffset >>> 4; + var digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + var digit = digitChar <= 57 /* _9 */ + ? digitChar - 48 /* _0 */ + : 10 + digitChar - + (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + var shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + var residual = shiftedDigit >>> 16; + if (residual) + segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + var base10Value = ""; + var firstNonzeroSegment = segments.length - 1; + var segmentsRemaining = true; + while (segmentsRemaining) { + var mod10 = 0; + segmentsRemaining = false; + for (var segment = firstNonzeroSegment; segment >= 0; segment--) { + var newSegment = mod10 << 16 | segments[segment]; + var segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + ts.parsePseudoBigInt = parsePseudoBigInt; + function pseudoBigIntToString(_a) { + var negative = _a.negative, base10Value = _a.base10Value; + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } + ts.pseudoBigIntToString = pseudoBigIntToString; })(ts || (ts = {})); var ts; (function (ts) { @@ -15277,10 +16130,10 @@ var ts; var SourceFileConstructor; // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 277 /* SourceFile */) { + if (kind === 279 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 71 /* Identifier */) { + else if (kind === 72 /* Identifier */) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } else if (!ts.isNodeKind(kind)) { @@ -15329,28 +16182,29 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 145 /* LastToken */) { + if (!node || node.kind <= 147 /* LastToken */) { return; } switch (node.kind) { - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -15358,7 +16212,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -15366,405 +16220,399 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 168 /* TupleType */: + case 170 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 174 /* InferType */: + case 176 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 181 /* ImportType */: + case 183 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 175 /* ParenthesizedType */: - case 177 /* TypeOperator */: + case 177 /* ParenthesizedType */: + case 179 /* TypeOperator */: return visitNode(cbNode, node.type); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 179 /* MappedType */: + case 181 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return visitNode(cbNode, node.literal); - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 210 /* AsExpression */: + case 212 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return visitNode(cbNode, node.name); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 277 /* SourceFile */: + case 279 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: return visitNode(cbNode, node.label); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 269 /* CaseClause */: + case 271 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 150 /* Decorator */: + case 152 /* Decorator */: return visitNode(cbNode, node.expression); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 276 /* EnumMember */: + case 278 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 250 /* NamedImports */: - case 254 /* NamedExports */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 169 /* OptionalType */: - case 170 /* RestType */: - case 281 /* JSDocTypeExpression */: - case 285 /* JSDocNonNullableType */: - case 284 /* JSDocNullableType */: - case 286 /* JSDocOptionalType */: - case 288 /* JSDocVariadicType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 283 /* JSDocTypeExpression */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 288 /* JSDocOptionalType */: + case 290 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 289 /* JSDocComment */: + case 291 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 297 /* JSDocParameterTag */: - case 303 /* JSDocPropertyTag */: - if (node.isNameFirst) { - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression); - } - else { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - } - case 298 /* JSDocReturnTag */: - return visitNode(cbNode, node.typeExpression); - case 300 /* JSDocTypeTag */: - return visitNode(cbNode, node.typeExpression); - case 293 /* JSDocAugmentsTag */: - return visitNode(cbNode, node.class); - case 301 /* JSDocTemplateTag */: - return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302 /* JSDocTypedefTag */: - if (node.typeExpression && - node.typeExpression.kind === 281 /* JSDocTypeExpression */) { - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName); - } - else { - return visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - } - case 295 /* JSDocCallbackTag */: - return visitNode(cbNode, node.fullName) || + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)); + case 295 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); + case 303 /* JSDocTemplateTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters); + case 304 /* JSDocTypedefTag */: + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 283 /* JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression)); + case 297 /* JSDocCallbackTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299 /* JSDocThisTag */: - return visitNode(cbNode, node.typeExpression); - case 296 /* JSDocEnumTag */: - return visitNode(cbNode, node.typeExpression); - case 291 /* JSDocSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - ts.forEach(node.typeParameters, cbNode) || + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression); + case 293 /* JSDocSignature */: + return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290 /* JSDocTypeLiteral */: - if (node.jsDocPropertyTags) { - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); - } - } - return; - case 306 /* PartiallyEmittedExpression */: + case 292 /* JSDocTypeLiteral */: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 294 /* JSDocTag */: + case 296 /* JSDocClassTag */: + return visitNode(cbNode, node.tagName); + case 308 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15774,7 +16622,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15943,8 +16791,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -15978,18 +16830,18 @@ var ts; sourceFile.endOfFileToken = parseTokenNode(); } else { - var statement = createNode(219 /* ExpressionStatement */); + var statement = createNode(221 /* ExpressionStatement */); switch (token()) { - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: statement.expression = parseArrayLiteralExpression(); break; - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: statement.expression = parseTokenNode(); break; - case 38 /* MinusToken */: - if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) { + case 39 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) { statement.expression = parsePrefixUnaryExpression(); } else { @@ -15997,8 +16849,8 @@ var ts; } break; case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) { + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) { statement.expression = parseLiteralNode(); break; } @@ -16134,7 +16986,7 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // 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(277 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -16339,20 +17191,20 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token() === 71 /* Identifier */) { + if (token() === 72 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token() === 116 /* YieldKeyword */ && inYieldContext()) { + if (token() === 117 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) { + if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token() > 107 /* LastReservedWord */; + return token() > 108 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -16395,29 +17247,29 @@ var ts; } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token() === 25 /* SemicolonToken */) { + if (token() === 26 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 25 /* SemicolonToken */) { + if (token() === 26 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } return true; } else { - return parseExpected(25 /* SemicolonToken */); + return parseExpected(26 /* SemicolonToken */); } } function createNode(kind, pos) { nodeCount++; var p = pos >= 0 ? pos : scanner.getStartPos(); return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : - kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } function createNodeWithJSDoc(kind, pos) { @@ -16459,7 +17311,7 @@ var ts; parseErrorAtCurrentToken(diagnosticMessage, arg0); } var result = createNode(kind); - if (kind === 71 /* Identifier */) { + if (kind === 72 /* Identifier */) { result.escapedText = ""; } else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { @@ -16480,9 +17332,9 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(71 /* Identifier */); + var node = createNode(72 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 71 /* Identifier */) { + if (token() !== 72 /* Identifier */) { node.originalKeywordKind = token(); } node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); @@ -16491,7 +17343,7 @@ var ts; } // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; - return createMissingNode(71 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -16501,16 +17353,16 @@ var ts; } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || + token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { var node = parseLiteralNode(); node.text = internIdentifier(node.text); return node; } - if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -16522,13 +17374,13 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(147 /* ComputedPropertyName */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(149 /* ComputedPropertyName */); + parseExpected(22 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker // will error if it sees a comma expression. node.expression = allowInAnd(parseExpression); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function parseContextualModifier(t) { @@ -16543,20 +17395,20 @@ var ts; } function nextTokenCanFollowModifier() { switch (token()) { - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; - case 84 /* ExportKeyword */: + return nextToken() === 84 /* EnumKeyword */; + case 85 /* ExportKeyword */: nextToken(); - if (token() === 79 /* DefaultKeyword */) { + if (token() === 80 /* DefaultKeyword */) { return lookAhead(nextTokenCanFollowDefaultKeyword); } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - case 79 /* DefaultKeyword */: + return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + case 80 /* DefaultKeyword */: return nextTokenCanFollowDefaultKeyword(); - case 115 /* StaticKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: + case 116 /* StaticKeyword */: + case 126 /* GetKeyword */: + case 137 /* SetKeyword */: nextToken(); return canFollowModifier(); default: @@ -16567,18 +17419,18 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 21 /* OpenBracketToken */ - || token() === 17 /* OpenBraceToken */ - || token() === 39 /* AsteriskToken */ - || token() === 24 /* DotDotDotToken */ + return token() === 22 /* OpenBracketToken */ + || token() === 18 /* OpenBraceToken */ + || token() === 40 /* AsteriskToken */ + || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenCanFollowDefaultKeyword() { nextToken(); - return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ || - token() === 109 /* InterfaceKeyword */ || - (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ || + token() === 110 /* InterfaceKeyword */ || + (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -16596,9 +17448,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -16606,21 +17458,29 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 22 /* OpenBracketToken */: + case 40 /* AsteriskToken */: + case 25 /* DotDotDotToken */: + case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` // That way we won't consume the body of a class in its heritage clause. - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -16635,37 +17495,39 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); + return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern(); case 19 /* TypeParameters */: return isIdentifier(); case 15 /* ArrayLiteralMembers */: - if (token() === 26 /* CommaToken */) { - return true; + switch (token()) { + case 27 /* CommaToken */: + case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; } // falls through case 11 /* ArgumentExpressions */: - return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(/*isJSDocParameter*/ false); case 17 /* JSDocParameters */: return isStartOfParameter(/*isJSDocParameter*/ true); case 20 /* TypeArguments */: case 21 /* TupleElementTypes */: - return token() === 26 /* CommaToken */ || isStartOfType(); + return token() === 27 /* CommaToken */ || isStartOfType(); case 22 /* HeritageClauses */: return isHeritageClause(); case 23 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; } return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17 /* OpenBraceToken */); - if (nextToken() === 18 /* CloseBraceToken */) { + ts.Debug.assert(token() === 18 /* OpenBraceToken */); + if (nextToken() === 19 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // @@ -16674,7 +17536,7 @@ var ts; // extends {} extends // extends {} implements var next = nextToken(); - return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */; + return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */; } return true; } @@ -16691,8 +17553,8 @@ var ts; return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 /* ImplementsKeyword */ || - token() === 85 /* ExtendsKeyword */) { + if (token() === 109 /* ImplementsKeyword */ || + token() === 86 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -16720,37 +17582,37 @@ var ts; case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: case 23 /* ImportOrExportSpecifiers */: - return token() === 18 /* CloseBraceToken */; + return token() === 19 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); case 19 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; + return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: case 21 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token() === 22 /* CloseBracketToken */; + return token() === 23 /* CloseBracketToken */; case 17 /* JSDocParameters */: case 16 /* Parameters */: case 18 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 20 /* TypeArguments */: // All other tokens should cause the type-argument to terminate except comma token - return token() !== 26 /* CommaToken */; + return token() !== 27 /* CommaToken */; case 22 /* HeritageClauses */: - return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; + return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; + return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */; case 14 /* JsxChildren */: - return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash); default: return false; } @@ -16770,7 +17632,7 @@ var ts; // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -16940,20 +17802,20 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 155 /* Constructor */: - case 160 /* IndexSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 152 /* PropertyDeclaration */: - case 215 /* SemicolonClassElement */: + case 157 /* Constructor */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 217 /* SemicolonClassElement */: return true; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ && - methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */; + var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */; return !nameIsConstructor; } } @@ -16962,8 +17824,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: return true; } } @@ -16972,58 +17834,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 217 /* VariableStatement */: - case 216 /* Block */: - case 220 /* IfStatement */: - case 219 /* ExpressionStatement */: - case 232 /* ThrowStatement */: - case 228 /* ReturnStatement */: - case 230 /* SwitchStatement */: - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 223 /* ForStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 218 /* EmptyStatement */: - case 233 /* TryStatement */: - case 231 /* LabeledStatement */: - case 221 /* DoStatement */: - case 234 /* DebuggerStatement */: - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: - case 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 219 /* VariableStatement */: + case 218 /* Block */: + case 222 /* IfStatement */: + case 221 /* ExpressionStatement */: + case 234 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 232 /* SwitchStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 225 /* ForStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 220 /* EmptyStatement */: + case 235 /* TryStatement */: + case 233 /* LabeledStatement */: + case 223 /* DoStatement */: + case 236 /* DebuggerStatement */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 276 /* EnumMember */; + return node.kind === 278 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 151 /* PropertySignature */: - case 158 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 153 /* PropertySignature */: + case 160 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 235 /* VariableDeclaration */) { + if (node.kind !== 237 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -17044,7 +17906,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 149 /* Parameter */) { + if (node.kind !== 151 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -17101,7 +17963,7 @@ var ts; var startPos = scanner.getStartPos(); list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(26 /* CommaToken */)) { + if (parseOptional(27 /* CommaToken */)) { // No need to check for a zero length node since we know we parsed a comma continue; } @@ -17111,13 +17973,13 @@ var ts; } // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. - parseExpected(26 /* CommaToken */); + parseExpected(27 /* CommaToken */); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // 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 (considerSemicolonAsDelimiter && token() === 25 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } if (startPos === scanner.getStartPos()) { @@ -17168,8 +18030,8 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); - while (parseOptional(23 /* DotToken */)) { - if (token() === 27 /* LessThanToken */) { + while (parseOptional(24 /* DotToken */)) { + if (token() === 28 /* LessThanToken */) { // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting entity.jsdocDotPos = dotPos; break; @@ -17180,7 +18042,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(146 /* QualifiedName */, entity.pos); + var node = createNode(148 /* QualifiedName */, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -17211,33 +18073,33 @@ 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(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(204 /* TemplateExpression */); + var template = createNode(206 /* TemplateExpression */); template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); var list = []; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */); + } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { - var span = createNode(214 /* TemplateSpan */); + var span = createNode(216 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 18 /* CloseBraceToken */) { + if (token() === 19 /* CloseBraceToken */) { reScanTemplateToken(); literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(16 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */)); + literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */)); } span.literal = literal; return finishNode(span); @@ -17247,18 +18109,17 @@ var ts; } function parseTemplateHead() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); return fragment; } function parseTemplateMiddleOrTemplateTail() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind"); + ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind"); return fragment; } function parseLiteralLikeNode(kind) { var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = text; + node.text = scanner.getTokenValue(); if (scanner.hasExtendedUnicodeEscape()) { node.hasExtendedUnicodeEscape = true; } @@ -17280,24 +18141,24 @@ var ts; } // TYPES function parseTypeReference() { - var node = createNode(162 /* TypeReference */); + var node = createNode(164 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + if (!scanner.hasPrecedingLineBreak() && token() === 28 /* LessThanToken */) { + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */); } return finishNode(node); } // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return ts.nodeIsMissing(node.typeName); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: { + case 165 /* FunctionType */: + case 166 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -17305,20 +18166,20 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(161 /* TypePredicate */, lhs.pos); + var node = createNode(163 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(176 /* ThisType */); + var node = createNode(178 /* ThisType */); nextToken(); return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(282 /* JSDocAllType */); + var result = createNode(284 /* JSDocAllType */); if (postFixEquals) { - return createPostfixType(286 /* JSDocOptionalType */, result); + return createPostfixType(288 /* JSDocOptionalType */, result); } else { nextToken(); @@ -17326,7 +18187,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(285 /* JSDocNonNullableType */); + var result = createNode(287 /* JSDocNonNullableType */); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -17344,64 +18205,66 @@ var ts; // Foo // Foo(?= // (?| - if (token() === 26 /* CommaToken */ || - token() === 18 /* CloseBraceToken */ || - token() === 20 /* CloseParenToken */ || - token() === 29 /* GreaterThanToken */ || - token() === 58 /* EqualsToken */ || - token() === 49 /* BarToken */) { - var result = createNode(283 /* JSDocUnknownType */, pos); + if (token() === 27 /* CommaToken */ || + token() === 19 /* CloseBraceToken */ || + token() === 21 /* CloseParenToken */ || + token() === 30 /* GreaterThanToken */ || + token() === 59 /* EqualsToken */ || + token() === 50 /* BarToken */) { + var result = createNode(285 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(284 /* JSDocNullableType */, pos); + var result = createNode(286 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(287 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); nextToken(); - fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); } - var node = createNode(162 /* TypeReference */); + var node = createNode(164 /* TypeReference */); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(149 /* Parameter */); - if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { + var parameter = createNode(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) { parameter.name = parseIdentifierName(); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); } parameter.type = parseJSDocType(); return finishNode(parameter); } function parseJSDocType() { - var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); + scanner.setInJSDocType(true); + var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { - var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); + var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } - if (token() === 58 /* EqualsToken */) { - return createPostfixType(286 /* JSDocOptionalType */, type); + if (token() === 59 /* EqualsToken */) { + return createPostfixType(288 /* JSDocOptionalType */, type); } return type; } function parseTypeQuery() { - var node = createNode(165 /* TypeQuery */); - parseExpected(103 /* TypeOfKeyword */); + var node = createNode(167 /* TypeQuery */); + parseExpected(104 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(148 /* TypeParameter */); + var node = createNode(150 /* TypeParameter */); node.name = parseIdentifier(); - if (parseOptional(85 /* ExtendsKeyword */)) { + if (parseOptional(86 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the // user writes a constraint that is an expression and not an actual type, then parse // it out as an expression (so we can recover well), but report that a type is needed @@ -17420,39 +18283,39 @@ var ts; node.expression = parseUnaryExpressionOrHigher(); } } - if (parseOptional(58 /* EqualsToken */)) { + if (parseOptional(59 /* EqualsToken */)) { node.default = parseType(); } return finishNode(node); } function parseTypeParameters() { - if (token() === 27 /* LessThanToken */) { - return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + if (token() === 28 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */); } } function parseParameterType() { - if (parseOptional(56 /* ColonToken */)) { + if (parseOptional(57 /* ColonToken */)) { return parseType(); } return undefined; } function isStartOfParameter(isJSDocParameter) { - return token() === 24 /* DotDotDotToken */ || + return token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 /* AtToken */ || + token() === 58 /* AtToken */ || isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseParameter() { - var node = createNodeWithJSDoc(149 /* Parameter */); - if (token() === 99 /* ThisKeyword */) { + var node = createNodeWithJSDoc(151 /* Parameter */); + if (token() === 100 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); @@ -17467,7 +18330,7 @@ var ts; // to avoid this we'll advance cursor to the next token. nextToken(); } - node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.questionToken = parseOptionalToken(56 /* QuestionToken */); node.type = parseParameterType(); node.initializer = parseInitializer(); return finishNode(node); @@ -17489,16 +18352,16 @@ var ts; return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { - if (returnToken === 36 /* EqualsGreaterThanToken */) { + if (returnToken === 37 /* EqualsGreaterThanToken */) { parseExpected(returnToken); return true; } - else if (parseOptional(56 /* ColonToken */)) { + else if (parseOptional(57 /* ColonToken */)) { return true; } - else if (isType && token() === 36 /* EqualsGreaterThanToken */) { + else if (isType && token() === 37 /* EqualsGreaterThanToken */) { // This is easy to get backward, especially in type contexts, so parse the type anyway - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); nextToken(); return true; } @@ -17519,7 +18382,7 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (!parseExpected(19 /* OpenParenToken */)) { + if (!parseExpected(20 /* OpenParenToken */)) { signature.parameters = createMissingList(); return false; } @@ -17532,12 +18395,12 @@ var ts; parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - return parseExpected(20 /* CloseParenToken */); + return parseExpected(21 /* CloseParenToken */); } function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. // First check if it was a comma. If so, we're done with the member. - if (parseOptional(26 /* CommaToken */)) { + if (parseOptional(27 /* CommaToken */)) { return; } // Didn't have a comma. We must have a (possible ASI) semicolon. @@ -17545,15 +18408,15 @@ var ts; } function parseSignatureMember(kind) { var node = createNodeWithJSDoc(kind); - if (kind === 159 /* ConstructSignature */) { - parseExpected(94 /* NewKeyword */); + if (kind === 161 /* ConstructSignature */) { + parseExpected(95 /* NewKeyword */); } - fillSignature(56 /* ColonToken */, 4 /* Type */, node); + fillSignature(57 /* ColonToken */, 4 /* Type */, node); parseTypeMemberSemicolon(); return finishNode(node); } function isIndexSignature() { - return token() === 21 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { // The only allowed sequence is: @@ -17573,7 +18436,7 @@ var ts; // [] // nextToken(); - if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) { + if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) { return true; } if (ts.isModifierKind(token())) { @@ -17592,39 +18455,39 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token() !== 55 /* QuestionToken */) { + if (token() !== 56 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; + return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(node) { - node.kind = 160 /* IndexSignature */; - node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.kind = 162 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(node) { node.name = parsePropertyName(); - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - node.kind = 153 /* MethodSignature */; + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + node.kind = 155 /* MethodSignature */; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] - fillSignature(56 /* ColonToken */, 4 /* Type */, node); + fillSignature(57 /* ColonToken */, 4 /* Type */, node); } else { - node.kind = 151 /* PropertySignature */; + node.kind = 153 /* PropertySignature */; node.type = parseTypeAnnotation(); - if (token() === 58 /* EqualsToken */) { + if (token() === 59 /* 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. @@ -17636,7 +18499,7 @@ var ts; } function isTypeMemberStart() { // Return true if we have the start of a signature member - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return true; } var idToken = false; @@ -17646,7 +18509,7 @@ var ts; nextToken(); } // Index signatures and computed property names are type members - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers @@ -17657,21 +18520,21 @@ var ts; // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token() === 19 /* OpenParenToken */ || - token() === 27 /* LessThanToken */ || - token() === 55 /* QuestionToken */ || - token() === 56 /* ColonToken */ || - token() === 26 /* CommaToken */ || + return token() === 20 /* OpenParenToken */ || + token() === 28 /* LessThanToken */ || + token() === 56 /* QuestionToken */ || + token() === 57 /* ColonToken */ || + token() === 27 /* CommaToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(158 /* CallSignature */); + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { + return parseSignatureMember(160 /* CallSignature */); } - if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(159 /* ConstructSignature */); + if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(161 /* ConstructSignature */); } var node = createNodeWithJSDoc(0 /* Unknown */); node.modifiers = parseModifiers(); @@ -17682,30 +18545,30 @@ var ts; } function nextTokenIsOpenParenOrLessThan() { nextToken(); - return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; + return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */; } function nextTokenIsDot() { - return nextToken() === 23 /* DotToken */; + return nextToken() === 24 /* DotToken */; } function nextTokenIsOpenParenOrLessThanOrDot() { switch (nextToken()) { - case 19 /* OpenParenToken */: - case 27 /* LessThanToken */: - case 23 /* DotToken */: + case 20 /* OpenParenToken */: + case 28 /* LessThanToken */: + case 24 /* DotToken */: return true; } return false; } function parseTypeLiteral() { - var node = createNode(166 /* TypeLiteral */); + var node = createNode(168 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { members = parseList(4 /* TypeMembers */, parseTypeMember); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { members = createMissingList(); @@ -17714,89 +18577,89 @@ var ts; } function isStartOfMappedType() { nextToken(); - if (token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { - return nextToken() === 132 /* ReadonlyKeyword */; + if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { + return nextToken() === 133 /* ReadonlyKeyword */; } - if (token() === 132 /* ReadonlyKeyword */) { + if (token() === 133 /* ReadonlyKeyword */) { nextToken(); } - return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; + return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */; } function parseMappedTypeParameter() { - var node = createNode(148 /* TypeParameter */); + var node = createNode(150 /* TypeParameter */); node.name = parseIdentifier(); - parseExpected(92 /* InKeyword */); + parseExpected(93 /* InKeyword */); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(179 /* MappedType */); - parseExpected(17 /* OpenBraceToken */); - if (token() === 132 /* ReadonlyKeyword */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { + var node = createNode(181 /* MappedType */); + parseExpected(18 /* OpenBraceToken */); + if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { node.readonlyToken = parseTokenNode(); - if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) { - parseExpectedToken(132 /* ReadonlyKeyword */); + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { + parseExpectedToken(133 /* ReadonlyKeyword */); } } - parseExpected(21 /* OpenBracketToken */); + parseExpected(22 /* OpenBracketToken */); node.typeParameter = parseMappedTypeParameter(); - parseExpected(22 /* CloseBracketToken */); - if (token() === 55 /* QuestionToken */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { + parseExpected(23 /* CloseBracketToken */); + if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) { node.questionToken = parseTokenNode(); - if (node.questionToken.kind !== 55 /* QuestionToken */) { - parseExpectedToken(55 /* QuestionToken */); + if (node.questionToken.kind !== 56 /* QuestionToken */) { + parseExpectedToken(56 /* QuestionToken */); } } node.type = parseTypeAnnotation(); parseSemicolon(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseTupleElementType() { var pos = getNodePos(); - if (parseOptional(24 /* DotDotDotToken */)) { - var node = createNode(170 /* RestType */, pos); + if (parseOptional(25 /* DotDotDotToken */)) { + var node = createNode(172 /* RestType */, pos); node.type = parseType(); return finishNode(node); } var type = parseType(); - if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 284 /* JSDocNullableType */ && type.pos === type.type.pos) { - type.kind = 169 /* OptionalType */; + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 171 /* OptionalType */; } return type; } function parseTupleType() { - var node = createNode(168 /* TupleType */); - node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + var node = createNode(170 /* TupleType */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(175 /* ParenthesizedType */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(177 /* ParenthesizedType */); + parseExpected(20 /* OpenParenToken */); node.type = parseType(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseFunctionOrConstructorType() { var pos = getNodePos(); - var kind = parseOptional(94 /* NewKeyword */) ? 164 /* ConstructorType */ : 163 /* FunctionType */; + var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */; var node = createNodeWithJSDoc(kind, pos); - fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 23 /* DotToken */ ? undefined : node; + return token() === 24 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(180 /* LiteralType */); + var node = createNode(182 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(200 /* PrefixUnaryExpression */); - unaryMinusExpression.operator = 38 /* MinusToken */; + unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 39 /* MinusToken */; nextToken(); } - var expression = token() === 101 /* TrueKeyword */ || token() === 86 /* FalseKeyword */ + var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */ ? parseTokenNode() : parseLiteralLikeNode(token()); if (negative) { @@ -17809,79 +18672,82 @@ var ts; } function isStartOfTypeOfImportType() { nextToken(); - return token() === 91 /* ImportKeyword */; + return token() === 92 /* ImportKeyword */; } function parseImportType() { sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; - var node = createNode(181 /* ImportType */); - if (parseOptional(103 /* TypeOfKeyword */)) { + var node = createNode(183 /* ImportType */); + if (parseOptional(104 /* TypeOfKeyword */)) { node.isTypeOf = true; } - parseExpected(91 /* ImportKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(92 /* ImportKeyword */); + parseExpected(20 /* OpenParenToken */); node.argument = parseType(); - parseExpected(20 /* CloseParenToken */); - if (parseOptional(23 /* DotToken */)) { + parseExpected(21 /* CloseParenToken */); + if (parseOptional(24 /* DotToken */)) { node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); } node.typeArguments = tryParseTypeArguments(); return finishNode(node); } - function nextTokenIsNumericLiteral() { - return nextToken() === 8 /* NumericLiteral */; + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */; } function parseNonArrayType() { switch (token()) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 138 /* SymbolKeyword */: - case 122 /* BooleanKeyword */: - case 140 /* UndefinedKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 139 /* SymbolKeyword */: + case 123 /* BooleanKeyword */: + case 141 /* UndefinedKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: return parseJSDocAllType(/*postfixEquals*/ false); - case 61 /* AsteriskEqualsToken */: + case 62 /* AsteriskEqualsToken */: return parseJSDocAllType(/*postfixEquals*/ true); - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseJSDocFunctionType(); - case 51 /* ExclamationToken */: + case 52 /* ExclamationToken */: return parseJSDocNonNullableType(); - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return parseLiteralTypeNode(); - case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); - case 105 /* VoidKeyword */: - case 95 /* NullKeyword */: + case 39 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 106 /* VoidKeyword */: + case 96 /* NullKeyword */: return parseTokenNode(); - case 99 /* ThisKeyword */: { + case 100 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 103 /* TypeOfKeyword */: + case 104 /* TypeOfKeyword */: return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: return parseTupleType(); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return parseParenthesizedType(); - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return parseImportType(); default: return parseTypeReference(); @@ -17889,42 +18755,44 @@ var ts; } function isStartOfType(inStartOfParameter) { switch (token()) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 141 /* UniqueKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 103 /* TypeOfKeyword */: - case 131 /* NeverKeyword */: - case 17 /* OpenBraceToken */: - case 21 /* OpenBracketToken */: - case 27 /* LessThanToken */: - case 49 /* BarToken */: - case 48 /* AmpersandToken */: - case 94 /* NewKeyword */: - case 9 /* StringLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 142 /* UniqueKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 100 /* ThisKeyword */: + case 104 /* TypeOfKeyword */: + case 132 /* NeverKeyword */: + case 18 /* OpenBraceToken */: + case 22 /* OpenBracketToken */: + case 28 /* LessThanToken */: + case 50 /* BarToken */: + case 49 /* AmpersandToken */: + case 95 /* NewKeyword */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 135 /* ObjectKeyword */: - case 39 /* AsteriskToken */: - case 55 /* QuestionToken */: - case 51 /* ExclamationToken */: - case 24 /* DotDotDotToken */: - case 126 /* InferKeyword */: - case 91 /* ImportKeyword */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 136 /* ObjectKeyword */: + case 40 /* AsteriskToken */: + case 56 /* QuestionToken */: + case 52 /* ExclamationToken */: + case 25 /* DotDotDotToken */: + case 127 /* InferKeyword */: + case 92 /* ImportKeyword */: return true; - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return !inStartOfParameter; - case 38 /* MinusToken */: - return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); - case 19 /* OpenParenToken */: + case 39 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 20 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); @@ -17934,35 +18802,35 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 51 /* ExclamationToken */: - type = createPostfixType(285 /* JSDocNonNullableType */, type); + case 52 /* ExclamationToken */: + type = createPostfixType(287 /* JSDocNonNullableType */, type); break; - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createPostfixType(284 /* JSDocNullableType */, type); + type = createPostfixType(286 /* JSDocNullableType */, type); break; - case 21 /* OpenBracketToken */: - parseExpected(21 /* OpenBracketToken */); + case 22 /* OpenBracketToken */: + parseExpected(22 /* OpenBracketToken */); if (isStartOfType()) { - var node = createNode(178 /* IndexedAccessType */, type.pos); + var node = createNode(180 /* IndexedAccessType */, type.pos); node.objectType = type; node.indexType = parseType(); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); type = finishNode(node); } else { - var node = createNode(167 /* ArrayType */, type.pos); + var node = createNode(169 /* ArrayType */, type.pos); node.elementType = type; - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); type = finishNode(node); } break; @@ -17979,16 +18847,16 @@ var ts; return finishNode(postfix); } function parseTypeOperator(operator) { - var node = createNode(177 /* TypeOperator */); + var node = createNode(179 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseInferType() { - var node = createNode(174 /* InferType */); - parseExpected(126 /* InferKeyword */); - var typeParameter = createNode(148 /* TypeParameter */); + var node = createNode(176 /* InferType */); + parseExpected(127 /* InferKeyword */); + var typeParameter = createNode(150 /* TypeParameter */); typeParameter.name = parseIdentifier(); node.typeParameter = finishNode(typeParameter); return finishNode(node); @@ -17996,10 +18864,10 @@ var ts; function parseTypeOperatorOrHigher() { var operator = token(); switch (operator) { - case 128 /* KeyOfKeyword */: - case 141 /* UniqueKeyword */: + case 129 /* KeyOfKeyword */: + case 142 /* UniqueKeyword */: return parseTypeOperator(operator); - case 126 /* InferKeyword */: + case 127 /* InferKeyword */: return parseInferType(); } return parsePostfixTypeOrHigher(); @@ -18019,27 +18887,27 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(172 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(171 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */); } function isStartOfFunctionType() { - if (token() === 27 /* LessThanToken */) { + if (token() === 28 /* LessThanToken */) { return true; } - return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token() === 99 /* ThisKeyword */) { + if (isIdentifier() || token() === 100 /* ThisKeyword */) { nextToken(); return true; } - if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) { + if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -18049,7 +18917,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -18057,17 +18925,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || - token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || + token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token() === 20 /* CloseParenToken */) { + if (token() === 21 /* CloseParenToken */) { nextToken(); - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -18079,7 +18947,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(161 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -18090,7 +18958,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -18101,49 +18969,50 @@ var ts; return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) { + if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) { return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); - if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { - var node = createNode(173 /* ConditionalType */, type.pos); + if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) { + var node = createNode(175 /* ConditionalType */, type.pos); node.checkType = type; // The type following 'extends' is not permitted to be another conditional type node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); - parseExpected(55 /* QuestionToken */); + parseExpected(56 /* QuestionToken */); node.trueType = parseTypeWorker(); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.falseType = parseTypeWorker(); return finishNode(node); } return type; } function parseTypeAnnotation() { - return parseOptional(56 /* ColonToken */) ? parseType() : undefined; + return parseOptional(57 /* ColonToken */) ? parseType() : undefined; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { switch (token()) { - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 19 /* OpenParenToken */: - case 21 /* OpenBracketToken */: - case 17 /* OpenBraceToken */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 94 /* NewKeyword */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 71 /* Identifier */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 20 /* OpenParenToken */: + case 22 /* OpenBracketToken */: + case 18 /* OpenBraceToken */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 95 /* NewKeyword */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 72 /* Identifier */: return true; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); default: return isIdentifier(); @@ -18154,18 +19023,18 @@ var ts; return true; } switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 27 /* LessThanToken */: - case 121 /* AwaitKeyword */: - case 116 /* YieldKeyword */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + case 28 /* LessThanToken */: + case 122 /* AwaitKeyword */: + case 117 /* YieldKeyword */: // Yield/await always starts an expression. Either it is an identifier (in which case // it is definitely an expression). Or it's a keyword (either because we're in // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. @@ -18183,10 +19052,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 17 /* OpenBraceToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && - token() !== 57 /* AtToken */ && + return token() !== 18 /* OpenBraceToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && + token() !== 58 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -18200,7 +19069,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) { + while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -18209,7 +19078,7 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(58 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { // AssignmentExpression[in,yield]: @@ -18254,7 +19123,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -18270,7 +19139,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 116 /* YieldKeyword */) { + if (token() === 117 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -18299,15 +19168,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(205 /* YieldExpression */); + var node = createNode(207 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 39 /* AsteriskToken */ || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + (token() === 40 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -18318,20 +19187,20 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(195 /* ArrowFunction */, asyncModifier.pos); + node = createNode(197 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(195 /* ArrowFunction */, identifier.pos); + node = createNode(197 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(149 /* Parameter */, identifier.pos); + var parameter = createNode(151 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); - node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -18356,8 +19225,8 @@ var ts; // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */); - arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */); + arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return finishNode(arrowFunction); @@ -18367,10 +19236,10 @@ var ts; // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) { + if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 36 /* EqualsGreaterThanToken */) { + if (token() === 37 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -18380,28 +19249,28 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) { + if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) { return 0 /* False */; } } var first = token(); var second = nextToken(); - if (first === 19 /* OpenParenToken */) { - if (second === 20 /* CloseParenToken */) { + if (first === 20 /* OpenParenToken */) { + if (second === 21 /* CloseParenToken */) { // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. var third = nextToken(); switch (third) { - case 36 /* EqualsGreaterThanToken */: - case 56 /* ColonToken */: - case 17 /* OpenBraceToken */: + case 37 /* EqualsGreaterThanToken */: + case 57 /* ColonToken */: + case 18 /* OpenBraceToken */: return 1 /* True */; default: return 0 /* False */; @@ -18413,42 +19282,42 @@ var ts; // ({ x }) => { } // ([ x ]) // ({ x }) - if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) { + if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) { return 2 /* Unknown */; } // Simple case: "(..." // This is an arrow function with a rest parameter. - if (second === 24 /* DotDotDotToken */) { + if (second === 25 /* DotDotDotToken */) { return 1 /* True */; } // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. - if (ts.isModifierKind(second) && second !== 120 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { return 1 /* True */; } // If we had "(" followed by something that's not an identifier, // then this definitely doesn't look like a lambda. "this" is not // valid, but we want to parse it and then give a semantic error. - if (!isIdentifier() && second !== 99 /* ThisKeyword */) { + if (!isIdentifier() && second !== 100 /* ThisKeyword */) { return 0 /* False */; } switch (nextToken()) { - case 56 /* ColonToken */: + case 57 /* ColonToken */: // If we have something like "(a:", then we must have a // type-annotated parameter in an arrow function expression. return 1 /* True */; - case 55 /* QuestionToken */: + case 56 /* QuestionToken */: nextToken(); // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 58 /* EqualsToken */ || token() === 20 /* CloseParenToken */) { + if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) { return 1 /* True */; } // Otherwise it is definitely not a lambda. return 0 /* False */; - case 26 /* CommaToken */: - case 58 /* EqualsToken */: - case 20 /* CloseParenToken */: + case 27 /* CommaToken */: + case 59 /* EqualsToken */: + case 21 /* CloseParenToken */: // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function return 2 /* Unknown */; } @@ -18456,7 +19325,7 @@ var ts; return 0 /* False */; } else { - ts.Debug.assert(first === 27 /* LessThanToken */); + ts.Debug.assert(first === 28 /* LessThanToken */); // If we have "<" not followed by an identifier, // then this definitely is not an arrow function. if (!isIdentifier()) { @@ -18466,17 +19335,17 @@ var ts; if (sourceFile.languageVariant === 1 /* JSX */) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 85 /* ExtendsKeyword */) { + if (third === 86 /* ExtendsKeyword */) { var fourth = nextToken(); switch (fourth) { - case 58 /* EqualsToken */: - case 29 /* GreaterThanToken */: + case 59 /* EqualsToken */: + case 30 /* GreaterThanToken */: return false; default: return true; } } - else if (third === 26 /* CommaToken */) { + else if (third === 27 /* CommaToken */) { return true; } return false; @@ -18495,7 +19364,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); @@ -18508,23 +19377,23 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) { return 1 /* True */; } } return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNodeWithJSDoc(195 /* ArrowFunction */); + var node = createNodeWithJSDoc(197 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. @@ -18534,7 +19403,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) { + if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) { return undefined; } // Parsing a signature isn't enough. @@ -18545,19 +19414,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { + if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); } - if (token() !== 25 /* SemicolonToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && + if (token() !== 26 /* SemicolonToken */ && + token() !== 90 /* FunctionKeyword */ && + token() !== 76 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -18582,20 +19451,20 @@ var ts; } function parseConditionalExpressionRest(leftOperand) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - var questionToken = parseOptionalToken(55 /* QuestionToken */); + var questionToken = parseOptionalToken(56 /* QuestionToken */); if (!questionToken) { return leftOperand; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(203 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(205 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56 /* ColonToken */); + node.colonToken = parseExpectedToken(57 /* ColonToken */); node.whenFalse = ts.nodeIsPresent(node.colonToken) ? parseAssignmentExpressionOrHigher() - : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -18603,7 +19472,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 145 /* OfKeyword */; + return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -18632,16 +19501,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 92 /* InKeyword */ && inDisallowInContext()) { + if (token() === 93 /* InKeyword */ && inDisallowInContext()) { break; } - if (token() === 118 /* AsKeyword */) { + if (token() === 119 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -18662,51 +19531,51 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 92 /* InKeyword */) { + if (inDisallowInContext() && token() === 93 /* InKeyword */) { return false; } return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(202 /* BinaryExpression */, left.pos); + var node = createNode(204 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(210 /* AsExpression */, left.pos); + var node = createNode(212 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(200 /* PrefixUnaryExpression */); + var node = createNode(202 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(196 /* DeleteExpression */); + var node = createNode(198 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(197 /* TypeOfExpression */); + var node = createNode(199 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(198 /* VoidExpression */); + var node = createNode(200 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 121 /* AwaitKeyword */) { + if (token() === 122 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -18716,7 +19585,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(199 /* AwaitExpression */); + var node = createNode(201 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -18740,7 +19609,7 @@ var ts; */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? + return token() === 41 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } @@ -18757,10 +19626,10 @@ var ts; */ var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40 /* AsteriskAsteriskToken */) { + if (token() === 41 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 192 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) { parseErrorAt(pos, end, 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 { @@ -18785,23 +19654,23 @@ var ts; */ function parseSimpleUnaryExpression() { switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: return parsePrefixUnaryExpression(); - case 80 /* DeleteKeyword */: + case 81 /* DeleteKeyword */: return parseDeleteExpression(); - case 103 /* TypeOfKeyword */: + case 104 /* TypeOfKeyword */: return parseTypeOfExpression(); - case 105 /* VoidKeyword */: + case 106 /* VoidKeyword */: return parseVoidExpression(); - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // This is modified UnaryExpression grammar in TypeScript // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); - case 121 /* AwaitKeyword */: + case 122 /* AwaitKeyword */: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -18824,16 +19693,16 @@ var ts; // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 121 /* AwaitKeyword */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: + case 52 /* ExclamationToken */: + case 81 /* DeleteKeyword */: + case 104 /* TypeOfKeyword */: + case 106 /* VoidKeyword */: + case 122 /* AwaitKeyword */: return false; - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression if (sourceFile.languageVariant !== 1 /* JSX */) { return false; @@ -18856,21 +19725,21 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseUpdateExpression() { - if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(200 /* PrefixUnaryExpression */); + if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) { + var node = createNode(202 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(201 /* PostfixUnaryExpression */, expression.pos); + if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(203 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -18911,7 +19780,7 @@ var ts; // 3)we have a MemberExpression which either completes the LeftHandSideExpression, // or starts the beginning of the first four CallExpression productions. var expression; - if (token() === 91 /* ImportKeyword */) { + if (token() === 92 /* ImportKeyword */) { if (lookAhead(nextTokenIsOpenParenOrLessThan)) { // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" // For example: @@ -18926,8 +19795,8 @@ var ts; var fullStart = scanner.getStartPos(); nextToken(); // advance past the 'import' nextToken(); // advance past the dot - var node = createNode(212 /* MetaProperty */, fullStart); - node.keywordToken = 91 /* ImportKeyword */; + var node = createNode(214 /* MetaProperty */, fullStart); + node.keywordToken = 92 /* ImportKeyword */; node.name = parseIdentifierName(); expression = finishNode(node); sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; @@ -18937,7 +19806,7 @@ var ts; } } else { - expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); } // Now, we *may* be complete. However, we might have consumed the start of a // CallExpression. As such, we need to consume the rest of it here to be complete. @@ -18996,22 +19865,22 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) { + if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(187 /* PropertyAccessExpression */, expression.pos); + var node = createNode(189 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - parseExpectedToken(23 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 260 /* JsxOpeningElement */) { - var node = createNode(258 /* JsxElement */, opening.pos); + if (opening.kind === 262 /* JsxOpeningElement */) { + var node = createNode(260 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -19020,15 +19889,15 @@ var ts; } result = finishNode(node); } - else if (opening.kind === 263 /* JsxOpeningFragment */) { - var node = createNode(262 /* JsxFragment */, opening.pos); + else if (opening.kind === 265 /* JsxOpeningFragment */) { + var node = createNode(264 /* JsxFragment */, opening.pos); node.openingFragment = opening; node.children = parseJsxChildren(node.openingFragment); node.closingFragment = parseJsxClosingFragment(inExpressionContext); result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 259 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -19039,15 +19908,15 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token() === 27 /* LessThanToken */) { + if (inExpressionContext && token() === 28 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(202 /* BinaryExpression */, result.pos); + var badNode = createNode(204 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 + badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -19055,8 +19924,8 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10 /* JsxText */); - node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; + var node = createNode(11 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; currentToken = scanner.scanJsxToken(); return finishNode(node); } @@ -19072,15 +19941,15 @@ var ts; parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); } return undefined; - case 28 /* LessThanSlashToken */: + case 29 /* LessThanSlashToken */: case 7 /* ConflictMarkerTrivia */: return undefined; - case 10 /* JsxText */: - case 11 /* JsxTextAllWhiteSpaces */: + case 11 /* JsxText */: + case 12 /* JsxTextAllWhiteSpaces */: return parseJsxText(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); - case 27 /* LessThanToken */: + case 28 /* LessThanToken */: return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); default: return ts.Debug.assertNever(token); @@ -19101,16 +19970,16 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(266 /* JsxAttributes */); + var jsxAttributes = createNode(268 /* JsxAttributes */); jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(27 /* LessThanToken */); - if (token() === 29 /* GreaterThanToken */) { + parseExpected(28 /* LessThanToken */); + if (token() === 30 /* GreaterThanToken */) { // See below for explanation of scanJsxText - var node_1 = createNode(263 /* JsxOpeningFragment */, fullStart); + var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart); scanJsxText(); return finishNode(node_1); } @@ -19118,23 +19987,23 @@ var ts; var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; - if (token() === 29 /* GreaterThanToken */) { + if (token() === 30 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(260 /* JsxOpeningElement */, fullStart); + node = createNode(262 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { - parseExpected(41 /* SlashToken */); + parseExpected(42 /* SlashToken */); if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(259 /* JsxSelfClosingElement */, fullStart); + node = createNode(261 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.typeArguments = typeArguments; @@ -19148,10 +20017,10 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token() === 99 /* ThisKeyword */ ? + var expression = token() === 100 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); + while (parseOptional(24 /* DotToken */)) { + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -19159,33 +20028,33 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(268 /* JsxExpression */); - if (!parseExpected(17 /* OpenBraceToken */)) { + var node = createNode(270 /* JsxExpression */); + if (!parseExpected(18 /* OpenBraceToken */)) { return undefined; } - if (token() !== 18 /* CloseBraceToken */) { - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + if (token() !== 19 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { - parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(265 /* JsxAttribute */); + var node = createNode(267 /* JsxAttribute */); node.name = parseIdentifierName(); - if (token() === 58 /* EqualsToken */) { + if (token() === 59 /* EqualsToken */) { switch (scanJsxAttributeValue()) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: node.initializer = parseLiteralNode(); break; default: @@ -19196,72 +20065,72 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(267 /* JsxSpreadAttribute */); - parseExpected(17 /* OpenBraceToken */); - parseExpected(24 /* DotDotDotToken */); + var node = createNode(269 /* JsxSpreadAttribute */); + parseExpected(18 /* OpenBraceToken */); + parseExpected(25 /* DotDotDotToken */); node.expression = parseExpression(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(261 /* JsxClosingElement */); - parseExpected(28 /* LessThanSlashToken */); + var node = createNode(263 /* JsxClosingElement */); + parseExpected(29 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxClosingFragment(inExpressionContext) { - var node = createNode(264 /* JsxClosingFragment */); - parseExpected(28 /* LessThanSlashToken */); + var node = createNode(266 /* JsxClosingFragment */); + parseExpected(29 /* LessThanSlashToken */); if (ts.tokenIsIdentifierOrKeyword(token())) { parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); } else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(192 /* TypeAssertionExpression */); - parseExpected(27 /* LessThanToken */); + var node = createNode(194 /* TypeAssertionExpression */); + parseExpected(28 /* LessThanToken */); node.type = parseType(); - parseExpected(29 /* GreaterThanToken */); + parseExpected(30 /* GreaterThanToken */); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(23 /* DotToken */); + var dotToken = parseOptionalToken(24 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; } - if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(211 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName - if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(188 /* ElementAccessExpression */, expression.pos); + if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) { + var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; - if (token() === 22 /* CloseBracketToken */) { - indexedAccess.argumentExpression = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + if (token() === 23 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); } else { var argument = allowInAnd(parseExpression); @@ -19270,7 +20139,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } @@ -19282,13 +20151,13 @@ var ts; } } function isTemplateStartOfTaggedTemplate() { - return token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */; + return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */; } function parseTaggedTemplateRest(tag, typeArguments) { - var tagExpression = createNode(191 /* TaggedTemplateExpression */, tag.pos); + var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos); tagExpression.tag = tag; tagExpression.typeArguments = typeArguments; - tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); return finishNode(tagExpression); @@ -19296,7 +20165,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 27 /* LessThanToken */) { + if (token() === 28 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -19309,15 +20178,15 @@ var ts; expression = parseTaggedTemplateRest(expression, typeArguments); continue; } - var callExpr = createNode(189 /* CallExpression */, expression.pos); + var callExpr = createNode(191 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(189 /* CallExpression */, expression.pos); + else if (token() === 20 /* OpenParenToken */) { + var callExpr = createNode(191 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -19327,17 +20196,17 @@ var ts; } } function parseArgumentList() { - parseExpected(19 /* OpenParenToken */); + parseExpected(20 /* OpenParenToken */); var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(27 /* LessThanToken */)) { + if (!parseOptional(28 /* LessThanToken */)) { return undefined; } var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); - if (!parseExpected(29 /* GreaterThanToken */)) { + if (!parseExpected(30 /* GreaterThanToken */)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } @@ -19349,34 +20218,34 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 19 /* OpenParenToken */: // foo( - case 13 /* NoSubstitutionTemplateLiteral */: // foo `...` - case 14 /* TemplateHead */: // foo `...${100}...` + case 20 /* OpenParenToken */: // foo( + case 14 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 15 /* TemplateHead */: // foo `...${100}...` // these are the only tokens can legally follow a type argument // list. So we definitely want to treat them as type arg lists. - case 23 /* DotToken */: // foo. - case 20 /* CloseParenToken */: // foo) - case 22 /* CloseBracketToken */: // foo] - case 56 /* ColonToken */: // foo: - case 25 /* SemicolonToken */: // foo; - case 55 /* QuestionToken */: // foo? - case 32 /* EqualsEqualsToken */: // foo == - case 34 /* EqualsEqualsEqualsToken */: // foo === - case 33 /* ExclamationEqualsToken */: // foo != - case 35 /* ExclamationEqualsEqualsToken */: // foo !== - case 53 /* AmpersandAmpersandToken */: // foo && - case 54 /* BarBarToken */: // foo || - case 50 /* CaretToken */: // foo ^ - case 48 /* AmpersandToken */: // foo & - case 49 /* BarToken */: // foo | - case 18 /* CloseBraceToken */: // foo } + case 24 /* DotToken */: // foo. + case 21 /* CloseParenToken */: // foo) + case 23 /* CloseBracketToken */: // foo] + case 57 /* ColonToken */: // foo: + case 26 /* SemicolonToken */: // foo; + case 56 /* QuestionToken */: // foo? + case 33 /* EqualsEqualsToken */: // foo == + case 35 /* EqualsEqualsEqualsToken */: // foo === + case 34 /* ExclamationEqualsToken */: // foo != + case 36 /* ExclamationEqualsEqualsToken */: // foo !== + case 54 /* AmpersandAmpersandToken */: // foo && + case 55 /* BarBarToken */: // foo || + case 51 /* CaretToken */: // foo ^ + case 49 /* AmpersandToken */: // foo & + case 50 /* BarToken */: // foo | + case 19 /* CloseBraceToken */: // foo } case 1 /* EndOfFileToken */: // foo // these cases can't legally follow a type arg list. However, they're not legal // expressions either. The user is probably in the middle of a generic type. So // treat it as such. return true; - case 26 /* CommaToken */: // foo, - case 17 /* OpenBraceToken */: // foo { + case 27 /* CommaToken */: // foo, + case 18 /* OpenBraceToken */: // foo { // We don't want to treat these as type arguments. Otherwise we'll parse this // as an invocation expression. Instead, we want to parse out the expression // in isolation from the type arguments. @@ -19388,22 +20257,23 @@ var ts; function parsePrimaryExpression() { switch (token()) { case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return parseLiteralNode(); - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 96 /* NullKeyword */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return parseTokenNode(); - case 19 /* OpenParenToken */: + case 20 /* OpenParenToken */: return parseParenthesizedExpression(); - case 21 /* OpenBracketToken */: + case 22 /* OpenBracketToken */: return parseArrayLiteralExpression(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseObjectLiteralExpression(); - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. // If we encounter `async [no LineTerminator here] function` then this is an async // function; otherwise, its an identifier. @@ -19411,75 +20281,76 @@ var ts; break; } return parseFunctionExpression(); - case 75 /* ClassKeyword */: + case 76 /* ClassKeyword */: return parseClassExpression(); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseFunctionExpression(); - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: return parseNewExpressionOrNewDotTarget(); - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) { return parseLiteralNode(); } break; - case 14 /* TemplateHead */: + case 15 /* TemplateHead */: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNodeWithJSDoc(193 /* ParenthesizedExpression */); - parseExpected(19 /* OpenParenToken */); + var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(206 /* SpreadElement */); - parseExpected(24 /* DotDotDotToken */); + var node = createNode(208 /* SpreadElement */); + parseExpected(25 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(208 /* OmittedExpression */) : + return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(185 /* ArrayLiteralExpression */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(187 /* ArrayLiteralExpression */); + parseExpected(22 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function parseObjectLiteralElement() { var node = createNodeWithJSDoc(0 /* Unknown */); - if (parseOptionalToken(24 /* DotDotDotToken */)) { - node.kind = 275 /* SpreadAssignment */; + if (parseOptionalToken(25 /* DotDotDotToken */)) { + node.kind = 277 /* SpreadAssignment */; node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* GetAccessor */); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); } - if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 157 /* SetAccessor */); + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); } - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } // check if it is short-hand property assignment or normal property assignment @@ -19487,30 +20358,30 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */); if (isShorthandPropertyAssignment) { - node.kind = 274 /* ShorthandPropertyAssignment */; - var equalsToken = parseOptionalToken(58 /* EqualsToken */); + node.kind = 276 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(59 /* EqualsToken */); if (equalsToken) { node.equalsToken = equalsToken; node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } } else { - node.kind = 273 /* PropertyAssignment */; - parseExpected(56 /* ColonToken */); + node.kind = 275 /* PropertyAssignment */; + parseExpected(57 /* ColonToken */); node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(186 /* ObjectLiteralExpression */); - parseExpected(17 /* OpenBraceToken */); + var node = createNode(188 /* ObjectLiteralExpression */); + parseExpected(18 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseFunctionExpression() { @@ -19523,10 +20394,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNodeWithJSDoc(194 /* FunctionExpression */); + var node = createNodeWithJSDoc(196 /* FunctionExpression */); node.modifiers = parseModifiers(); - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; node.name = @@ -19534,7 +20405,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlock(isGenerator | isAsync); if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -19546,10 +20417,10 @@ var ts; } function parseNewExpressionOrNewDotTarget() { var fullStart = scanner.getStartPos(); - parseExpected(94 /* NewKeyword */); - if (parseOptional(23 /* DotToken */)) { - var node_2 = createNode(212 /* MetaProperty */, fullStart); - node_2.keywordToken = 94 /* NewKeyword */; + parseExpected(95 /* NewKeyword */); + if (parseOptional(24 /* DotToken */)) { + var node_2 = createNode(214 /* MetaProperty */, fullStart); + node_2.keywordToken = 95 /* NewKeyword */; node_2.name = parseIdentifierName(); return finishNode(node_2); } @@ -19565,23 +20436,23 @@ var ts; } break; } - var node = createNode(190 /* NewExpression */, fullStart); + var node = createNode(192 /* NewExpression */, fullStart); node.expression = expression; node.typeArguments = typeArguments; - if (node.typeArguments || token() === 19 /* OpenParenToken */) { + if (node.typeArguments || token() === 20 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(216 /* Block */); - if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(218 /* Block */); + if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -19608,52 +20479,52 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(218 /* EmptyStatement */); - parseExpected(25 /* SemicolonToken */); + var node = createNode(220 /* EmptyStatement */); + parseExpected(26 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(220 /* IfStatement */); - parseExpected(90 /* IfKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(222 /* IfStatement */); + parseExpected(91 /* IfKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined; + node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(221 /* DoStatement */); - parseExpected(81 /* DoKeyword */); + var node = createNode(223 /* DoStatement */); + parseExpected(82 /* DoKeyword */); node.statement = parseStatement(); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. - parseOptional(25 /* SemicolonToken */); + parseOptional(26 /* SemicolonToken */); return finishNode(node); } function parseWhileStatement() { - var node = createNode(222 /* WhileStatement */); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(224 /* WhileStatement */); + parseExpected(107 /* WhileKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(88 /* ForKeyword */); - var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); - parseExpected(19 /* OpenParenToken */); + parseExpected(89 /* ForKeyword */); + var awaitToken = parseOptionalToken(122 /* AwaitKeyword */); + parseExpected(20 /* OpenParenToken */); var initializer; - if (token() !== 25 /* SemicolonToken */) { - if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { + if (token() !== 26 /* SemicolonToken */) { + if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -19661,33 +20532,33 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(145 /* OfKeyword */) : parseOptional(145 /* OfKeyword */)) { - var forOfStatement = createNode(225 /* ForOfStatement */, pos); + if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) { + var forOfStatement = createNode(227 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } - else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(224 /* ForInStatement */, pos); + else if (parseOptional(93 /* InKeyword */)) { + var forInStatement = createNode(226 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(223 /* ForStatement */, pos); + var forStatement = createNode(225 /* ForStatement */, pos); forStatement.initializer = initializer; - parseExpected(25 /* SemicolonToken */); - if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { + parseExpected(26 /* SemicolonToken */); + if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(25 /* SemicolonToken */); - if (token() !== 20 /* CloseParenToken */) { + parseExpected(26 /* SemicolonToken */); + if (token() !== 21 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -19695,7 +20566,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 227 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -19703,8 +20574,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(228 /* ReturnStatement */); - parseExpected(96 /* ReturnKeyword */); + var node = createNode(230 /* ReturnStatement */); + parseExpected(97 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -19712,42 +20583,42 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(229 /* WithStatement */); - parseExpected(107 /* WithKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(231 /* WithStatement */); + parseExpected(108 /* WithKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(269 /* CaseClause */); - parseExpected(73 /* CaseKeyword */); + var node = createNode(271 /* CaseClause */); + parseExpected(74 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(270 /* DefaultClause */); - parseExpected(79 /* DefaultKeyword */); - parseExpected(56 /* ColonToken */); + var node = createNode(272 /* DefaultClause */); + parseExpected(80 /* DefaultKeyword */); + parseExpected(57 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(230 /* SwitchStatement */); - parseExpected(98 /* SwitchKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(232 /* SwitchStatement */); + parseExpected(99 /* SwitchKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(244 /* CaseBlock */); - parseExpected(17 /* OpenBraceToken */); + parseExpected(21 /* CloseParenToken */); + var caseBlock = createNode(246 /* CaseBlock */); + parseExpected(18 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); node.caseBlock = finishNode(caseBlock); return finishNode(node); } @@ -19759,32 +20630,32 @@ 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(232 /* ThrowStatement */); - parseExpected(100 /* ThrowKeyword */); + var node = createNode(234 /* ThrowStatement */); + parseExpected(101 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(233 /* TryStatement */); - parseExpected(102 /* TryKeyword */); + var node = createNode(235 /* TryStatement */); + parseExpected(103 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token() === 87 /* FinallyKeyword */) { - parseExpected(87 /* FinallyKeyword */); + if (!node.catchClause || token() === 88 /* FinallyKeyword */) { + parseExpected(88 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(272 /* CatchClause */); - parseExpected(74 /* CatchKeyword */); - if (parseOptional(19 /* OpenParenToken */)) { + var result = createNode(274 /* CatchClause */); + parseExpected(75 /* CatchKeyword */); + if (parseOptional(20 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); } else { // Keep shape of node to avoid degrading performance. @@ -19794,8 +20665,8 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(234 /* DebuggerStatement */); - parseExpected(78 /* DebuggerKeyword */); + var node = createNode(236 /* DebuggerStatement */); + parseExpected(79 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); } @@ -19805,13 +20676,13 @@ var ts; // a colon. var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); - if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - node.kind = 231 /* LabeledStatement */; + if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) { + node.kind = 233 /* LabeledStatement */; node.label = expression; node.statement = parseStatement(); } else { - node.kind = 219 /* ExpressionStatement */; + node.kind = 221 /* ExpressionStatement */; node.expression = expression; parseSemicolon(); } @@ -19823,25 +20694,25 @@ var ts; } function nextTokenIsClassKeywordOnSameLine() { nextToken(); - return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: return true; // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; // however, an identifier cannot be followed by another identifier on the same line. This is what we @@ -19864,41 +20735,41 @@ var ts; // I {} // // could be legal, it would add complexity for very little gain. - case 109 /* InterfaceKeyword */: - case 139 /* TypeKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 132 /* ReadonlyKeyword */: + case 118 /* AbstractKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: nextToken(); // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 144 /* GlobalKeyword */: + case 145 /* GlobalKeyword */: nextToken(); - return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; - case 91 /* ImportKeyword */: + return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */; + case 92 /* ImportKeyword */: nextToken(); - return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); - case 84 /* ExportKeyword */: + return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 85 /* ExportKeyword */: nextToken(); - if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ || - token() === 118 /* AsKeyword */) { + if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ || + token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ || + token() === 119 /* AsKeyword */) { return true; } continue; - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: nextToken(); continue; default: @@ -19911,50 +20782,50 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 57 /* AtToken */: - case 25 /* SemicolonToken */: - case 17 /* OpenBraceToken */: - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 90 /* IfKeyword */: - case 81 /* DoKeyword */: - case 106 /* WhileKeyword */: - case 88 /* ForKeyword */: - case 77 /* ContinueKeyword */: - case 72 /* BreakKeyword */: - case 96 /* ReturnKeyword */: - case 107 /* WithKeyword */: - case 98 /* SwitchKeyword */: - case 100 /* ThrowKeyword */: - case 102 /* TryKeyword */: - case 78 /* DebuggerKeyword */: + case 58 /* AtToken */: + case 26 /* SemicolonToken */: + case 18 /* OpenBraceToken */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 90 /* FunctionKeyword */: + case 76 /* ClassKeyword */: + case 84 /* EnumKeyword */: + case 91 /* IfKeyword */: + case 82 /* DoKeyword */: + case 107 /* WhileKeyword */: + case 89 /* ForKeyword */: + case 78 /* ContinueKeyword */: + case 73 /* BreakKeyword */: + case 97 /* ReturnKeyword */: + case 108 /* WithKeyword */: + case 99 /* SwitchKeyword */: + case 101 /* ThrowKeyword */: + case 103 /* TryKeyword */: + case 79 /* DebuggerKeyword */: // 'catch' and 'finally' do not actually indicate that the code is part of a statement, // however, we say they are here so that we may gracefully parse them and error later. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return true; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); - case 76 /* ConstKeyword */: - case 84 /* ExportKeyword */: + case 77 /* ConstKeyword */: + case 85 /* ExportKeyword */: return isStartOfDeclaration(); - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 109 /* InterfaceKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: - case 139 /* TypeKeyword */: - case 144 /* GlobalKeyword */: + case 121 /* AsyncKeyword */: + case 125 /* DeclareKeyword */: + case 110 /* InterfaceKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 140 /* TypeKeyword */: + case 145 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 116 /* StaticKeyword */: + case 133 /* 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); @@ -19964,7 +20835,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */; + return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -19973,67 +20844,67 @@ var ts; } function parseStatement() { switch (token()) { - case 25 /* SemicolonToken */: + case 26 /* SemicolonToken */: return parseEmptyStatement(); - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); - case 104 /* VarKeyword */: - return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); - case 110 /* LetKeyword */: + case 105 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); + case 111 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */)); } break; - case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(createNodeWithJSDoc(237 /* FunctionDeclaration */)); - case 75 /* ClassKeyword */: - return parseClassDeclaration(createNodeWithJSDoc(238 /* ClassDeclaration */)); - case 90 /* IfKeyword */: + case 90 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */)); + case 76 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */)); + case 91 /* IfKeyword */: return parseIfStatement(); - case 81 /* DoKeyword */: + case 82 /* DoKeyword */: return parseDoStatement(); - case 106 /* WhileKeyword */: + case 107 /* WhileKeyword */: return parseWhileStatement(); - case 88 /* ForKeyword */: + case 89 /* ForKeyword */: return parseForOrForInOrForOfStatement(); - case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(226 /* ContinueStatement */); - case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(227 /* BreakStatement */); - case 96 /* ReturnKeyword */: + case 78 /* ContinueKeyword */: + return parseBreakOrContinueStatement(228 /* ContinueStatement */); + case 73 /* BreakKeyword */: + return parseBreakOrContinueStatement(229 /* BreakStatement */); + case 97 /* ReturnKeyword */: return parseReturnStatement(); - case 107 /* WithKeyword */: + case 108 /* WithKeyword */: return parseWithStatement(); - case 98 /* SwitchKeyword */: + case 99 /* SwitchKeyword */: return parseSwitchStatement(); - case 100 /* ThrowKeyword */: + case 101 /* ThrowKeyword */: return parseThrowStatement(); - case 102 /* TryKeyword */: + case 103 /* TryKeyword */: // Include 'catch' and 'finally' for error recovery. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: + case 75 /* CatchKeyword */: + case 88 /* FinallyKeyword */: return parseTryStatement(); - case 78 /* DebuggerKeyword */: + case 79 /* DebuggerKeyword */: return parseDebuggerStatement(); - case 57 /* AtToken */: + case 58 /* AtToken */: return parseDeclaration(); - case 120 /* AsyncKeyword */: - case 109 /* InterfaceKeyword */: - case 139 /* TypeKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 83 /* EnumKeyword */: - case 84 /* ExportKeyword */: - case 91 /* ImportKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: - case 144 /* GlobalKeyword */: + case 121 /* AsyncKeyword */: + case 110 /* InterfaceKeyword */: + case 140 /* TypeKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 84 /* EnumKeyword */: + case 85 /* ExportKeyword */: + case 92 /* ImportKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 118 /* AbstractKeyword */: + case 116 /* StaticKeyword */: + case 133 /* ReadonlyKeyword */: + case 145 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -20042,7 +20913,7 @@ var ts; return parseExpressionOrLabeledStatement(); } function isDeclareModifier(modifier) { - return modifier.kind === 124 /* DeclareKeyword */; + return modifier.kind === 125 /* DeclareKeyword */; } function parseDeclaration() { var node = createNodeWithJSDoc(0 /* Unknown */); @@ -20061,33 +20932,33 @@ var ts; } function parseDeclarationWorker(node) { switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: + case 105 /* VarKeyword */: + case 111 /* LetKeyword */: + case 77 /* ConstKeyword */: return parseVariableStatement(node); - case 89 /* FunctionKeyword */: + case 90 /* FunctionKeyword */: return parseFunctionDeclaration(node); - case 75 /* ClassKeyword */: + case 76 /* ClassKeyword */: return parseClassDeclaration(node); - case 109 /* InterfaceKeyword */: + case 110 /* InterfaceKeyword */: return parseInterfaceDeclaration(node); - case 139 /* TypeKeyword */: + case 140 /* TypeKeyword */: return parseTypeAliasDeclaration(node); - case 83 /* EnumKeyword */: + case 84 /* EnumKeyword */: return parseEnumDeclaration(node); - case 144 /* GlobalKeyword */: - case 129 /* ModuleKeyword */: - case 130 /* NamespaceKeyword */: + case 145 /* GlobalKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: return parseModuleDeclaration(node); - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: return parseImportDeclarationOrImportEqualsDeclaration(node); - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: nextToken(); switch (token()) { - case 79 /* DefaultKeyword */: - case 58 /* EqualsToken */: + case 80 /* DefaultKeyword */: + case 59 /* EqualsToken */: return parseExportAssignment(node); - case 118 /* AsKeyword */: + case 119 /* AsKeyword */: return parseNamespaceExportDeclaration(node); default: return parseExportDeclaration(node); @@ -20096,7 +20967,7 @@ var ts; if (node.decorators || node.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 missing = createMissingNode(256 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; @@ -20107,10 +20978,10 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) { + if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -20118,25 +20989,25 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token() === 26 /* CommaToken */) { - return createNode(208 /* OmittedExpression */); + if (token() === 27 /* CommaToken */) { + return createNode(210 /* OmittedExpression */); } - var node = createNode(184 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(184 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var node = createNode(186 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56 /* ColonToken */) { + if (tokenIsIdentifier && token() !== 57 /* ColonToken */) { node.name = propertyName; } else { - parseExpected(56 /* ColonToken */); + parseExpected(57 /* ColonToken */); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -20144,27 +21015,27 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(182 /* ObjectBindingPattern */); - parseExpected(17 /* OpenBraceToken */); + var node = createNode(184 /* ObjectBindingPattern */); + parseExpected(18 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(183 /* ArrayBindingPattern */); - parseExpected(21 /* OpenBracketToken */); + var node = createNode(185 /* ArrayBindingPattern */); + parseExpected(22 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier(); + return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -20173,10 +21044,10 @@ var ts; return parseVariableDeclaration(/*allowExclamation*/ true); } function parseVariableDeclaration(allowExclamation) { - var node = createNode(235 /* VariableDeclaration */); + var node = createNode(237 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); - if (allowExclamation && node.name.kind === 71 /* Identifier */ && - token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (allowExclamation && node.name.kind === 72 /* Identifier */ && + token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -20186,14 +21057,14 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(236 /* VariableDeclarationList */); + var node = createNode(238 /* VariableDeclarationList */); switch (token()) { - case 104 /* VarKeyword */: + case 105 /* VarKeyword */: break; - case 110 /* LetKeyword */: + case 111 /* LetKeyword */: node.flags |= 1 /* Let */; break; - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: node.flags |= 2 /* Const */; break; default: @@ -20209,7 +21080,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() === 145 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -20221,44 +21092,44 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; + return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */; } function parseVariableStatement(node) { - node.kind = 217 /* VariableStatement */; + node.kind = 219 /* VariableStatement */; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return finishNode(node); } function parseFunctionDeclaration(node) { - node.kind = 237 /* FunctionDeclaration */; - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.kind = 239 /* FunctionDeclaration */; + parseExpected(90 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); return finishNode(node); } function parseConstructorDeclaration(node) { - node.kind = 155 /* Constructor */; - parseExpected(123 /* ConstructorKeyword */); - fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.kind = 157 /* Constructor */; + parseExpected(124 /* ConstructorKeyword */); + fillSignature(57 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); return finishNode(node); } function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { - node.kind = 154 /* MethodDeclaration */; + node.kind = 156 /* MethodDeclaration */; node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + fillSignature(57 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); return finishNode(node); } function parsePropertyDeclaration(node) { - node.kind = 152 /* PropertyDeclaration */; - if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.kind = 154 /* PropertyDeclaration */; + if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); @@ -20278,12 +21149,12 @@ var ts; return finishNode(node); } function parsePropertyOrMethodDeclaration(node) { - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(40 /* AsteriskToken */); node.name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + node.questionToken = parseOptionalToken(56 /* QuestionToken */); + if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } return parsePropertyDeclaration(node); @@ -20291,13 +21162,13 @@ var ts; function parseAccessorDeclaration(node, kind) { node.kind = kind; node.name = parsePropertyName(); - fillSignature(56 /* ColonToken */, 0 /* None */, node); + fillSignature(57 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */); return finishNode(node); } function isClassMemberStart() { var idToken; - if (token() === 57 /* AtToken */) { + if (token() === 58 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. @@ -20314,7 +21185,7 @@ var ts; } nextToken(); } - if (token() === 39 /* AsteriskToken */) { + if (token() === 40 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. @@ -20324,24 +21195,24 @@ var ts; nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token() === 21 /* OpenBracketToken */) { + if (token() === 22 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... if (idToken !== undefined) { // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!ts.isKeyword(idToken) || idToken === 136 /* SetKeyword */ || idToken === 125 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. switch (token()) { - case 19 /* OpenParenToken */: // Method declaration - case 27 /* LessThanToken */: // Generic Method declaration - case 51 /* ExclamationToken */: // Non-null assertion on property name - case 56 /* ColonToken */: // Type Annotation for declaration - case 58 /* EqualsToken */: // Initializer for declaration - case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. + case 20 /* OpenParenToken */: // Method declaration + case 28 /* LessThanToken */: // Generic Method declaration + case 52 /* ExclamationToken */: // Non-null assertion on property name + case 57 /* ColonToken */: // Type Annotation for declaration + case 59 /* EqualsToken */: // Initializer for declaration + case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. return true; default: // Covers @@ -20359,10 +21230,10 @@ var ts; var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(57 /* AtToken */)) { + if (!parseOptional(58 /* AtToken */)) { break; } - var decorator = createNode(150 /* Decorator */, decoratorStart); + var decorator = createNode(152 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -20382,7 +21253,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) { + if (token() === 77 /* 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)) { @@ -20401,7 +21272,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 120 /* AsyncKeyword */) { + if (token() === 121 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -20411,21 +21282,21 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 25 /* SemicolonToken */) { - var result = createNode(215 /* SemicolonClassElement */); + if (token() === 26 /* SemicolonToken */) { + var result = createNode(217 /* SemicolonClassElement */); nextToken(); return finishNode(result); } var node = createNodeWithJSDoc(0 /* Unknown */); node.decorators = parseDecorators(); node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* GetAccessor */); + if (parseContextualModifier(126 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 158 /* GetAccessor */); } - if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 157 /* SetAccessor */); + if (parseContextualModifier(137 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 159 /* SetAccessor */); } - if (token() === 123 /* ConstructorKeyword */) { + if (token() === 124 /* ConstructorKeyword */) { return parseConstructorDeclaration(node); } if (isIndexSignature()) { @@ -20434,37 +21305,37 @@ var ts; // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || + token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || - token() === 39 /* AsteriskToken */ || - token() === 21 /* OpenBracketToken */) { + token() === 40 /* AsteriskToken */ || + token() === 22 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(node); } if (node.decorators || node.modifiers) { // treat this as a property declaration with a missing name. - node.name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 207 /* ClassExpression */); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */); } function parseClassDeclaration(node) { - return parseClassDeclarationOrExpression(node, 238 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(node, kind) { node.kind = kind; - parseExpected(75 /* ClassKeyword */); + parseExpected(76 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } node.members = parseClassMembers(); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -20482,7 +21353,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses() { // ClassTail[Yield,Await] : (Modified) See 14.5 @@ -20494,33 +21365,33 @@ var ts; } function parseHeritageClause() { var tok = token(); - ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. - var node = createNode(271 /* HeritageClause */); + ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(273 /* HeritageClause */); node.token = tok; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); } function parseExpressionWithTypeArguments() { - var node = createNode(209 /* ExpressionWithTypeArguments */); + var node = createNode(211 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); node.typeArguments = tryParseTypeArguments(); return finishNode(node); } function tryParseTypeArguments() { - return token() === 27 /* LessThanToken */ - ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + return token() === 28 /* LessThanToken */ + ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */) : undefined; } function isHeritageClause() { - return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(node) { - node.kind = 239 /* InterfaceDeclaration */; - parseExpected(109 /* InterfaceKeyword */); + node.kind = 241 /* InterfaceDeclaration */; + parseExpected(110 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); @@ -20528,11 +21399,11 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(node) { - node.kind = 240 /* TypeAliasDeclaration */; - parseExpected(139 /* TypeKeyword */); + node.kind = 242 /* TypeAliasDeclaration */; + parseExpected(140 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(58 /* EqualsToken */); + parseExpected(59 /* EqualsToken */); node.type = parseType(); parseSemicolon(); return finishNode(node); @@ -20542,18 +21413,18 @@ 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 = createNodeWithJSDoc(276 /* EnumMember */); + var node = createNodeWithJSDoc(278 /* EnumMember */); node.name = parsePropertyName(); node.initializer = allowInAnd(parseInitializer); return finishNode(node); } function parseEnumDeclaration(node) { - node.kind = 241 /* EnumDeclaration */; - parseExpected(83 /* EnumKeyword */); + node.kind = 243 /* EnumDeclaration */; + parseExpected(84 /* EnumKeyword */); node.name = parseIdentifier(); - if (parseExpected(17 /* OpenBraceToken */)) { + if (parseExpected(18 /* OpenBraceToken */)) { node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -20561,10 +21432,10 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(243 /* ModuleBlock */); - if (parseExpected(17 /* OpenBraceToken */)) { + var node = createNode(245 /* ModuleBlock */); + if (parseExpected(18 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -20572,20 +21443,20 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(node, flags) { - node.kind = 242 /* ModuleDeclaration */; + node.kind = 244 /* ModuleDeclaration */; // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(23 /* DotToken */) + node.body = parseOptional(24 /* DotToken */) ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(node) { - node.kind = 242 /* ModuleDeclaration */; - if (token() === 144 /* GlobalKeyword */) { + node.kind = 244 /* ModuleDeclaration */; + if (token() === 145 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -20594,7 +21465,7 @@ var ts; node.name = parseLiteralNode(); node.name.text = internIdentifier(node.name.text); } - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -20604,68 +21475,68 @@ var ts; } function parseModuleDeclaration(node) { var flags = 0; - if (token() === 144 /* GlobalKeyword */) { + if (token() === 145 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(node); } - else if (parseOptional(130 /* NamespaceKeyword */)) { + else if (parseOptional(131 /* NamespaceKeyword */)) { flags |= 16 /* Namespace */; } else { - parseExpected(129 /* ModuleKeyword */); - if (token() === 9 /* StringLiteral */) { + parseExpected(130 /* ModuleKeyword */); + if (token() === 10 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(node); } } return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { - return token() === 133 /* RequireKeyword */ && + return token() === 134 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 19 /* OpenParenToken */; + return nextToken() === 20 /* OpenParenToken */; } function nextTokenIsSlash() { - return nextToken() === 41 /* SlashToken */; + return nextToken() === 42 /* SlashToken */; } function parseNamespaceExportDeclaration(node) { - node.kind = 245 /* NamespaceExportDeclaration */; - parseExpected(118 /* AsKeyword */); - parseExpected(130 /* NamespaceKeyword */); + node.kind = 247 /* NamespaceExportDeclaration */; + parseExpected(119 /* AsKeyword */); + parseExpected(131 /* NamespaceKeyword */); node.name = parseIdentifier(); parseSemicolon(); return finishNode(node); } function parseImportDeclarationOrImportEqualsDeclaration(node) { - parseExpected(91 /* ImportKeyword */); + parseExpected(92 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 143 /* FromKeyword */) { + if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) { return parseImportEqualsDeclaration(node, identifier); } } // Import statement - node.kind = 247 /* ImportDeclaration */; + node.kind = 249 /* ImportDeclaration */; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || // import id - token() === 39 /* AsteriskToken */ || // import * - token() === 17 /* OpenBraceToken */) { // import { + token() === 40 /* AsteriskToken */ || // import * + token() === 18 /* OpenBraceToken */) { // import { node.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(143 /* FromKeyword */); + parseExpected(144 /* FromKeyword */); } node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(node); } function parseImportEqualsDeclaration(node, identifier) { - node.kind = 246 /* ImportEqualsDeclaration */; + node.kind = 248 /* ImportEqualsDeclaration */; node.name = identifier; - parseExpected(58 /* EqualsToken */); + parseExpected(59 /* EqualsToken */); node.moduleReference = parseModuleReference(); parseSemicolon(); return finishNode(node); @@ -20677,7 +21548,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(248 /* ImportClause */, fullStart); + var importClause = createNode(250 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -20686,8 +21557,8 @@ var ts; // If there was no default import or if there is comma token after default import // parse namespace or named imports if (!importClause.name || - parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(250 /* NamedImports */); + parseOptional(27 /* CommaToken */)) { + importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */); } return finishNode(importClause); } @@ -20697,15 +21568,15 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(257 /* ExternalModuleReference */); - parseExpected(133 /* RequireKeyword */); - parseExpected(19 /* OpenParenToken */); + var node = createNode(259 /* ExternalModuleReference */); + parseExpected(134 /* RequireKeyword */); + parseExpected(20 /* OpenParenToken */); node.expression = parseModuleSpecifier(); - parseExpected(20 /* CloseParenToken */); + parseExpected(21 /* CloseParenToken */); return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9 /* StringLiteral */) { + if (token() === 10 /* StringLiteral */) { var result = parseLiteralNode(); result.text = internIdentifier(result.text); return result; @@ -20720,9 +21591,9 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(249 /* NamespaceImport */); - parseExpected(39 /* AsteriskToken */); - parseExpected(118 /* AsKeyword */); + var namespaceImport = createNode(251 /* NamespaceImport */); + parseExpected(40 /* AsteriskToken */); + parseExpected(119 /* AsKeyword */); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } @@ -20735,14 +21606,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(255 /* ExportSpecifier */); + return parseImportOrExportSpecifier(257 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(251 /* ImportSpecifier */); + return parseImportOrExportSpecifier(253 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -20756,9 +21627,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 118 /* AsKeyword */) { + if (token() === 119 /* AsKeyword */) { node.propertyName = identifierName; - parseExpected(118 /* AsKeyword */); + parseExpected(119 /* AsKeyword */); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -20767,24 +21638,24 @@ var ts; else { node.name = identifierName; } - if (kind === 251 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(node) { - node.kind = 253 /* ExportDeclaration */; - if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(143 /* FromKeyword */); + node.kind = 255 /* ExportDeclaration */; + if (parseOptional(40 /* AsteriskToken */)) { + parseExpected(144 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(254 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(256 /* 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() === 143 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(143 /* FromKeyword */); + if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(144 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -20792,12 +21663,12 @@ var ts; return finishNode(node); } function parseExportAssignment(node) { - node.kind = 252 /* ExportAssignment */; - if (parseOptional(58 /* EqualsToken */)) { + node.kind = 254 /* ExportAssignment */; + if (parseOptional(59 /* EqualsToken */)) { node.isExportEquals = true; } else { - parseExpected(79 /* DefaultKeyword */); + parseExpected(80 /* DefaultKeyword */); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -20812,10 +21683,10 @@ var ts; } function isAnExternalModuleIndicatorNode(node) { return ts.hasModifier(node, 1 /* Export */) - || node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */ - || node.kind === 247 /* ImportDeclaration */ - || node.kind === 252 /* ExportAssignment */ - || node.kind === 253 /* ExportDeclaration */ + || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */ + || node.kind === 249 /* ImportDeclaration */ + || node.kind === 254 /* ExportAssignment */ + || node.kind === 255 /* ExportDeclaration */ ? node : undefined; } @@ -20828,7 +21699,7 @@ var ts; return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); } function isImportMeta(node) { - return ts.isMetaProperty(node) && node.keywordToken === 91 /* ImportKeyword */ && node.name.escapedText === "meta"; + return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta"; } var ParsingContext; (function (ParsingContext) { @@ -20879,11 +21750,11 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); - var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); + var result = createNode(283 /* JSDocTypeExpression */); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } fixupParentReferences(result); return finishNode(result); @@ -20971,7 +21842,7 @@ var ts; } loop: while (true) { switch (token()) { - case 57 /* AtToken */: + case 58 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingWhitespace(comments); addTag(parseTag(indent)); @@ -20991,7 +21862,7 @@ var ts; state = 0 /* BeginningOfLine */; indent = 0; break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: var asterisk = scanner.getTokenText(); if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { // If we've already seen an asterisk, then we can no longer parse a tag on this line @@ -21004,13 +21875,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21025,7 +21889,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21047,7 +21913,7 @@ var ts; } } function createJSDocComment() { - var result = createNode(289 /* JSDocComment */, start); + var result = createNode(291 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -21081,61 +21947,60 @@ var ts; } } var precedingLineBreak = scanner.hasPrecedingLineBreak(); - while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { if (token() === 4 /* NewLineTrivia */) { precedingLineBreak = true; } - else if (token() === 39 /* AsteriskToken */) { + else if (token() === 40 /* AsteriskToken */) { precedingLineBreak = false; } nextJSDocToken(); } } function parseTag(indent) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getTokenPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": case "extends": - tag = parseAugmentsTag(atToken, tagName); + tag = parseAugmentsTag(start, tagName); break; case "class": case "constructor": - tag = parseClassTag(atToken, tagName); + tag = parseClassTag(start, tagName); break; case "this": - tag = parseThisTag(atToken, tagName); + tag = parseThisTag(start, tagName); break; case "enum": - tag = parseEnumTag(atToken, tagName); + tag = parseEnumTag(start, tagName); break; case "arg": case "argument": case "param": - return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent); + return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent); case "return": case "returns": - tag = parseReturnTag(atToken, tagName); + tag = parseReturnTag(start, tagName); break; case "template": - tag = parseTemplateTag(atToken, tagName); + tag = parseTemplateTag(start, tagName); break; case "type": - tag = parseTypeTag(atToken, tagName); + tag = parseTypeTag(start, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName, indent); + tag = parseTypedefTag(start, tagName, indent); break; case "callback": - tag = parseCallbackTag(atToken, tagName, indent); + tag = parseCallbackTag(start, tagName, indent); break; default: - tag = parseUnknownTag(atToken, tagName); + tag = parseUnknownTag(start, tagName); break; } if (!tag.comment) { @@ -21165,7 +22030,7 @@ var ts; } indent = 0; break; - case 57 /* AtToken */: + case 58 /* AtToken */: scanner.setTextPos(scanner.getTextPos() - 1); // falls through case 1 /* EndOfFileToken */: @@ -21184,9 +22049,9 @@ var ts; indent += whitespace.length; } break; - case 17 /* OpenBraceToken */: + case 18 /* OpenBraceToken */: state = 2 /* SavingComments */; - if (lookAhead(function () { return nextJSDocToken() === 57 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { pushComment(scanner.getTokenText()); nextJSDocToken(); pushComment(scanner.getTokenText()); @@ -21194,7 +22059,7 @@ var ts; } pushComment(scanner.getTokenText()); break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; @@ -21214,9 +22079,8 @@ var ts; removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } - function parseUnknownTag(atToken, tagName) { - var result = createNode(292 /* JSDocTag */, atToken.pos); - result.atToken = atToken; + function parseUnknownTag(start, tagName) { + var result = createNode(294 /* JSDocTag */, start); result.tagName = tagName; return finishNode(result); } @@ -21235,37 +22099,37 @@ var ts; } function tryParseTypeExpression() { skipWhitespaceOrAsterisk(); - return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; + return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { - if (token() === 13 /* NoSubstitutionTemplateLiteral */) { + if (token() === 14 /* NoSubstitutionTemplateLiteral */) { // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; } // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' - var isBracketed = parseOptional(21 /* OpenBracketToken */); + var isBracketed = parseOptional(22 /* OpenBracketToken */); var name = parseJSDocEntityName(); if (isBracketed) { skipWhitespace(); // May have an optional default, e.g. '[foo = 42]' - if (parseOptionalToken(58 /* EqualsToken */)) { + if (parseOptionalToken(59 /* EqualsToken */)) { parseExpression(); } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); } return { name: name, isBracketed: isBracketed }; } function isObjectOrObjectArrayTypeReference(node) { switch (node.kind) { - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return true; - case 167 /* ArrayType */: + case 169 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; } } - function parseParameterOrPropertyTag(atToken, tagName, target, indent) { + function parseParameterOrPropertyTag(start, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -21275,17 +22139,14 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(303 /* JSDocPropertyTag */, atToken.pos) : - createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + createNode(305 /* JSDocPropertyTag */, start) : + createNode(299 /* JSDocParameterTag */, start); + var comment = parseTagComments(indent + scanner.getStartPos() - start); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; } - result.atToken = atToken; result.tagName = tagName; result.typeExpression = typeExpression; result.name = name; @@ -21294,22 +22155,22 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { + if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 167 /* ArrayType */) { + if (typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -21317,81 +22178,74 @@ var ts; } } } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) { + function parseReturnTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(298 /* JSDocReturnTag */, atToken.pos); - result.atToken = atToken; + var result = createNode(300 /* JSDocReturnTag */, start); result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) { + function parseTypeTag(start, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(300 /* JSDocTypeTag */, atToken.pos); - result.atToken = atToken; + var result = createNode(302 /* JSDocTypeTag */, start); result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } - function parseAugmentsTag(atToken, tagName) { - var result = createNode(293 /* JSDocAugmentsTag */, atToken.pos); - result.atToken = atToken; + function parseAugmentsTag(start, tagName) { + var result = createNode(295 /* JSDocAugmentsTag */, start); result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } function parseExpressionWithTypeArgumentsForAugments() { - var usedBrace = parseOptional(17 /* OpenBraceToken */); - var node = createNode(209 /* ExpressionWithTypeArguments */); + var usedBrace = parseOptional(18 /* OpenBraceToken */); + var node = createNode(211 /* ExpressionWithTypeArguments */); node.expression = parsePropertyAccessEntityNameExpression(); node.typeArguments = tryParseTypeArguments(); var res = finishNode(node); if (usedBrace) { - parseExpected(18 /* CloseBraceToken */); + parseExpected(19 /* CloseBraceToken */); } return res; } function parsePropertyAccessEntityNameExpression() { var node = parseJSDocIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var prop = createNode(187 /* PropertyAccessExpression */, node.pos); + while (parseOptional(24 /* DotToken */)) { + var prop = createNode(189 /* PropertyAccessExpression */, node.pos); prop.expression = node; prop.name = parseJSDocIdentifierName(); node = finishNode(prop); } return node; } - function parseClassTag(atToken, tagName) { - var tag = createNode(294 /* JSDocClassTag */, atToken.pos); - tag.atToken = atToken; + function parseClassTag(start, tagName) { + var tag = createNode(296 /* JSDocClassTag */, start); tag.tagName = tagName; return finishNode(tag); } - function parseThisTag(atToken, tagName) { - var tag = createNode(299 /* JSDocThisTag */, atToken.pos); - tag.atToken = atToken; + function parseThisTag(start, tagName) { + var tag = createNode(301 /* JSDocThisTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseEnumTag(atToken, tagName) { - var tag = createNode(296 /* JSDocEnumTag */, atToken.pos); - tag.atToken = atToken; + function parseEnumTag(start, tagName) { + var tag = createNode(298 /* JSDocEnumTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseTypedefTag(atToken, tagName, indent) { + function parseTypedefTag(start, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); - typedefTag.atToken = atToken; + skipWhitespaceOrAsterisk(); + var typedefTag = createNode(304 /* JSDocTypedefTag */, start); typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); @@ -21403,12 +22257,11 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); } - if (child.kind === 300 /* JSDocTypeTag */) { + if (child.kind === 302 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -21421,7 +22274,7 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 167 /* ArrayType */) { + if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? @@ -21439,8 +22292,8 @@ var ts; return undefined; } var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(242 /* ModuleDeclaration */, pos); + if (parseOptional(24 /* DotToken */)) { + var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos); if (nested) { jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } @@ -21453,25 +22306,23 @@ var ts; } return typeNameOrNamespaceName; } - function parseCallbackTag(atToken, tagName, indent) { - var callbackTag = createNode(295 /* JSDocCallbackTag */, atToken.pos); - callbackTag.atToken = atToken; + function parseCallbackTag(start, tagName, indent) { + var callbackTag = createNode(297 /* JSDocCallbackTag */, start); callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); skipWhitespace(); callbackTag.comment = parseTagComments(indent); var child; - var start = scanner.getStartPos(); - var jsdocSignature = createNode(291 /* JSDocSignature */, start); + var jsdocSignature = createNode(293 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { - if (parseOptionalJsdoc(57 /* AtToken */)) { + if (parseOptionalJsdoc(58 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 298 /* JSDocReturnTag */) { + if (tag && tag.kind === 300 /* JSDocReturnTag */) { return tag; } } @@ -21505,18 +22356,18 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { - case 57 /* AtToken */: + case 58 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); - if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && + var child = tryParseChildTag(target, indent); + if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -21529,13 +22380,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 39 /* AsteriskToken */: + case 40 /* AsteriskToken */: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 71 /* Identifier */: + case 72 /* Identifier */: canParseTag = false; break; case 1 /* EndOfFileToken */: @@ -21543,17 +22394,16 @@ var ts; } } } - function tryParseChildTag(target) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */); - atToken.end = scanner.getTextPos(); + function tryParseChildTag(target, indent) { + ts.Debug.assert(token() === 58 /* AtToken */); + var start = scanner.getStartPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); skipWhitespace(); var t; switch (tagName.escapedText) { case "type": - return target === 1 /* Property */ && parseTypeTag(atToken, tagName); + return target === 1 /* Property */ && parseTypeTag(start, tagName); case "prop": case "property": t = 1 /* Property */; @@ -21569,28 +22419,25 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(start, tagName, target, indent); } - function parseTemplateTag(atToken, tagName) { + function parseTemplateTag(start, tagName) { // the template tag looks like '@template {Constraint} T,U,V' var constraint; - if (token() === 17 /* OpenBraceToken */) { + if (token() === 18 /* OpenBraceToken */) { constraint = parseJSDocTypeExpression(); } var typeParameters = []; var typeParametersPos = getNodePos(); do { skipWhitespace(); - var typeParameter = createNode(148 /* TypeParameter */); + var typeParameter = createNode(150 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); finishNode(typeParameter); skipWhitespace(); typeParameters.push(typeParameter); - } while (parseOptionalJsdoc(26 /* CommaToken */)); - var result = createNode(301 /* JSDocTemplateTag */, atToken.pos); - result.atToken = atToken; + } while (parseOptionalJsdoc(27 /* CommaToken */)); + var result = createNode(303 /* JSDocTemplateTag */, start); result.tagName = tagName; result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -21609,16 +22456,16 @@ var ts; } function parseJSDocEntityName() { var entity = parseJSDocIdentifierName(); - if (parseOptional(21 /* OpenBracketToken */)) { - parseExpected(22 /* CloseBracketToken */); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> // but it's not worth it to enforce that restriction. } - while (parseOptional(23 /* DotToken */)) { + while (parseOptional(24 /* DotToken */)) { var name = parseJSDocIdentifierName(); - if (parseOptional(21 /* OpenBracketToken */)) { - parseExpected(22 /* CloseBracketToken */); + if (parseOptional(22 /* OpenBracketToken */)) { + parseExpected(23 /* CloseBracketToken */); } entity = createQualifiedName(entity, name); } @@ -21626,11 +22473,11 @@ var ts; } function parseJSDocIdentifierName(message) { if (!ts.tokenIsIdentifierOrKeyword(token())) { - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); + return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(71 /* Identifier */, pos); + var result = createNode(72 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); @@ -21756,9 +22603,9 @@ var ts; } function shouldCheckNode(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 71 /* Identifier */: + case 72 /* Identifier */: return true; } return false; @@ -22336,10 +23183,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 71 /* Identifier */) { + if (lhs.kind === 72 /* Identifier */) { return lhs.escapedText === rhs.escapedText; } - if (lhs.kind === 99 /* ThisKeyword */) { + if (lhs.kind === 100 /* ThisKeyword */) { return true; } // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only @@ -22396,7 +23243,8 @@ var ts; ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.symbol", "lib.esnext.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], - ["esnext.intl", "lib.esnext.intl.d.ts"] + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -22412,8 +23260,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22427,6 +23274,61 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22468,26 +23370,11 @@ var ts; description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date }, { - name: "pretty", + name: "showConfig", type: "boolean", - showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental - }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, // Basic { @@ -22503,6 +23390,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22521,6 +23410,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22533,6 +23423,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22540,6 +23431,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22557,6 +23449,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22666,6 +23559,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22674,6 +23568,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22682,14 +23577,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22698,6 +23603,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22706,6 +23612,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22739,6 +23646,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22751,6 +23659,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22758,6 +23667,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22767,6 +23677,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22782,6 +23693,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22793,6 +23705,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22803,6 +23716,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22875,42 +23789,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h }, - { - name: "diagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_diagnostic_information - }, - { - name: "extendedDiagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_verbose_diagnostic_information - }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22969,12 +23853,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22987,6 +23873,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23032,6 +23919,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23039,6 +23927,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23066,6 +23955,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23093,7 +23983,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23146,20 +24074,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23195,16 +24124,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23216,7 +24144,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23224,7 +24152,7 @@ var ts; 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)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23260,7 +24188,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23303,9 +24231,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23318,7 +24256,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23445,6 +24411,9 @@ var ts; } var result = ts.parseJsonText(configFileName, configFileText); var cwd = host.getCurrentDirectory(); + result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; @@ -23584,7 +24553,7 @@ var ts; var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 273 /* PropertyAssignment */) { + if (element.kind !== 275 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -23632,20 +24601,24 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { - case 101 /* TrueKeyword */: + case 102 /* TrueKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return true; - case 86 /* FalseKeyword */: + case 87 /* FalseKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return false; - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for return null; // tslint:disable-line:no-null-keyword - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } @@ -23662,13 +24635,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 200 /* PrefixUnaryExpression */: - if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + case 202 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return -Number(valueExpression.operand.text); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -23685,7 +24658,7 @@ var ts; return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); } - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -23725,6 +24698,115 @@ var ts; } return false; } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + function convertToTSConfig(configParseResult, configFileName, host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { + var _a; + return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); + return config; + } + ts.convertToTSConfig = convertToTSConfig; + function filterSameAsDefaultInclude(specs) { + if (!ts.length(specs)) + return undefined; + if (ts.length(specs) !== 1) + return specs; + if (specs[0] === "**/*") + return undefined; + return specs; + } + function matchesSpecs(path, includeSpecs, excludeSpecs) { + if (!includeSpecs) + return function (_) { return false; }; + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + } + return function (path) { return includeRe.test(path); }; + } + if (excludeRe) { + return function (path) { return !excludeRe.test(path); }; + } + return function (_) { return false; }; + } + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options, pathOptions) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } /** * Generate tsconfig configuration when running command line "--init" * @param options commandlineOptions to be generated into tsconfig.json @@ -23735,62 +24817,6 @@ var ts; var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - // There is a typeMap associated with this command-line option so use it to map value back to its name - return ts.forEachEntry(customTypeMap, function (mapValue, key) { - if (mapValue === value) { - return key; - } - }); - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_3 = function (name) { - if (ts.hasProperty(options, name)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - return "continue"; - } - var value = options[name]; - var optionDefinition = optionsNameMap.get(name.toLowerCase()); - if (optionDefinition) { - var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap_1) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result.set(name, value); - } - else { - if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); - } - } - } - } - }; - for (var name in options) { - _loop_3(name); - } - return result; - } function getDefaultValueForOption(option) { switch (option.type) { case "number": @@ -23939,7 +24965,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23956,8 +24983,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23993,19 +25034,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24013,7 +25053,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24027,17 +25066,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24123,11 +25178,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24155,26 +25205,30 @@ var ts; } function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { - errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return undefined; - } - var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return undefined; + if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } } + return extendedConfigPath; } - return extendedConfigPath; + // If the path isn't a rooted or relative path, resolve like a module + var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24182,7 +25236,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24396,7 +25450,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24421,10 +25475,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24434,9 +25493,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24444,7 +25519,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24455,16 +25530,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24597,7 +25672,7 @@ var ts; } } /** - * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. * Also converts enum values back to strings. */ /* @internal */ @@ -24653,6 +25728,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24662,14 +25743,15 @@ var ts; Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; Extensions[Extensions["Json"] = 2] = "Json"; - Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */ + Extensions[Extensions["TSConfig"] = 3] = "TSConfig"; + Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24678,48 +25760,97 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24761,9 +25892,13 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24782,8 +25917,10 @@ var ts; trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24792,13 +25929,12 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - if (!options.preserveSymlinks) { - resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); - } + var fileName = resolved.fileName, packageId = resolved.packageId; + var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -24807,14 +25943,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } - return ts.forEach(typeRoots, function (typeRoot) { + return ts.firstDefined(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24830,8 +25966,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - var resolvedFile = resolvedTypeScriptOnly(result && result.value); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + var resolvedFile = resolvedTypeScriptOnly(result); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -24869,14 +26013,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -24887,29 +26035,56 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName); } ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ + function createCacheWithRedirects() { + var ownMap = ts.createMap(); + var redirectsMap = ts.createMap(); + return { + ownMap: ownMap, + redirectsMap: redirectsMap, + getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, + clear: clear + }; + function getOrCreateMapOfCacheRedirects(redirectedReference) { + if (!redirectedReference) { + return ownMap; + } + var path = redirectedReference.sourceFile.path; + var redirects = redirectsMap.get(path); + if (!redirects) { + redirects = ts.createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + ts.createCacheWithRedirects = createCacheWithRedirects; + /*@internal*/ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName) { + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); - var perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = ts.createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap); } - function getOrCreateCacheForModuleName(nonRelativeModuleName) { + function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); - var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); } - return perModuleNameCache; + return result; } function createPerModuleNameCache() { var directoryPathMap = ts.createMap(); @@ -24984,13 +26159,19 @@ var ts; return perFolderCache && perFolderCache.get(moduleName); } ts.resolveModuleNameFromCache = resolveModuleNameFromCache; - function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } var containingDirectory = ts.getDirectoryPath(containingFile); - var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { @@ -25012,10 +26193,10 @@ var ts; } switch (moduleResolution) { case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; default: return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); @@ -25024,7 +26205,7 @@ var ts; perFolderCache.set(moduleName, result); if (!ts.isExternalModuleNameRelative(moduleName)) { // put result in per-module name cache - cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); + cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); } } } @@ -25099,15 +26280,28 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) + return resolved.value; if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (baseUrl && paths && !ts.pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25145,7 +26339,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25164,7 +26358,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25175,95 +26369,72 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var baseUrl = state.compilerOptions.baseUrl; + if (!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); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; - function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]); + var tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? - tryResolve(Extensions.JavaScript) : - (tryResolve(Extensions.TypeScript) || - tryResolve(Extensions.JavaScript) || - (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); if (result && result.value) { var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25277,7 +26448,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25294,29 +26465,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25324,10 +26496,15 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + function pathContainsNodeModules(path) { + return ts.stringContains(path, ts.nodeModulesPathPart); + } + ts.pathContainsNodeModules = pathContainsNodeModules; /** * This will be called on the successfully resolved path from `loadModuleFromFile`. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) @@ -25365,52 +26542,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @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; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - if (extensions === Extensions.Json) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25420,16 +26591,17 @@ var ts; return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.TSConfig: case Extensions.Json: return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25443,40 +26615,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25488,6 +26653,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25499,51 +26665,72 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { - // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return ts.Debug.assertNever(extensions); + } + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25555,6 +26742,7 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TSConfig: case Extensions.Json: return extension === ".json" /* Json */; case Extensions.TypeScript: @@ -25563,87 +26751,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25651,11 +26881,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25664,68 +26894,69 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } - function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } if (!ts.isExternalModuleNameRelative(moduleName)) { - var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25740,9 +26971,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25771,24 +27002,24 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: if (!(ts.hasModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. other uninstantiated module declarations. - case 243 /* ModuleBlock */: { + case 245 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateWorker(n); @@ -25810,9 +27041,9 @@ var ts; }); return state_1; } - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return getModuleInstanceState(node); - case 71 /* Identifier */: + case 72 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should // be considered the same as type alias if (node.isInJSDocNamespace) { @@ -25957,19 +27188,23 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + 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.kind === 252 /* ExportAssignment */) { + if (node.kind === 254 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -25978,7 +27213,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -25990,36 +27225,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: return "__constructor" /* Constructor */; - case 163 /* FunctionType */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: + case 165 /* FunctionType */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: return "__call" /* Call */; - case 164 /* ConstructorType */: - case 159 /* ConstructSignature */: + case 166 /* ConstructorType */: + case 161 /* ConstructSignature */: return "__new" /* New */; - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return "__index" /* Index */; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + case 204 /* BinaryExpression */: + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 149 /* Parameter */: + case 151 /* 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 === 287 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -26088,7 +27323,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26116,7 +27352,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; } @@ -26143,7 +27379,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 255 /* ExportSpecifier */ || (node.kind === 246 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -26166,12 +27402,12 @@ var ts; // 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.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26210,7 +27446,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 195 /* ArrowFunction */) { + if (node.kind !== 197 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -26242,7 +27478,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property intialization checks. - currentReturnTarget = isIIFE || node.kind === 155 /* Constructor */ ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; @@ -26255,13 +27491,13 @@ var ts; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { node.flags |= emitFlags; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 155 /* Constructor */) { + if (node.kind === 157 /* Constructor */) { node.returnFlowNode = currentFlow; } } @@ -26304,8 +27540,8 @@ var ts; } } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -26334,81 +27570,82 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: bindWhileStatement(node); break; - case 221 /* DoStatement */: + case 223 /* DoStatement */: bindDoStatement(node); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: bindForStatement(node); break; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: bindIfStatement(node); break; - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: bindTryStatement(node); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: bindSwitchStatement(node); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: bindCaseBlock(node); break; - case 269 /* CaseClause */: + case 271 /* CaseClause */: bindCaseClause(node); break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: bindLabeledStatement(node); break; - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: bindCallExpressionFlow(node); break; - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 277 /* SourceFile */: { + case 279 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; default: @@ -26419,24 +27656,26 @@ var ts; } function isNarrowingExpression(expr) { switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return isNarrowableReference(expr); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return hasNarrowableArgument(expr); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 200 /* PrefixUnaryExpression */: - return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 202 /* PrefixUnaryExpression */: + return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 199 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || + return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && @@ -26451,7 +27690,7 @@ var ts; } } } - if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26465,32 +27704,32 @@ var ts; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return isNarrowableReference(expr.left); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); - case 92 /* InKeyword */: + case 93 /* InKeyword */: return isNarrowableInOperands(expr.left, expr.right); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return isNarrowableOperand(expr.right); } } @@ -26525,8 +27764,8 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -26564,34 +27803,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 220 /* IfStatement */: - case 222 /* WhileStatement */: - case 221 /* DoStatement */: + case 222 /* IfStatement */: + case 224 /* WhileStatement */: + case 223 /* DoStatement */: return parent.expression === node; - case 223 /* ForStatement */: - case 203 /* ConditionalExpression */: + case 225 /* ForStatement */: + case 205 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 193 /* ParenthesizedExpression */) { + if (node.kind === 195 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 200 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 202 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 54 /* BarBarToken */); + return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 55 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 193 /* ParenthesizedExpression */ || - node.parent.kind === 200 /* PrefixUnaryExpression */ && - node.parent.operator === 51 /* ExclamationToken */) { + while (node.parent.kind === 195 /* ParenthesizedExpression */ || + node.parent.kind === 202 /* PrefixUnaryExpression */ && + node.parent.operator === 52 /* ExclamationToken */) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -26632,7 +27871,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 231 /* LabeledStatement */ + var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */ ? ts.lastOrUndefined(activeLabels) : undefined; // if do statement is wrapped in labeled statement then target labels for break/continue with or without @@ -26666,13 +27905,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 225 /* ForOfStatement */) { + if (node.kind === 227 /* ForOfStatement */) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 236 /* VariableDeclarationList */) { + if (node.initializer.kind !== 238 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -26694,7 +27933,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 228 /* ReturnStatement */) { + if (node.kind === 230 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -26714,7 +27953,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 227 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -26810,7 +28049,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 270 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; @@ -26834,7 +28073,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -26878,14 +28116,14 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } - if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { + if (!node.statement || node.statement.kind !== 223 /* DoStatement */) { // do statement sets current flow inside bindDoStatement addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -26896,10 +28134,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 185 /* ArrayLiteralExpression */) { + else if (node.kind === 187 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 206 /* SpreadElement */) { + if (e.kind === 208 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -26907,16 +28145,16 @@ var ts; } } } - else if (node.kind === 186 /* ObjectLiteralExpression */) { + else if (node.kind === 188 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 273 /* PropertyAssignment */) { + if (p.kind === 275 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 274 /* ShorthandPropertyAssignment */) { + else if (p.kind === 276 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 275 /* SpreadAssignment */) { + else if (p.kind === 277 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -26924,7 +28162,7 @@ var ts; } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -26935,7 +28173,7 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51 /* ExclamationToken */) { + if (node.operator === 52 /* ExclamationToken */) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; @@ -26945,20 +28183,20 @@ var ts; } else { bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -26972,7 +28210,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 188 /* ElementAccessExpression */) { + if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -26983,7 +28221,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -27021,6 +28259,7 @@ var ts; } } function bindJSDocTypeAlias(node) { + node.tagName.parent = node; if (node.fullName) { setParentPointers(node, node.fullName); } @@ -27030,10 +28269,10 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 193 /* ParenthesizedExpression */) { + while (expr.kind === 195 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 194 /* FunctionExpression */ || expr.kind === 195 /* ArrowFunction */) { + if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -27041,7 +28280,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -27050,54 +28289,54 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 186 /* ObjectLiteralExpression */: - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 266 /* JsxAttributes */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 188 /* ObjectLiteralExpression */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 268 /* JsxAttributes */: return 1 /* IsContainer */; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 179 /* MappedType */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 155 /* Constructor */: - case 237 /* FunctionDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 291 /* JSDocSignature */: - case 287 /* JSDocFunctionType */: - case 163 /* FunctionType */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 164 /* ConstructorType */: + case 157 /* Constructor */: + case 239 /* FunctionDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 160 /* CallSignature */: + case 293 /* JSDocSignature */: + case 289 /* JSDocFunctionType */: + case 165 /* FunctionType */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 166 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 272 /* CatchClause */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: - case 244 /* CaseBlock */: + case 274 /* CatchClause */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: + case 246 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 216 /* Block */: + case 218 /* 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 @@ -27130,45 +28369,45 @@ var ts; // 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 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 277 /* SourceFile */: + case 279 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 186 /* ObjectLiteralExpression */: - case 239 /* InterfaceDeclaration */: - case 266 /* JsxAttributes */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 188 /* ObjectLiteralExpression */: + case 241 /* InterfaceDeclaration */: + case 268 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 291 /* JSDocSignature */: - case 160 /* IndexSignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 287 /* JSDocFunctionType */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 240 /* TypeAliasDeclaration */: - case 179 /* MappedType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 293 /* JSDocSignature */: + case 162 /* IndexSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 289 /* JSDocFunctionType */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 242 /* TypeAliasDeclaration */: + case 181 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -27189,11 +28428,11 @@ var ts; : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 277 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 277 /* SourceFile */ || body.kind === 243 /* ModuleBlock */)) { + var body = node.kind === 279 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 253 /* ExportDeclaration */ || stat.kind === 252 /* ExportAssignment */) { + if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { return true; } } @@ -27221,7 +28460,7 @@ var ts; } else { var pattern = void 0; - if (node.name.kind === 9 /* StringLiteral */) { + if (node.name.kind === 10 /* StringLiteral */) { var text = node.name.text; if (ts.hasZeroOrOneAsteriskCharacter(text)) { pattern = ts.tryParsePattern(text); @@ -27230,7 +28469,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27250,7 +28489,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27277,7 +28516,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) { continue; } var identifier = prop.name; @@ -27289,7 +28528,7 @@ var ts; // 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 === 273 /* PropertyAssignment */ || prop.kind === 274 /* ShorthandPropertyAssignment */ || prop.kind === 154 /* MethodDeclaration */ + var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -27321,10 +28560,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -27338,9 +28577,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27358,9 +28594,9 @@ var ts; currentFlow = { flags: 2 /* Start */ }; parent = typeAlias; bind(typeAlias.typeExpression); - if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { + if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27376,8 +28612,8 @@ var ts; // check for reserved words used as identifiers in strict mode code. function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && + node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 117 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && !(node.flags & 4194304 /* Ambient */)) { // Report error only if there are no parse errors in file @@ -27413,7 +28649,7 @@ var ts; } function checkStrictModeDeleteExpression(node) { // Grammar checking - if (inStrictMode && node.expression.kind === 71 /* Identifier */) { + if (inStrictMode && node.expression.kind === 72 /* 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); @@ -27424,7 +28660,7 @@ var ts; return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71 /* Identifier */) { + if (name && name.kind === 72 /* 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 @@ -27465,8 +28701,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 277 /* SourceFile */ && - blockScopeContainer.kind !== 242 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 279 /* SourceFile */ && + blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -27492,7 +28728,7 @@ var ts; function checkStrictModePrefixUnaryExpression(node) { // Grammar checking if (inStrictMode) { - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -27561,7 +28797,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 145 /* LastToken */) { + if (node.kind > 147 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -27585,7 +28821,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27623,7 +28859,7 @@ var ts; function bindWorker(node) { switch (node.kind) { /* Strict mode checks */ - case 71 /* Identifier */: + case 72 /* Identifier */: // for typedef type names with namespaces, bind the new jsdoc type symbol here // because it requires all containing namespaces to be in effect, namely the // current "blockScopeContainer" needs to be set to its immediate namespace parent. @@ -27632,32 +28868,32 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through - case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 274 /* ShorthandPropertyAssignment */)) { + case 100 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; - case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + case 204 /* BinaryExpression */: + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27681,142 +28917,155 @@ var ts; // Nothing to do break; default: - ts.Debug.fail("Unknown special property assignment kind"); + ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return checkStrictModeCatchClause(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return checkStrictModeWithStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 176 /* ThisType */: + case 178 /* ThisType */: seenThisKeyword = true; return; - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: break; // Binding the children will handle everything - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return bindTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return bindParameter(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return bindPropertyWorker(node); - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 276 /* EnumMember */: + case 278 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); - case 237 /* FunctionDeclaration */: + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); + case 239 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); - case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); - case 163 /* FunctionType */: - case 287 /* JSDocFunctionType */: - case 291 /* JSDocSignature */: - case 164 /* ConstructorType */: + case 158 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); + case 159 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); + case 165 /* FunctionType */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: + case 166 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 179 /* MappedType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 181 /* MappedType */: return bindAnonymousTypeWorker(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return bindFunctionExpression(node); - case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + case 191 /* CallExpression */: + var assignmentKind = ts.getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; // Nothing to do + default: + return ts.Debug.fail("Unknown call expression assignment declaration kind"); + } + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 207 /* ClassExpression */: - case 238 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 240 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); - case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - case 241 /* EnumDeclaration */: + case 241 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); + case 242 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); + case 243 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return bindJsxAttributes(node); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return bindImportClause(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return bindExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return bindExportAssignment(node); - case 277 /* SourceFile */: + case 279 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 216 /* Block */: + case 218 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 297 /* JSDocParameterTag */: - if (node.parent.kind === 291 /* JSDocSignature */) { + case 299 /* JSDocParameterTag */: + if (node.parent.kind === 293 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 290 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { break; } // falls through - case 303 /* JSDocPropertyTag */: + case 305 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -27848,37 +29097,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27905,6 +29152,21 @@ var ts; } return true; } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol; + }); + if (symbol) { + var flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } function bindExportsPropertyAssignment(node) { // When we create a property via 'exports.foo = bar', the 'exports.foo' property access // expression is the declaration @@ -27914,7 +29176,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27941,17 +29203,17 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); + declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. - if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) { var l = thisContainer.parent.left; if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); @@ -27964,18 +29226,18 @@ var ts; declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } break; - case 155 /* Constructor */: - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; - case 277 /* SourceFile */: + case 279 /* SourceFile */: // this.foo assignment in a source file // Do not bind. It would be nice to support this someday though. break; @@ -27984,10 +29246,10 @@ var ts; } } function bindSpecialPropertyDeclaration(node) { - if (node.expression.kind === 99 /* ThisKeyword */) { + if (node.expression.kind === 100 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 277 /* SourceFile */) { + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -28001,7 +29263,11 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + function bindObjectDefinePrototypeProperty(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28018,11 +29284,17 @@ var ts; classPrototype.parent = lhs; bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); } + function bindObjectDefinePropertyAssignment(node) { + var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } function bindSpecialPropertyAssignment(node) { var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28046,42 +29318,48 @@ var ts; node.expression.parent = node; bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); } - function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) - : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; - namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ + : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28090,11 +29368,14 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } var node = symbol.valueDeclaration; + if (node && ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -28103,7 +29384,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28145,7 +29426,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 238 /* ClassDeclaration */) { + if (node.kind === 240 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); } else { @@ -28187,8 +29468,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28200,15 +29484,15 @@ var ts; // 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 */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } function bindParameter(node) { - if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -28220,7 +29504,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28238,10 +29522,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28279,26 +29563,26 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 174 /* InferType */) { + else if (node.parent.kind === 176 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28313,13 +29597,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 218 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) || // report error on class declarations - node.kind === 238 /* ClassDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28357,24 +29639,23 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return true; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.hasModifier(s, 2048 /* Const */); default: return false; } } - /* @internal */ function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || @@ -28395,6 +29676,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28406,58 +29690,58 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return computeNewExpression(node, subtreeFlags); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); - case 149 /* Parameter */: + case 151 /* Parameter */: return computeParameter(node, subtreeFlags); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return computeCatchClause(node, subtreeFlags); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 155 /* Constructor */: + case 157 /* Constructor */: return computeConstructor(node, subtreeFlags); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return computePropertyDeclaration(node, subtreeFlags); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return computeMethod(node, subtreeFlags); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -28470,61 +29754,61 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } - if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + if (expression.kind === 92 /* ImportKeyword */) { + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 186 /* ObjectLiteralExpression */) { + if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ESNext if they contain rest transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 185 /* ArrayLiteralExpression */) { + else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ - || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { + else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ + || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28535,25 +29819,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28563,8 +29847,8 @@ 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 (expressionKind === 210 /* AsExpression */ - || expressionKind === 192 /* TypeAssertionExpression */) { + if (expressionKind === 212 /* AsExpression */ + || expressionKind === 194 /* TypeAssertionExpression */) { transformFlags |= 3 /* AssertTypeScript */; } // If the expression of a ParenthesizedExpression is a destructuring assignment, @@ -28588,44 +29872,44 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 85 /* ExtendsKeyword */: + case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; - case 108 /* ImplementsKeyword */: + case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; @@ -28634,7 +29918,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28645,7 +29929,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28657,7 +29941,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28667,11 +29951,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28687,7 +29971,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28698,7 +29982,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28712,11 +29996,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28724,10 +30008,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28739,7 +30023,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28752,13 +30036,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28771,7 +30055,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28787,13 +30071,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28803,7 +30087,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28820,26 +30104,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28847,18 +30133,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28866,7 +30154,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28877,22 +30165,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28901,7 +30189,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28912,7 +30200,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28921,78 +30209,78 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { - case 120 /* AsyncKeyword */: - case 199 /* AwaitExpression */: + case 121 /* AsyncKeyword */: + case 201 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 306 /* PartiallyEmittedExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; break; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 211 /* NonNullExpression */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 125 /* DeclareKeyword */: + case 77 /* ConstKeyword */: + case 243 /* EnumDeclaration */: + case 278 /* EnumMember */: + case 213 /* NonNullExpression */: + case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; - case 258 /* JsxElement */: - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: - case 10 /* JsxText */: - case 261 /* JsxClosingElement */: - case 262 /* JsxFragment */: - case 263 /* JsxOpeningFragment */: - case 264 /* JsxClosingFragment */: - case 265 /* JsxAttribute */: - case 266 /* JsxAttributes */: - case 267 /* JsxSpreadAttribute */: - case 268 /* JsxExpression */: + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 11 /* JsxText */: + case 263 /* JsxClosingElement */: + case 264 /* JsxFragment */: + case 265 /* JsxOpeningFragment */: + case 266 /* JsxClosingFragment */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 270 /* JsxExpression */: // These nodes are Jsx syntax. transformFlags |= 4 /* AssertJsx */; break; - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 204 /* TemplateExpression */: - case 191 /* TaggedTemplateExpression */: - case 274 /* ShorthandPropertyAssignment */: - case 115 /* StaticKeyword */: - case 212 /* MetaProperty */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + case 206 /* TemplateExpression */: + case 193 /* TaggedTemplateExpression */: + case 276 /* ShorthandPropertyAssignment */: + case 116 /* StaticKeyword */: + case 214 /* MetaProperty */: // These nodes are ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { transformFlags |= 192 /* AssertES2015 */; } @@ -29002,65 +30290,69 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } break; - case 225 /* ForOfStatement */: + case 9 /* BigIntLiteral */: + transformFlags |= 8 /* AssertESNext */; + break; + case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { transformFlags |= 8 /* AssertESNext */; } transformFlags |= 192 /* AssertES2015 */; break; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 148 /* TypeParameter */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 161 /* TypePredicate */: - case 162 /* TypeReference */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 165 /* TypeQuery */: - case 166 /* TypeLiteral */: - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 169 /* OptionalType */: - case 170 /* RestType */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 173 /* ConditionalType */: - case 174 /* InferType */: - case 175 /* ParenthesizedType */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 176 /* ThisType */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 180 /* LiteralType */: - case 245 /* NamespaceExportDeclaration */: + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 136 /* ObjectKeyword */: + case 138 /* StringKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 163 /* TypePredicate */: + case 164 /* TypeReference */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 167 /* TypeQuery */: + case 168 /* TypeLiteral */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 176 /* InferType */: + case 177 /* ParenthesizedType */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: + case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = 3 /* AssertTypeScript */; excludeFlags = -3 /* TypeExcludes */; break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29069,93 +30361,93 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + case 208 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; - case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + case 277 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; - case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + case 184 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; - case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + case 185 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; - case 150 /* Decorator */: + case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; - case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + case 188 /* ObjectLiteralExpression */: + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; } break; - case 185 /* ArrayLiteralExpression */: - case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + case 187 /* ArrayLiteralExpression */: + case 192 /* NewExpression */: + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } break; - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + case 279 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29168,71 +30460,71 @@ var ts; * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather * than calling this function. */ - /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) { + if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { return -3 /* TypeExcludes */; } switch (kind) { - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; - case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; - case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; - case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; - case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 137 /* StringKeyword */: - case 135 /* ObjectKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 148 /* TypeParameter */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 187 /* ArrayLiteralExpression */: + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + case 244 /* ModuleDeclaration */: + return 647001409 /* ModuleExcludes */; + case 151 /* Parameter */: + return 637535553 /* ParameterExcludes */; + case 197 /* ArrowFunction */: + return 653604161 /* ArrowFunctionExcludes */; + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + return 653620545 /* FunctionExcludes */; + case 238 /* VariableDeclarationList */: + return 639894849 /* VariableDeclarationListExcludes */; + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 638121281 /* ClassExcludes */; + case 157 /* Constructor */: + return 653616449 /* ConstructorExcludes */; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return 653616449 /* MethodOrAccessorExcludes */; + case 120 /* AnyKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 132 /* NeverKeyword */: + case 138 /* StringKeyword */: + case 136 /* ObjectKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 106 /* VoidKeyword */: + case 150 /* TypeParameter */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; - case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; - case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 306 /* PartiallyEmittedExpression */: - case 193 /* ParenthesizedExpression */: - case 97 /* SuperKeyword */: + case 188 /* ObjectLiteralExpression */: + return 638358849 /* ObjectLiteralExcludes */; + case 274 /* CatchClause */: + return 637797697 /* CatchClauseExcludes */; + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + return 637666625 /* BindingPatternExcludes */; + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 308 /* PartiallyEmittedExpression */: + case 195 /* ParenthesizedExpression */: + case 98 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29290,7 +30582,7 @@ var ts; if (shouldBail) return; // Visit the type's related types, if any - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var objectType = type; var objectFlags = objectType.objectFlags; if (objectFlags & 4 /* Reference */) { @@ -29306,16 +30598,16 @@ var ts; visitObjectType(objectType); } } - if (type.flags & 65536 /* TypeParameter */) { + if (type.flags & 262144 /* TypeParameter */) { visitTypeParameter(type); } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { visitUnionOrIntersectionType(type); } - if (type.flags & 1048576 /* Index */) { + if (type.flags & 4194304 /* Index */) { visitIndexType(type); } - if (type.flags & 2097152 /* IndexedAccess */) { + if (type.flags & 8388608 /* IndexedAccess */) { visitIndexedAccessType(type); } } @@ -29404,7 +30696,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 165 /* TypeQuery */) { + if (d.type && d.type.kind === 167 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -29447,6 +30739,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29467,7 +30771,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29476,10 +30781,12 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); @@ -29638,27 +30945,13 @@ var ts; var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); return parsed ? isImplementationOfOverload(parsed) : undefined; }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return ts.Debug.fail(); - links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); - } - return links.immediateTarget; - }, + getImmediateAliasedSymbol: getImmediateAliasedSymbol, getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { - var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isParameter); @@ -29682,15 +30975,17 @@ var ts; getNumberType: function () { return numberType; }, createPromiseType: createPromiseType, createArrayType: createArrayType, + getElementTypeOfArrayType: getElementTypeOfArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, getESSymbolType: function () { return esSymbolType; }, getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, + getObjectFlags: ts.getObjectFlags, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -29698,7 +30993,7 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, - getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, @@ -29752,7 +31047,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29775,24 +31071,43 @@ var ts; var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); - var undefinedType = createIntrinsicType(8192 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(8192 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(16384 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(16384 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); - var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); - var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); - var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(4096 /* Void */, "void"); - var neverType = createIntrinsicType(32768 /* Never */, "never"); - var silentNeverType = createIntrinsicType(32768 /* Never */, "never"); - var implicitNeverType = createIntrinsicType(32768 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + var numberOrBigIntType = getUnionType([numberType, bigintType]); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -29805,18 +31120,18 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(65536 /* TypeParameter */); - var markerSubType = createType(65536 /* TypeParameter */); + var markerSuperType = createType(262144 /* TypeParameter */); + var markerSubType = createType(262144 /* TypeParameter */); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(65536 /* TypeParameter */); + var markerOtherType = createType(262144 /* TypeParameter */); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29828,6 +31143,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29846,6 +31163,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29857,7 +31175,9 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; + var deferredGlobalExcludeSymbol; + var deferredGlobalPickSymbol; + var deferredGlobalBigIntType; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29865,6 +31185,7 @@ var ts; var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); + var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -29890,84 +31211,99 @@ var ts; TypeFacts[TypeFacts["None"] = 0] = "None"; TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; - TypeFacts[TypeFacts["TypeofEQBoolean"] = 4] = "TypeofEQBoolean"; - TypeFacts[TypeFacts["TypeofEQSymbol"] = 8] = "TypeofEQSymbol"; - TypeFacts[TypeFacts["TypeofEQObject"] = 16] = "TypeofEQObject"; - TypeFacts[TypeFacts["TypeofEQFunction"] = 32] = "TypeofEQFunction"; - TypeFacts[TypeFacts["TypeofEQHostObject"] = 64] = "TypeofEQHostObject"; - TypeFacts[TypeFacts["TypeofNEString"] = 128] = "TypeofNEString"; - TypeFacts[TypeFacts["TypeofNENumber"] = 256] = "TypeofNENumber"; - TypeFacts[TypeFacts["TypeofNEBoolean"] = 512] = "TypeofNEBoolean"; - TypeFacts[TypeFacts["TypeofNESymbol"] = 1024] = "TypeofNESymbol"; - TypeFacts[TypeFacts["TypeofNEObject"] = 2048] = "TypeofNEObject"; - TypeFacts[TypeFacts["TypeofNEFunction"] = 4096] = "TypeofNEFunction"; - TypeFacts[TypeFacts["TypeofNEHostObject"] = 8192] = "TypeofNEHostObject"; - TypeFacts[TypeFacts["EQUndefined"] = 16384] = "EQUndefined"; - TypeFacts[TypeFacts["EQNull"] = 32768] = "EQNull"; - TypeFacts[TypeFacts["EQUndefinedOrNull"] = 65536] = "EQUndefinedOrNull"; - TypeFacts[TypeFacts["NEUndefined"] = 131072] = "NEUndefined"; - TypeFacts[TypeFacts["NENull"] = 262144] = "NENull"; - TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; - TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; - TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["All"] = 4194303] = "All"; + TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; + TypeFacts[TypeFacts["All"] = 16777215] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. - TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; - TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; - TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; - TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; - TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; - TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; - TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; - TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; - TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; - TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; - TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; - TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; - TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; - TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; - TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; - TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; - TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; - TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; - TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; - TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; - TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; - TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; - TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; - TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; - TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; - TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts"; + TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts"; + TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, number: 2 /* TypeofEQNumber */, - boolean: 4 /* TypeofEQBoolean */, - symbol: 8 /* TypeofEQSymbol */, - undefined: 16384 /* EQUndefined */, - object: 16 /* TypeofEQObject */, - function: 32 /* TypeofEQFunction */ + bigint: 4 /* TypeofEQBigInt */, + boolean: 8 /* TypeofEQBoolean */, + symbol: 16 /* TypeofEQSymbol */, + undefined: 65536 /* EQUndefined */, + object: 32 /* TypeofEQObject */, + function: 64 /* TypeofEQFunction */ }); var typeofNEFacts = ts.createMapFromTemplate({ - string: 128 /* TypeofNEString */, - number: 256 /* TypeofNENumber */, - boolean: 512 /* TypeofNEBoolean */, - symbol: 1024 /* TypeofNESymbol */, - undefined: 131072 /* NEUndefined */, - object: 2048 /* TypeofNEObject */, - function: 4096 /* TypeofNEFunction */ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ }); var typeofTypesByName = ts.createMapFromTemplate({ string: stringType, number: numberType, + bigint: bigintType, boolean: booleanType, symbol: esSymbolType, undefined: undefinedType @@ -29988,6 +31324,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30123,35 +31461,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30184,10 +31522,14 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { - target = cloneSymbol(target); + var resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); } // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { @@ -30197,8 +31539,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30217,55 +31560,56 @@ var ts; else if (target.flags & 1024 /* NamespaceModule */) { error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } - else { + else { // error var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30281,7 +31625,8 @@ var ts; } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { - target.set(id, target.has(id) ? mergeSymbol(target.get(id), sourceSymbol) : sourceSymbol); + var targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); }); } function mergeModuleAugmentation(moduleName) { @@ -30343,7 +31688,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { - return node.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -30373,8 +31718,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30401,17 +31746,17 @@ var ts; } if (declaration.pos <= usage.pos) { // declaration is before usage - if (declaration.kind === 184 /* BindingElement */) { + if (declaration.kind === 186 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 184 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 235 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage); } - else if (declaration.kind === 235 /* VariableDeclaration */) { + else if (declaration.kind === 237 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -30430,12 +31775,12 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 252 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -30443,9 +31788,9 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 217 /* VariableStatement */: - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: + case 219 /* VariableStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -30466,16 +31811,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 152 /* PropertyDeclaration */ && + current.parent.kind === 154 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 154 /* MethodDeclaration */) { + if (declaration.kind === 156 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -30517,27 +31862,35 @@ var ts; // - 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 & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 149 /* Parameter */ || - lastLocation.kind === 148 /* TypeParameter */ + lastLocation.kind === 151 /* Parameter */ || + lastLocation.kind === 150 /* TypeParameter */ // local types not visible outside the function body : false; } - if (meaning & 67216319 /* 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 === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (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 === 151 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } - else if (location.kind === 173 /* ConditionalType */) { + else if (location.kind === 175 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -30551,14 +31904,14 @@ var ts; } } switch (location.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -30582,7 +31935,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 255 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) { break; } } @@ -30596,13 +31949,13 @@ var ts; } } break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* 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 @@ -30612,17 +31965,20 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } } } break; - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30637,7 +31993,7 @@ var ts; } break loop; } - if (location.kind === 207 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -30645,11 +32001,11 @@ var ts; } } break; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. - if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { + if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30665,29 +32021,29 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -30700,7 +32056,7 @@ var ts; } } break; - case 150 /* Decorator */: + case 152 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -30709,7 +32065,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 === 149 /* Parameter */) { + if (location.parent && location.parent.kind === 151 /* Parameter */) { location = location.parent; } // @@ -30722,8 +32078,8 @@ var ts; location = location.parent; } break; - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); break; @@ -30737,13 +32093,13 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { result.isReferenced |= meaning; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30752,7 +32108,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30807,16 +32163,15 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -30825,12 +32180,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 242 /* ModuleDeclaration */: // For `namespace N { N; }` + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 244 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -30842,7 +32197,7 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 148 /* TypeParameter */) { + if (decl.kind === 150 /* TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 @@ -30897,10 +32252,10 @@ var ts; */ function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -30910,9 +32265,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30931,29 +32286,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30964,7 +32322,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30981,6 +32339,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -30996,13 +32357,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return node; - case 248 /* ImportClause */: + case 250 /* ImportClause */: return node.parent; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return node.parent.parent; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -31012,7 +32373,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -31050,7 +32411,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31104,7 +32465,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31160,7 +32521,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31194,7 +32555,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31204,20 +32565,20 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 252 /* ExportAssignment */: - case 202 /* BinaryExpression */: + case 257 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 254 /* ExportAssignment */: + case 204 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -31228,10 +32589,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31262,7 +32623,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31278,11 +32639,11 @@ var ts; var node = getDeclarationOfAliasSymbol(symbol); if (!node) return ts.Debug.fail(); - if (node.kind === 252 /* ExportAssignment */) { + if (node.kind === 254 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 255 /* ExportSpecifier */) { + else if (node.kind === 257 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -31300,22 +32661,22 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 146 /* QualifiedName */) { + if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31324,19 +32685,19 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; - if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + if (name.kind === 72 /* Identifier */) { + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; } } - else if (name.kind === 146 /* QualifiedName */ || name.kind === 187 /* PropertyAccessExpression */) { - var left = name.kind === 146 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 146 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) { + var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -31344,7 +32705,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31379,15 +32740,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31395,9 +32756,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31405,8 +32778,18 @@ var ts; return symbol && symbol.valueDeclaration; } } - function resolveExternalModuleName(location, moduleReferenceExpression) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + if (!decl) { + return undefined; + } + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); } function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { if (isForAugmentation === void 0) { isForAugmentation = false; } @@ -31434,7 +32817,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31453,7 +32836,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31485,7 +32868,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31493,7 +32876,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31505,24 +32888,28 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; + if (moduleSymbol) { + var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + var exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { return exported; } var merged = cloneSymbol(exported); @@ -31543,7 +32930,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 277 /* SourceFile */)) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); return symbol; } @@ -31611,7 +32998,7 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 32764 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -31701,6 +33088,50 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + var containingFile = ts.getSourceFileOfNode(enclosingDeclaration); + var id = "" + getNodeId(containingFile); + var links = getSymbolLinks(symbol); + var results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) { + var importRef = _a[_i]; + if (ts.nodeIsSynthesized(importRef)) + continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) + continue; + var ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) + continue; + results = ts.append(results, resolvedModule); + } + if (ts.length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + var otherFiles = host.getSourceFiles(); + for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) { + var file = otherFiles_1[_b]; + if (!ts.isExternalModule(file)) + continue; + var sym = getSymbolOfNode(file); + var ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) + continue; + results = ts.append(results, sym); + } + return links.extendedContainers = results || ts.emptyArray; + } /** * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` @@ -31709,10 +33140,12 @@ var ts; var container = getParentOfSymbol(symbol); if (container) { var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { - return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope } - return ts.append(additionalContainers, container); + var res = ts.append(additionalContainers, container); + return ts.concatenate(res, reexportContainers); } var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); if (!ts.length(candidates)) { @@ -31750,13 +33183,13 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 155 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -31779,7 +33212,7 @@ var ts; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(131072 /* Object */); + var type = createType(524288 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; type.members = undefined; @@ -31834,12 +33267,12 @@ var ts; } } switch (location.kind) { - case 277 /* SourceFile */: + case 279 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -31850,7 +33283,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31900,7 +33333,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31936,7 +33372,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -31951,10 +33387,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: continue; default: return false; @@ -31965,11 +33401,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -32007,7 +33443,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32061,10 +33507,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -32111,21 +33557,21 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 165 /* TypeQuery */ || + if (entityName.parent.kind === 167 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 147 /* ComputedPropertyName */) { + entityName.parent.kind === 149 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || - entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ || + entityName.parent.kind === 248 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32138,7 +33584,7 @@ var ts; } function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } - var nodeFlags = 3112960 /* IgnoreErrors */; + var nodeFlags = 70221824 /* IgnoreErrors */; if (flags & 2 /* UseOnlyExternalAliasing */) { nodeFlags |= 128 /* UseOnlyExternalAliasing */; } @@ -32148,6 +33594,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32164,15 +33613,15 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 164 /* ConstructorType */ : 163 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 159 /* ConstructSignature */ : 158 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */; } - var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 return writer; } } @@ -32180,7 +33629,7 @@ var ts; if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -32230,9 +33679,15 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, - visitedSymbols: undefined, + visitedTypes: undefined, + symbolDepth: undefined, inferTypeParameters: undefined, approximateLength: 0 }; @@ -32256,85 +33711,92 @@ var ts; } if (type.flags & 1 /* Any */) { context.approximateLength += 3; - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } if (type.flags & 2 /* Unknown */) { - return ts.createKeywordTypeNode(142 /* UnknownKeyword */); + return ts.createKeywordTypeNode(143 /* UnknownKeyword */); } if (type.flags & 4 /* String */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(137 /* StringKeyword */); + return ts.createKeywordTypeNode(138 /* StringKeyword */); } if (type.flags & 8 /* Number */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(134 /* NumberKeyword */); + return ts.createKeywordTypeNode(135 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return ts.createKeywordTypeNode(146 /* BigIntKeyword */); } if (type.flags & 16 /* Boolean */) { context.approximateLength += 7; - return ts.createKeywordTypeNode(122 /* BooleanKeyword */); + return ts.createKeywordTypeNode(123 /* BooleanKeyword */); } - if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { + if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined)); + return enumLiteralName; } - if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - context.approximateLength += ts.symbolName(type.symbol).length; - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + if (type.flags & 1056 /* EnumLike */) { + return symbolToTypeNode(type.symbol, context, 67897832 /* Type */); } - if (type.flags & 64 /* StringLiteral */) { + if (type.flags & 128 /* StringLiteral */) { context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & 128 /* NumberLiteral */) { + if (type.flags & 256 /* NumberLiteral */) { context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } - if (type.flags & 256 /* BooleanLiteral */) { + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1; + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 512 /* BooleanLiteral */) { context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 2048 /* UniqueESSymbol */) { + if (type.flags & 8192 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } context.approximateLength += 13; - return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); + return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */)); } - if (type.flags & 4096 /* Void */) { + if (type.flags & 16384 /* Void */) { context.approximateLength += 4; - return ts.createKeywordTypeNode(105 /* VoidKeyword */); + return ts.createKeywordTypeNode(106 /* VoidKeyword */); } - if (type.flags & 8192 /* Undefined */) { + if (type.flags & 32768 /* Undefined */) { context.approximateLength += 9; - return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + return ts.createKeywordTypeNode(141 /* UndefinedKeyword */); } - if (type.flags & 16384 /* Null */) { + if (type.flags & 65536 /* Null */) { context.approximateLength += 4; - return ts.createKeywordTypeNode(95 /* NullKeyword */); + return ts.createKeywordTypeNode(96 /* NullKeyword */); } - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { context.approximateLength += 5; - return ts.createKeywordTypeNode(131 /* NeverKeyword */); + return ts.createKeywordTypeNode(132 /* NeverKeyword */); } - if (type.flags & 1024 /* ESSymbol */) { + if (type.flags & 4096 /* ESSymbol */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(138 /* SymbolKeyword */); + return ts.createKeywordTypeNode(139 /* SymbolKeyword */); } - if (type.flags & 16777216 /* NonPrimitive */) { + if (type.flags & 67108864 /* NonPrimitive */) { context.approximateLength += 6; - return ts.createKeywordTypeNode(135 /* ObjectKeyword */); + return ts.createKeywordTypeNode(136 /* ObjectKeyword */); } - if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { + if (type.flags & 262144 /* TypeParameter */ && type.isThisType) { if (context.flags & 4194304 /* InObjectTypeLiteral */) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; @@ -32348,16 +33810,16 @@ var ts; } var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); return typeReferenceToTypeNode(type); } - if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && - type.flags & 65536 /* TypeParameter */ && + type.flags & 262144 /* TypeParameter */ && ts.length(type.symbol.declarations) && ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && @@ -32368,20 +33830,23 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } - if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { - var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -32392,23 +33857,23 @@ var ts; } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & 1048576 /* Index */) { + if (type.flags & 4194304 /* Index */) { var indexedType = type.type; context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 2097152 /* IndexedAccess */) { + if (type.flags & 8388608 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } - if (type.flags & 4194304 /* Conditional */) { + if (type.flags & 16777216 /* Conditional */) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); var saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; @@ -32419,12 +33884,12 @@ var ts; context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } - if (type.flags & 8388608 /* Substitution */) { + if (type.flags & 33554432 /* Substitution */) { return typeToTypeNodeHelper(type.typeVariable, context); } return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 131072 /* Object */)); + ts.Debug.assert(!!(type.flags & 524288 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; var appropriateConstraintTypeNode; @@ -32443,43 +33908,52 @@ var ts; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { + var typeId = "" + type.id; var symbol = type.symbol; var id; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects - else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } - else if (context.visitedSymbols && context.visitedSymbols.has(id)) { + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { - context.approximateLength += 3; - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return createElidedInformationPlaceholder(context); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.visitedSymbols) { - context.visitedSymbols = ts.createMap(); + if (!context.visitedTypes) { + context.visitedTypes = ts.createMap(); } - context.visitedSymbols.set(id, true); + if (!context.symbolDepth) { + context.symbolDepth = ts.createMap(); + } + var depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); var result = createTypeNodeFromObjectType(type); - context.visitedSymbols.delete(id); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); return result; } } @@ -32493,11 +33967,11 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 277 /* SourceFile */ || declaration.parent.kind === 243 /* ModuleBlock */; + return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } @@ -32514,12 +33988,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 163 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 164 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context); return signatureNode; } } @@ -32546,8 +34020,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32586,7 +34060,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32599,7 +34073,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32651,17 +34125,22 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 158 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 159 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ? - createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : - resolvedType.stringIndexInfo; - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context)); + var indexSignature = void 0; + if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context); + } + typeElements.push(indexSignature); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); @@ -32692,31 +34171,34 @@ var ts; return typeElements.length ? typeElements : undefined; } } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; if (propertySymbol.valueDeclaration) { @@ -32728,10 +34210,16 @@ var ts; } else { var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = void 0; + if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */); + } context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; } @@ -32782,7 +34270,7 @@ var ts; } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 137 /* StringKeyword */ : 134 /* NumberKeyword */); + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -32795,7 +34283,7 @@ var ts; } context.approximateLength += (name.length + 4); return ts.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { var typeParameters; @@ -32806,7 +34294,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -32825,18 +34313,18 @@ var ts; returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } if (context.flags & 256 /* SuppressAnyReturnType */) { - if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) { returnTypeNode = undefined; } } else if (!returnTypeNode) { - returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */); } context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32847,7 +34335,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32859,9 +34347,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -32870,16 +34358,16 @@ var ts; var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; - var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - parameterDeclaration.name.kind === 146 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; - var questionToken = isOptional ? ts.createToken(55 /* QuestionToken */) : undefined; + var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); @@ -32888,21 +34376,34 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 184 /* BindingElement */) { + if (clone.kind === 186 /* BindingElement */) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32913,13 +34414,22 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + var parentSpecifiers; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); - if (ts.length(parents)) { - for (var _i = 0, _a = parents; _i < _a.length; _i++) { - var parent = _a[_i]; + var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents_1)) { + parentSpecifiers = parents_1.map(function (symbol) { + return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined; + }); + var indices = parents_1.map(function (_, i) { return i; }); + indices.sort(sortByBestName); + var sortedParents = indices.map(function (i) { return parents_1[i]; }); + for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) { + var parent = sortedParents_1[_i]; var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); @@ -32942,6 +34452,24 @@ var ts; } return [symbol]; } + function sortByBestName(a, b) { + var specifierA = parentSpecifiers[a]; + var specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + var isBRelative = ts.pathIsRelative(specifierB); + if (ts.pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } } } function typeParametersToTypeParameterDeclarations(symbol, context) { @@ -32979,7 +34507,7 @@ var ts; return top; } function getSpecifierForModuleSymbol(symbol, context) { - var file = ts.getDeclarationOfKind(symbol, 277 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -33009,7 +34537,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33017,12 +34552,20 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); var specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); @@ -33116,6 +34659,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33156,7 +34702,7 @@ var ts; if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { - var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); @@ -33169,12 +34715,12 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 24576 /* Nullable */)) { - if (t.flags & (256 /* BooleanLiteral */ | 512 /* EnumLiteral */)) { - var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 262144 /* Union */) { + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) { + var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 1048576 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33184,9 +34730,9 @@ var ts; result.push(t); } } - if (flags & 16384 /* Null */) + if (flags & 65536 /* Null */) result.push(nullType); - if (flags & 8192 /* Undefined */) + if (flags & 32768 /* Undefined */) result.push(undefinedType); return result || types; } @@ -33201,8 +34747,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 175 /* ParenthesizedType */; }); - if (node.kind === 240 /* TypeAliasDeclaration */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; }); + if (node.kind === 242 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -33210,11 +34756,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 243 /* ModuleBlock */ && + node.parent.kind === 245 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); } /** * Gets a human-readable name for a symbol. @@ -33237,27 +34783,30 @@ var ts; var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { + if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { + return ts.symbolName(symbol); + } return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 235 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 207 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var nameType = symbol.nameType; if (nameType) { - if (nameType.flags & 64 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; } - if (nameType && nameType.flags & 2048 /* UniqueESSymbol */) { + if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; } } @@ -33274,27 +34823,27 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 295 /* JSDocCallbackTag */: - case 302 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 237 /* FunctionDeclaration */: - case 241 /* EnumDeclaration */: - case 246 /* ImportEqualsDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + case 243 /* EnumDeclaration */: + case 248 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -33302,53 +34851,53 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 246 /* ImportEqualsDeclaration */ && parent.kind !== 277 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 155 /* Constructor */: - case 159 /* ConstructSignature */: - case 158 /* CallSignature */: - case 160 /* IndexSignature */: - case 149 /* Parameter */: - case 243 /* ModuleBlock */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 166 /* TypeLiteral */: - case 162 /* TypeReference */: - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 175 /* ParenthesizedType */: + case 157 /* Constructor */: + case 161 /* ConstructSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 151 /* Parameter */: + case 245 /* ModuleBlock */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 164 /* TypeReference */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 177 /* 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 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: return false; // Type parameters are always visible - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: // Source file and namespace export are always visible - case 277 /* SourceFile */: - case 245 /* NamespaceExportDeclaration */: + case 279 /* SourceFile */: + case 247 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return false; default: return false; @@ -33357,11 +34906,11 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + if (node.parent && node.parent.kind === 254 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + else if (node.parent.kind === 257 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33382,7 +34931,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33431,6 +34980,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33439,6 +34990,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33452,12 +35005,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 235 /* VariableDeclaration */: - case 236 /* VariableDeclarationList */: - case 251 /* ImportSpecifier */: - case 250 /* NamedImports */: - case 249 /* NamespaceImport */: - case 248 /* ImportClause */: + case 237 /* VariableDeclaration */: + case 238 /* VariableDeclarationList */: + case 253 /* ImportSpecifier */: + case 252 /* NamedImports */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: return false; default: return true; @@ -33487,28 +35040,36 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); + return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); - if (source.flags & 32768 /* Never */) { + source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); + if (source.flags & 131072 /* Never */) { return emptyObjectType; } - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } - var members = ts.createSymbolTable(); - var names = ts.createUnderscoreEscapedMap(); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var name = properties_2[_i]; - names.set(ts.getTextOfPropertyName(name), true); + var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + var pickTypeAlias = getGlobalPickSymbol(); + var excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - if (!names.has(prop.escapedName) + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getNonReadonlySymbol(prop)); + members.set(prop.escapedName, getSpreadSymbol(prop)); } } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); @@ -33532,8 +35093,12 @@ var ts; if (isTypeAny(parentType)) { return parentType; } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } var type; - if (pattern.kind === 182 /* ObjectBindingPattern */) { + if (pattern.kind === 184 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -33551,51 +35116,9 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - var isLate = isLateBindableName(name); - var isWellKnown = ts.isComputedPropertyName(name) && ts.isWellKnownSymbolSyntactically(name.expression); - if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { - var exprType = checkExpression(name.expression); - if (isTypeAssignableToKind(exprType, 3072 /* ESSymbolLike */)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); - } - return anyType; - } - var indexerType = isTypeAssignableToKind(exprType, 168 /* NumberLike */) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); - if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(parentType, 1 /* Number */)) { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType)); - } - } - return indexerType || 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. - var nameType = isLate ? checkComputedPropertyName(name) : undefined; - var text = isLate ? getLateBoundNameFromType(nameType) : - isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : - ts.getTextOfPropertyName(name); - // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation - if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { - parentType = getNonNullableType(parentType); - } - if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - if (noImplicitAny) { - error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType)); - } - return anyType; - } - var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); - type = declaredType && getFlowTypeOfReference(declaration, declaredType) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || - getIndexTypeOfType(parentType, 0 /* String */); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return errorType; - } + var exprType = getLiteralTypeFromPropertyName(name); + var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); } } else { @@ -33603,27 +35126,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33631,11 +35154,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { - type = getTypeWithFacts(type, 131072 /* NEUndefined */); + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) { + type = getTypeWithFacts(type, 524288 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33647,11 +35170,11 @@ var ts; } function isNullOrUndefined(node) { var expr = ts.skipParentheses(node); - return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 185 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -33661,11 +35184,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 224 /* ForInStatement */) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (65536 /* TypeParameter */ | 1048576 /* Index */) ? getExtractStringType(indexType) : stringType; + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) { + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 225 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* 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, @@ -33683,8 +35206,8 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && + declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no @@ -33698,11 +35221,11 @@ var ts; return autoArrayType; } } - if (declaration.kind === 149 /* Parameter */) { + if (declaration.kind === 151 /* 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 === 157 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 156 /* GetAccessor */); + if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -33714,16 +35237,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33743,16 +35272,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33760,14 +35289,14 @@ var ts; var types; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = ts.isBinaryExpression(declaration) ? declaration : + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33775,9 +35304,11 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!ts.isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33785,26 +35316,24 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; } } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(24576 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33823,7 +35352,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33837,10 +35366,35 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (ts.isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + var objectLitType = checkExpressionCached(expression.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + var getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + var getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + var setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + var setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); - if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + if (type.flags & 524288 /* Object */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33864,9 +35418,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33875,9 +35427,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 155 /* Constructor */ || - thisContainer.kind === 237 /* FunctionDeclaration */ || - (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 157 /* Constructor */ || + thisContainer.kind === 239 /* FunctionDeclaration */ || + (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -33889,8 +35441,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33898,7 +35450,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33912,8 +35464,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33952,7 +35504,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var hasRestElement = !!(lastElement && lastElement.kind === 184 /* BindingElement */ && lastElement.dotDotDotToken); + var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken); if (elements.length === 0 || elements.length === 1 && hasRestElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -33975,7 +35527,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 182 /* ObjectBindingPattern */ + return pattern.kind === 184 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -33997,7 +35549,7 @@ var ts; reportErrorsFromWidening(declaration, type); } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & 2048 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } return getWidenedType(type); @@ -34005,16 +35557,16 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 149 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -34050,19 +35602,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 524288 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } - if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + if (declaration.kind === 254 /* ExportAssignment */) { + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && - (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + if (ts.isInJSFile(declaration) && + (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34076,7 +35635,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34098,6 +35657,14 @@ var ts; || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (ts.isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (ts.isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } @@ -34108,7 +35675,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 156 /* GetAccessor */) { + if (accessor.kind === 158 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -34135,9 +35702,9 @@ var ts; return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); } function getTypeOfAccessorsWorker(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */); + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34165,14 +35732,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34181,7 +35746,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* 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)); } } @@ -34189,13 +35754,13 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 2162688 /* TypeVariable */ ? baseConstructorType : undefined; + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34221,9 +35786,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 202 /* BinaryExpression */ || - declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + else if (declaration.kind === 204 /* BinaryExpression */ || + declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) { + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34232,11 +35797,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34261,7 +35826,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34270,22 +35835,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34342,7 +35899,7 @@ var ts; var target = getTargetType(type); return target === checkBase || ts.some(getBaseTypes(target), check); } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return ts.some(type.types, check); } return false; @@ -34366,35 +35923,35 @@ var ts; return undefined; } switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 239 /* InterfaceDeclaration */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 153 /* MethodSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 287 /* JSDocFunctionType */: - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTemplateTag */: - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: - case 179 /* MappedType */: - case 173 /* ConditionalType */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 241 /* InterfaceDeclaration */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 155 /* MethodSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 289 /* JSDocFunctionType */: + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 242 /* TypeAliasDeclaration */: + case 303 /* JSDocTemplateTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: + case 181 /* MappedType */: + case 175 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 179 /* MappedType */) { + if (node.kind === 181 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 173 /* ConditionalType */) { + else if (node.kind === 175 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */ || node.kind === 239 /* InterfaceDeclaration */) && + (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } @@ -34402,7 +35959,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, 239 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -34411,9 +35968,9 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 239 /* InterfaceDeclaration */ || - node.kind === 238 /* ClassDeclaration */ || - node.kind === 207 /* ClassExpression */ || + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 240 /* ClassDeclaration */ || + node.kind === 209 /* ClassExpression */ || ts.isTypeAlias(node)) { var declaration = node; result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); @@ -34440,27 +35997,24 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { return true; } - if (type.flags & 2162688 /* TypeVariable */) { + if (type.flags & 8650752 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34486,7 +36040,7 @@ var ts; ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag checkExpression(extended.expression); } - if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */)) { + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -34496,7 +36050,18 @@ var ts; return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(baseConstructorType); + var ctorReturn = unknownType; + if (constraint) { + var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } return type.resolvedBaseConstructorType = errorType; } type.resolvedBaseConstructorType = baseConstructorType; @@ -34525,13 +36090,15 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 1 /* Any */))) { + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? 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 @@ -34542,8 +36109,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34560,7 +36127,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { @@ -34590,14 +36157,14 @@ var ts; // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return !!(type.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 524288 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -34616,7 +36183,7 @@ var ts; } } else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -34633,7 +36200,7 @@ var ts; function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 239 /* InterfaceDeclaration */) { + if (declaration.kind === 241 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -34642,7 +36209,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34674,7 +36241,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536 /* TypeParameter */); + type.thisType = createType(262144 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -34691,7 +36258,7 @@ var ts; return errorType; } var declaration = ts.find(symbol.declarations, function (d) { - return ts.isJSDocTypeAlias(d) || d.kind === 240 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */; }); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. @@ -34715,10 +36282,10 @@ var ts; return links.declaredType; } function isStringConcatExpression(expr) { - if (expr.kind === 9 /* StringLiteral */) { + if (expr.kind === 10 /* StringLiteral */) { return true; } - else if (expr.kind === 202 /* BinaryExpression */) { + else if (expr.kind === 204 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -34729,15 +36296,15 @@ var ts; return !(member.flags & 4194304 /* Ambient */); } switch (expr.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return true; - case 200 /* PrefixUnaryExpression */: - return expr.operator === 38 /* MinusToken */ && + case 202 /* PrefixUnaryExpression */: + return expr.operator === 39 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -34751,10 +36318,10 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241 /* EnumDeclaration */) { + if (declaration.kind === 243 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) { return links.enumKind = 1 /* Literal */; } if (!isLiteralEnumMember(member)) { @@ -34766,7 +36333,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -34778,19 +36345,19 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 241 /* EnumDeclaration */) { + if (declaration.kind === 243 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); - if (enumType_1.flags & 262144 /* Union */) { - enumType_1.flags |= 512 /* EnumLiteral */; + if (enumType_1.flags & 1048576 /* Union */) { + enumType_1.flags |= 1024 /* EnumLiteral */; enumType_1.symbol = symbol; } return links.declaredType = enumType_1; @@ -34813,7 +36380,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(65536 /* TypeParameter */); + var type = createType(262144 /* TypeParameter */); type.symbol = symbol; links.declaredType = type; } @@ -34857,22 +36424,23 @@ var ts; */ function isThislessType(node) { switch (node.kind) { - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 135 /* ObjectKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: - case 180 /* LiteralType */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 139 /* SymbolKeyword */: + case 136 /* ObjectKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: + case 182 /* LiteralType */: return true; - case 167 /* ArrayType */: + case 169 /* ArrayType */: return isThislessType(node.elementType); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -34898,7 +36466,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 155 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -34914,12 +36482,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -34963,7 +36531,7 @@ var ts; * Indicates whether a type can be used as a late-bound name. */ function isTypeUsableAsLateBoundName(type) { - return !!(type.flags & 2240 /* StringOrNumberLiteralOrUnique */); + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); } /** * Indicates whether a declaration name is definitely late-bindable. @@ -35006,10 +36574,10 @@ var ts; * Gets the symbolic name for a late-bound member from its type. */ function getLateBoundNameFromType(type) { - if (type.flags & 2048 /* UniqueESSymbol */) { + if (type.flags & 8192 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35029,7 +36597,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35174,7 +36742,7 @@ var ts; return needApparentType ? getApparentType(ref) : ref; } } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } return needApparentType ? getApparentType(type) : type; @@ -35283,7 +36851,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35303,7 +36871,7 @@ var ts; function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { return s; } } @@ -35337,8 +36905,7 @@ var ts; // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional // parameters and may differ in return types. When signatures differ in return types, the resulting return // type is the union of the constituent return types. - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + function getUnionSignatures(signatureLists) { var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { @@ -35384,8 +36951,8 @@ var ts; 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 callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -35420,7 +36987,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35443,7 +37010,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35481,7 +37048,7 @@ var ts; if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 2162688 /* TypeVariable */)) { + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -35497,6 +37064,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35514,7 +37082,7 @@ var ts; var modifiers = getMappedTypeModifiers(type.mappedType); var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; - var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; @@ -35524,6 +37092,7 @@ var ts; inferredProp.nameType = prop.nameType; inferredProp.propertyType = getTypeOfSymbol(prop); inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -35542,12 +37111,12 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateModifiers = getMappedTypeModifiers(type); - var include = keyofStringsOnly ? 64 /* StringLiteral */ : 2240 /* StringOrNumberLiteralOrUnique */; + var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); @@ -35557,11 +37126,9 @@ var ts; } } else { - // First, if the constraint type is a type parameter, obtain the base constraint. Then, - // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 14745600 /* InstantiableNonPrimitive */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 1048576 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); @@ -35573,7 +37140,7 @@ var ts; var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. - if (t.flags & 2240 /* StringOrNumberLiteralOrUnique */) { + if (t.flags & 8576 /* StringOrNumberLiteralOrUnique */) { var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || @@ -35585,7 +37152,7 @@ var ts; // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks // mode, if the underlying property is optional we remove 'undefined' from the type. prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; @@ -35608,7 +37175,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35621,8 +37188,8 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 177 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; + return constraintDeclaration.kind === 179 /* TypeOperator */ && + constraintDeclaration.operator === 129 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { @@ -35638,16 +37205,16 @@ var ts; // the modifiers type is T. Otherwise, the modifiers type is {}. var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 1048576 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } function getMappedTypeModifiers(type) { var declaration = type.declaration; - return (declaration.readonlyToken ? declaration.readonlyToken.kind === 38 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | - (declaration.questionToken ? declaration.questionToken.kind === 38 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | + (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); } function getMappedTypeOptionality(type) { var modifiers = getMappedTypeModifiers(type); @@ -35666,7 +37233,7 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { if (type.objectFlags & 4 /* Reference */) { resolveTypeReferenceMembers(type); } @@ -35683,10 +37250,10 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 262144 /* Union */) { + else if (type.flags & 1048576 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -35694,7 +37261,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; @@ -35703,7 +37270,7 @@ var ts; * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -35727,7 +37294,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { break; } } @@ -35737,12 +37304,13 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 786432 /* UnionOrIntersection */ ? + return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { - return obj.properties.some(function (property) { + var list = obj.properties; + return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); @@ -35750,7 +37318,7 @@ var ts; } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 262144 /* Union */)) { + if (!(unionType.flags & 1048576 /* Union */)) { return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); @@ -35769,24 +37337,33 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : - type.flags & 2097152 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : - type.flags & 4194304 /* Conditional */ ? getConstraintOfConditionalType(type) : + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { var rootTrueType = type.root.trueType; - var rootTrueConstraint = rootTrueType.flags & 8388608 /* Substitution */ ? rootTrueType.substitute : rootTrueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); } return type.resolvedDefaultConstraint; @@ -35798,11 +37375,12 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); - if (!(instantiated.flags & 32768 /* Never */)) { + if (!(instantiated.flags & 131072 /* Never */)) { return instantiated; } } @@ -35817,23 +37395,23 @@ var ts; var hasDisjointDomainType = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 15794176 /* Instantiable */) { + if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). var constraint = getConstraintOfType(t); - while (constraint && constraint.flags & (65536 /* TypeParameter */ | 1048576 /* Index */ | 4194304 /* Conditional */)) { + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { constraint = getConstraintOfType(constraint); } if (constraint) { // A constraint that isn't a union type implies that the final type would be a non-union // type as well. Since non-union constraints are of no interest, we can exit here. - if (!(constraint.flags & 262144 /* Union */)) { + if (!(constraint.flags & 1048576 /* Union */)) { return undefined; } constraints = ts.append(constraints, constraint); } } - else if (t.flags & 16809468 /* DisjointDomains */) { + else if (t.flags & 67238908 /* DisjointDomains */) { hasDisjointDomainType = true; } } @@ -35845,7 +37423,7 @@ var ts; // intersection operation to reduce the union constraints. for (var _b = 0, _c = type.types; _b < _c.length; _b++) { var t = _c[_b]; - if (t.flags & 16809468 /* DisjointDomains */) { + if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } } @@ -35855,11 +37433,11 @@ var ts; return undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; + return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -35877,6 +37455,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35884,8 +37463,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35897,45 +37486,42 @@ var ts; return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { - if (t.flags & 65536 /* TypeParameter */) { + if (t.flags & 262144 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint); } - if (t.flags & 786432 /* UnionOrIntersection */) { + if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 262144 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 524288 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 1048576 /* Index */) { + if (t.flags & 4194304 /* Index */) { return keyofConstraintType; } - if (t.flags & 2097152 /* IndexedAccess */) { + if (t.flags & 8388608 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } - if (t.flags & 4194304 /* Conditional */) { + if (t.flags & 16777216 /* Conditional */) { var constraint = getConstraintOfConditionalType(t); return constraint && getBaseConstraint(constraint); } - if (t.flags & 8388608 /* Substitution */) { + if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35985,26 +37571,42 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 132 /* StringLike */ ? globalStringType : + t.flags & 296 /* NumberLike */ ? globalNumberType : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 528 /* BooleanLike */ ? globalBooleanType : + t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : + t.flags & 4194304 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var indexTypes; - var isUnion = containingType.flags & 262144 /* Union */; + var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; @@ -36029,10 +37631,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36117,27 +37719,31 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 917504 /* StructuredType */) { + if (type.flags & 3670016 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -36151,7 +37757,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 917504 /* StructuredType */) { + if (type.flags & 3670016 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -36205,12 +37811,12 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 286 /* JSDocOptionalType */ + node.type && node.type.kind === 288 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -36244,7 +37850,7 @@ var ts; return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -36269,30 +37875,32 @@ var ts; } function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { - if (!typeArguments) { - typeArguments = []; - } - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { - defaultType = anyType; - } - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - typeArguments.length = typeParameters.length; - } + if (!numTypeParameters) { + return []; } - return typeArguments; + var numTypeArguments = ts.length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + var result = typeArguments ? typeArguments.slice() : []; + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + for (var i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, result); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); @@ -36305,7 +37913,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36318,7 +37926,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36328,7 +37936,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 180 /* LiteralType */) { + if (type && type.kind === 182 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter @@ -36342,20 +37950,20 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 156 /* GetAccessor */ || declaration.kind === 157 /* SetAccessor */) && + if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) && !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 155 /* Constructor */ ? + var classType = declaration.kind === 157 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36386,7 +37994,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36409,13 +38017,13 @@ var ts; if (!node) return false; switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node.escapedText === "arguments" && ts.isExpressionNode(node); - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return node.name.kind === 147 /* ComputedPropertyName */ + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + return node.name.kind === 149 /* ComputedPropertyName */ && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -36473,7 +38081,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36490,7 +38098,7 @@ var ts; function createTypePredicateFromTypePredicateNode(node, func) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71 /* Identifier */) { + if (parameterName.kind === 72 /* Identifier */) { return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); } else { @@ -36500,7 +38108,7 @@ var ts; function getTypePredicateParameterIndex(parameterList, parameter) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { return i; } } @@ -36514,6 +38122,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36539,7 +38148,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 155 /* Constructor */) { + if (declaration.kind === 157 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -36549,12 +38158,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -36569,8 +38178,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36611,7 +38224,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36628,7 +38241,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 === 155 /* Constructor */ || signature.declaration.kind === 159 /* ConstructSignature */; // TODO: GH#18217 + var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217 var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -36642,7 +38255,7 @@ var ts; return symbol.members.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 134 /* NumberKeyword */ : 137 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -36669,7 +38282,7 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */); return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { @@ -36677,13 +38290,13 @@ var ts; if (typeParameter.symbol) { for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.parent.kind === 174 /* InferType */) { + if (declaration.parent.kind === 176 /* InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. var grandParent = declaration.parent.parent; - if (grandParent.kind === 162 /* TypeReference */) { + if (grandParent.kind === 164 /* TypeReference */) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -36708,7 +38321,7 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter // declaration, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 149 /* Parameter */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } } @@ -36732,7 +38345,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -36805,10 +38418,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36838,7 +38451,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36865,9 +38478,9 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -36893,14 +38506,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36908,7 +38535,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36917,16 +38544,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -36949,13 +38581,13 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { - var result = createType(8388608 /* Substitution */); + var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 168 /* TupleType */ && node.elementTypes.length === 1; + return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1; } function getImpliedConstraint(typeVariable, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : @@ -36964,9 +38596,9 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 289 /* JSDocComment */) { + while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 173 /* ConditionalType */ && node === parent.trueType) { + if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -36977,7 +38609,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */); + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -37035,23 +38667,23 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getNullableType(type, 16384 /* Null */) : type; + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37078,9 +38710,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 241 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 243 /* EnumDeclaration */: return declaration; } } @@ -37089,7 +38721,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 131072 /* Object */)) { + if (!(type.flags & 524288 /* Object */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } @@ -37100,10 +38732,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37131,6 +38763,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37157,12 +38792,21 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 } + function getGlobalExcludeSymbol() { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalPickSymbol() { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } + function getGlobalBigIntType(reportErrors) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType; + } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -37211,7 +38855,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(65536 /* TypeParameter */); + var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); if (i < maxLength) { var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); property.type = typeParameter; @@ -37233,7 +38877,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(65536 /* TypeParameter */); + type.thisType = createType(262144 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -37268,8 +38912,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var lastElement = ts.lastOrUndefined(node.elementTypes); - var restElement_1 = lastElement && lastElement.kind === 170 /* RestType */ ? lastElement : undefined; - var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 169 /* OptionalType */ && n !== restElement_1; }) + 1; + var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1; var elementTypes = ts.map(node.elementTypes, function (n) { var type = getTypeFromTypeNode(n); return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; @@ -37278,6 +38922,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37308,16 +38960,17 @@ var ts; var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 27072 /* Unit */ && combined & 27072 /* Unit */) { + if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) { return true; } combined |= t.flags; - if (combined & 24576 /* Nullable */ && combined & (131072 /* Object */ | 16777216 /* NonPrimitive */) || - combined & 16777216 /* NonPrimitive */ && combined & (16809468 /* DisjointDomains */ & ~16777216 /* NonPrimitive */) || - combined & 68 /* StringLike */ && combined & (16809468 /* DisjointDomains */ & ~68 /* StringLike */) || - combined & 168 /* NumberLike */ && combined & (16809468 /* DisjointDomains */ & ~168 /* NumberLike */) || - combined & 3072 /* ESSymbolLike */ && combined & (16809468 /* DisjointDomains */ & ~3072 /* ESSymbolLike */) || - combined & 12288 /* VoidLike */ && combined & (16809468 /* DisjointDomains */ & ~12288 /* VoidLike */)) { + if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) || + combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || + combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || + combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || + combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) || + combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || + combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) { return true; } } @@ -37325,20 +38978,18 @@ var ts; } function addTypeToUnion(typeSet, includes, type) { var flags = type.flags; - if (flags & 262144 /* Union */) { + if (flags & 1048576 /* Union */) { return addTypesToUnion(typeSet, includes, type.types); } // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are // another form of 'never' (in that they have an empty value domain). We could in theory turn // intersections of unit types into 'never' upon construction, but deferring the reduction makes it // easier to reason about their origin. - if (!(flags & 32768 /* Never */ || flags & 524288 /* Intersection */ && isEmptyIntersectionType(type))) { + if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { includes |= flags & ~939524096 /* ConstructionFlags */; - if (flags & 3 /* AnyOrUnknown */) { - if (type === wildcardType) - includes |= 268435456 /* Wildcard */; - } - else if (!strictNullChecks && flags & 24576 /* Nullable */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(flags & 134217728 /* ContainsWideningType */)) includes |= 134217728 /* NonWideningType */; } @@ -37346,10 +38997,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37364,15 +39012,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - 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 isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37386,11 +39025,11 @@ var ts; } function isSetOfLiteralsFromSameEnum(types) { var first = types[0]; - if (first.flags & 512 /* EnumLiteral */) { + if (first.flags & 1024 /* EnumLiteral */) { var firstEnum = getParentOfSymbol(first.symbol); for (var i = 1; i < types.length; i++) { var other = types[i]; - if (!(other.flags & 512 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { return false; } } @@ -37415,10 +39054,11 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || - t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37441,25 +39081,27 @@ var ts; } var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); - if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case 1 /* Literal */: + if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + neverType; + } } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { - removeRedundantLiteralTypes(typeSet, includes); - } - break; - case 2 /* Subtype */: - removeSubtypes(typeSet); - break; - } - if (typeSet.length === 0) { - return includes & 16384 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : - includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -37496,7 +39138,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -37506,10 +39148,11 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 24576 /* Nullable */); - type = createType(262144 /* Union */ | propagatedFlags | unionOfUnitTypes); + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(1048576 /* Union */ | propagatedFlags); unionTypes.set(id, type); type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; /* Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. @@ -37531,11 +39174,14 @@ var ts; } function addTypeToIntersection(typeSet, includes, type) { var flags = type.flags; - if (flags & 524288 /* Intersection */) { + if (flags & 2097152 /* Intersection */) { return addTypesToIntersection(typeSet, includes, type.types); } - if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { - includes |= 536870912 /* EmptyObject */; + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 536870912 /* EmptyObject */)) { + includes |= 536870912 /* EmptyObject */; + typeSet.push(type); + } } else { includes |= flags & ~939524096 /* ConstructionFlags */; @@ -37543,10 +39189,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37555,8 +39198,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37566,9 +39209,10 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 4 /* String */ && includes & 64 /* StringLiteral */ || - t.flags & 8 /* Number */ && includes & 128 /* NumberLiteral */ || - t.flags & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */; + var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37581,10 +39225,11 @@ var ts; for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { var u = unionTypes_1[_i]; if (!containsType(u.types, type)) { - var primitive = type.flags & 64 /* StringLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ ? numberType : - type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : - undefined; + var primitive = type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + undefined; if (!primitive || !containsType(u.types, primitive)) { return false; } @@ -37597,13 +39242,16 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; }); + var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + if (index < 0) { + return false; + } var i = index + 1; // Remove all but the first union of primitive types and collect them in // the unionTypes array. while (i < types.length) { var t = types[i]; - if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) { + if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -37632,7 +39280,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */); + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -37648,22 +39296,23 @@ var ts; function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); - if (includes & 32768 /* Never */) { + if (includes & 131072 /* Never */) { return neverType; } if (includes & 1 /* Any */) { return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; } - if (!strictNullChecks && includes & 24576 /* Nullable */) { - return includes & 8192 /* Undefined */ ? undefinedType : nullType; + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 32768 /* Undefined */ ? undefinedType : nullType; } - if (includes & 4 /* String */ && includes & 64 /* StringLiteral */ || - includes & 8 /* Number */ && includes & 128 /* NumberLiteral */ || - includes & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */) { + if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || + includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || + includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 536870912 /* EmptyObject */ && !(includes & 131072 /* Object */)) { - typeSet.push(emptyObjectType); + if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { return unknownType; @@ -37671,8 +39320,8 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - if (includes & 262144 /* Union */) { - if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) { + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -37680,15 +39329,15 @@ var ts; } // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. - var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 262144 /* Union */) !== 0; }); + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; }); var unionType = typeSet[unionIndex_1]; return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 24576 /* Nullable */); - type = createType(524288 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); + type = createType(2097152 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. @@ -37705,7 +39354,7 @@ var ts; return links.resolvedType; } function createIndexType(type, stringsOnly) { - var result = createType(1048576 /* Index */); + var result = createType(4194304 /* Index */); result.type = type; result.stringsOnly = stringsOnly; return result; @@ -37715,14 +39364,22 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } - function getLiteralTypeFromPropertyName(prop, include) { + function getLiteralTypeFromPropertyName(name) { + return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + function getBigIntLiteralType(node) { + return getLiteralType({ + negative: false, + base10Value: ts.parsePseudoBigInt(node.text) + }); + } + function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) : - name && name.kind === 147 /* ComputedPropertyName */ && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : - getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); } if (type && type.flags & include) { return type; @@ -37730,8 +39387,8 @@ var ts; } return neverType; } - function getLiteralTypeFromPropertyNames(type, include) { - return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromPropertyName(t, include); })); + function getLiteralTypeFromProperties(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); } function getNonEnumNumberIndexInfo(type) { var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); @@ -37739,16 +39396,16 @@ var ts; } function getIndexType(type, stringsOnly) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } - return type.flags & 262144 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - type.flags & 524288 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : - maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : type === wildcardType ? wildcardType : type.flags & 1 /* Any */ ? keyofConstraintType : - stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */) : - getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, 2048 /* UniqueESSymbol */)]) : - getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */ | 2048 /* UniqueESSymbol */)]) : - getLiteralTypeFromPropertyNames(type, 2240 /* StringOrNumberLiteralOrUnique */); + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) : + getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */); } function getExtractStringType(type) { if (keyofStringsOnly) { @@ -37759,17 +39416,17 @@ var ts; } function getIndexTypeOrString(type) { var indexType = getExtractStringType(getIndexType(type)); - return indexType.flags & 32768 /* Never */ ? stringType : indexType; + return indexType.flags & 131072 /* Never */ ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { switch (node.operator) { - case 128 /* KeyOfKeyword */: + case 129 /* KeyOfKeyword */: links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); break; - case 141 /* UniqueKeyword */: - links.resolvedType = node.type.kind === 138 /* SymbolKeyword */ + case 142 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 139 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) : errorType; break; @@ -37778,7 +39435,7 @@ var ts; return links.resolvedType; // TODO: GH#18217 } function createIndexedAccessType(objectType, indexType) { - var type = createType(2097152 /* IndexedAccess */); + var type = createType(8388608 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; return type; @@ -37799,56 +39456,63 @@ var ts; if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { return true; } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { return ts.every(type.types, isJSLiteralType); } - if (type.flags & 524288 /* Intersection */) { + if (type.flags & 2097152 /* Intersection */) { return ts.some(type.types, isJSLiteralType); } - if (type.flags & 15794176 /* Instantiable */) { + if (type.flags & 63176704 /* Instantiable */) { return isJSLiteralType(getResolvedBaseConstraint(type)); } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - undefined; + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { + var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) + : accessNode && ts.isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? ts.getPropertyNameForPropertyNameNode(accessNode) + : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } - if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { - if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) { + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { return objectType; } - var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { - var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = getIndexNodeForAccessExpression(accessNode); error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { @@ -37856,7 +39520,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768 /* Never */) { + if (indexType.flags & 131072 /* Never */) { return neverType; } if (isJSLiteralType(objectType)) { @@ -37882,15 +39546,15 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { return anyType; } if (accessNode) { - var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; - if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { + var indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { @@ -37900,30 +39564,38 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 190 /* ElementAccessExpression */ + ? accessNode.argumentExpression + : accessNode.kind === 180 /* IndexedAccessType */ + ? accessNode.indexType + : accessNode.kind === 149 /* ComputedPropertyName */ + ? accessNode.expression + : accessNode; } function isGenericObjectType(type) { - return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); } function isGenericIndexType(type) { - return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); - } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); } function getSimplifiedType(type) { - return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; + } + function distributeIndexOverObjectType(objectType, indexType) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 1048576 /* Union */) { + return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); + } } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // the type itself if no transformation is possible. @@ -37935,37 +39607,20 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); - } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 1048576 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 63176704 /* Instantiable */)) { + var simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +39628,7 @@ var ts; if (isGenericMappedType(objectType)) { return type.simplified = substituteIndexedMappedType(objectType, type); } - if (objectType.flags & 65536 /* TypeParameter */) { + if (objectType.flags & 262144 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); @@ -37986,7 +39641,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -37995,7 +39651,7 @@ var ts; // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 188 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } @@ -38011,19 +39667,30 @@ var ts; // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38031,7 +39698,7 @@ var ts; var objectType = getTypeFromTypeNode(node.objectType); var indexType = getTypeFromTypeNode(node.indexType); var resolved = getIndexedAccessType(objectType, indexType, node); - links.resolvedType = resolved.flags & 2097152 /* IndexedAccess */ && + links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && resolved.objectType === objectType && resolved.indexType === indexType ? getConstrainedTypeVariable(resolved, node) : resolved; @@ -38053,7 +39720,7 @@ var ts; return links.resolvedType; } function getActualTypeVariable(type) { - return type.flags & 8388608 /* Substitution */ ? type.typeVariable : type; + return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); @@ -38064,7 +39731,7 @@ var ts; // If this is a distributive conditional type and the check type is generic we need to defer // resolution of the conditional type such that a later instantiation will properly distribute // over union types. - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 15794176 /* Instantiable */); + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); @@ -38103,7 +39770,7 @@ var ts; } // Return a deferred type for a check that is neither definitely true nor definitely false var erasedCheckType = getActualTypeVariable(checkType); - var result = createType(4194304 /* Conditional */); + var result = createType(16777216 /* Conditional */); result.root = root; result.checkType = erasedCheckType; result.extendsType = extendsType; @@ -38135,7 +39802,7 @@ var ts; return true; } while (node) { - if (node.kind === 173 /* ConditionalType */) { + if (node.kind === 175 /* ConditionalType */) { if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { return true; } @@ -38158,7 +39825,7 @@ var ts; extendsType: getTypeFromTypeNode(node.extendsType), trueType: getTypeFromTypeNode(node.trueType), falseType: getTypeFromTypeNode(node.falseType), - isDistributive: !!(checkType.flags & 65536 /* TypeParameter */), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, @@ -38201,7 +39868,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38231,7 +39898,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38245,7 +39912,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38278,6 +39945,9 @@ var ts; function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } /** * Since the source of spread types are object literals, which are not binary, * this function should be called in a left folding style, with left = previous result of getSpreadType @@ -38290,21 +39960,37 @@ var ts; if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { return unknownType; } - if (left.flags & 32768 /* Never */) { + if (left.flags & 131072 /* Never */) { return right; } - if (right.flags & 32768 /* Never */) { + if (right.flags & 131072 /* Never */) { return left; } - if (left.flags & 262144 /* Union */) { + if (left.flags & 1048576 /* Union */) { return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); } - if (right.flags & 262144 /* Union */) { + if (right.flags & 1048576 /* Union */) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); } - if (right.flags & (272 /* BooleanLike */ | 168 /* NumberLike */ | 68 /* StringLike */ | 544 /* EnumLike */ | 16777216 /* NonPrimitive */ | 1048576 /* Index */)) { + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { return left; } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & 2097152 /* Intersection */) { + var types = left.types; + var lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); var stringIndexInfo; @@ -38324,7 +40010,7 @@ var ts; skippedPrivateMembers.set(rightProp.escapedName, true); } else if (isSpreadableProperty(rightProp)) { - members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { @@ -38339,7 +40025,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); var result = createSymbol(flags, leftProp.escapedName); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -38348,27 +40034,28 @@ var ts; } } else { - members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= typeFlags | 268435456 /* ContainsObjectLiteral */; - spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); + spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */) - ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) - : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable + return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { + function getSpreadSymbol(prop) { + var isReadonly = isReadonlySymbol(prop); + var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isReadonly && !isSetonlyAccessor) { return prop; } var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); var result = createSymbol(flags, prop.escapedName); - result.type = getTypeOfSymbol(prop); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); result.declarations = prop.declarations; result.nameType = prop.nameType; result.syntheticOrigin = prop; @@ -38387,10 +40074,11 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; + freshType.freshType = freshType; type.freshType = freshType; } return type.freshType; @@ -38398,21 +40086,27 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + return type.flags & 2944 /* Literal */ ? type.regularType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } + function isFreshLiteralType(type) { + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; + } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', // where NNN is the text representation of a numeric literal and SSS are the characters // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where // EEE is a unique id for the containing enum type. - var qualifier = typeof value === "number" ? "#" : "@"; - var key = enumId ? enumId + qualifier + value : qualifier + value; + var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value); var type = literalTypes.get(key); if (!type) { - var flags = (typeof value === "number" ? 128 /* NumberLiteral */ : 64 /* StringLiteral */) | (enumId ? 512 /* EnumLiteral */ : 0); + var flags = (typeof value === "number" ? 256 /* NumberLiteral */ : + typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) | + (enumId ? 1024 /* EnumLiteral */ : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; } return type; } @@ -38424,7 +40118,7 @@ var ts; return links.resolvedType; } function createUniqueESSymbolType(symbol) { - var type = createType(2048 /* UniqueESSymbol */); + var type = createType(8192 /* UniqueESSymbol */); type.symbol = symbol; return type; } @@ -38439,9 +40133,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 239 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) { if (!ts.hasModifier(container, 32 /* Static */) && - (container.kind !== 155 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -38457,87 +40151,89 @@ var ts; } function getTypeFromTypeNode(node) { switch (node.kind) { - case 119 /* AnyKeyword */: - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: + case 120 /* AnyKeyword */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: return anyType; - case 142 /* UnknownKeyword */: + case 143 /* UnknownKeyword */: return unknownType; - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: return stringType; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: return numberType; - case 122 /* BooleanKeyword */: + case 146 /* BigIntKeyword */: + return bigintType; + case 123 /* BooleanKeyword */: return booleanType; - case 138 /* SymbolKeyword */: + case 139 /* SymbolKeyword */: return esSymbolType; - case 105 /* VoidKeyword */: + case 106 /* VoidKeyword */: return voidType; - case 140 /* UndefinedKeyword */: + case 141 /* UndefinedKeyword */: return undefinedType; - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: return nullType; - case 131 /* NeverKeyword */: + case 132 /* NeverKeyword */: return neverType; - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; - case 176 /* ThisType */: - case 99 /* ThisKeyword */: + case 178 /* ThisType */: + case 100 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return getTypeFromTypeReference(node); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return booleanType; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return getTypeFromOptionalTypeNode(node); - case 171 /* UnionType */: + case 173 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 175 /* ParenthesizedType */: - case 170 /* RestType */: - case 285 /* JSDocNonNullableType */: - case 281 /* JSDocTypeExpression */: + case 177 /* ParenthesizedType */: + case 172 /* RestType */: + case 287 /* JSDocNonNullableType */: + case 283 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 166 /* TypeLiteral */: - case 290 /* JSDocTypeLiteral */: - case 287 /* JSDocFunctionType */: - case 291 /* JSDocSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 168 /* TypeLiteral */: + case 292 /* JSDocTypeLiteral */: + case 289 /* JSDocFunctionType */: + case 293 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 174 /* InferType */: + case 176 /* InferType */: return getTypeFromInferTypeNode(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode - case 71 /* Identifier */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 148 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -38604,7 +40300,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38618,10 +40314,10 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function wildcardMapper(type) { - return type.flags & 65536 /* TypeParameter */ ? wildcardType : type; + return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; } function cloneTypeParameter(typeParameter) { - var result = createType(65536 /* TypeParameter */); + var result = createType(262144 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -38667,7 +40363,7 @@ var ts; } function instantiateSymbol(symbol, mapper) { var links = getSymbolLinks(symbol); - if (links.type && !maybeTypeOfKind(links.type, 131072 /* Object */ | 15794176 /* Instantiable */)) { + if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { // If the type of the symbol is already resolved, and if that type could not possibly // be affected by instantiation, simply return the symbol itself. return symbol; @@ -38705,7 +40401,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38715,7 +40411,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38747,8 +40443,8 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 146 /* QualifiedName */ || - node.parent.kind === 162 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + return !(node.kind === 148 /* QualifiedName */ || + node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks @@ -38756,26 +40452,36 @@ var ts; // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 216 /* Block */ ? "quit" : n === container_3; })) { + if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) { return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { - case 176 /* ThisType */: + case 178 /* ThisType */: return !!tp.isThisType; - case 71 /* Identifier */: + case 72 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return true; } return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38785,30 +40491,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38825,13 +40535,19 @@ var ts; var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); var modifiers = getMappedTypeModifiers(type); return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38864,61 +40580,77 @@ var ts; if (root.isDistributive) { var checkType_1 = root.checkType; var instantiatedType = mapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & (262144 /* Union */ | 32768 /* Never */)) { + if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return mapper(type); + } + if (flags & 524288 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 2097152 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 33554432 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } function getWildcardInstantiation(type) { - return type.flags & (32764 /* Primitive */ | 3 /* AnyOrUnknown */ | 32768 /* Never */) ? type : + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); } function instantiateIndexInfo(info, mapper) { @@ -38927,34 +40659,34 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 202 /* BinaryExpression */: - return node.operatorToken.kind === 54 /* BarBarToken */ && + case 204 /* BinaryExpression */: + return node.operatorToken.kind === 55 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 266 /* JsxAttributes */: - return ts.some(node.properties, isContextSensitive); - case 265 /* JsxAttribute */: { + case 268 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); + case 267 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 268 /* JsxExpression */: { + case 270 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -38971,7 +40703,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 195 /* ArrowFunction */) { + if (node.kind !== 197 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -38984,14 +40716,14 @@ var ts; function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. var body = node.body; - return body.kind === 216 /* Block */ ? false : isContextSensitive(body); + return body.kind === 218 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); @@ -39002,7 +40734,7 @@ var ts; return result; } } - else if (type.flags & 524288 /* Intersection */) { + else if (type.flags & 2097152 /* Intersection */) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -39017,6 +40749,9 @@ var ts; function compareTypesAssignable(source, target) { return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } function isTypeSubtypeOf(source, target) { return isTypeRelatedTo(source, target, subtypeRelation); } @@ -39032,11 +40767,12 @@ var ts; // Note that this check ignores type parameters and only considers the // inheritance hierarchy. function isTypeDerivedFrom(source, target) { - return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : - target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : - source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39062,33 +40798,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { - case 268 /* JsxExpression */: - case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); - case 202 /* BinaryExpression */: + case 270 /* JsxExpression */: + case 195 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage); + case 204 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: - case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + case 59 /* EqualsToken */: + case 27 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage); } break; - case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); - case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); - case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + case 188 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation); + case 187 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation); + case 268 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target, relation); + case 197 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39097,15 +40898,17 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */) + continue; // Don't elaborate on indexes on generic variables + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39114,10 +40917,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39125,16 +40928,19 @@ var ts; var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; var issuedElaboration = false; if (!targetProp) { - var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39168,8 +40974,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39201,9 +41007,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39221,17 +41032,17 @@ var ts; prop = _a[_i]; if (ts.isSpreadAssignment(prop)) return [3 /*break*/, 7]; - type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), 2240 /* StringOrNumberLiteralOrUnique */); - if (!type || (type.flags & 32768 /* Never */)) { + type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 131072 /* Never */)) { return [3 /*break*/, 7]; } _b = prop.kind; switch (_b) { - case 157 /* SetAccessor */: return [3 /*break*/, 2]; - case 156 /* GetAccessor */: return [3 /*break*/, 2]; - case 154 /* MethodDeclaration */: return [3 /*break*/, 2]; - case 274 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 273 /* PropertyAssignment */: return [3 /*break*/, 4]; + case 159 /* SetAccessor */: return [3 /*break*/, 2]; + case 158 /* GetAccessor */: return [3 /*break*/, 2]; + case 156 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 275 /* PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -39252,8 +41063,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39283,14 +41094,15 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 154 /* MethodDeclaration */ && - kind !== 153 /* MethodSignature */ && kind !== 155 /* Constructor */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ && + kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -39308,11 +41120,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39324,7 +41136,7 @@ var ts; var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && - (getFalsyFlags(sourceType) & 24576 /* Nullable */) === (getFalsyFlags(targetType) & 24576 /* Nullable */); + (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); var related = callbacks ? // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : @@ -39338,13 +41150,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39416,12 +41228,15 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 131072 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 /* NonPrimitive */ ? true : - type.flags & 262144 /* Union */ ? ts.some(type.types, isEmptyObjectType) : - type.flags & 524288 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : + return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 67108864 /* NonPrimitive */ ? true : + type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : false; } + function isEmptyAnonymousObjectType(type) { + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type); + } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { if (sourceSymbol === targetSymbol) { return true; @@ -39458,43 +41273,45 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 3 /* AnyOrUnknown */ || s & 32768 /* Never */ || source === wildcardType) + if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType) return true; - if (t & 32768 /* Never */) + if (t & 131072 /* Never */) return false; - if (s & 68 /* StringLike */ && t & 4 /* String */) + if (s & 132 /* StringLike */ && t & 4 /* String */) return true; - if (s & 64 /* StringLiteral */ && s & 512 /* EnumLiteral */ && - t & 64 /* StringLiteral */ && !(t & 512 /* EnumLiteral */) && + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && + t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 168 /* NumberLike */ && t & 8 /* Number */) + if (s & 296 /* NumberLike */ && t & 8 /* Number */) return true; - if (s & 128 /* NumberLiteral */ && s & 512 /* EnumLiteral */ && - t & 128 /* NumberLiteral */ && !(t & 512 /* EnumLiteral */) && + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && + t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 272 /* BooleanLike */ && t & 16 /* Boolean */) + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) return true; - if (s & 3072 /* ESSymbolLike */ && t & 1024 /* ESSymbol */) + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) + return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) return true; if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 512 /* EnumLiteral */ && t & 512 /* EnumLiteral */) { - if (s & 262144 /* Union */ && t & 262144 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 448 /* Literal */ && t & 448 /* Literal */ && + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 8192 /* Undefined */ && (!strictNullChecks || t & (8192 /* Undefined */ | 4096 /* Void */))) + if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */))) return true; - if (s & 16384 /* Null */ && (!strictNullChecks || t & 16384 /* Null */)) + if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */)) return true; - if (s & 131072 /* Object */ && t & 16777216 /* NonPrimitive */) + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) return true; - if (s & 2048 /* UniqueESSymbol */ || t & 2048 /* UniqueESSymbol */) + if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) @@ -39502,30 +41319,30 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (8 /* Number */ | 128 /* NumberLiteral */) && !(s & 512 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 128 /* NumberLiteral */ && t & 512 /* EnumLiteral */)) + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; } return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(target)) { target = target.regularType; } if (source === target || - relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */) { + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */) { + if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) { return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); } return false; @@ -39545,6 +41362,7 @@ var ts; */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -39552,7 +41370,7 @@ var ts; var depth = 0; var expandingFlags = 0 /* None */; var overflow = false; - var isIntersectionConstituent = false; + var suppressNextError = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (overflow) { @@ -39579,15 +41397,27 @@ var ts; } } var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + } if (errorOutputContainer) { errorOutputContainer.error = diag; } diagnostics.add(diag); // TODO: GH#18217 } return result !== 0 /* False */; - function reportError(message, arg0, arg1, arg2) { + function reportError(message, arg0, arg1, arg2, arg3) { ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + function associateRelatedInfo(info) { + ts.Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } } function reportRelationError(message, source, target) { var sourceType = typeToString(source); @@ -39620,7 +41450,7 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 786432 /* UnionOrIntersection */)) { + if (!(type.flags & 3145728 /* UnionOrIntersection */)) { return false; } // at this point we know that this is union or intersection type possibly with nullable constituents. @@ -39628,7 +41458,7 @@ var ts; var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 24576 /* Nullable */) { + if (t.flags & 98304 /* Nullable */) { continue; } if (seenNonNullable) { @@ -39644,24 +41474,24 @@ var ts; * * Ternary.Maybe if they are related with assumptions of other relationships, or * * Ternary.False if they are not related. */ - function isRelatedTo(source, target, reportErrors, headMessage) { + function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(source)) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (isFreshLiteralType(target)) { target = target.regularType; } - if (source.flags & 8388608 /* Substitution */) { + if (source.flags & 33554432 /* Substitution */) { source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } - if (target.flags & 8388608 /* Substitution */) { + if (target.flags & 33554432 /* Substitution */) { target = target.typeVariable; } - if (source.flags & 2097152 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { source = getSimplifiedType(source); } - if (target.flags & 2097152 /* IndexedAccess */) { + if (target.flags & 8388608 /* IndexedAccess */) { target = getSimplifiedType(target); } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. @@ -39673,10 +41503,10 @@ var ts; // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" // when dealing with generics. // * We also don't deal with primitive source types, since we already halt elaboration below. - if (target.flags & 262144 /* Union */ && source.flags & 131072 /* Object */ && - target.types.length <= 3 && maybeTypeOfKind(target, 24576 /* Nullable */)) { - var nullStrippedTarget = extractTypesOfKind(target, ~24576 /* Nullable */); - if (!(nullStrippedTarget.flags & (262144 /* Union */ | 32768 /* Never */))) { + if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); + if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { target = nullStrippedTarget; } } @@ -39686,11 +41516,12 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (isObjectLiteralType(source) && source.flags & 33554432 /* FreshLiteral */) { - var discriminantType = target.flags & 262144 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) { + var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -39705,14 +41536,11 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isApparentIntersectionConstituent && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && - !hasCommonProperties(source, target)) { + !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); var constructs = getSignaturesOfType(source, 1 /* Construct */); @@ -39728,25 +41556,24 @@ var ts; } var result = 0 /* False */; var saveErrorInfo = errorInfo; - var saveIsIntersectionConstituent = isIntersectionConstituent; - isIntersectionConstituent = false; + var isIntersectionConstituent = !!isApparentIntersectionConstituent; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); } else { - if (target.flags & 262144 /* Union */) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */) && !(target.flags & 32764 /* Primitive */)); + if (target.flags & 1048576 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); } - else if (target.flags & 524288 /* Intersection */) { - isIntersectionConstituent = true; + else if (target.flags & 2097152 /* Intersection */) { + isIntersectionConstituent = true; // set here to affect the following trio of checks result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 524288 /* Intersection */) { + else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -39762,13 +41589,13 @@ var ts; // breaking the intersection apart. result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } - if (!result && (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - if (!result && source.flags & 524288 /* Intersection */) { + if (!result && source.flags & 2097152 /* Intersection */) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -39778,22 +41605,23 @@ var ts; // we need to check this constraint against a union on the target side. Also, given a type // variable V constrained to 'string | number', 'V & number' has a combined constraint of // 'string & number | number & number' which reduces to just 'number'. - var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 262144 /* Union */)); + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */)); if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 131072 /* Object */ && target.flags & 32764 /* Primitive */) { + var maybeSuppress = suppressNextError; + suppressNextError = false; + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 131072 /* Object */ && globalObjectType === source) { + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } - else if (ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && target.flags & 524288 /* Intersection */) { + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { var targetTypes = target.types; var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); @@ -39803,6 +41631,10 @@ var ts; return result; } } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } reportRelationError(headMessage, source, target); } return result; @@ -39810,49 +41642,23 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); + if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); } - if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { + if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { @@ -39862,17 +41668,18 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. if (!errorNode) return { value: ts.Debug.fail() }; - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { @@ -39901,13 +41708,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +41733,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 262144 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -39936,16 +41746,17 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; } function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { var sourceObjectFlags = ts.getObjectFlags(source); - if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 262144 /* Union */) { + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { return ts.find(unionTarget.types, function (target) { - if (target.flags & 131072 /* Object */) { + if (target.flags & 524288 /* Object */) { var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); if (overlapObjFlags & 4 /* Reference */) { return source.target === target.target; @@ -39963,39 +41774,33 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); - if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } + if (target.flags & 1048576 /* Union */) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; var targetTypes = target.types; for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); + var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); if (!related) { return 0 /* False */; } @@ -40005,7 +41810,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 262144 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -40030,9 +41835,10 @@ var ts; } return result; } - function typeArgumentsRelatedTo(source, target, variances, reportErrors) { - var sources = source.typeArguments || ts.emptyArray; - var targets = target.typeArguments || ts.emptyArray; + function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) { + if (sources === void 0) { sources = ts.emptyArray; } + if (targets === void 0) { targets = ts.emptyArray; } + if (variances === void 0) { variances = ts.emptyArray; } if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } @@ -40086,7 +41892,7 @@ var ts; // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function recursiveTypeRelatedTo(source, target, reportErrors) { + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { if (overflow) { return 0 /* False */; } @@ -40129,7 +41935,7 @@ var ts; expandingFlags |= 1 /* Source */; if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) expandingFlags |= 2 /* Target */; - var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -40152,13 +41958,57 @@ var ts; function getConstraintForRelation(type) { return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } - function structuredTypeRelatedTo(source, target, reportErrors) { + function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 524288 /* Object */)) { + if (flags & 4194304 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 8388608 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 16777216 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 33554432 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 65536 /* TypeParameter */) { - // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + var variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & 262144 /* TypeParameter */) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -40168,9 +42018,9 @@ var ts; } } } - else if (target.flags & 1048576 /* Index */) { + else if (target.flags & 4194304 /* Index */) { // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 1048576 /* Index */) { + if (source.flags & 4194304 /* Index */) { if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } @@ -40181,20 +42031,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } - else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (target.flags & 8388608 /* IndexedAccess */) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40203,23 +42058,24 @@ var ts; var template = getTemplateTypeFromMappedType(target); var modifiers = getMappedTypeModifiers(target); if (!(modifiers & 8 /* ExcludeOptional */)) { - if (template.flags & 2097152 /* IndexedAccess */ && template.objectType === source && + if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source && template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } } - if (source.flags & 2162688 /* TypeVariable */) { - if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + if (source.flags & 8650752 /* TypeVariable */) { + if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { // A type S[K] is related to a type T[J] if S is related to T and K is related to J. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { result &= isRelatedTo(source.indexType, target.indexType, reportErrors); @@ -40230,29 +42086,32 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 65536 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~16777216 /* NonPrimitive */))) { + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { errorInfo = saveErrorInfo; return result; } } - else { - var instantiated = getTypeWithThisArgument(constraint, source); - if (result = isRelatedTo(instantiated, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; } } - else if (source.flags & 1048576 /* Index */) { + else if (source.flags & 4194304 /* Index */) { if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { errorInfo = saveErrorInfo; return result; } } - else if (source.flags & 4194304 /* Conditional */) { - if (target.flags & 4194304 /* Conditional */) { + else if (source.flags & 16777216 /* Conditional */) { + if (target.flags & 16777216 /* Conditional */) { // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, // and Y1 is related to Y2. @@ -40285,13 +42144,33 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); - if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { + if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { return result; } // The type arguments did not relate appropriately, but it may be because we have no variance @@ -40318,36 +42197,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40370,10 +42239,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40386,7 +42255,24 @@ var ts; var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + var propName = symbolToString(unmatchedProperty); + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (ts.length(unmatchedProperty.declarations)) { + associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4); + } + else { + reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", ")); + } } return 0 /* False */; } @@ -40433,8 +42319,8 @@ var ts; } } var properties = getPropertiesOfObjectType(target); - for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { - var targetProp = properties_3[_b]; + for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) { + var targetProp = properties_2[_b]; if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { @@ -40504,35 +42390,8 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { + if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -40562,8 +42421,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40660,7 +42519,7 @@ var ts; continue; } // Skip over symbol-named members - if (prop.nameType && prop.nameType.flags & 2048 /* UniqueESSymbol */) { + if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) { continue; } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { @@ -40755,6 +42614,51 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 2097152 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -40762,62 +42666,71 @@ var ts; result.objectFlags |= 8192 /* MarkerType */; return result; } + function getAliasVariances(symbol) { + var links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) { + var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } // Return an array containing the variance of each type parameter. The variance is effectively // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters, cache, createMarkerType) { + if (typeParameters === void 0) { typeParameters = ts.emptyArray; } + var variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = createMarkerType(cache, tp, markerSuperType); + var typeWithSub = createMarkerType(cache, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } function getVariances(type) { if (!strictFunctionTypes) { return ts.emptyArray; } - var typeParameters = type.typeParameters || ts.emptyArray; - var variances = type.variances; - if (!variances) { - if (type === globalArrayType || type === globalReadonlyArrayType) { - // Arrays are known to be covariant, no need to spend time computing this - variances = [1 /* Covariant */]; - } - else { - // The emptyArray singleton is used to signal a recursive invocation. - type.variances = ts.emptyArray; - variances = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - // We first compare instantiations where the type parameter is replaced with - // marker types that have a known subtype relationship. From this we can infer - // invariance, covariance, contravariance or bivariance. - var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); - var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); - var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | - (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); - // If the instantiations appear to be related bivariantly it may be because the - // type parameter is independent (i.e. it isn't witnessed anywhere in the generic - // type). To determine this we compare instantiations where the type parameter is - // replaced with marker types that are known to be unrelated. - if (variance === 3 /* Bivariant */ && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { - variance = 4 /* Independent */; - } - variances.push(variance); - } - } - type.variances = variances; + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return ts.emptyArray; } - return variances; + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } // Return true if the given type reference has a 'void' type argument for a covariant type parameter. // See comment at call in recursiveTypeRelatedTo for when this case matters. function hasCovariantVoidArgument(type, variances) { for (var i = 0; i < variances.length; i++) { - if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 4096 /* Void */) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { return true; } } return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -40910,13 +42823,13 @@ var ts; // levels, but unequal at some level beyond that. function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 131072 /* Object */) { + if (depth >= 5 && type.flags & 524288 /* Object */) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 131072 /* Object */ && t.symbol === symbol) { + if (t.flags & 524288 /* Object */ && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -40971,12 +42884,8 @@ var ts; return true; } // A source signature partially matches a target signature if the target signature has no fewer required - // parameters and no more overall parameters than the source signature (where a signature with a rest - // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = sourceHasRestParameter ? 1 : 0; - var targetRestCount = targetHasRestParameter ? 1 : 0; - if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) { + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { return true; } return false; @@ -41022,7 +42931,7 @@ var ts; for (var i = 0; i < targetLen; i++) { var s = getTypeAtPosition(source, i); var t = getTypeAtPosition(target, i); - var related = compareTypes(s, t); + var related = compareTypes(t, s); if (!related) { return 0 /* False */; } @@ -41043,8 +42952,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41067,9 +42976,9 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 24576 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 24576 /* Nullable */) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) : getUnionType(types, 2 /* Subtype */); } // Return the leftmost type for which no type to the right is a subtype. @@ -41082,11 +42991,14 @@ var ts; function isReadonlyArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; } + function getElementTypeOfArrayType(type) { + return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined; + } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 24576 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isEmptyArrayLiteralType(type) { var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; @@ -41096,40 +43008,47 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { - return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); + return !(type.flags & (109440 /* Unit */ | 131072 /* Never */)); } function isUnitType(type) { - return !!(type.flags & 27072 /* Unit */); + return !!(type.flags & 109440 /* Unit */); } function isLiteralType(type) { return type.flags & 16 /* Boolean */ ? true : - type.flags & 262144 /* Union */ ? type.flags & 512 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : + type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 /* StringLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : - type; + return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & 256 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* BigIntLiteral */ ? bigintType : + type.flags & 512 /* BooleanLiteral */ ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : - type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : - type; + return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : + type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : + type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type; } function getWidenedUniqueESSymbolType(type) { - return type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : - type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : type; } function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { @@ -41148,13 +43067,21 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } + function isZeroBigInt(_a) { + var value = _a.value; + return value.base10Value === "0"; + } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41163,15 +43090,16 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : - type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : - type.flags & 29148 /* PossiblyFalsy */; + return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 : + type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 : + type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 : + type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 : + type.flags & 117724 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 29120 /* DefinitelyFalsy */); }) : + return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) : type; } function extractDefinitelyFalsyTypes(type) { @@ -41180,10 +43108,13 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : - type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + type.flags & 64 /* BigInt */ ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) || + type.flags & 128 /* StringLiteral */ && type.value === "" || + type.flags & 256 /* NumberLiteral */ && type.value === 0 || + type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : neverType; } /** @@ -41192,15 +43123,15 @@ var ts; * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both */ function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (8192 /* Undefined */ | 16384 /* Null */); + var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */); return missing === 0 ? type : - missing === 8192 /* Undefined */ ? getUnionType([type, undefinedType]) : - missing === 16384 /* Null */ ? getUnionType([type, nullType]) : + missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 65536 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } function getOptionalType(type) { ts.Debug.assert(strictNullChecks); - return type.flags & 8192 /* Undefined */ ? type : getUnionType([type, undefinedType]); + return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { if (!deferredGlobalNonNullableTypeAlias) { @@ -41210,7 +43141,7 @@ var ts; if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); } - return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -41253,7 +43184,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && type.flags & 33554432 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -41263,7 +43194,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; + regularNew.flags = resolved.flags; regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); type.regularType = regularNew; return regularNew; @@ -41351,15 +43282,15 @@ var ts; } function getWidenedTypeWithContext(type, context) { if (type.flags & 402653184 /* RequiresWidening */) { - if (type.flags & 24576 /* Nullable */) { + if (type.flags & 98304 /* Nullable */) { return anyType; } if (isObjectLiteralType(type)) { return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); - var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 24576 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). @@ -41385,7 +43316,7 @@ var ts; function reportWideningErrorsInType(type) { var errorReported = false; if (type.flags & 134217728 /* ContainsWideningType */) { - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } @@ -41421,68 +43352,90 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { - case 202 /* BinaryExpression */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + case 204 /* BinaryExpression */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 149 /* Parameter */: + case 151 /* Parameter */: + var param = declaration; + if (ts.isIdentifier(param.name) && + (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { + var newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + return; + } diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 237 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - if (!declaration.name) { + case 289 /* JSDocFunctionType */: + error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; break; - case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + case 181 /* MappedType */: + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41531,11 +43484,11 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - return !!(type.flags & 15794176 /* Instantiable */ || + return !!(type.flags & 63176704 /* Instantiable */ || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || - type.flags & 786432 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -41544,13 +43497,13 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || !!(type.flags & 786432 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { - if (!(t.flags & 64 /* StringLiteral */)) { + if (!(t.flags & 128 /* StringLiteral */)) { return; } var name = ts.escapeLeadingUnderscores(t.value); @@ -41571,25 +43524,25 @@ var ts; * property is computed by inferring from the source property type to X for the type * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ - function inferTypeForHomomorphicMappedType(source, target) { - var key = source.id + "," + target.id; + function inferTypeForHomomorphicMappedType(source, target, constraint) { + var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } reverseMappedCache.set(key, undefined); - var type = createReverseMappedType(source, target); + var type = createReverseMappedType(source, target, constraint); reverseMappedCache.set(key, type); return type; } - function createReverseMappedType(source, target) { + function createReverseMappedType(source, target, constraint) { var properties = getPropertiesOfType(source); if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { return undefined; } // If any property contains context sensitive functions that have been skipped, the source type // is incomplete and we can't infer a meaningful input type. - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var prop = properties_4[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var prop = properties_3[_i]; if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { return undefined; } @@ -41597,13 +43550,13 @@ var ts; // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been // applied to the element type(s). if (isArrayType(source)) { - return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isReadonlyArrayType(source)) { - return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); } if (isTupleType(source)) { - var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); @@ -41613,30 +43566,46 @@ var ts; var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; + reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); } - function inferReverseMappedType(sourceType, target) { - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + function inferReverseMappedType(sourceType, target, constraint) { + var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = target.flags & 524288 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; - if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (!sourceProp) { - return targetProp; - } + function getUnmatchedProperties(source, target, requireOptionalProperties) { + var properties, _i, properties_4, targetProp, sourceProp; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + _i = 0, properties_4 = properties; + _a.label = 1; + case 1: + if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + targetProp = properties_4[_i]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!!sourceProp) return [3 /*break*/, 3]; + return [4 /*yield*/, targetProp]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; } - } - return undefined; + }); + } + function getUnmatchedProperty(source, target, requireOptionalProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -41658,7 +43627,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41684,8 +43655,8 @@ var ts; } return; } - if (source.flags & 262144 /* Union */ && target.flags & 262144 /* Union */ && !(source.flags & 512 /* EnumLiteral */ && target.flags & 512 /* EnumLiteral */) || - source.flags & 524288 /* Intersection */ && target.flags & 524288 /* Intersection */) { + if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) || + source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -41708,7 +43679,7 @@ var ts; (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } - else if (t.flags & (128 /* NumberLiteral */ | 64 /* StringLiteral */)) { + else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) { var b = getBaseTypeOfLiteralType(t); if (typeIdenticalToSomeType(b, target.types)) { (matchingTypes || (matchingTypes = [])).push(t, b); @@ -41723,7 +43694,7 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 2162688 /* TypeVariable */) { + if (target.flags & 8650752 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding @@ -41731,7 +43702,7 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType) { + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -41744,19 +43715,39 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } - if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 63176704 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType); + if (simplified_1 && simplified_1 !== target) { + inferFromTypesOnce(source, simplified_1); + } + } + } + } } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments @@ -41773,12 +43764,12 @@ var ts; } } } - else if (source.flags & 1048576 /* Index */ && target.flags & 1048576 /* Index */) { + else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { contravariant = !contravariant; inferFromTypes(source.type, target.type); contravariant = !contravariant; } - else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 1048576 /* Index */) { + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; var savePriority = priority; @@ -41787,17 +43778,20 @@ var ts; priority = savePriority; contravariant = !contravariant; } - else if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (source.flags & 4194304 /* Conditional */ && target.flags & 4194304 /* Conditional */) { + else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } - else if (target.flags & 786432 /* UnionOrIntersection */) { + else if (target.flags & 16777216 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } + else if (target.flags & 3145728 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -41822,7 +43816,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 262144 /* Union */) { + else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -41831,10 +43825,25 @@ var ts; } } else { - if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } - if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -41844,7 +43853,7 @@ var ts; // an instantiation of the same generic type), we do not explore this target as it would yield // no further inferences. We exclude the static side of classes from this check since it shares // its symbol with the instance side which would lead to false positives. - var isNonConstructorObject = target.flags & 131072 /* Object */ && + var isNonConstructorObject = target.flags & 524288 /* Object */ && !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { @@ -41860,6 +43869,13 @@ var ts; } } } + function inferFromTypesOnce(source, target) { + var key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = ts.createMap())).set(key, true); + inferFromTypes(source, target); + } + } } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { @@ -41872,7 +43888,7 @@ var ts; } } function getInferenceInfoForType(type) { - if (type.flags & 2162688 /* TypeVariable */) { + if (type.flags & 8650752 /* TypeVariable */) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -41882,6 +43898,44 @@ var ts; } return undefined; } + function inferFromMappedTypeConstraint(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */) { + var result = false; + for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { + var type = _a[_i]; + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* HomomorphicMappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } function inferFromObjectTypes(source, target) { if (isGenericMappedType(source) && isGenericMappedType(target)) { // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer @@ -41891,31 +43945,7 @@ var ts; } if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 1048576 /* Index */) { - // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, - // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source - // type and then make a secondary inference from that type to T. We make a secondary inference - // such that direct inferences to T get priority over inferences to Partial, for example. - var inference = getInferenceInfoForType(constraintType.type); - if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - var savePriority = priority; - priority |= 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; - } - } - return; - } - if (constraintType.flags & 65536 /* TypeParameter */) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. - var savePriority = priority; - priority |= 4 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { return; } } @@ -41928,33 +43958,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41964,12 +43999,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -42000,8 +44043,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42020,11 +44063,11 @@ var ts; reducedTypes.push(t); } } - return type.flags & 262144 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42042,7 +44085,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42055,10 +44098,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42069,16 +44111,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42095,7 +44140,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42124,11 +44169,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42137,7 +44211,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 165 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 146 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the @@ -42146,20 +44220,20 @@ var ts; // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } - if (node.kind === 99 /* ThisKeyword */) { + if (node.kind === 100 /* ThisKeyword */) { return "0"; } - if (node.kind === 187 /* PropertyAccessExpression */) { + if (node.kind === 189 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); return key && key + "." + ts.idText(node.name); } - if (node.kind === 184 /* BindingElement */) { + if (node.kind === 186 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 184 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -42168,14 +44242,14 @@ var ts; } function getBindingElementNameText(element) { var parent = element.parent; - if (parent.kind === 182 /* ObjectBindingPattern */) { + if (parent.kind === 184 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.idText(name); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return name.text; default: @@ -42189,29 +44263,29 @@ var ts; } function isMatchingReference(source, target) { switch (source.kind) { - case 71 /* Identifier */: - return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 235 /* VariableDeclaration */ || target.kind === 184 /* BindingElement */) && + case 72 /* Identifier */: + return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99 /* ThisKeyword */: - return target.kind === 99 /* ThisKeyword */; - case 97 /* SuperKeyword */: - return target.kind === 97 /* SuperKeyword */; - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 100 /* ThisKeyword */: + return target.kind === 100 /* ThisKeyword */; + case 98 /* SuperKeyword */: + return target.kind === 98 /* SuperKeyword */; + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 184 /* BindingElement */: - if (target.kind !== 187 /* PropertyAccessExpression */) + case 186 /* BindingElement */: + if (target.kind !== 189 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 184 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 235 /* VariableDeclaration */) { + if (source.parent.parent.kind === 237 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; return !!maybeId && isMatchingReference(maybeId, t.expression); } @@ -42224,7 +44298,7 @@ var ts; undefined; } function containsMatchingReference(source, target) { - while (source.kind === 187 /* PropertyAccessExpression */) { + while (source.kind === 189 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -42237,32 +44311,52 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 187 /* PropertyAccessExpression */ && + return target.kind === 189 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71 /* Identifier */) { + if (expr.kind === 72 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 187 /* PropertyAccessExpression */) { + if (expr.kind === 189 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 262144 /* Union */) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; + function isDiscriminantType(type) { + if (type.flags & 1048576 /* Union */) { + if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { + return true; } } return false; } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + } + return !!prop.isDiscriminantProperty; + } + } + return false; + } + function hasNarrowableDeclaredType(expr) { + var type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & 1048576 /* Union */); + } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -42289,7 +44383,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -42302,16 +44396,35 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 32768 /* Never */) { + if (assignedType.flags & 131072 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42319,8 +44432,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42335,55 +44448,66 @@ var ts; function getTypeFacts(type) { var flags = type.flags; if (flags & 4 /* String */) { - return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; } - if (flags & 64 /* StringLiteral */) { + if (flags & 128 /* StringLiteral */) { var isEmpty = type.value === ""; return strictNullChecks ? - isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : + isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; } if (flags & (8 /* Number */ | 32 /* Enum */)) { - return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; } - if (flags & 128 /* NumberLiteral */) { + if (flags & 256 /* NumberLiteral */) { var isZero = type.value === 0; return strictNullChecks ? - isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : - isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; + isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : + isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + var isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : + isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; } if (flags & 16 /* Boolean */) { - return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; } - if (flags & 272 /* BooleanLike */) { + if (flags & 528 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 524288 /* Object */) { + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ : + strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } - if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { - return 2457472 /* UndefinedFacts */; + if (flags & (16384 /* Void */ | 32768 /* Undefined */)) { + return 9830144 /* UndefinedFacts */; } - if (flags & 16384 /* Null */) { - return 2340752 /* NullFacts */; + if (flags & 65536 /* Null */) { + return 9363232 /* NullFacts */; } - if (flags & 3072 /* ESSymbolLike */) { - return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; } - if (flags & 16777216 /* NonPrimitive */) { - return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } - if (flags & 15794176 /* Instantiable */) { + if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 786432 /* UnionOrIntersection */) { + if (flags & 3145728 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } - return 4194303 /* All */; + return 16777215 /* All */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -42391,7 +44515,7 @@ var ts; function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); + return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); } return type; } @@ -42403,7 +44527,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42411,15 +44535,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 185 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 273 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 225 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -42436,21 +44560,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return stringType; - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return undefinedType; - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -42458,7 +44582,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 182 /* ObjectBindingPattern */ ? + var type = pattern.kind === 184 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -42476,39 +44600,39 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 224 /* ForInStatement */) { + if (node.parent.parent.kind === 226 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 225 /* ForOfStatement */) { + if (node.parent.parent.kind === 227 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 235 /* VariableDeclaration */ ? + return node.kind === 237 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { - return node.kind === 235 /* VariableDeclaration */ && node.initializer && + return node.kind === 237 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 184 /* BindingElement */ && node.parent.kind === 202 /* BinaryExpression */ && + node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return getReferenceCandidate(node.left); - case 26 /* CommaToken */: + case 27 /* CommaToken */: return getReferenceCandidate(node.right); } } @@ -42516,13 +44640,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 193 /* ParenthesizedExpression */ || - parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + return parent.kind === 195 /* ParenthesizedExpression */ || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node || + parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 269 /* CaseClause */) { + if (clause.kind === 271 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -42538,14 +44662,31 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 271 /* CaseClause */) { + if (clause.expression.kind === 10 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { - return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 262144 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 262144 /* Union */) { + if (source.flags & 1048576 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -42554,34 +44695,37 @@ var ts; } return true; } - if (source.flags & 512 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); + return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); } return f(type) ? type : neverType; } function mapType(type, mapper, noReductions) { - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { return type; } - if (!(type.flags & 262144 /* Union */)) { + if (!(type.flags & 1048576 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42604,12 +44748,14 @@ var ts; // typeWithPrimitives have been replaced with occurrences of string literals and numeric // literals in typeWithLiterals, respectively. function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* StringLiteral */) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* NumberLiteral */)) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) { return mapType(typeWithPrimitives, function (t) { - return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 64 /* StringLiteral */) : - t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 128 /* NumberLiteral */) : - t; + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : + t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : + t; }); } return typeWithPrimitives; @@ -42643,9 +44789,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 32768 /* Never */ ? + return elementType.flags & 131072 /* Never */ ? autoArrayType : - createArrayType(elementType.flags & 262144 /* Union */ ? + createArrayType(elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType); } @@ -42661,9 +44807,9 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - if (!(t.flags & 32768 /* Never */)) { + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; + if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; } @@ -42685,15 +44831,15 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 187 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || - parent.parent.kind === 189 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 188 /* ElementAccessExpression */ && + var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 202 /* BinaryExpression */ && - parent.parent.operatorToken.kind === 58 /* EqualsToken */ && + parent.parent.kind === 204 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 59 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 168 /* NumberLike */); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -42704,7 +44850,7 @@ var ts; return links.maybeTypePredicate; } function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97 /* SuperKeyword */) { + if (node.expression.kind !== 98 /* SuperKeyword */) { var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); @@ -42726,7 +44872,7 @@ var ts; if (flowAnalysisDisabled) { return errorType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 33492479 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) { return declaredType; } var sharedFlowStart = sharedFlowCount; @@ -42736,14 +44882,14 @@ var ts; // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. - var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent && reference.parent.kind === 211 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 32768 /* Never */) { + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { return declaredType; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42809,9 +44955,9 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.container; if (container && container !== flowContainer && - reference.kind !== 187 /* PropertyAccessExpression */ && - reference.kind !== 188 /* ElementAccessExpression */ && - reference.kind !== 99 /* ThisKeyword */) { + reference.kind !== 189 /* PropertyAccessExpression */ && + reference.kind !== 190 /* ElementAccessExpression */ && + reference.kind !== 100 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -42846,11 +44992,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + if (declaredType.flags & 1048576 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42859,15 +45005,27 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } + // for (const _ in ref) acts as a nonnull on ref + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } // Assignment doesn't affect reference return undefined; } function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 189 /* CallExpression */ ? + var expr = node.kind === 191 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -42875,15 +45033,16 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -42897,7 +45056,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { return flowType; } // If we have an antecedent type (meaning we're reachable in some way), we first @@ -42914,19 +45073,25 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 32768 /* Never */ ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43040,8 +45205,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 262144 /* Union */) || - expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + if (!(computedType.flags & 1048576 /* Union */) || + expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { return false; } var access = expr; @@ -43062,10 +45227,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); + return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } if (isMatchingReferenceDiscriminant(expr, declaredType)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } if (containsMatchingReferenceDiscriminant(reference, expr)) { return declaredType; @@ -43083,7 +45248,7 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if ((type.flags & (262144 /* Union */ | 131072 /* Object */)) || (type.flags & 65536 /* TypeParameter */ && type.isThisType)) { + if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); } @@ -43091,19 +45256,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: + case 59 /* EqualsToken */: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -43122,15 +45287,15 @@ var ts; return declaredType; } break; - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 92 /* InKeyword */: + case 93 /* InKeyword */: var target = getReferenceCandidate(expr.right); if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; - case 26 /* CommaToken */: + case 27 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } return type; @@ -43139,28 +45304,28 @@ var ts; if (type.flags & 1 /* Any */) { return type; } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 24576 /* Nullable */) { + if (valueType.flags & 98304 /* Nullable */) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; + var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */; var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - valueType.flags & 16384 /* Null */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : + valueType.flags & 65536 /* Null */ ? + assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : + assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 16909315 /* NotUnionOrUnit */) { + if (type.flags & 67637251 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 32768 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -43172,40 +45337,47 @@ var ts; // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { return declaredType; } return type; } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 15794176 /* Instantiable */) { + if (type.flags & 63176704 /* Instantiable */) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43216,27 +45388,115 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 32768 /* Never */ ? neverType : + var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function getImpliedTypeFromTypeofCase(type, text) { + switch (text) { + case "function": + return type.flags & 1 /* Any */ ? type : globalFunctionType; + case "object": + return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + function narrowTypeForTypeofSwitch(candidate) { + return function (type) { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & 63176704 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjusted clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (hasDefaultClause) { + return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts); + if (impliedType.flags & 1048576 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type)); + } + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { return declaredType; } return type; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43253,22 +45513,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43276,9 +45526,9 @@ var ts; } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 32768 /* Never */)) { + if (!(assignableType.flags & 131072 /* Never */)) { return assignableType; } } @@ -43318,7 +45568,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 188 /* ElementAccessExpression */ || invokedExpression.kind === 187 /* PropertyAccessExpression */) { + if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -43335,20 +45585,20 @@ var ts; // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 72 /* Identifier */: + case 100 /* ThisKeyword */: + case 98 /* SuperKeyword */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 200 /* PrefixUnaryExpression */: - if (expr.operator === 51 /* ExclamationToken */) { + case 202 /* PrefixUnaryExpression */: + if (expr.operator === 52 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -43362,7 +45612,7 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 71 /* Identifier */) { + if (location.kind === 72 /* Identifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } @@ -43383,17 +45633,17 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 243 /* ModuleBlock */ || - node.kind === 277 /* SourceFile */ || - node.kind === 152 /* PropertyDeclaration */; + node.kind === 245 /* ModuleBlock */ || + node.kind === 279 /* SourceFile */ || + node.kind === 154 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43401,13 +45651,13 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 149 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) { symbol.isAssigned = true; } } @@ -43422,21 +45672,21 @@ var ts; /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 149 /* Parameter */ && + declaration.kind === 151 /* Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 8192 /* Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 8192 /* Undefined */); - return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 187 /* PropertyAccessExpression */ || - parent.kind === 189 /* CallExpression */ && parent.expression === node || - parent.kind === 188 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 184 /* BindingElement */ && parent.name === node && !!parent.initializer; + return parent.kind === 189 /* PropertyAccessExpression */ || + parent.kind === 191 /* CallExpression */ && parent.expression === node || + parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { - return type.flags & 14745600 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 24576 /* Nullable */); + return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */); } function getConstraintForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, @@ -43449,7 +45699,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43467,7 +45717,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 195 /* ArrowFunction */) { + if (container.kind === 197 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { @@ -43488,28 +45738,28 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 238 /* ClassDeclaration */ + if (declaration.kind === 240 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); } } - else if (declaration.kind === 207 /* ClassExpression */) { + else if (declaration.kind === 209 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 277 /* SourceFile */) { + while (container.kind !== 279 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43522,12 +45772,17 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } return errorType; } } @@ -43551,7 +45806,7 @@ var ts; // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 149 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -43560,8 +45815,8 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 194 /* FunctionExpression */ || - flowContainer.kind === 195 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ || + flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -43570,9 +45825,9 @@ var ts; // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || - isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || - node.parent.kind === 211 /* NonNullExpression */ || - declaration.kind === 235 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) || + node.parent.kind === 213 /* NonNullExpression */ || + declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 4194304 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -43581,7 +45836,7 @@ var ts; // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (type === autoType || type === autoArrayType) { + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); @@ -43590,7 +45845,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -43600,10 +45855,13 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 272 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -43624,26 +45882,46 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + 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 === 223 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && + if (container.kind === 225 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 193 /* ParenthesizedExpression */) { + while (current.parent.kind === 195 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -43651,9 +45929,9 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 200 /* PrefixUnaryExpression */ || current.parent.kind === 201 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) { var expr = current.parent; - isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; + isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */; } if (!isAssigned) { return false; @@ -43664,7 +45942,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 152 /* PropertyDeclaration */ || container.kind === 155 /* Constructor */) { + if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -43732,37 +46010,37 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 155 /* Constructor */) { + if (container.kind === 157 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 195 /* ArrowFunction */) { + if (container.kind === 197 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } switch (container.kind) { - case 242 /* ModuleDeclaration */: + case 244 /* 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 241 /* EnumDeclaration */: + case 243 /* 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 155 /* Constructor */: + case 157 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: if (ts.hasModifier(container, 32 /* Static */)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -43773,39 +46051,43 @@ var ts; var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ? + var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } } return type || anyType; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43820,16 +46102,68 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 196 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 156 /* MethodDeclaration */ && + container.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 196 /* FunctionExpression */ && + container.parent.kind === 275 /* PropertyAssignment */ && + container.parent.parent.kind === 188 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === 196 /* FunctionExpression */ && + ts.isPropertyAssignment(container.parent) && + ts.isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent.parent) && + ts.isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (ts.isMethodDeclaration(container) && + ts.isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + ts.isObjectLiteralExpression(container.parent) && + ts.isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -43843,15 +46177,15 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 149 /* Parameter */; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 189 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 195 /* ArrowFunction */) { + while (container && container.kind === 197 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -43864,14 +46198,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 147 /* ComputedPropertyName */; }); - if (current && current.kind === 147 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; }); + if (current && current.kind === 149 /* 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 === 186 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -43879,7 +46213,7 @@ var ts; } return errorType; } - if (!isCallExpression && container.kind === 155 /* Constructor */) { + if (!isCallExpression && container.kind === 157 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { @@ -43911,16 +46245,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // 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: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43932,20 +46268,21 @@ var ts; // // 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); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = 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 === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. + if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -43959,7 +46296,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 186 /* ObjectLiteralExpression */) { + if (container.parent.kind === 188 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -43980,7 +46317,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 155 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 157 /* 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 errorType; @@ -43995,7 +46332,7 @@ 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 === 155 /* Constructor */; + return container.kind === 157 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -44003,21 +46340,21 @@ var 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\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) { if (ts.hasModifier(container, 32 /* Static */)) { - return container.kind === 154 /* MethodDeclaration */ || - container.kind === 153 /* MethodSignature */ || - container.kind === 156 /* GetAccessor */ || - container.kind === 157 /* SetAccessor */; + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */; } else { - return container.kind === 154 /* MethodDeclaration */ || - container.kind === 153 /* MethodSignature */ || - container.kind === 156 /* GetAccessor */ || - container.kind === 157 /* SetAccessor */ || - container.kind === 152 /* PropertyDeclaration */ || - container.kind === 151 /* PropertySignature */ || - container.kind === 155 /* Constructor */; + return container.kind === 156 /* MethodDeclaration */ || + container.kind === 155 /* MethodSignature */ || + container.kind === 158 /* GetAccessor */ || + container.kind === 159 /* SetAccessor */ || + container.kind === 154 /* PropertyDeclaration */ || + container.kind === 153 /* PropertySignature */ || + container.kind === 157 /* Constructor */; } } } @@ -44025,10 +46362,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 154 /* MethodDeclaration */ || - func.kind === 156 /* GetAccessor */ || - func.kind === 157 /* SetAccessor */) && func.parent.kind === 186 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 194 /* FunctionExpression */ && func.parent.kind === 273 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 156 /* MethodDeclaration */ || + func.kind === 158 /* GetAccessor */ || + func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -44036,11 +46373,11 @@ var ts; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 524288 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 195 /* ArrowFunction */) { + if (func.kind === 197 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -44052,7 +46389,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44067,7 +46404,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 273 /* PropertyAssignment */) { + if (literal.parent.kind !== 275 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -44081,9 +46418,9 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = func.parent; - if (parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) { var target = parent.left; - if (target.kind === 187 /* PropertyAccessExpression */ || target.kind === 188 /* ElementAccessExpression */) { + if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) { var expression = target.expression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { @@ -44109,7 +46446,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44143,7 +46480,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 149 /* Parameter */) { + if (declaration.kind === 151 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -44155,7 +46492,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 184 /* BindingElement */) { + if (parentDeclaration.kind !== 186 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -44176,9 +46513,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44225,7 +46574,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,10 +46582,13 @@ var ts; // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 191 /* TaggedTemplateExpression */) { + if (template.parent.kind === 193 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -44245,26 +46597,33 @@ var ts; var binaryExpression = node.parent; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { - case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; - case 54 /* BarBarToken */: + case 59 /* EqualsToken */: + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; + case 55 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; - case 53 /* AmpersandAmpersandToken */: - case 26 /* CommaToken */: + case 54 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; default: return undefined; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44282,26 +46641,57 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return ts.Debug.fail("Does not apply"); default: return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - if (t.flags & 917504 /* StructuredType */) { + if (t.flags & 3670016 /* StructuredType */) { var prop = getPropertyOfType(t, name); if (prop) { return getTypeOfSymbol(prop); @@ -44312,6 +46702,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44319,10 +46711,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44342,8 +46730,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44359,7 +46747,6 @@ var ts; // type of T. function getContextualTypeForElementExpression(arrayContextualType, index) { return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) - || getIndexTypeOfContextualType(arrayContextualType, 1 /* Number */) || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); } // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. @@ -44401,54 +46788,44 @@ var ts; // recursive (and possibly infinite) invocations of getContextualType. function isPossiblyDiscriminantValue(node) { switch (node.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 71 /* Identifier */: + case 9 /* BigIntLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 72 /* Identifier */: + case 141 /* UndefinedKeyword */: return true; - case 187 /* PropertyAccessExpression */: - case 193 /* ParenthesizedExpression */: + case 189 /* PropertyAccessExpression */: + case 195 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 270 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44477,52 +46854,54 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 184 /* BindingElement */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 186 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 195 /* ArrowFunction */: - case 228 /* ReturnStatement */: + case 197 /* ArrowFunction */: + case 230 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 189 /* CallExpression */: - case 190 /* NewExpression */: + case 201 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); + case 191 /* CallExpression */: + case 192 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 185 /* ArrayLiteralExpression */: { + case 187 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 214 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 204 /* TemplateExpression */); + case 216 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 193 /* ParenthesizedExpression */: { + case 195 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: + case 267 /* JsxAttribute */: + case 269 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent); } return undefined; @@ -44532,67 +46911,16 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; } - var valueType = checkExpression(node.tagName); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); + return getContextualTypeForArgumentAtIndex(node, 0); } - function getJsxSignaturesParameterTypes(valueType, isJs, context) { - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (valueType.flags & 4 /* String */) { - return anyType; - } - else if (valueType.flags & 64 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = valueType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - } - return anyType; - } - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(valueType, 1 /* Construct */); - var ctor = true; - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, 0 /* Call */); - ctor = false; - if (signatures.length === 0) { - // We found no signatures at all, which is an error - return errorType; - } - } - var links = getNodeLinks(context); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(valueType); - var cachedResolved = links.resolvedSignatures.get(cacheKey); - if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { - signatures = cachedResolved; - } - else if (!cachedResolved) { - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); - } - return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); @@ -44607,22 +46935,40 @@ var ts; var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + var tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + var fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var ctorType = getStaticTypeOfReferencedJsxConstructor(context); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } return attributesType; } - function getJsxPropsTypeFromClassType(sig, isJs, context, reportErrors) { + function getJsxPropsTypeFromClassType(sig, context) { var ns = getJsxNamespaceAt(context); var forcedLookupLocation = getJsxElementPropertiesName(ns); var attributesType = forcedLookupLocation === undefined @@ -44635,7 +46981,7 @@ var ts; : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); if (!attributesType) { // There is no property named 'props' on this instance type - if (reportErrors && !!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) { error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); } return emptyObjectType; @@ -44653,7 +46999,7 @@ var ts; var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); var hostClassType = getReturnTypeOfSignature(sig); apparentAttributesType = intersectTypes(typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) : intrinsicClassAttribs, apparentAttributesType); } var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); @@ -44689,7 +47035,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 194 /* FunctionExpression */ || node.kind === 195 /* ArrowFunction */; + return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -44708,7 +47054,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -44717,13 +47063,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 262144 /* Union */)) { + if (!(type.flags & 1048576 /* Union */)) { return getContextualCallSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44756,10 +47102,10 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 184 /* BindingElement */ && !!node.initializer) || - (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + return (node.kind === 186 /* BindingElement */ && !!node.initializer) || + (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +47114,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elementCount; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 206 /* SpreadElement */) { + if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -44781,7 +47127,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44790,47 +47136,59 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } - if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { + if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) { hasNonEndingSpreadElement = true; } } if (!hasNonEndingSpreadElement) { - var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206 /* SpreadElement */; + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - 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 (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + 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 (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) { + if (e.kind !== 210 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44839,12 +47197,12 @@ var ts; } function isNumericName(name) { switch (name.kind) { - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return isNumericComputedName(name); - case 71 /* Identifier */: + case 72 /* Identifier */: return isNumericLiteralName(name.escapedText); case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return isNumericLiteralName(name.text); default: return false; @@ -44853,7 +47211,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAssignableToKind(checkComputedPropertyName(name), 168 /* NumberLike */); + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -44888,8 +47246,8 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (links.resolvedType.flags & 24576 /* Nullable */ || - !isTypeAssignableToKind(links.resolvedType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */) && + if (links.resolvedType.flags & 98304 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -44909,6 +47267,17 @@ var ts; var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } + function getImmediateAliasedSymbol(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + if (!node) + return ts.Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + } function checkObjectLiteral(node, checkMode) { var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking @@ -44916,13 +47285,13 @@ var ts; var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 33554432 /* FreshLiteral */; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44932,15 +47301,15 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 147 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 273 /* PropertyAssignment */ || - memberDecl.kind === 274 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 275 /* PropertyAssignment */ || + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : - memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -44951,7 +47320,7 @@ var ts; } } typeFlags |= type.flags; - var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? + var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : @@ -44962,8 +47331,8 @@ 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 === 273 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 274 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -44988,12 +47357,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 275 /* SpreadAssignment */) { + else if (memberDecl.kind === 277 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -45005,7 +47374,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); offset = i + 1; continue; } @@ -45015,10 +47384,10 @@ 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 === 156 /* GetAccessor */ || memberDecl.kind === 157 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (computedNameType && !(computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */)) { + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { if (isTypeAssignableTo(computedNameType, numberType)) { hasComputedNumberProperty = true; @@ -45052,7 +47421,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); } return spread; } @@ -45061,9 +47430,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; - result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); - result.objectFlags |= 128 /* ObjectLiteral */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; + result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -45073,20 +47441,17 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 24576 /* Nullable */)) { - propagatedFlags |= (result.flags & 939524096 /* PropagatingFlags */); - } + propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; return result; } } function isValidSpreadType(type) { - return !!(type.flags & (3 /* AnyOrUnknown */ | 16777216 /* NonPrimitive */) || - getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 131072 /* Object */ && !isGenericMappedType(type) || - type.flags & 786432 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); } function checkJsxSelfClosingElementDeferred(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node, 0 /* Normal */); + checkJsxOpeningLikeElementOrOpeningFragment(node); } function checkJsxSelfClosingElement(node, _checkMode) { checkNodeDeferred(node); @@ -45094,7 +47459,7 @@ var ts; } function checkJsxElementDeferred(node) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, 0 /* Normal */); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -45102,18 +47467,20 @@ var ts; else { checkExpression(node.closingElement.tagName); } + checkJsxChildren(node); } function checkJsxElement(node, _checkMode) { checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } - function checkJsxFragment(node, checkMode) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { error(node, compilerOptions.jsxFactory ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } + checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } /** @@ -45127,7 +47494,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) { - return tagName.kind === 71 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); + return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); } function checkJsxAttribute(node, checkMode) { return node.initializer @@ -45146,16 +47513,19 @@ var ts; function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); - var spread = emptyObjectType; + var spread = emptyJsxObjectType; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var typeFlags = 0; + var objectFlags = 4096 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45170,9 +47540,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45180,7 +47550,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45189,11 +47559,11 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 258 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -45204,32 +47574,35 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); } } if (hasSpreadAnyType) { return anyType; } - if (typeToIntersect && spread !== emptyObjectType) { + if (typeToIntersect && spread !== emptyJsxObjectType) { return getIntersectionType([typeToIntersect, spread]); } - return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable * @param attributesTable a symbol table of attributes property */ function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; - result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; + result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; return result; } } @@ -45239,7 +47612,7 @@ var ts; var child = _a[_i]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. - if (child.kind === 10 /* JsxText */) { + if (child.kind === 11 /* JsxText */) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); } @@ -45261,7 +47634,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45302,57 +47675,6 @@ var ts; } return links.resolvedSymbol; } - function instantiateJsxSignatures(node, signatures) { - var instantiatedSignatures = []; - var candidateForTypeArgumentError; - var hasTypeArgumentError = !!node.typeArguments; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); - if (typeArgumentInstantiated) { - hasTypeArgumentError = false; - instantiatedSignatures.push(typeArgumentInstantiated); - } - else { - if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - candidateForTypeArgumentError = signature; - } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - } - else { - instantiatedSignatures.push(signature); - } - } - if (node.typeArguments && hasTypeArgumentError) { - if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); - } - // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine - else if (node.typeArguments.length !== 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); - } - } - return instantiatedSignatures; - } - function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { - if (reportErrors === void 0) { reportErrors = false; } - if (!node.typeArguments) { - return; - } - if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - return; - } - var args = checkTypeArguments(signature, node.typeArguments, reportErrors); - if (!args) { - return; - } - return getSignatureInstantiation(signature, args, isJavascript); - } function getJsxNamespaceAt(location) { var links = location && getNodeLinks(location); if (links && links.jsxNamespace) { @@ -45386,7 +47708,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45410,7 +47732,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45423,217 +47745,78 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - return undefined; + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; } - if (propsType.flags & 524288 /* Intersection */) { - var propsApparentType = []; - for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { - var t = _a[_i]; - propsApparentType.push(getApparentType(t)); + else if (elementType.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return ts.emptyArray; } - return getIntersectionType(propsApparentType); - } - return getApparentType(propsType); - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return only attributes type of successfully resolved call signature. - * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) - * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); - if (callSignature !== unknownSignature) { - var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); - var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } + else { + var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; } } - return undefined; - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return all attributes type of resolved call signature including candidate signatures. - * This function assumes that the caller handled other possible element type of the JSX element. - * This function is a behavior used by language service when looking up completion in JSX element. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type - var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - var candidate = candidatesOutArray_1[_i]; - var callReturnType = getReturnTypeOfSignature(candidate); - // TODO: GH#18217: callReturnType should always be defined... - var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - var shouldBeCandidate = true; - for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217 - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - // If we can't find any matching, just return everything. - if (!result) { - result = allMatchingAttributesType; - } - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { - var links = getNodeLinks(openingLikeElement); - if (!links.resolvedSignatures) { - links.resolvedSignatures = ts.createMap(); - } - var cacheKey = "" + getTypeId(elementType); - if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { - return; - } - else if (links.resolvedSignatures.get(cacheKey)) { - return links.resolvedSignatures.get(cacheKey); - } - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + var apparentElemType = getApparentType(elementType); // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(elementType, 1 /* Construct */); + var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); if (signatures.length === 0) { // No construct signatures, try call signatures - signatures = getSignaturesOfType(elementType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - if (reportErrors) { - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - } + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); })); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + var stringLiteralTypeName = type.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else if (refKind === 0 /* Component */) { + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + } + else { // Mixed + var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + var classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { return; } + var combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - // Instantiate in context of source type - var results = instantiateJsxSignatures(openingLikeElement, signatures); - links.resolvedSignatures.set(cacheKey, results); - return results; - } - /** - * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. - * For instance: - * declare function Foo(attr: { p1: string}): JSX.Element; - * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" - * - * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. - * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component - * - * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement - * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature - * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present - * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) - * @return attributes type if able to resolve the type of node - * anyType if there is no type ElementAttributesProperty or there is an error - * emptyObjectType if there is no "prop" in the element instance type - */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType.flags & 262144 /* Union */) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), 2 /* Subtype */); - } - // Shortcircuit any - if (isTypeAny(elementType)) { - return elementType; - } - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - else if (elementType.flags & 4 /* String */) { - return anyType; - } - else if (elementType.flags & 64 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); - if (intrinsicElementsType !== errorType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - // If we need to report an error, we already done so here. So just return any to prevent any more error downstream - return anyType; - } - // Get the element instance type (the result of newing or invoking this tag) - var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); - if (!ts.length(instantiatedSignatures)) { - return errorType; - } - var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */); - // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. - // Otherwise get only attributes type from the signature picked by choose-overload logic. - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -45657,53 +47840,6 @@ var ts; } return links.resolvedJsxElementAttributesType; } - /** - * Get attributes type of the given custom opening-like JSX element. - * This function is intended to be called from a caller that handles intrinsic JSX element already. - * @param node a custom JSX opening-like element - * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component - */ - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); - } - /** - * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. - * This function is called by language service (see: completions-tryGetGlobalSymbols). - * @param node a JSX opening-like element to get attributes type for - */ - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - // Because in language service, the given JSX opening-like element may be incomplete and therefore, - // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); - } - } - /** - * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. - * @param node a JSXOpeningLikeElement node - * @return an attributes type of the given node - */ - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); - } - } - /** - * Given a JSX attribute, returns the symbol for the corresponds property - * of the element attributes type. Will return unknownSymbol for attributes - * that have no matching element attributes type property. - */ - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.escapedText); - return prop || unknownSymbol; - } function getJsxElementClassTypeAt(location) { var type = getJsxType(JsxNames.ElementClass, location); if (type === errorType) @@ -45737,7 +47873,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -45748,7 +47884,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45759,10 +47895,8 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } /** @@ -45779,7 +47913,7 @@ var ts; * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType */ function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 131072 /* Object */) { + if (targetType.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -45789,7 +47923,7 @@ var ts; return true; } } - else if (targetType.flags & 786432 /* UnionOrIntersection */) { + else if (targetType.flags & 3145728 /* UnionOrIntersection */) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -45797,55 +47931,12 @@ var ts; } } } - else if (targetType.flags & 4194304 /* Conditional */) { + else if (targetType.flags & 16777216 /* Conditional */) { return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); } return false; } - /** - * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. - * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" - * Check assignablity between given attributes property, "source attributes", and the "target attributes" - * @param openingLikeElement an opening-like JSX element to check its JSXAttributes - */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { - // The function involves following steps: - // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. - // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) - // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. - // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); - // sourceAttributesType is a type of an attributes properties. - // i.e
- // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); - // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties - var isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); - // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { - var attribute = _a[_i]; - if (!ts.isJsxAttribute(attribute)) { - continue; - } - var attrName = attribute.name; - var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); - // We break here so that errors won't be cascading - break; - } - } - } - else if (!isSourceAttributeTypeAssignableToTarget) { - checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); - } - } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -45869,10 +47960,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45885,7 +47976,7 @@ var ts; */ function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name; + var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); @@ -45917,7 +48008,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -45957,13 +48048,13 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { return true; } - if (type.flags & 65536 /* TypeParameter */) { + if (type.flags & 262144 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } @@ -45983,19 +48074,26 @@ var ts; function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } + function getNonNullableTypeIfNeeded(type) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; + if (kind) { + return getNonNullableType(type); + } + return type; + } function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { if (type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 24576 /* Nullable */; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 8192 /* Undefined */ ? kind & 16384 /* Null */ ? + error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); - return t.flags & (24576 /* Nullable */ | 32768 /* Never */) ? errorType : t; + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } @@ -46028,7 +48126,7 @@ var ts; return anyType; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } return errorType; } @@ -46039,12 +48137,12 @@ var ts; } else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); + markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } } @@ -46053,9 +48151,9 @@ var ts; // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 187 /* PropertyAccessExpression */ || + if (node.kind !== 189 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 262144 /* Union */)) { + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } // If strict null checks and strict property initialization checks are enabled, if we have @@ -46063,17 +48161,23 @@ var ts; // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && left.kind === 99 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 155 /* Constructor */ && flowContainer.parent === declaration.parent) { + if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) { assumeUninitialized = true; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -46092,8 +48196,8 @@ var ts; && !isPropertyDeclaredInAncestorClass(prop)) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 238 /* ClassDeclaration */ && - node.parent.kind !== 162 /* TypeReference */ && + else if (valueDeclaration.kind === 240 /* ClassDeclaration */ && + node.parent.kind !== 164 /* TypeReference */ && !(valueDeclaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -46105,9 +48209,9 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return true; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: @@ -46145,7 +48249,7 @@ var ts; function reportNonexistentProperty(propNode, containingType) { var errorInfo; var relatedInfo; - if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { + if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -46185,7 +48289,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46237,7 +48341,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -46254,16 +48358,16 @@ var ts; } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: - return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 146 /* QualifiedName */: + case 189 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 148 /* QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 181 /* ImportType */: + case 183 /* ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -46290,20 +48394,20 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * 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 === 236 /* VariableDeclarationList */) { + if (initializer.kind === 238 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 71 /* Identifier */) { + else if (initializer.kind === 72 /* Identifier */) { return getResolvedSymbol(initializer); } return undefined; @@ -46320,13 +48424,13 @@ var ts; */ function isForInVariableForNumericPropertyNames(expr) { var e = ts.skipParentheses(expr); - if (e.kind === 71 /* Identifier */) { + if (e.kind === 72 /* Identifier */) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3 /* Variable */) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 224 /* ForInStatement */ && + if (node.kind === 226 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -46344,7 +48448,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 190 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 192 /* 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); @@ -46356,15 +48460,15 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) { error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46375,7 +48479,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 3072 /* ESSymbolLike */) === 0) { + if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -46402,8 +48506,7 @@ var ts; return true; } function callLikeExpressionMayHaveTypeArguments(node) { - // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) - return ts.isCallOrNewExpression(node); + return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); } function resolveUntypedCall(node) { if (callLikeExpressionMayHaveTypeArguments(node)) { @@ -46411,10 +48514,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 191 /* TaggedTemplateExpression */) { + if (node.kind === 193 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 150 /* Decorator */) { + else if (ts.isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } + else if (node.kind !== 152 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -46441,8 +48547,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -46478,25 +48584,23 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 206 /* SpreadElement */ || arg.kind === 213 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call + var argCount; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". - return true; - } - if (node.kind === 191 /* TaggedTemplateExpression */) { - // 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 + var effectiveParameterCount = getParameterCount(signature); + var effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 193 /* TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 204 /* TemplateExpression */) { + if (node.template.kind === 206 /* 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 lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -46507,35 +48611,53 @@ var ts; // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. var templateLiteral = node.template; - ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */); + ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + else if (node.kind === 152 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } + else if (ts.isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 190 /* NewExpression */); + ts.Debug.assert(node.kind === 192 /* NewExpression */); return getMinArgumentCount(signature) === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. - if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { return false; } // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = argCount >= getMinArgumentCount(signature); - return callIsIncomplete || hasEnoughArguments; + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (var i = argCount; i < effectiveMinimumArguments; i++) { + var type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; } function hasCorrectTypeArgumentArity(signature, typeArguments) { // If the user supplied type arguments, but the number of type arguments does not match @@ -46547,7 +48669,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 131072 /* Object */) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -46558,7 +48680,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46567,16 +48689,11 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, node, context) { - // Skip context sensitive pass - var skipContextParamType = getTypeAtPosition(signature, 0); - var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); - inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); - // Standard pass - var paramType = getTypeAtPosition(signature, 0); - var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + function inferJsxTypeArguments(node, signature, excludeArgument, context) { + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } @@ -46592,11 +48709,14 @@ var ts; inference.inferredType = undefined; } } + if (ts.isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (node.kind !== 150 /* Decorator */) { + if (node.kind !== 152 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -46625,71 +48745,50 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; 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 !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. - return arg.kind === 213 /* SyntheticExpression */ ? + return arg.kind === 215 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; - var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 32764 /* Primitive */ | 1048576 /* Index */); + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */); var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46698,27 +48797,40 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return 2 /* Mixed */; + } + var tagType = getApparentType(checkExpression(node.tagName)); + if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. * @param node a JSX opening-like element we are trying to figure its call signature @@ -46726,37 +48838,20 @@ var ts; * @param relation a relationship to check parameter and argument type * @param excludeArgument */ - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: - // 1. callIsIncomplete - // 2. attributes property has same number of properties as the parameter object type. - // We can figure that out by resolving attributes property and check number of properties in the resolved type - // If the call has correct arity, we will then check if the argument type and parameter type is assignable - var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete - if (callIsIncomplete) { - return true; - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, // can be specified by users through attributes property. - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); + var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 190 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -46769,346 +48864,142 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; 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 !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 210 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 189 /* CallExpression */) { + if (node.kind === 191 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); - if (callee.kind === 187 /* PropertyAccessExpression */ || callee.kind === 188 /* ElementAccessExpression */) { + if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) { return callee.expression; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { - if (node.kind === 191 /* TaggedTemplateExpression */) { + if (node.kind === 193 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 - if (template.kind === 204 /* TemplateExpression */) { + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 206 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 152 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* 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); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 151 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* 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. + var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + return 1; + case 154 /* PropertyDeclaration */: + return 2; + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 151 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47117,15 +49008,19 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + var closestSignature; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var sig = signatures_4[_i]; var minCount = getMinArgumentCount(sig); var maxCount = getParameterCount(sig); if (minCount < argCount && minCount > belowArgCount) belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47136,22 +49031,31 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -47159,14 +49063,15 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { - var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 150 /* Decorator */; + var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 152 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var reportErrors = !candidatesOutArray; var typeArguments; if (!isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -47174,40 +49079,26 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + if (reportErrors) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + } return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47235,7 +49126,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -47259,32 +49150,33 @@ var ts; // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, // skip the checkApplicableSignature check. - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". - return candidateForArgumentError; + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); + } + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); - } - else if (candidateForArgumentArityError) { - diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); - } - else if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); - } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47304,60 +49196,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47377,7 +49289,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47388,7 +49300,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47427,17 +49339,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47456,7 +49378,7 @@ var ts; return maxParamsIndex; } function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { @@ -47490,11 +49412,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47506,16 +49428,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47528,8 +49457,8 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -47588,11 +49517,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47605,7 +49536,7 @@ var ts; return false; } var firstBase = baseTypes[0]; - if (firstBase.flags & 524288 /* Intersection */) { + if (firstBase.flags & 2097152 /* Intersection */) { var types = firstBase.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); var i = 0; @@ -47662,10 +49593,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47689,8 +49621,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47704,16 +49636,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 149 /* Parameter */: + case 151 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -47729,8 +49661,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47749,6 +49681,46 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } + function createSignatureForJSXIntrinsic(node, result) { + var namespace = getJsxNamespaceAt(node); + var exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */); + var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node); + var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */)); + var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.type = result; + return createSignature(declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false); + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + var fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + var exprTypes = checkExpression(node.tagName); + var apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } /** * Sometimes, we have a decorator that could accept zero arguments, * but is receiving too many arguments as part of the decorator invocation. @@ -47758,52 +49730,22 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } - /** - * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. - * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName - * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) - * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. - * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function - * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { - ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); - var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); - if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); - } - return undefined; - } function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); - case 150 /* Decorator */: + case 152 /* Decorator */: return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); - case 260 /* JsxOpeningElement */: - case 259 /* JsxSelfClosingElement */: - // This code-path is called by language service - var exprTypes = checkExpression(node.tagName); - return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); - if (sfcResult && sfcResult !== unknownSignature) { - return sfcResult; - } - var sigs = getInstantiatedJsxSignatures(node, exprType); - if (candidatesOutArray && ts.length(sigs)) { - candidatesOutArray.push.apply(candidatesOutArray, sigs); - } - return ts.length(sigs) ? sigs[0] : unknownSignature; - }) || unknownSignature; + case 262 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -47837,34 +49779,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { - if (type.flags & 131072 /* Object */) { + function isJSConstructorType(type) { + if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47877,22 +49823,19 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } var parent = node.parent; - while (parent && parent.kind === 187 /* PropertyAccessExpression */) { + while (parent && parent.kind === 189 /* PropertyAccessExpression */) { parent = parent.parent; } - if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) { var right = ts.getInitializerOfBinaryExpression(parent); return ts.isObjectLiteralExpression(right) && right; } @@ -47918,15 +49861,15 @@ var ts; if (!checkGrammarTypeArguments(node, node.typeArguments)) checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { return voidType; } - if (node.kind === 190 /* NewExpression */) { + if (node.kind === 192 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 155 /* Constructor */ && - declaration.kind !== 159 /* ConstructSignature */ && - declaration.kind !== 164 /* ConstructorType */ && + declaration.kind !== 157 /* Constructor */ && + declaration.kind !== 161 /* ConstructSignature */ && + declaration.kind !== 166 /* 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 @@ -47934,10 +49877,10 @@ var ts; // Note:JS inferred classes might come from a variable declaration instead of a function declaration. // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. var funcSymbol = checkExpression(node.expression).symbol; - if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { + if (!funcSymbol && node.expression.kind === 72 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47948,18 +49891,18 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property // as a fresh unique symbol literal type. - if (returnType.flags & 3072 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47985,7 +49928,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48000,7 +49943,7 @@ var ts; for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 8192 /* Undefined */ || specifierType.flags & 16384 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal @@ -48044,7 +49987,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48053,9 +49996,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 237 /* FunctionDeclaration */ + ? 239 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 235 /* VariableDeclaration */ + ? 237 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -48091,10 +50034,10 @@ var ts; } function checkMetaProperty(node) { checkGrammarMetaProperty(node); - if (node.keywordToken === 94 /* NewKeyword */) { + if (node.keywordToken === 95 /* NewKeyword */) { return checkNewTargetMetaProperty(node); } - if (node.keywordToken === 91 /* ImportKeyword */) { + if (node.keywordToken === 92 /* ImportKeyword */) { return checkImportMetaProperty(node); } return ts.Debug.assertNever(node.keywordToken); @@ -48105,7 +50048,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 155 /* Constructor */) { + else if (container.kind === 157 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -48169,14 +50112,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48185,17 +50125,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48219,15 +50149,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48235,6 +50156,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48287,7 +50219,7 @@ var ts; for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71 /* Identifier */) { + if (element.name.kind === 72 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } else { @@ -48301,7 +50233,7 @@ var ts; if (!links.type) { links.type = contextualType; var decl = parameter.valueDeclaration; - if (decl.name.kind !== 71 /* Identifier */) { + if (decl.name.kind !== 72 /* Identifier */) { // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType) { links.type = getTypeFromBindingPattern(decl.name); @@ -48320,6 +50252,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48341,7 +50283,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 216 /* Block */) { + if (func.body.kind !== 218 /* Block */) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any @@ -48437,10 +50379,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 199 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48455,7 +50448,7 @@ var ts; if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - if (ts.some(func.body.statements, function (statement) { return statement.kind === 230 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -48477,7 +50470,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 32768 /* Never */) { + if (type.flags & 131072 /* Never */) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -48490,7 +50483,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48498,11 +50491,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return true; - case 154 /* MethodDeclaration */: - return func.parent.kind === 186 /* ObjectLiteralExpression */; + case 156 /* MethodDeclaration */: + return func.parent.kind === 188 /* ObjectLiteralExpression */; default: return false; } @@ -48521,16 +50514,16 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 153 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 216 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 32768 /* Never */) { + if (returnType && returnType.flags & 131072 /* Never */) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -48559,7 +50552,8 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48569,14 +50563,16 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 194 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -48611,7 +50607,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48622,7 +50617,7 @@ var ts; getAwaitedType(type) || errorType : type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function @@ -48638,7 +50633,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 216 /* Block */) { + if (node.body.kind === 218 /* Block */) { checkSourceElement(node.body); } else { @@ -48661,34 +50656,66 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAssignableToKind(type, 168 /* NumberLike */)) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { error(operand, diagnostic); return false; } return true; } + function isReadonlyAssignmentDeclaration(d) { + if (!ts.isCallExpression(d)) { + return false; + } + if (!ts.isBindableObjectDefinePropertyCall(d)) { + return false; + } + var objectLitType = checkExpressionCached(d.arguments[2]); + var valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + var writableProp = getPropertyOfType(objectLitType, "writable"); + var writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) { + var initializer = writableProp.valueDeclaration.initializer; + var rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + var setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } 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 + // Object.defineProperty assignments with writable false or no setter // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || - symbol.flags & 8 /* EnumMember */); + symbol.flags & 8 /* EnumMember */ || + ts.some(symbol.declarations, isReadonlyAssignmentDeclaration)); } 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 === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) && - expr.expression.kind === 99 /* ThisKeyword */) { + (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) && + expr.expression.kind === 100 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 155 /* Constructor */)) { + if (!(func && func.kind === 157 /* Constructor */)) { return true; } // If func.parent is a class and symbol is a (readonly) property of that class, or @@ -48701,13 +50728,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) { + if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return !!declaration && declaration.kind === 249 /* NamespaceImport */; + return !!declaration && declaration.kind === 251 /* NamespaceImport */; } } } @@ -48716,7 +50743,7 @@ var ts; function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); - if (node.kind !== 71 /* Identifier */ && node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { + if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -48725,7 +50752,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -48762,37 +50789,52 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operand.kind === 8 /* NumericLiteral */) { - if (node.operator === 38 /* MinusToken */) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - else if (node.operator === 37 /* PlusToken */) { - return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); - } + switch (node.operand.kind) { + case 8 /* NumericLiteral */: + switch (node.operator) { + case 39 /* MinusToken */: + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + case 38 /* PlusToken */: + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } + break; + case 9 /* BigIntLiteral */: + if (node.operator === 39 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: ts.parsePseudoBigInt(node.operand.text) + })); + } } switch (node.operator) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 3072 /* ESSymbolLike */)) { + if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } - return numberType; - case 51 /* ExclamationToken */: + if (node.operator === 38 /* PlusToken */) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); + case 52 /* ExclamationToken */: checkTruthinessExpression(node.operand); - var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); - return facts === 1048576 /* Truthy */ ? falseType : - facts === 2097152 /* Falsy */ ? trueType : + var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : + facts === 8388608 /* Falsy */ ? trueType : booleanType; - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + case 44 /* PlusPlusToken */: + case 45 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } - return numberType; + return getUnaryResultType(operandType); } return errorType; } @@ -48801,11 +50843,20 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number return numberType; } // Return true if type might be of the given kind. A union or intersection type might be of a given @@ -48814,10 +50865,10 @@ var ts; if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { return true; } - if (type.flags & 786432 /* UnionOrIntersection */) { + if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48829,21 +50880,22 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (3 /* AnyOrUnknown */ | 4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */)) { + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { return false; } - return !!(kind & 168 /* NumberLike */) && isTypeAssignableTo(source, numberType) || - !!(kind & 68 /* StringLike */) && isTypeAssignableTo(source, stringType) || - !!(kind & 272 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || - !!(kind & 4096 /* Void */) && isTypeAssignableTo(source, voidType) || - !!(kind & 32768 /* Never */) && isTypeAssignableTo(source, neverType) || - !!(kind & 16384 /* Null */) && isTypeAssignableTo(source, nullType) || - !!(kind & 8192 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || - !!(kind & 1024 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || - !!(kind & 16777216 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || + !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { - return source.flags & 262144 /* Union */ ? + return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : isTypeAssignableToKind(source, kind, strict); } @@ -48863,7 +50915,7 @@ var ts; // 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 (!isTypeAny(leftType) && - allTypesAssignableToKind(leftType, 32764 /* Primitive */)) { + allTypesAssignableToKind(leftType, 131068 /* 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 @@ -48882,10 +50934,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 168 /* NumberLike */ | 3072 /* ESSymbolLike */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + if (!isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -48895,8 +50947,8 @@ var ts; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; @@ -48904,9 +50956,9 @@ var ts; /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { if (rightIsThis === void 0) { rightIsThis = false; } - if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { + if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -48915,13 +50967,13 @@ var ts; var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 275 /* SpreadAssignment */) { + else if (property.kind === 277 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } @@ -48973,11 +51025,11 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 208 /* OmittedExpression */) { - if (element.kind !== 206 /* SpreadElement */) { + if (element.kind !== 210 /* OmittedExpression */) { + if (element.kind !== 208 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48998,13 +51050,13 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 202 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49015,14 +51067,14 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 8192 /* Undefined */)) { - sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); } @@ -49031,21 +51083,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 202 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 186 /* ObjectLiteralExpression */) { + if (target.kind === 188 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 185 /* ArrayLiteralExpression */) { + if (target.kind === 187 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 275 /* SpreadAssignment */ ? + var error = target.parent.kind === 277 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { @@ -49064,72 +51116,73 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 191 /* TaggedTemplateExpression */: - case 204 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 72 /* Identifier */: + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 193 /* TaggedTemplateExpression */: + case 206 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 140 /* UndefinedKeyword */: - case 194 /* FunctionExpression */: - case 207 /* ClassExpression */: - case 195 /* ArrowFunction */: - case 185 /* ArrayLiteralExpression */: - case 186 /* ObjectLiteralExpression */: - case 197 /* TypeOfExpression */: - case 211 /* NonNullExpression */: - case 259 /* JsxSelfClosingElement */: - case 258 /* JsxElement */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 141 /* UndefinedKeyword */: + case 196 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 197 /* ArrowFunction */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + case 199 /* TypeOfExpression */: + case 213 /* NonNullExpression */: + case 261 /* JsxSelfClosingElement */: + case 260 /* JsxElement */: return true; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { - case 51 /* ExclamationToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: + case 52 /* ExclamationToken */: + case 38 /* PlusToken */: + case 39 /* MinusToken */: + case 53 /* TildeToken */: return true; } return false; // Some forms listed here for clarity - case 198 /* VoidExpression */: // Explicit opt-out - case 192 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 210 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 200 /* VoidExpression */: // Explicit opt-out + case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */); + if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */); } var leftType; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) { leftType = checkTruthinessExpression(left, checkMode); } else { @@ -49137,28 +51190,28 @@ var ts; } var rightType = checkExpression(right, checkMode); switch (operator) { - case 39 /* AsteriskToken */: - case 40 /* AsteriskAsteriskToken */: - case 61 /* AsteriskEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 42 /* PercentToken */: - case 64 /* PercentEqualsToken */: - case 38 /* MinusToken */: - case 60 /* MinusEqualsToken */: - case 45 /* LessThanLessThanToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: + case 40 /* AsteriskToken */: + case 41 /* AsteriskAsteriskToken */: + case 62 /* AsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: + case 42 /* SlashToken */: + case 64 /* SlashEqualsToken */: + case 43 /* PercentToken */: + case 65 /* PercentEqualsToken */: + case 39 /* MinusToken */: + case 61 /* MinusEqualsToken */: + case 46 /* LessThanLessThanToken */: + case 66 /* LessThanLessThanEqualsToken */: + case 47 /* GreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanEqualsToken */: + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -49167,36 +51220,61 @@ var ts; 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 & 272 /* BooleanLike */) && - (rightType.flags & 272 /* BooleanLike */) && + if ((leftType.flags & 528 /* BooleanLike */) && + (rightType.flags & 528 /* BooleanLike */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + return numberType; } else { // otherwise just check each operand separately and report errors as normal - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + var resultType_1; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType_1 = numberType; } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) { + switch (operator) { + case 48 /* GreaterThanGreaterThanGreaterThanToken */: + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + } + resultType_1 = bigintType; + } + else { + reportOperatorError(); + resultType_1 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType_1); + } + return resultType_1; } - return numberType; - case 37 /* PlusToken */: - case 59 /* PlusEqualsToken */: + case 38 /* PlusToken */: + case 60 /* PlusEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 68 /* StringLike */) && !isTypeAssignableToKind(rightType, 68 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeAssignableToKind(leftType, 168 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 168 /* NumberLike */, /*strict*/ true)) { + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) { // 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 (isTypeAssignableToKind(leftType, 68 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 68 /* StringLike */, /*strict*/ true)) { + else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } + else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -49213,26 +51291,27 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 59 /* PlusEqualsToken */) { + if (operator === 60 /* PlusEqualsToken */) { checkAssignmentOperator(resultType); } return resultType; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: + case 28 /* LessThanToken */: + case 30 /* GreaterThanToken */: + case 31 /* LessThanEqualsToken */: + case 32 /* GreaterThanEqualsToken */: if (checkForDisallowedESSymbolOperand(operator)) { leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) { reportOperatorError(); } } return booleanType; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -49243,29 +51322,38 @@ var ts; reportOperatorError(); } return booleanType; - case 93 /* InstanceOfKeyword */: + case 94 /* InstanceOfKeyword */: return checkInstanceOfExpression(left, right, leftType, rightType); - case 92 /* InKeyword */: + case 93 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); - case 53 /* AmpersandAmpersandToken */: - return getTypeFacts(leftType) & 1048576 /* Truthy */ ? + case 54 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 4194304 /* Truthy */ ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; - case 54 /* BarBarToken */: - return getTypeFacts(leftType) & 2097152 /* Falsy */ ? + case 55 /* BarBarToken */: + return getTypeFacts(leftType) & 8388608 /* Falsy */ ? getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; - case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + case 59 /* EqualsToken */: + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || + declKind !== 2 /* ModuleExports */ && + declKind !== 6 /* Prototype */ && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType) && + !(ts.getObjectFlags(rightType) & 1 /* Class */)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } return leftType; } else { checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); } - case 26 /* CommaToken */: + case 27 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -49273,15 +51361,14 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { - var rightType_1 = checkExpression(right, checkMode); - for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { + function checkAssignmentDeclaration(kind, rightType) { + if (kind === 2 /* ModuleExports */) { + for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49291,12 +51378,12 @@ var ts; } } function isEvalNode(node) { - return node.kind === 71 /* Identifier */ && node.escapedText === "eval"; + return node.kind === 72 /* Identifier */ && node.escapedText === "eval"; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 3072 /* ESSymbolLike */) ? left : - maybeTypeOfKind(rightType, 3072 /* ESSymbolLike */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -49306,15 +51393,15 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - return 54 /* BarBarToken */; - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - return 35 /* ExclamationEqualsEqualsToken */; - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: - return 53 /* AmpersandAmpersandToken */; + case 50 /* BarToken */: + case 70 /* BarEqualsToken */: + return 55 /* BarBarToken */; + case 51 /* CaretToken */: + case 71 /* CaretEqualsToken */: + return 36 /* ExclamationEqualsEqualsToken */; + case 49 /* AmpersandToken */: + case 69 /* AmpersandEqualsToken */: + return 54 /* AmpersandAmpersandToken */; default: return undefined; } @@ -49334,8 +51421,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49344,7 +51431,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49361,11 +51448,11 @@ var ts; } function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { switch (operatorToken.kind) { - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: + case 35 /* EqualsEqualsEqualsToken */: + case 33 /* EqualsEqualsToken */: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: + case 36 /* ExclamationEqualsEqualsToken */: + case 34 /* ExclamationEqualsToken */: return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); } return undefined; @@ -49443,14 +51530,14 @@ var ts; // A place where we actually *are* concerned with the expressions' types are // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { - if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) { error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49486,25 +51573,21 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 192 /* TypeAssertionExpression */ || node.kind === 210 /* AsExpression */; + return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */; } function checkDeclarationInitializer(declaration) { var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { - if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + if (ts.isInJSFile(declaration)) { + if (widened.flags & 98304 /* Nullable */) { + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49512,34 +51595,36 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 786432 /* UnionOrIntersection */) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { var types = contextualType.types; return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } - if (contextualType.flags & 14745600 /* InstantiableNonPrimitive */) { + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { // If the contextual type is a type variable constrained to a primitive type, consider // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || - maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || - maybeTypeOfKind(constraint, 1024 /* ESSymbol */) && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (64 /* StringLiteral */ | 1048576 /* Index */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || - contextualType.flags & 128 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || - contextualType.flags & 256 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 256 /* BooleanLiteral */) || - contextualType.flags & 2048 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */)); + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || + contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || + contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || + contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || + contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49547,7 +51632,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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -49558,7 +51643,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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -49586,15 +51671,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49608,9 +51697,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49621,13 +51714,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; - if (node.kind === 146 /* QualifiedName */) { + if (node.kind === 148 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49635,10 +51728,10 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 165 /* TypeQuery */ && node.parent.exprName === node)); + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === 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_or_type_query); } @@ -49646,102 +51739,105 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return checkIdentifier(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return checkThisExpression(node); - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return checkSuperExpression(node); - case 95 /* NullKeyword */: + case 96 /* NullKeyword */: return nullWideningType; - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101 /* TrueKeyword */: + case 9 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node)); + case 102 /* TrueKeyword */: return trueType; - case 86 /* FalseKeyword */: + case 87 /* FalseKeyword */: return falseType; - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return checkTemplateExpression(node); - case 12 /* RegularExpressionLiteral */: + case 13 /* RegularExpressionLiteral */: return globalRegExpType; - case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); - case 186 /* ObjectLiteralExpression */: + case 187 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 188 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 189 /* CallExpression */: - if (node.expression.kind === 91 /* ImportKeyword */) { + case 191 /* CallExpression */: + if (node.expression.kind === 92 /* ImportKeyword */) { return checkImportCallExpression(node); } /* falls through */ - case 190 /* NewExpression */: + case 192 /* NewExpression */: return checkCallExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return checkClassExpression(node); - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: return checkAssertion(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return checkNonNullAssertion(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return checkMetaProperty(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return checkDeleteExpression(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return checkVoidExpression(node); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return checkAwaitExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 208 /* OmittedExpression */: + case 210 /* OmittedExpression */: return undefinedWideningType; - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return checkYieldExpression(node); - case 213 /* SyntheticExpression */: + case 215 /* SyntheticExpression */: return node.type; - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return checkJsxElement(node, checkMode); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 262 /* JsxFragment */: - return checkJsxFragment(node, checkMode); - case 266 /* JsxAttributes */: + case 264 /* JsxFragment */: + return checkJsxFragment(node); + case 268 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -49770,9 +51866,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49782,7 +51875,7 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 155 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -49793,16 +51886,16 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { + if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 195 /* ArrowFunction */) { + if (func.kind === 197 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -49851,13 +51944,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 195 /* ArrowFunction */: - case 158 /* CallSignature */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 163 /* FunctionType */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 197 /* ArrowFunction */: + case 160 /* CallSignature */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 165 /* FunctionType */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -49871,11 +51964,11 @@ var ts; continue; } var name = element.name; - if (name.kind === 71 /* Identifier */ && name.escapedText === predicateVariableName) { + if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 183 /* ArrayBindingPattern */ || name.kind === 182 /* ObjectBindingPattern */) { + else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -49884,13 +51977,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 160 /* IndexSignature */) { + if (node.kind === 162 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 163 /* FunctionType */ || node.kind === 237 /* FunctionDeclaration */ || node.kind === 164 /* ConstructorType */ || - node.kind === 158 /* CallSignature */ || node.kind === 155 /* Constructor */ || - node.kind === 159 /* ConstructSignature */) { + else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ || + node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ || + node.kind === 161 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -49920,10 +52013,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 158 /* CallSignature */: + case 160 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -49953,7 +52046,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -49970,7 +52063,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 155 /* Constructor */) { + if (member.kind === 157 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -49985,16 +52078,16 @@ var ts; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (name && memberName) { switch (member.kind) { - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: addName(names, name, memberName, 1 /* Getter */); break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: addName(names, name, memberName, 2 /* Setter */); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: addName(names, name, memberName, 3 /* Property */); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: addName(names, name, memberName, 4 /* Method */); break; } @@ -50057,15 +52150,15 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151 /* PropertySignature */) { + if (member.kind === 153 /* PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: case 8 /* NumericLiteral */: memberName = name.text; break; - case 71 /* Identifier */: + case 72 /* Identifier */: memberName = ts.idText(name); break; default: @@ -50082,7 +52175,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 239 /* InterfaceDeclaration */) { + if (node.kind === 241 /* 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 @@ -50102,7 +52195,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -50110,7 +52203,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -50137,7 +52230,7 @@ var ts; checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 154 /* MethodDeclaration */ && node.body) { + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -50162,7 +52255,7 @@ var ts; return; } function isInstancePropertyWithInitializer(n) { - return n.kind === 152 /* PropertyDeclaration */ && + return n.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } @@ -50192,7 +52285,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -50217,7 +52310,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -50227,13 +52320,13 @@ 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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(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 === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); @@ -50251,7 +52344,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -50268,7 +52361,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50299,7 +52392,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50347,7 +52440,7 @@ var ts; var seenOptionalElement = false; for (var i = 0; i < elementTypes.length; i++) { var e = elementTypes[i]; - if (e.kind === 170 /* RestType */) { + if (e.kind === 172 /* RestType */) { if (i !== elementTypes.length - 1) { grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); break; @@ -50356,7 +52449,7 @@ var ts; error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); } } - else if (e.kind === 169 /* OptionalType */) { + else if (e.kind === 171 /* OptionalType */) { seenOptionalElement = true; } else if (seenOptionalElement) { @@ -50371,14 +52464,14 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 2097152 /* IndexedAccess */)) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { return type; } // Check if the index type is assignable to 'keyof T' for the object type. var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 188 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -50386,7 +52479,7 @@ var ts; } // Check if we're indexing with a numeric type and if either object or index types // is a generic type with a constraint that has a numeric index signature. - if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -50400,8 +52493,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50418,7 +52511,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 173 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -50435,9 +52528,9 @@ var ts; var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 239 /* InterfaceDeclaration */ && - n.parent.kind !== 238 /* ClassDeclaration */ && - n.parent.kind !== 207 /* ClassExpression */ && + if (n.parent.kind !== 241 /* InterfaceDeclaration */ && + n.parent.kind !== 240 /* ClassDeclaration */ && + n.parent.kind !== 209 /* ClassExpression */ && n.flags & 4194304 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -50528,7 +52621,7 @@ var ts; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */) && + var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) && ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -50567,7 +52660,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = node.flags & 4194304 /* Ambient */; - var inAmbientContextOrInterface = node.parent.kind === 239 /* InterfaceDeclaration */ || node.parent.kind === 166 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -50578,7 +52671,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 === 237 /* FunctionDeclaration */ || node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */ || node.kind === 155 /* Constructor */) { + if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -50630,8 +52723,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var signature = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var signature = signatures_6[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -50640,6 +52733,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50697,32 +52797,25 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return 2 /* ExportType */; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 277 /* SourceFile */: + case 279 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values if (!ts.isEntityNameExpression(d.expression)) { return 1 /* ExportValue */; @@ -50730,17 +52823,17 @@ var ts; d = d.expression; /* falls through */ // The below options all declare an Alias, which is allowed to merge with other values within the importing module - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 248 /* ImportClause */: - var result_3 = 0 /* None */; + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 250 /* ImportClause */: + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 235 /* VariableDeclaration */: - case 184 /* BindingElement */: - case 237 /* FunctionDeclaration */: - case 251 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; + case 237 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 239 /* FunctionDeclaration */: + case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); @@ -50787,7 +52880,7 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -50818,7 +52911,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 262144 /* Union */) { + if (type.flags & 1048576 /* Union */) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -50966,10 +53059,10 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { - if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { @@ -50989,7 +53082,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51008,24 +53101,24 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 149 /* Parameter */: + case 151 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -51046,7 +53139,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51071,50 +53164,55 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 172 /* IntersectionType */: - case 171 /* UnionType */: - var commonEntityName = void 0; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175 /* ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 131 /* NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); - if (!individualEntityName) { - // Individual is something like string number - // So it would be serialized to either that type or object - // Safe to return here - return undefined; - } - if (commonEntityName) { - // Note this is in sync with the transformation that happens for type node. - // Keep this in sync with serializeUnionOrIntersectionType - // Verify if they refer to same entity and is identifier - // return undefined if they dont match because we would emit object - if (!ts.isIdentifier(commonEntityName) || - !ts.isIdentifier(individualEntityName) || - commonEntityName.escapedText !== individualEntityName.escapedText) { - return undefined; - } - } - else { - commonEntityName = individualEntityName; - } - } - return commonEntityName; - case 175 /* ParenthesizedType */: + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 175 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 177 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return node.typeName; } } } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + var commonEntityName; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var typeNode = types_16[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 132 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } function getParameterTypeNodeForDecoratorCheck(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; @@ -51134,14 +53232,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 149 /* Parameter */) { + if (node.kind === 151 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -51150,23 +53248,23 @@ var ts; } } break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 149 /* Parameter */: + case 151 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -51219,16 +53317,22 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); } } } } + function checkJSDocFunctionType(node) { + if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } function checkJSDocAugmentsTag(node) { var classLike = ts.getJSDocHost(node); if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { @@ -51251,9 +53355,9 @@ var ts; } function getIdentifierFromEntityNameExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return node.name; default: return undefined; @@ -51266,7 +53370,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 && node.name.kind === 147 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 149 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -51295,7 +53399,7 @@ var ts; } } } - var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); @@ -51304,8 +53408,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51315,7 +53419,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51324,7 +53428,7 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. - if (produceDiagnostics) { + if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) { var sourceFile = ts.getSourceFileOfNode(node); var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); if (!potentiallyUnusedIdentifiers) { @@ -51340,44 +53444,44 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 239 /* InterfaceDeclaration */: - checkUnusedTypeParameters(node, addDiagnostic); - break; - case 277 /* SourceFile */: - case 242 /* ModuleDeclaration */: - case 216 /* Block */: - case 244 /* CaseBlock */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 279 /* SourceFile */: + case 244 /* ModuleDeclaration */: + case 218 /* Block */: + case 246 /* CaseBlock */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 155 /* Constructor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - if (node.body) { + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 240 /* TypeAliasDeclaration */: - case 174 /* InferType */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 242 /* TypeAliasDeclaration */: + case 241 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; + case 176 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; default: ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); } @@ -51392,77 +53496,73 @@ var ts; return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 154 /* MethodDeclaration */: - case 152 /* PropertyDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - if (member.kind === 157 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { - // Already would have reported an error on the getter. - break; - } - var symbol = getSymbolOfNode(member); - if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 156 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. break; - case 155 /* Constructor */: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 157 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } - break; - case 160 /* IndexSignature */: - case 215 /* SemicolonClassElement */: - // Can't be private - break; - default: - ts.Debug.fail(); - } + } + break; + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) + if (ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174 /* InferType */) { - var typeParameter = node.typeParameter; - if (isTypeParameterUnused(typeParameter)) { - addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } } - } - else { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - var seenParentsWithEveryUnused = new ts.NodeSet(); - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var typeParameter = typeParameters_2[_i]; - if (!isTypeParameterUnused(typeParameter)) - continue; - var name = ts.idText(typeParameter.name); - var parent = typeParameter.parent; - if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { - if (seenParentsWithEveryUnused.tryAdd(parent)) { - var range = ts.isJSDocTemplateTag(parent) - // Whole @template tag - ? ts.rangeOfNode(parent) - // Include the `<>` in the error message - : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; - var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; - var arg0 = only ? name : undefined; - addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); - } - } - else { - addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); - } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } @@ -51533,7 +53633,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 @@ -51551,7 +53651,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 235 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 236 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -51572,7 +53672,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -51584,24 +53684,24 @@ var ts; } function bindingNameText(name) { switch (name.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.idText(name); - case 183 /* ArrayBindingPattern */: - case 182 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 248 /* ImportClause */ || node.kind === 251 /* ImportSpecifier */ || node.kind === 249 /* NamespaceImport */; + return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 248 /* ImportClause */ ? decl : decl.kind === 249 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 216 /* Block */) { + if (node.kind === 218 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -51631,12 +53731,12 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 151 /* PropertySignature */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 153 /* MethodSignature */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { + if (node.kind === 154 /* PropertyDeclaration */ || + node.kind === 153 /* PropertySignature */ || + node.kind === 156 /* MethodDeclaration */ || + node.kind === 155 /* MethodSignature */ || + node.kind === 158 /* GetAccessor */ || + node.kind === 159 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -51645,7 +53745,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 149 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -51655,7 +53755,7 @@ var ts; function checkIfThisIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { - var isDeclaration_1 = node.kind !== 71 /* Identifier */; + var isDeclaration_1 = node.kind !== 72 /* Identifier */; if (isDeclaration_1) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -51670,7 +53770,7 @@ var ts; function checkIfNewTargetIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { - var isDeclaration_2 = node.kind !== 71 /* Identifier */; + var isDeclaration_2 = node.kind !== 72 /* Identifier */; if (isDeclaration_2) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } @@ -51696,7 +53796,7 @@ var ts; } // 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 === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 279 /* 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)); } @@ -51711,7 +53811,7 @@ var ts; } // 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 === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -51746,7 +53846,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 235 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -51758,17 +53858,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 236 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 217 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 219 /* 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 === 216 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 243 /* ModuleBlock */ || - container.kind === 242 /* ModuleDeclaration */ || - container.kind === 277 /* SourceFile */); + (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 245 /* ModuleBlock */ || + container.kind === 244 /* ModuleDeclaration */ || + container.kind === 279 /* 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 @@ -51783,7 +53883,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 !== 149 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -51794,14 +53894,14 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 187 /* PropertyAccessExpression */) { + if (n.kind === 189 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } - else if (n.kind === 71 /* Identifier */) { + else if (n.kind === 72 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51813,8 +53913,8 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 149 /* Parameter */ || - symbol.valueDeclaration.kind === 184 /* BindingElement */) { + if (symbol.valueDeclaration.kind === 151 /* Parameter */ || + symbol.valueDeclaration.kind === 186 /* BindingElement */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -51828,7 +53928,7 @@ var ts; return ts.isFunctionLike(current.parent) || // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - (current.parent.kind === 152 /* PropertyDeclaration */ && + (current.parent.kind === 154 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)); })) { @@ -51861,18 +53961,18 @@ 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 === 147 /* ComputedPropertyName */) { + if (node.name.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 184 /* BindingElement */) { - if (node.parent.kind === 182 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + if (node.kind === 186 /* BindingElement */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 147 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -51883,29 +53983,29 @@ var ts; var nameText = ts.getTextOfPropertyName(name); if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { - checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property); } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 183 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 149 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) { var initializerType = checkExpressionCached(node.initializer); if (strictNullChecks && node.name.elements.length === 0) { checkNonNullType(initializerType, node); @@ -51924,15 +54024,20 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); checkParameterInitializer(node); } } + if (symbol.declarations.length > 1) { + if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } + } } else { // Node is a secondary declaration, check that type is identical to primary declaration and check that @@ -51940,21 +54045,20 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */) { + if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -51963,14 +54067,14 @@ var ts; } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 152 /* PropertyDeclaration */ || nextDeclaration.kind === 151 /* PropertySignature */ + var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 149 /* Parameter */ && right.kind === 235 /* VariableDeclaration */) || - (left.kind === 235 /* VariableDeclaration */ && right.kind === 149 /* Parameter */)) { + if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) || + (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -52009,7 +54113,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 218 /* EmptyStatement */) { + if (node.thenStatement.kind === 220 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -52028,7 +54132,7 @@ var ts; } function checkTruthinessExpression(node, checkMode) { var type = checkExpression(node, checkMode); - if (type.flags & 4096 /* Void */) { + if (type.flags & 16384 /* Void */) { error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); } return type; @@ -52036,12 +54140,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -52075,14 +54179,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 === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side - if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* 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. @@ -52108,13 +54212,13 @@ var ts; function checkForInStatement(node) { // Grammar checking checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); + var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 236 /* VariableDeclarationList */) { + if (node.initializer.kind === 238 /* 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); @@ -52128,7 +54232,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 === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { + if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -52141,7 +54245,7 @@ var ts; } // 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 (rightType === neverType || !isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -52196,16 +54300,16 @@ var ts; // This allows us to find other non-string element types from an array unioned with // a string. if (allowStringInput) { - if (arrayType.flags & 262144 /* Union */) { + if (arrayType.flags & 1048576 /* Union */) { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the result of filter is a new array. var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 68 /* StringLike */); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } } - else if (arrayType.flags & 68 /* StringLike */) { + else if (arrayType.flags & 132 /* StringLike */) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -52218,7 +54322,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType.flags & 32768 /* Never */) { + if (arrayType.flags & 131072 /* Never */) { return stringType; } } @@ -52249,7 +54353,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); if (hasStringConstituent && arrayElementType) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 68 /* StringLike */) { + if (arrayElementType.flags & 132 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], 2 /* Subtype */); @@ -52314,13 +54418,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52347,9 +54455,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52457,7 +54567,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 4096 /* Void */ | 3 /* AnyOrUnknown */); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { // Grammar checking @@ -52473,7 +54583,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); var functionFlags = ts.getFunctionFlags(func); var isGenerator = functionFlags & 1 /* Generator */; - if (strictNullChecks || node.expression || returnType.flags & 32768 /* Never */) { + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (isGenerator) { // AsyncGenerator function or Generator function // A generator does not need its return expressions checked against its return type. @@ -52482,12 +54592,12 @@ var ts; // for generators. return; } - else if (func.kind === 157 /* SetAccessor */) { + else if (func.kind === 159 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 155 /* Constructor */) { + else if (func.kind === 157 /* Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -52508,7 +54618,7 @@ var ts; } } } - else if (func.kind !== 155 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -52537,7 +54647,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 270 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -52549,7 +54659,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 269 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 271 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -52578,7 +54688,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 231 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -52685,8 +54795,8 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 202 /* BinaryExpression */ || - name.kind === 147 /* ComputedPropertyName */ || + (propDeclaration.kind === 204 /* BinaryExpression */ || + name.kind === 149 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -52715,6 +54825,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -52890,18 +55001,21 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 2162688 /* TypeVariable */)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52929,7 +55043,7 @@ var ts; } } else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -52944,7 +55058,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52963,7 +55077,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -52989,7 +55103,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 238 /* ClassDeclaration */ || d.kind === 239 /* InterfaceDeclaration */; + return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -53028,7 +55142,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 || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { - if (derivedClassDecl.kind === 207 /* ClassExpression */) { + if (derivedClassDecl.kind === 209 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -53078,8 +55192,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -53110,7 +55224,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 8192 /* Undefined */)) { + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -53120,16 +55234,18 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 152 /* PropertyDeclaration */ && + return node.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 8192 /* Undefined */); + return !(getFalsyFlags(flowType) & 32768 /* Undefined */); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -53142,7 +55258,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -53247,60 +55363,60 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { - case 37 /* PlusToken */: return value_2; - case 38 /* MinusToken */: return -value_2; - case 52 /* TildeToken */: return ~value_2; + case 38 /* PlusToken */: return value_2; + case 39 /* MinusToken */: return -value_2; + case 53 /* TildeToken */: return ~value_2; } } break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { switch (expr.operatorToken.kind) { - case 49 /* BarToken */: return left | right; - case 48 /* AmpersandToken */: return left & right; - case 46 /* GreaterThanGreaterThanToken */: return left >> right; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; - case 45 /* LessThanLessThanToken */: return left << right; - case 50 /* CaretToken */: return left ^ right; - case 39 /* AsteriskToken */: return left * right; - case 41 /* SlashToken */: return left / right; - case 37 /* PlusToken */: return left + right; - case 38 /* MinusToken */: return left - right; - case 42 /* PercentToken */: return left % right; - case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right); + case 50 /* BarToken */: return left | right; + case 49 /* AmpersandToken */: return left & right; + case 47 /* GreaterThanGreaterThanToken */: return left >> right; + case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 46 /* LessThanLessThanToken */: return left << right; + case 51 /* CaretToken */: return left ^ right; + case 40 /* AsteriskToken */: return left * right; + case 42 /* SlashToken */: return left / right; + case 38 /* PlusToken */: return left + right; + case 39 /* MinusToken */: return left - right; + case 43 /* PercentToken */: return left % right; + case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right); } } - else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 37 /* PlusToken */) { + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) { return left + right; } break; - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return expr.text; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return evaluate(expr.expression); - case 71 /* Identifier */: + case 72 /* Identifier */: var identifier = expr; if (isInfinityOrNaNString(identifier.escapedText)) { return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 188 /* ElementAccessExpression */: - case 187 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 187 /* PropertyAccessExpression */) { + if (ex.kind === 189 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -53331,10 +55447,10 @@ var ts; } } function isConstantMemberAccess(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 187 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 188 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && - node.argumentExpression.kind === 9 /* StringLiteral */; + return node.kind === 72 /* Identifier */ || + node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 10 /* StringLiteral */; } function checkEnumDeclaration(node) { if (!produceDiagnostics) { @@ -53371,7 +55487,7 @@ var ts; 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 !== 241 /* EnumDeclaration */) { + if (declaration.kind !== 243 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -53394,8 +55510,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { var declaration = declarations_8[_i]; - if ((declaration.kind === 238 /* ClassDeclaration */ || - (declaration.kind === 237 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 240 /* ClassDeclaration */ || + (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304 /* Ambient */)) { return declaration; } @@ -53432,7 +55548,7 @@ var ts; return; } if (!checkGrammarDecoratorsAndModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { + if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } @@ -53458,7 +55574,7 @@ 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, 238 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -53508,23 +55624,23 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* 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 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 184 /* BindingElement */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 237 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -53535,12 +55651,12 @@ var ts; break; } // falls through - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 237 /* FunctionDeclaration */: - case 239 /* InterfaceDeclaration */: - case 242 /* ModuleDeclaration */: - case 240 /* TypeAliasDeclaration */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 241 /* InterfaceDeclaration */: + case 244 /* ModuleDeclaration */: + case 242 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -53553,7 +55669,7 @@ var ts; var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { // symbol should not originate in augmentation - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -53561,17 +55677,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return node; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: do { node = node.left; - } while (node.kind !== 71 /* Identifier */); + } while (node.kind !== 72 /* Identifier */); return node; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: do { node = node.expression; - } while (node.kind !== 71 /* Identifier */); + } while (node.kind !== 72 /* Identifier */); return node; } } @@ -53585,9 +55701,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 253 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 255 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -53616,19 +55732,19 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 255 /* ExportSpecifier */ ? + var message = node.kind === 257 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && node.kind === 257 /* ExportSpecifier */ + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53654,7 +55770,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 251 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -53678,17 +55794,17 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53714,10 +55830,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 243 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; - if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -53734,7 +55850,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 277 /* SourceFile */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 242 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -53742,13 +55858,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53763,8 +55879,8 @@ 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 === 277 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -53777,9 +55893,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 71 /* Identifier */) { + if (node.expression.kind === 72 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53811,7 +55927,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53852,14 +55968,14 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 237 /* FunctionDeclaration */ && declaration.kind !== 154 /* MethodDeclaration */) || + return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -53870,163 +55986,163 @@ var ts; // 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 242 /* ModuleDeclaration */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 237 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 239 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return checkTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return checkParameter(node); - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: return checkPropertyDeclaration(node); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 160 /* CallSignature */: + case 161 /* ConstructSignature */: + case 162 /* IndexSignature */: return checkSignatureDeclaration(node); - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: return checkMethodDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return checkConstructorDeclaration(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return checkAccessorDeclaration(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return checkTypeReferenceNode(node); - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return checkTypePredicate(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return checkTypeQuery(node); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return checkTypeLiteral(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return checkArrayType(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return checkTupleType(node); - case 171 /* UnionType */: - case 172 /* IntersectionType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 175 /* ParenthesizedType */: - case 169 /* OptionalType */: - case 170 /* RestType */: + case 177 /* ParenthesizedType */: + case 171 /* OptionalType */: + case 172 /* RestType */: return checkSourceElement(node.type); - case 176 /* ThisType */: + case 178 /* ThisType */: return checkThisType(node); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return checkTypeOperator(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return checkConditionalType(node); - case 174 /* InferType */: + case 176 /* InferType */: return checkInferType(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return checkImportType(node); - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 302 /* JSDocTypedefTag */: - case 295 /* JSDocCallbackTag */: + case 304 /* JSDocTypedefTag */: + case 297 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 297 /* JSDocParameterTag */: + case 299 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 287 /* JSDocFunctionType */: - checkSignatureDeclaration(node); + case 289 /* JSDocFunctionType */: + checkJSDocFunctionType(node); // falls through - case 285 /* JSDocNonNullableType */: - case 284 /* JSDocNullableType */: - case 282 /* JSDocAllType */: - case 283 /* JSDocUnknownType */: - case 290 /* JSDocTypeLiteral */: + case 287 /* JSDocNonNullableType */: + case 286 /* JSDocNullableType */: + case 284 /* JSDocAllType */: + case 285 /* JSDocUnknownType */: + case 292 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 288 /* JSDocVariadicType */: + case 290 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 281 /* JSDocTypeExpression */: + case 283 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return checkMappedType(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 216 /* Block */: - case 243 /* ModuleBlock */: + case 218 /* Block */: + case 245 /* ModuleBlock */: return checkBlock(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return checkVariableStatement(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return checkExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return checkIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return checkDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return checkWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return checkForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return checkForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return checkForOfStatement(node); - case 226 /* ContinueStatement */: - case 227 /* BreakStatement */: + case 228 /* ContinueStatement */: + case 229 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return checkReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return checkWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return checkSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return checkLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return checkThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return checkTryStatement(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return checkBindingElement(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return checkClassDeclaration(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return checkImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return checkExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return checkExportAssignment(node); - case 218 /* EmptyStatement */: - case 234 /* DebuggerStatement */: + case 220 /* EmptyStatement */: + case 236 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return checkMissingDeclaration(node); } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54097,31 +56213,38 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: checkClassExpressionDeferred(node); break; - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 258 /* JsxElement */: + case 260 /* JsxElement */: checkJsxElementDeferred(node); break; } @@ -54157,9 +56280,9 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54170,7 +56293,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54252,13 +56374,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 242 /* ModuleDeclaration */: + case 279 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + // falls through + case 244 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -54266,17 +56392,17 @@ var ts; // falls through // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 241 /* 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 (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -54318,17 +56444,17 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 71 /* Identifier */ && + return name.kind === 72 /* Identifier */ && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 148 /* TypeParameter */: - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: + case 150 /* TypeParameter */: + case 240 /* ClassDeclaration */: + case 241 /* InterfaceDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: return true; default: return false; @@ -54336,16 +56462,16 @@ var ts; } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 146 /* QualifiedName */) { + while (node.parent.kind === 148 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 162 /* TypeReference */; + return node.parent.kind === 164 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 187 /* PropertyAccessExpression */) { + while (node.parent.kind === 189 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 209 /* ExpressionWithTypeArguments */; + return node.parent.kind === 211 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -54358,12 +56484,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54373,13 +56499,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 146 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 246 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 252 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -54388,7 +56514,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54405,7 +56531,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 181 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -54414,8 +56540,8 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 187 /* PropertyAccessExpression */ && + if (ts.isInJSFile(entityName) && + entityName.parent.kind === 189 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -54423,17 +56549,17 @@ var ts; return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } } else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 246 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } @@ -54451,11 +56577,11 @@ 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 === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) { + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54467,11 +56593,11 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 297 /* JSDocParameterTag */) { + if (entityName.parent.kind === 299 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54480,19 +56606,19 @@ var ts; // Missing entity name. return undefined; } - if (entityName.kind === 71 /* Identifier */) { + if (entityName.kind === 72 /* Identifier */) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { + else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 187 /* PropertyAccessExpression */) { + if (entityName.kind === 189 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -54502,20 +56628,17 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 265 /* JsxAttribute */) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 161 /* TypePredicate */) { + if (entityName.parent.kind === 163 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -54526,17 +56649,20 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(parent); + var parentSymbol = getSymbolOfNode(parent); + return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(parent.parent); } - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (parent.kind === 184 /* BindingElement */ && - grandParent.kind === 182 /* ObjectBindingPattern */ && + else if (parent.kind === 186 /* BindingElement */ && + grandParent.kind === 184 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -54546,11 +56672,11 @@ var ts; } } switch (node.kind) { - case 71 /* Identifier */: - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + case 72 /* Identifier */: + case 189 /* PropertyAccessExpression */: + case 148 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -54562,29 +56688,32 @@ var ts; return checkExpression(node).symbol; } // falls through - case 176 /* ThisType */: + case 178 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return checkExpression(node).symbol; - case 123 /* ConstructorKeyword */: + case 124 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 155 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } + if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } // falls through case 8 /* NumericLiteral */: // index access @@ -54594,19 +56723,22 @@ var ts; ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); - case 79 /* DefaultKeyword */: - case 89 /* FunctionKeyword */: - case 36 /* EqualsGreaterThanToken */: + case 80 /* DefaultKeyword */: + case 90 /* FunctionKeyword */: + case 37 /* EqualsGreaterThanToken */: + case 76 /* ClassKeyword */: return getSymbolOfNode(node.parent); - case 181 /* ImportType */: + case 183 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case 85 /* ExportKeyword */: + return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + if (location && location.kind === 276 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54614,30 +56746,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54678,28 +56805,28 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 186 /* ObjectLiteralExpression */ || expr.kind === 185 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 225 /* ForOfStatement */) { + if (expr.parent.kind === 227 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 202 /* BinaryExpression */) { + if (expr.parent.kind === 204 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 273 /* PropertyAssignment */) { + if (expr.parent.kind === 275 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 185 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; @@ -54732,13 +56859,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 72 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + return getLiteralType(name.text); + case 149 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54778,7 +56924,7 @@ var ts; if (!ts.isGeneratedIdentifier(nodeIn)) { var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -54799,13 +56945,13 @@ var ts; // 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 & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54834,7 +56980,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 277 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -54854,7 +57000,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54867,11 +57013,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54887,9 +57033,9 @@ var ts; // * 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 isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -54930,18 +57076,18 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: - case 248 /* ImportClause */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 248 /* ImportEqualsDeclaration */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return node.expression - && node.expression.kind === 71 /* Identifier */ + && node.expression.kind === 72 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -54949,7 +57095,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 277 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -54963,7 +57109,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54976,7 +57122,8 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && + target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55021,6 +57168,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55030,15 +57196,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 276 /* EnumMember */: - case 187 /* PropertyAccessExpression */: - case 188 /* ElementAccessExpression */: + case 278 /* EnumMember */: + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 276 /* EnumMember */) { + if (node.kind === 278 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -55052,7 +57218,7 @@ var ts; return undefined; } function isFunctionType(type) { - return !!(type.flags & 131072 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeNameIn, location) { // ensure both `typeName` and `location` are parse tree nodes. @@ -55065,9 +57231,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55089,22 +57255,25 @@ var ts; else if (type.flags & 3 /* AnyOrUnknown */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 4096 /* Void */ | 24576 /* Nullable */ | 32768 /* Never */)) { + else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeAssignableToKind(type, 272 /* BooleanLike */)) { + else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeAssignableToKind(type, 168 /* NumberLike */)) { + else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 68 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return ts.TypeReferenceSerializationKind.BigIntLikeType; + } + else if (isTypeAssignableToKind(type, 132 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 3072 /* ESSymbolLike */)) { + else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -55120,14 +57289,14 @@ var ts; function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; - if (type.flags & 2048 /* UniqueESSymbol */ && + if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } @@ -55139,7 +57308,7 @@ var ts; function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); @@ -55147,7 +57316,7 @@ var ts; function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { - return ts.createToken(119 /* AnyKeyword */); + return ts.createToken(120 /* AnyKeyword */); } var type = getWidenedType(getRegularTypeOfExpression(expr)); return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); @@ -55169,7 +57338,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55184,18 +57353,19 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing, tracker) { + var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } - function createLiteralConstValue(node) { + function createLiteralConstValue(node, tracker) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node, tracker); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55238,6 +57408,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55266,12 +57438,12 @@ var ts; getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 157 /* SetAccessor */ ? 156 /* GetAccessor */ : 157 /* SetAccessor */; + var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 157 /* SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 156 /* GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -55279,10 +57451,15 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { - return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; + return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -55293,9 +57470,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55345,7 +57522,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 277 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -55360,12 +57537,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 242 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 277 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -55384,6 +57561,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55428,6 +57608,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55455,31 +57637,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55491,7 +57672,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55539,14 +57720,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 154 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 156 /* 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 === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */) { + else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* 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); @@ -55563,23 +57744,23 @@ var ts; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 132 /* ReadonlyKeyword */) { - if (node.kind === 151 /* PropertySignature */ || node.kind === 153 /* MethodSignature */) { + if (modifier.kind !== 133 /* ReadonlyKeyword */) { + if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 160 /* IndexSignature */) { + if (node.kind === 162 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 76 /* ConstKeyword */: - if (node.kind !== 241 /* EnumDeclaration */) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); + case 77 /* ConstKeyword */: + if (node.kind !== 243 /* EnumDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */)); } break; - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: + case 115 /* PublicKeyword */: + case 114 /* ProtectedKeyword */: + case 113 /* PrivateKeyword */: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); @@ -55593,11 +57774,11 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { - if (modifier.kind === 112 /* PrivateKeyword */) { + if (modifier.kind === 113 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -55606,7 +57787,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -55616,10 +57797,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -55628,18 +57809,18 @@ var ts; flags |= 32 /* Static */; lastStatic = modifier; break; - case 132 /* ReadonlyKeyword */: + case 133 /* ReadonlyKeyword */: if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */ && node.kind !== 160 /* IndexSignature */ && node.kind !== 149 /* Parameter */) { + else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; lastReadonly = modifier; break; - case 84 /* ExportKeyword */: + case 85 /* ExportKeyword */: if (flags & 1 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -55652,52 +57833,52 @@ 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 === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; - case 79 /* DefaultKeyword */: - var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + case 80 /* DefaultKeyword */: + var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; break; - case 124 /* DeclareKeyword */: + case 125 /* DeclareKeyword */: if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 243 /* ModuleBlock */) { + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; lastDeclare = modifier; break; - case 117 /* AbstractKeyword */: + case 118 /* AbstractKeyword */: if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 238 /* ClassDeclaration */) { - if (node.kind !== 154 /* MethodDeclaration */ && - node.kind !== 152 /* PropertyDeclaration */ && - node.kind !== 156 /* GetAccessor */ && - node.kind !== 157 /* SetAccessor */) { + if (node.kind !== 240 /* ClassDeclaration */) { + if (node.kind !== 156 /* MethodDeclaration */ && + node.kind !== 154 /* PropertyDeclaration */ && + node.kind !== 158 /* GetAccessor */ && + node.kind !== 159 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 238 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -55709,14 +57890,14 @@ var ts; } flags |= 128 /* Abstract */; break; - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 149 /* Parameter */) { + else if (node.kind === 151 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -55724,7 +57905,7 @@ var ts; break; } } - if (node.kind === 155 /* Constructor */) { + if (node.kind === 157 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -55739,13 +57920,13 @@ var ts; } return false; } - else if ((node.kind === 247 /* ImportDeclaration */ || node.kind === 246 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -55766,38 +57947,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 155 /* Constructor */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 160 /* IndexSignature */: - case 242 /* ModuleDeclaration */: - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 149 /* Parameter */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 157 /* Constructor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 162 /* IndexSignature */: + case 244 /* ModuleDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 151 /* Parameter */: return false; default: - if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { return false; } switch (node.kind) { - case 237 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 238 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 239 /* InterfaceDeclaration */: - case 217 /* VariableStatement */: - case 240 /* TypeAliasDeclaration */: + case 239 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */); + case 240 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */); + case 241 /* InterfaceDeclaration */: + case 219 /* VariableStatement */: + case 242 /* TypeAliasDeclaration */: return true; - case 241 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); + case 243 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */); default: ts.Debug.fail(); return false; @@ -55809,10 +57990,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 154 /* MethodDeclaration */: - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -55865,11 +58046,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -55909,12 +58111,12 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 137 /* StringKeyword */ && parameter.type.kind !== 134 /* NumberKeyword */) { + if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) { var type = getTypeFromTypeNode(parameter.type); if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); } - if (type.flags & 262144 /* Union */ && allTypesAssignableToKind(type, 64 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); @@ -55945,7 +58147,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 208 /* OmittedExpression */) { + if (arg.kind === 210 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -55975,7 +58177,7 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (heritageClause.token === 86 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -55988,7 +58190,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -56004,14 +58206,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (heritageClause.token === 86 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } // Grammar checking heritageClause inside class declaration @@ -56022,20 +58224,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 147 /* ComputedPropertyName */) { + if (node.kind !== 149 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 202 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 237 /* FunctionDeclaration */ || - node.kind === 194 /* FunctionExpression */ || - node.kind === 154 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ || + node.kind === 196 /* FunctionExpression */ || + node.kind === 156 /* MethodDeclaration */); if (node.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -56047,6 +58249,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56058,15 +58263,15 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 275 /* SpreadAssignment */) { + if (prop.kind === 277 /* SpreadAssignment */) { continue; } var name = prop.name; - if (name.kind === 147 /* ComputedPropertyName */) { + if (name.kind === 149 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 274 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 276 /* 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); @@ -56075,7 +58280,7 @@ var ts; if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 154 /* MethodDeclaration */) { + if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -56090,21 +58295,23 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 275 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { checkGrammarNumericLiteral(name); } // falls through - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: currentKind = 1 /* Property */; break; - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: currentKind = 2 /* GetAccessor */; break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: currentKind = 4 /* SetAccessor */; break; default: @@ -56141,7 +58348,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 267 /* JsxSpreadAttribute */) { + if (attr.kind === 269 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -56151,7 +58358,7 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 268 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -56160,12 +58367,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 225 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 236 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -56180,20 +58387,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* 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 === 224 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 226 /* 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); @@ -56220,11 +58427,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 156 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 157 /* SetAccessor */) { + else if (kind === 159 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -56248,23 +58455,23 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } function checkGrammarTypeOperatorNode(node) { - if (node.operator === 141 /* UniqueKeyword */) { - if (node.type.kind !== 138 /* SymbolKeyword */) { - return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(138 /* SymbolKeyword */)); + if (node.operator === 142 /* UniqueKeyword */) { + if (node.type.kind !== 139 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */)); } var parent = ts.walkUpParenthesizedTypes(node.parent); switch (parent.kind) { - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: var decl = parent; - if (decl.name.kind !== 71 /* Identifier */) { + if (decl.name.kind !== 72 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); } if (!ts.isVariableDeclarationInVariableStatement(decl)) { @@ -56274,13 +58481,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: if (!ts.hasModifier(parent, 32 /* Static */) || !ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: if (!ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -56299,15 +58506,18 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 154 /* MethodDeclaration */) { - if (node.parent.kind === 186 /* ObjectLiteralExpression */) { + if (node.kind === 156 /* MethodDeclaration */) { + if (node.parent.kind === 188 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 120 /* AsyncKeyword */)) { + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56325,14 +58535,14 @@ var ts; if (node.flags & 4194304 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 154 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 156 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 239 /* InterfaceDeclaration */) { + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 166 /* TypeLiteral */) { + else if (node.parent.kind === 168 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -56343,11 +58553,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 226 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 228 /* 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); @@ -56355,8 +58565,8 @@ var ts; return false; } break; - case 230 /* SwitchStatement */: - if (node.kind === 227 /* BreakStatement */ && !node.label) { + case 232 /* SwitchStatement */: + if (node.kind === 229 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -56371,13 +58581,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 227 /* BreakStatement */ + var message = node.kind === 229 /* 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 === 227 /* BreakStatement */ + var message = node.kind === 229 /* 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); @@ -56400,30 +58610,45 @@ var ts; } } function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isBigIntLiteralExpression(expr) { + return expr.kind === 9 /* BigIntLiteral */ || + expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ && + expr.operand.kind === 9 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + var initializer = node.initializer; + if (initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ || + isBigIntLiteralExpression(initializer)); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { + if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56434,7 +58659,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 217 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && @@ -56451,7 +58676,7 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkESModuleMarker(name) { - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } @@ -56468,8 +58693,8 @@ var ts; return false; } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71 /* Identifier */) { - if (name.originalKeywordKind === 110 /* LetKeyword */) { + if (name.kind === 72 /* Identifier */) { + if (name.originalKeywordKind === 111 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -56496,15 +58721,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 220 /* IfStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 229 /* WithStatement */: - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 222 /* IfStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: return false; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -56522,12 +58747,12 @@ var ts; function checkGrammarMetaProperty(node) { var escapedText = node.name.escapedText; switch (node.keywordToken) { - case 94 /* NewKeyword */: + case 95 /* NewKeyword */: if (escapedText !== "target") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); } break; - case 91 /* ImportKeyword */: + case 92 /* ImportKeyword */: if (escapedText !== "meta") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); } @@ -56563,10 +58788,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56581,7 +58807,7 @@ var ts; return true; } } - else if (node.parent.kind === 239 /* InterfaceDeclaration */) { + else if (node.parent.kind === 241 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -56589,7 +58815,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 166 /* TypeLiteral */) { + else if (node.parent.kind === 168 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -56597,8 +58823,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -56618,13 +58844,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 239 /* InterfaceDeclaration */ || - node.kind === 240 /* TypeAliasDeclaration */ || - node.kind === 247 /* ImportDeclaration */ || - node.kind === 246 /* ImportEqualsDeclaration */ || - node.kind === 253 /* ExportDeclaration */ || - node.kind === 252 /* ExportAssignment */ || - node.kind === 245 /* NamespaceExportDeclaration */ || + if (node.kind === 241 /* InterfaceDeclaration */ || + node.kind === 242 /* TypeAliasDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 248 /* ImportEqualsDeclaration */ || + node.kind === 255 /* ExportDeclaration */ || + node.kind === 254 /* ExportAssignment */ || + node.kind === 247 /* NamespaceExportDeclaration */ || ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -56633,7 +58859,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 === 217 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -56660,7 +58886,7 @@ var ts; // 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 === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -56682,20 +58908,32 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 180 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 276 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */; + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */; var literal = (withMinus ? "-" : "") + "0o" + node.text; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } return false; } + function checkGrammarBigIntLiteral(node) { + var literalType = ts.isLiteralTypeNode(node.parent) || + ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 6 /* ESNext */) { + if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { @@ -56740,8 +58978,8 @@ var ts; /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); @@ -56749,14 +58987,14 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 248 /* ImportClause */: // For default import - case 246 /* ImportEqualsDeclaration */: - case 249 /* NamespaceImport */: - case 251 /* ImportSpecifier */: // For rename import `x as y` + case 250 /* ImportClause */: // For default import + case 248 /* ImportEqualsDeclaration */: + case 251 /* NamespaceImport */: + case 253 /* ImportSpecifier */: // For rename import `x as y` return true; - case 71 /* Identifier */: + case 72 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 251 /* ImportSpecifier */; + return decl.parent.kind === 253 /* ImportSpecifier */; default: return false; } @@ -56776,7 +59014,7 @@ var ts; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); function typeIsLiteralType(type) { - return !!(type.flags & 448 /* Literal */); + return !!(type.flags & 2944 /* Literal */); } })(ts || (ts = {})); var ts; @@ -56840,6 +59078,9 @@ var ts; if (typeof value === "number") { return createNumericLiteral(value + ""); } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n"); + } if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } @@ -56859,14 +59100,20 @@ var ts; return node; } ts.createNumericLiteral = createNumericLiteral; + function createBigIntLiteral(value) { + var node = createSynthesizedNode(9 /* BigIntLiteral */); + node.text = value; + return node; + } + ts.createBigIntLiteral = createBigIntLiteral; function createStringLiteral(text) { - var node = createSynthesizedNode(9 /* StringLiteral */); + var node = createSynthesizedNode(10 /* StringLiteral */); node.text = text; return node; } ts.createStringLiteral = createStringLiteral; function createRegularExpressionLiteral(text) { - var node = createSynthesizedNode(12 /* RegularExpressionLiteral */); + var node = createSynthesizedNode(13 /* RegularExpressionLiteral */); node.text = text; return node; } @@ -56877,7 +59124,7 @@ var ts; return node; } function createIdentifier(text, typeArguments) { - var node = createSynthesizedNode(71 /* Identifier */); + var node = createSynthesizedNode(72 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateFlags = 0 /* None */; @@ -56958,23 +59205,23 @@ var ts; ts.createToken = createToken; // Reserved words function createSuper() { - return createSynthesizedNode(97 /* SuperKeyword */); + return createSynthesizedNode(98 /* SuperKeyword */); } ts.createSuper = createSuper; function createThis() { - return createSynthesizedNode(99 /* ThisKeyword */); + return createSynthesizedNode(100 /* ThisKeyword */); } ts.createThis = createThis; function createNull() { - return createSynthesizedNode(95 /* NullKeyword */); + return createSynthesizedNode(96 /* NullKeyword */); } ts.createNull = createNull; function createTrue() { - return createSynthesizedNode(101 /* TrueKeyword */); + return createSynthesizedNode(102 /* TrueKeyword */); } ts.createTrue = createTrue; function createFalse() { - return createSynthesizedNode(86 /* FalseKeyword */); + return createSynthesizedNode(87 /* FalseKeyword */); } ts.createFalse = createFalse; // Modifiers @@ -56985,44 +59232,44 @@ var ts; function createModifiersFromModifierFlags(flags) { var result = []; if (flags & 1 /* Export */) { - result.push(createModifier(84 /* ExportKeyword */)); + result.push(createModifier(85 /* ExportKeyword */)); } if (flags & 2 /* Ambient */) { - result.push(createModifier(124 /* DeclareKeyword */)); + result.push(createModifier(125 /* DeclareKeyword */)); } if (flags & 512 /* Default */) { - result.push(createModifier(79 /* DefaultKeyword */)); + result.push(createModifier(80 /* DefaultKeyword */)); } if (flags & 2048 /* Const */) { - result.push(createModifier(76 /* ConstKeyword */)); + result.push(createModifier(77 /* ConstKeyword */)); } if (flags & 4 /* Public */) { - result.push(createModifier(114 /* PublicKeyword */)); + result.push(createModifier(115 /* PublicKeyword */)); } if (flags & 8 /* Private */) { - result.push(createModifier(112 /* PrivateKeyword */)); + result.push(createModifier(113 /* PrivateKeyword */)); } if (flags & 16 /* Protected */) { - result.push(createModifier(113 /* ProtectedKeyword */)); + result.push(createModifier(114 /* ProtectedKeyword */)); } if (flags & 128 /* Abstract */) { - result.push(createModifier(117 /* AbstractKeyword */)); + result.push(createModifier(118 /* AbstractKeyword */)); } if (flags & 32 /* Static */) { - result.push(createModifier(115 /* StaticKeyword */)); + result.push(createModifier(116 /* StaticKeyword */)); } if (flags & 64 /* Readonly */) { - result.push(createModifier(132 /* ReadonlyKeyword */)); + result.push(createModifier(133 /* ReadonlyKeyword */)); } if (flags & 256 /* Async */) { - result.push(createModifier(120 /* AsyncKeyword */)); + result.push(createModifier(121 /* AsyncKeyword */)); } return result; } ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; // Names function createQualifiedName(left, right) { - var node = createSynthesizedNode(146 /* QualifiedName */); + var node = createSynthesizedNode(148 /* QualifiedName */); node.left = left; node.right = asName(right); return node; @@ -57041,7 +59288,7 @@ var ts; : expression; } function createComputedPropertyName(expression) { - var node = createSynthesizedNode(147 /* ComputedPropertyName */); + var node = createSynthesizedNode(149 /* ComputedPropertyName */); node.expression = parenthesizeForComputedName(expression); return node; } @@ -57054,7 +59301,7 @@ var ts; ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(148 /* TypeParameter */); + var node = createSynthesizedNode(150 /* TypeParameter */); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -57070,7 +59317,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149 /* Parameter */); + var node = createSynthesizedNode(151 /* Parameter */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -57094,7 +59341,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(150 /* Decorator */); + var node = createSynthesizedNode(152 /* Decorator */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -57107,7 +59354,7 @@ var ts; ts.updateDecorator = updateDecorator; // Type Elements function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(151 /* PropertySignature */); + var node = createSynthesizedNode(153 /* PropertySignature */); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -57127,12 +59374,12 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createSynthesizedNode(152 /* PropertyDeclaration */); + var node = createSynthesizedNode(154 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); - node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined; - node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined; + node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined; + node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined; node.type = type; node.initializer = initializer; return node; @@ -57142,8 +59389,8 @@ var ts; return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name - || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined) - || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined) + || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) @@ -57151,7 +59398,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(153 /* MethodSignature */, typeParameters, parameters, type); + var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -57168,7 +59415,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(154 /* MethodDeclaration */); + var node = createSynthesizedNode(156 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -57196,7 +59443,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(155 /* Constructor */); + var node = createSynthesizedNode(157 /* Constructor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -57216,7 +59463,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(156 /* GetAccessor */); + var node = createSynthesizedNode(158 /* GetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57239,7 +59486,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(157 /* SetAccessor */); + var node = createSynthesizedNode(159 /* SetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -57260,7 +59507,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(158 /* CallSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -57268,7 +59515,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(159 /* ConstructSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -57276,7 +59523,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(160 /* IndexSignature */); + var node = createSynthesizedNode(162 /* IndexSignature */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -57316,7 +59563,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(161 /* TypePredicate */); + var node = createSynthesizedNode(163 /* TypePredicate */); node.parameterName = asName(parameterName); node.type = type; return node; @@ -57330,7 +59577,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(162 /* TypeReference */); + var node = createSynthesizedNode(164 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -57344,7 +59591,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(163 /* FunctionType */, typeParameters, parameters, type); + return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -57352,7 +59599,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(164 /* ConstructorType */, typeParameters, parameters, type); + return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -57360,7 +59607,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(165 /* TypeQuery */); + var node = createSynthesizedNode(167 /* TypeQuery */); node.exprName = exprName; return node; } @@ -57372,7 +59619,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(166 /* TypeLiteral */); + var node = createSynthesizedNode(168 /* TypeLiteral */); node.members = createNodeArray(members); return node; } @@ -57384,7 +59631,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(167 /* ArrayType */); + var node = createSynthesizedNode(169 /* ArrayType */); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -57396,7 +59643,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(168 /* TupleType */); + var node = createSynthesizedNode(170 /* TupleType */); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -57408,7 +59655,7 @@ var ts; } ts.updateTupleTypeNode = updateTupleTypeNode; function createOptionalTypeNode(type) { - var node = createSynthesizedNode(169 /* OptionalType */); + var node = createSynthesizedNode(171 /* OptionalType */); node.type = ts.parenthesizeArrayTypeMember(type); return node; } @@ -57420,7 +59667,7 @@ var ts; } ts.updateOptionalTypeNode = updateOptionalTypeNode; function createRestTypeNode(type) { - var node = createSynthesizedNode(170 /* RestType */); + var node = createSynthesizedNode(172 /* RestType */); node.type = type; return node; } @@ -57432,7 +59679,7 @@ var ts; } ts.updateRestTypeNode = updateRestTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(171 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(173 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -57440,7 +59687,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(172 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -57459,7 +59706,7 @@ var ts; : node; } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createSynthesizedNode(173 /* ConditionalType */); + var node = createSynthesizedNode(175 /* ConditionalType */); node.checkType = ts.parenthesizeConditionalTypeMember(checkType); node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); node.trueType = trueType; @@ -57477,7 +59724,7 @@ var ts; } ts.updateConditionalTypeNode = updateConditionalTypeNode; function createInferTypeNode(typeParameter) { - var node = createSynthesizedNode(174 /* InferType */); + var node = createSynthesizedNode(176 /* InferType */); node.typeParameter = typeParameter; return node; } @@ -57489,7 +59736,7 @@ var ts; } ts.updateInferTypeNode = updateInferTypeNode; function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { - var node = createSynthesizedNode(181 /* ImportType */); + var node = createSynthesizedNode(183 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = asNodeArray(typeArguments); @@ -57507,7 +59754,7 @@ var ts; } ts.updateImportTypeNode = updateImportTypeNode; function createParenthesizedType(type) { - var node = createSynthesizedNode(175 /* ParenthesizedType */); + var node = createSynthesizedNode(177 /* ParenthesizedType */); node.type = type; return node; } @@ -57519,12 +59766,12 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(176 /* ThisType */); + return createSynthesizedNode(178 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; function createTypeOperatorNode(operatorOrType, type) { - var node = createSynthesizedNode(177 /* TypeOperator */); - node.operator = typeof operatorOrType === "number" ? operatorOrType : 128 /* KeyOfKeyword */; + var node = createSynthesizedNode(179 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */; node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } @@ -57534,7 +59781,7 @@ var ts; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(178 /* IndexedAccessType */); + var node = createSynthesizedNode(180 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -57548,7 +59795,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(179 /* MappedType */); + var node = createSynthesizedNode(181 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -57566,7 +59813,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(180 /* LiteralType */); + var node = createSynthesizedNode(182 /* LiteralType */); node.literal = literal; return node; } @@ -57579,7 +59826,7 @@ var ts; ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(182 /* ObjectBindingPattern */); + var node = createSynthesizedNode(184 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -57591,7 +59838,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(183 /* ArrayBindingPattern */); + var node = createSynthesizedNode(185 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -57603,7 +59850,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(184 /* BindingElement */); + var node = createSynthesizedNode(186 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -57622,7 +59869,7 @@ var ts; ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(185 /* ArrayLiteralExpression */); + var node = createSynthesizedNode(187 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -57636,7 +59883,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(186 /* ObjectLiteralExpression */); + var node = createSynthesizedNode(188 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -57650,7 +59897,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(187 /* PropertyAccessExpression */); + var node = createSynthesizedNode(189 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); @@ -57667,7 +59914,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(188 /* ElementAccessExpression */); + var node = createSynthesizedNode(190 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -57681,7 +59928,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(189 /* CallExpression */); + var node = createSynthesizedNode(191 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -57697,7 +59944,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(190 /* NewExpression */); + var node = createSynthesizedNode(192 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -57713,7 +59960,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { - var node = createSynthesizedNode(191 /* TaggedTemplateExpression */); + var node = createSynthesizedNode(193 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); if (template) { node.typeArguments = asNodeArray(typeArgumentsOrTemplate); @@ -57736,7 +59983,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(192 /* TypeAssertionExpression */); + var node = createSynthesizedNode(194 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -57750,7 +59997,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(193 /* ParenthesizedExpression */); + var node = createSynthesizedNode(195 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -57762,7 +60009,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(194 /* FunctionExpression */); + var node = createSynthesizedNode(196 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -57786,12 +60033,12 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(195 /* ArrowFunction */); + var node = createSynthesizedNode(197 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(36 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */); node.body = ts.parenthesizeConciseBody(body); return node; } @@ -57808,7 +60055,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(196 /* DeleteExpression */); + var node = createSynthesizedNode(198 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57820,7 +60067,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(197 /* TypeOfExpression */); + var node = createSynthesizedNode(199 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57832,7 +60079,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(198 /* VoidExpression */); + var node = createSynthesizedNode(200 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57844,7 +60091,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(199 /* AwaitExpression */); + var node = createSynthesizedNode(201 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -57856,7 +60103,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(200 /* PrefixUnaryExpression */); + var node = createSynthesizedNode(202 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -57869,7 +60116,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(201 /* PostfixUnaryExpression */); + var node = createSynthesizedNode(203 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -57882,7 +60129,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(202 /* BinaryExpression */); + var node = createSynthesizedNode(204 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -57899,11 +60146,11 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(203 /* ConditionalExpression */); + var node = createSynthesizedNode(205 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); - node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); - node.colonToken = whenFalse ? colonToken : createToken(56 /* ColonToken */); + node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */); node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); return node; } @@ -57919,7 +60166,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(204 /* TemplateExpression */); + var node = createSynthesizedNode(206 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -57933,33 +60180,33 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createTemplateHead(text) { - var node = createSynthesizedNode(14 /* TemplateHead */); + var node = createSynthesizedNode(15 /* TemplateHead */); node.text = text; return node; } ts.createTemplateHead = createTemplateHead; function createTemplateMiddle(text) { - var node = createSynthesizedNode(15 /* TemplateMiddle */); + var node = createSynthesizedNode(16 /* TemplateMiddle */); node.text = text; return node; } ts.createTemplateMiddle = createTemplateMiddle; function createTemplateTail(text) { - var node = createSynthesizedNode(16 /* TemplateTail */); + var node = createSynthesizedNode(17 /* TemplateTail */); node.text = text; return node; } ts.createTemplateTail = createTemplateTail; function createNoSubstitutionTemplateLiteral(text) { - var node = createSynthesizedNode(13 /* NoSubstitutionTemplateLiteral */); + var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */); node.text = text; return node; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(205 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + var node = createSynthesizedNode(207 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; } ts.createYield = createYield; @@ -57971,7 +60218,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(206 /* SpreadElement */); + var node = createSynthesizedNode(208 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -57983,7 +60230,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(207 /* ClassExpression */); + var node = createSynthesizedNode(209 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58004,11 +60251,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(208 /* OmittedExpression */); + return createSynthesizedNode(210 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(209 /* ExpressionWithTypeArguments */); + var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -58022,7 +60269,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(210 /* AsExpression */); + var node = createSynthesizedNode(212 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -58036,7 +60283,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(211 /* NonNullExpression */); + var node = createSynthesizedNode(213 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -58048,7 +60295,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(212 /* MetaProperty */); + var node = createSynthesizedNode(214 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -58062,7 +60309,7 @@ var ts; ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(214 /* TemplateSpan */); + var node = createSynthesizedNode(216 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -58076,12 +60323,12 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(215 /* SemicolonClassElement */); + return createSynthesizedNode(217 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(216 /* Block */); + var block = createSynthesizedNode(218 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -58095,7 +60342,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(217 /* VariableStatement */); + var node = createSynthesizedNode(219 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -58110,11 +60357,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(218 /* EmptyStatement */); + return createSynthesizedNode(220 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; function createExpressionStatement(expression) { - var node = createSynthesizedNode(219 /* ExpressionStatement */); + var node = createSynthesizedNode(221 /* ExpressionStatement */); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -58130,7 +60377,7 @@ var ts; /** @deprecated Use `updateExpressionStatement` instead. */ ts.updateStatement = updateExpressionStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(220 /* IfStatement */); + var node = createSynthesizedNode(222 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -58146,7 +60393,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(221 /* DoStatement */); + var node = createSynthesizedNode(223 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -58160,7 +60407,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(222 /* WhileStatement */); + var node = createSynthesizedNode(224 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -58174,7 +60421,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(223 /* ForStatement */); + var node = createSynthesizedNode(225 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -58192,7 +60439,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(224 /* ForInStatement */); + var node = createSynthesizedNode(226 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -58208,7 +60455,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(225 /* ForOfStatement */); + var node = createSynthesizedNode(227 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -58226,7 +60473,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(226 /* ContinueStatement */); + var node = createSynthesizedNode(228 /* ContinueStatement */); node.label = asName(label); return node; } @@ -58238,7 +60485,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(227 /* BreakStatement */); + var node = createSynthesizedNode(229 /* BreakStatement */); node.label = asName(label); return node; } @@ -58250,7 +60497,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(228 /* ReturnStatement */); + var node = createSynthesizedNode(230 /* ReturnStatement */); node.expression = expression; return node; } @@ -58262,7 +60509,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(229 /* WithStatement */); + var node = createSynthesizedNode(231 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -58276,7 +60523,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(230 /* SwitchStatement */); + var node = createSynthesizedNode(232 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -58290,7 +60537,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(231 /* LabeledStatement */); + var node = createSynthesizedNode(233 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -58304,7 +60551,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(232 /* ThrowStatement */); + var node = createSynthesizedNode(234 /* ThrowStatement */); node.expression = expression; return node; } @@ -58316,7 +60563,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(233 /* TryStatement */); + var node = createSynthesizedNode(235 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -58332,11 +60579,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(234 /* DebuggerStatement */); + return createSynthesizedNode(236 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(235 /* VariableDeclaration */); + var node = createSynthesizedNode(237 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -58353,7 +60600,7 @@ var ts; ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(236 /* VariableDeclarationList */); + var node = createSynthesizedNode(238 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; @@ -58366,7 +60613,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(237 /* FunctionDeclaration */); + var node = createSynthesizedNode(239 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -58392,7 +60639,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(238 /* ClassDeclaration */); + var node = createSynthesizedNode(240 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58414,7 +60661,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(239 /* InterfaceDeclaration */); + var node = createSynthesizedNode(241 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58436,7 +60683,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(240 /* TypeAliasDeclaration */); + var node = createSynthesizedNode(242 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58456,7 +60703,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(241 /* EnumDeclaration */); + var node = createSynthesizedNode(243 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58475,7 +60722,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(242 /* ModuleDeclaration */); + var node = createSynthesizedNode(244 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -58494,7 +60741,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(243 /* ModuleBlock */); + var node = createSynthesizedNode(245 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -58506,7 +60753,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(244 /* CaseBlock */); + var node = createSynthesizedNode(246 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -58518,7 +60765,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(245 /* NamespaceExportDeclaration */); + var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -58530,7 +60777,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(246 /* ImportEqualsDeclaration */); + var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -58548,7 +60795,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(247 /* ImportDeclaration */); + var node = createSynthesizedNode(249 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -58566,7 +60813,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(248 /* ImportClause */); + var node = createSynthesizedNode(250 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -58580,7 +60827,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(249 /* NamespaceImport */); + var node = createSynthesizedNode(251 /* NamespaceImport */); node.name = name; return node; } @@ -58592,7 +60839,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(250 /* NamedImports */); + var node = createSynthesizedNode(252 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -58604,7 +60851,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(251 /* ImportSpecifier */); + var node = createSynthesizedNode(253 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -58618,11 +60865,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(252 /* ExportAssignment */); + var node = createSynthesizedNode(254 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -58635,7 +60882,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(253 /* ExportDeclaration */); + var node = createSynthesizedNode(255 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -58653,7 +60900,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(254 /* NamedExports */); + var node = createSynthesizedNode(256 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -58665,7 +60912,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(255 /* ExportSpecifier */); + var node = createSynthesizedNode(257 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -58680,7 +60927,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(257 /* ExternalModuleReference */); + var node = createSynthesizedNode(259 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -58691,9 +60938,57 @@ var ts; : node; } ts.updateExternalModuleReference = updateExternalModuleReference; + // JSDoc + /* @internal */ + function createJSDocTypeExpression(type) { + var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + node.type = type; + return node; + } + ts.createJSDocTypeExpression = createJSDocTypeExpression; + /* @internal */ + function createJSDocTypeTag(typeExpression, comment) { + var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocTypeTag = createJSDocTypeTag; + /* @internal */ + function createJSDocReturnTag(typeExpression, comment) { + var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + ts.createJSDocReturnTag = createJSDocReturnTag; + /* @internal */ + function createJSDocParamTag(name, isBracketed, typeExpression, comment) { + var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + ts.createJSDocParamTag = createJSDocParamTag; + /* @internal */ + function createJSDocComment(comment, tags) { + var node = createSynthesizedNode(291 /* JSDocComment */); + node.comment = comment; + node.tags = tags; + return node; + } + ts.createJSDocComment = createJSDocComment; + /* @internal */ + function createJSDocTag(kind, tagName) { + var node = createSynthesizedNode(kind); + node.tagName = createIdentifier(tagName); + return node; + } // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(258 /* JsxElement */); + var node = createSynthesizedNode(260 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -58709,7 +61004,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); + var node = createSynthesizedNode(261 /* JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -58725,7 +61020,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(260 /* JsxOpeningElement */); + var node = createSynthesizedNode(262 /* JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -58741,7 +61036,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(261 /* JsxClosingElement */); + var node = createSynthesizedNode(263 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -58753,7 +61048,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxFragment(openingFragment, children, closingFragment) { - var node = createSynthesizedNode(262 /* JsxFragment */); + var node = createSynthesizedNode(264 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -58769,7 +61064,7 @@ var ts; } ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(265 /* JsxAttribute */); + var node = createSynthesizedNode(267 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -58783,7 +61078,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(266 /* JsxAttributes */); + var node = createSynthesizedNode(268 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -58795,7 +61090,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(267 /* JsxSpreadAttribute */); + var node = createSynthesizedNode(269 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -58807,7 +61102,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(268 /* JsxExpression */); + var node = createSynthesizedNode(270 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -58821,7 +61116,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(269 /* CaseClause */); + var node = createSynthesizedNode(271 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -58835,7 +61130,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(270 /* DefaultClause */); + var node = createSynthesizedNode(272 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -58847,7 +61142,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(271 /* HeritageClause */); + var node = createSynthesizedNode(273 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -58860,7 +61155,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(272 /* CatchClause */); + var node = createSynthesizedNode(274 /* CatchClause */); node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -58875,7 +61170,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(273 /* PropertyAssignment */); + var node = createSynthesizedNode(275 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = ts.parenthesizeExpressionForList(initializer); @@ -58890,7 +61185,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(274 /* ShorthandPropertyAssignment */); + var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -58904,7 +61199,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(275 /* SpreadAssignment */); + var node = createSynthesizedNode(277 /* SpreadAssignment */); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } @@ -58917,7 +61212,7 @@ var ts; ts.updateSpreadAssignment = updateSpreadAssignment; // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(276 /* EnumMember */); + var node = createSynthesizedNode(278 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -58938,7 +61233,7 @@ var ts; (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { - var updated = createSynthesizedNode(277 /* SourceFile */); + var updated = createSynthesizedNode(279 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -59022,7 +61317,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(305 /* NotEmittedStatement */); + var node = createSynthesizedNode(307 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -59034,7 +61329,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -59046,7 +61341,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(308 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -59061,7 +61356,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -59077,17 +61372,17 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 307 /* CommaListExpression */) { + if (node.kind === 309 /* CommaListExpression */) { return node.elements; } - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { return [node.left, node.right]; } } return node; } function createCommaList(elements) { - var node = createSynthesizedNode(307 /* CommaListExpression */); + var node = createSynthesizedNode(309 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -59100,14 +61395,14 @@ var ts; ts.updateCommaList = updateCommaList; function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = ts.createNode(278 /* Bundle */); + var node = ts.createNode(280 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; function createUnparsedSourceFile(text, mapPath, map) { - var node = ts.createNode(279 /* UnparsedSource */); + var node = ts.createNode(281 /* UnparsedSource */); node.text = text; node.sourceMapPath = mapPath; node.sourceMapText = map; @@ -59115,7 +61410,7 @@ var ts; } ts.createUnparsedSourceFile = createUnparsedSourceFile; function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { - var node = ts.createNode(280 /* InputFiles */); + var node = ts.createNode(282 /* InputFiles */); node.javascriptText = javascript; node.javascriptMapPath = javascriptMapPath; node.javascriptMapText = javascriptMapText; @@ -59157,47 +61452,47 @@ var ts; } ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { - return createBinary(left, 26 /* CommaToken */, right); + return createBinary(left, 27 /* CommaToken */, right); } ts.createComma = createComma; function createLessThan(left, right) { - return createBinary(left, 27 /* LessThanToken */, right); + return createBinary(left, 28 /* LessThanToken */, right); } ts.createLessThan = createLessThan; function createAssignment(left, right) { - return createBinary(left, 58 /* EqualsToken */, right); + return createBinary(left, 59 /* EqualsToken */, right); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 34 /* EqualsEqualsEqualsToken */, right); + return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 35 /* ExclamationEqualsEqualsToken */, right); + return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 37 /* PlusToken */, right); + return createBinary(left, 38 /* PlusToken */, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 38 /* MinusToken */, right); + return createBinary(left, 39 /* MinusToken */, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand) { - return createPostfix(operand, 43 /* PlusPlusToken */); + return createPostfix(operand, 44 /* PlusPlusToken */); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 53 /* AmpersandAmpersandToken */, right); + return createBinary(left, 54 /* AmpersandAmpersandToken */, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 54 /* BarBarToken */, right); + return createBinary(left, 55 /* BarBarToken */, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(51 /* ExclamationToken */, operand); + return createPrefix(52 /* ExclamationToken */, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { @@ -59258,7 +61553,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -59769,7 +62064,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 231 /* LabeledStatement */ + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -59781,19 +62076,20 @@ var ts; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = ts.skipParentheses(node); switch (target.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return cacheIdentifiers; - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: + case 9 /* BigIntLiteral */: + case 10 /* StringLiteral */: return false; - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -59808,7 +62104,7 @@ var ts; thisArg = ts.createThis(); target = callee; } - else if (callee.kind === 97 /* SuperKeyword */) { + else if (callee.kind === 98 /* SuperKeyword */) { thisArg = ts.createThis(); target = languageVersion < 2 /* ES2015 */ ? ts.setTextRange(ts.createIdentifier("_super"), callee) @@ -59820,7 +62116,7 @@ var ts; } else { switch (callee.kind) { - case 187 /* PropertyAccessExpression */: { + case 189 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -59833,7 +62129,7 @@ var ts; } break; } - case 188 /* ElementAccessExpression */: { + case 190 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -59890,14 +62186,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -59905,7 +62201,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_9 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -59916,7 +62212,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_9.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -59928,15 +62224,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_9.push(setter); + properties_8.push(setter); } - properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_9, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -60174,6 +62470,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60187,19 +62498,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -60220,7 +62519,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 193 /* ParenthesizedExpression */) { + if (skipped.kind === 195 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -60254,10 +62553,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -60269,7 +62568,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 205 /* YieldExpression */) { + && operand.kind === 207 /* YieldExpression */) { return false; } return true; @@ -60306,7 +62605,7 @@ var ts; // the same kind (recursively). // "a"+(1+2) => "a"+(1+2) // "a"+("b"+"c") => "a"+"b"+"c" - if (binaryOperator === 37 /* PlusToken */) { + if (binaryOperator === 38 /* PlusToken */) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -60341,10 +62640,10 @@ var ts; // // While addition is associative in mathematics, JavaScript's `+` is not // guaranteed to be associative as it is overloaded with string concatenation. - return binaryOperator === 39 /* AsteriskToken */ - || binaryOperator === 49 /* BarToken */ - || binaryOperator === 48 /* AmpersandToken */ - || binaryOperator === 50 /* CaretToken */; + return binaryOperator === 40 /* AsteriskToken */ + || binaryOperator === 50 /* BarToken */ + || binaryOperator === 49 /* AmpersandToken */ + || binaryOperator === 51 /* CaretToken */; } /** * This function determines whether an expression consists of a homogeneous set of @@ -60357,7 +62656,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { + if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -60372,7 +62671,7 @@ var ts; return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(203 /* ConditionalExpression */, 55 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { @@ -60407,8 +62706,8 @@ var ts; var needsParens = isCommaSequence(check); if (!needsParens) { switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 207 /* ClassExpression */: - case 194 /* FunctionExpression */: + case 209 /* ClassExpression */: + case 196 /* FunctionExpression */: needsParens = true; } } @@ -60424,9 +62723,9 @@ var ts; function parenthesizeForNew(expression) { var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 189 /* CallExpression */: + case 191 /* CallExpression */: return ts.createParen(expression); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return !leftmostExpr.arguments ? ts.createParen(expression) : expression; @@ -60449,7 +62748,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 190 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -60487,7 +62786,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, 26 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -60498,29 +62797,29 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 194 /* FunctionExpression */ || kind === 195 /* ArrowFunction */) { + if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 186 /* ObjectLiteralExpression */ || leftmostExpressionKind === 194 /* FunctionExpression */) { + if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeConditionalTypeMember(member) { - return member.kind === 173 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; } ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return ts.createParenthesizedType(member); } return parenthesizeConditionalTypeMember(member); @@ -60528,9 +62827,9 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 165 /* TypeQuery */: - case 177 /* TypeOperator */: - case 174 /* InferType */: + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 176 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -60556,28 +62855,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: node = node.operand; continue; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: node = node.left; continue; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: node = node.condition; continue; - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: node = node.tag; continue; - case 189 /* CallExpression */: + case 191 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 210 /* AsExpression */: - case 188 /* ElementAccessExpression */: - case 187 /* PropertyAccessExpression */: - case 211 /* NonNullExpression */: - case 306 /* PartiallyEmittedExpression */: + case 212 /* AsExpression */: + case 190 /* ElementAccessExpression */: + case 189 /* PropertyAccessExpression */: + case 213 /* NonNullExpression */: + case 308 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -60585,15 +62884,15 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 186 /* ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) { return ts.setTextRange(ts.createParen(body), body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { - return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || - node.kind === 307 /* CommaListExpression */; + return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 309 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; @@ -60606,13 +62905,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: - case 211 /* NonNullExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: + case 213 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -60637,7 +62936,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 211 /* NonNullExpression */) { + while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) { node = node.expression; } return node; @@ -60645,11 +62944,11 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 193 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); - case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -60667,7 +62966,7 @@ var ts; * the containing expression is created/updated. */ function isIgnorableParen(node) { - return node.kind === 193 /* ParenthesizedExpression */ + return node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -60732,10 +63031,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 247 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 249 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 253 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -60751,7 +63050,7 @@ var ts; */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 - if (moduleName.kind === 9 /* StringLiteral */) { + if (moduleName.kind === 10 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) || ts.getSynthesizedClone(moduleName); @@ -60854,7 +63153,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -60866,11 +63165,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -60902,12 +63201,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 149 /* Parameter */: - case 184 /* BindingElement */: + case 151 /* Parameter */: + case 186 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 206 /* SpreadElement */: - case 275 /* SpreadAssignment */: + case 208 /* SpreadElement */: + case 277 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -60919,7 +63218,7 @@ var ts; */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 184 /* BindingElement */: + case 186 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -60931,7 +63230,7 @@ var ts; : propertyName; } break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -60943,7 +63242,7 @@ var ts; : propertyName; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -60958,7 +63257,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; - return kind === 9 /* StringLiteral */ + return kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */; } /** @@ -60966,13 +63265,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -61012,11 +63311,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 183 /* ArrayBindingPattern */: - case 185 /* ArrayLiteralExpression */: + case 185 /* ArrayBindingPattern */: + case 187 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 182 /* ObjectBindingPattern */: - case 186 /* ObjectLiteralExpression */: + case 184 /* ObjectBindingPattern */: + case 188 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -61177,276 +63476,276 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */) || kind === 176 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) { return node; } switch (kind) { // Names - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 149 /* Parameter */: + case 151 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 150 /* Decorator */: + case 152 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); // Type elements - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 153 /* MethodSignature */: + case 155 /* MethodSignature */: return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 155 /* Constructor */: + case 157 /* Constructor */: return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 158 /* CallSignature */: + case 160 /* CallSignature */: return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 163 /* FunctionType */: + case 165 /* FunctionType */: return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 164 /* ConstructorType */: + case 166 /* ConstructorType */: return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); - case 168 /* TupleType */: + case 170 /* TupleType */: return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 170 /* RestType */: + case 172 /* RestType */: return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 171 /* UnionType */: + case 173 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); - case 174 /* InferType */: + case 176 /* InferType */: return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 181 /* ImportType */: + case 183 /* ImportType */: return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 179 /* MappedType */: + case 181 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); // Binding patterns - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); // Expression - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 210 /* AsExpression */: + case 212 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 216 /* Block */: + case 218 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 250 /* NamedImports */: + case 252 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 254 /* NamedExports */: + case 256 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 255 /* ExportSpecifier */: + case 257 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 260 /* JsxOpeningElement */: + case 262 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 277 /* SourceFile */: + case 279 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -61488,58 +63787,58 @@ var ts; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 161 /* TypePredicate */ && kind <= 180 /* LiteralType */)) { + if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 215 /* SemicolonClassElement */: - case 218 /* EmptyStatement */: - case 208 /* OmittedExpression */: - case 234 /* DebuggerStatement */: - case 305 /* NotEmittedStatement */: + case 217 /* SemicolonClassElement */: + case 220 /* EmptyStatement */: + case 210 /* OmittedExpression */: + case 236 /* DebuggerStatement */: + case 307 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 149 /* Parameter */: + case 151 /* Parameter */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 150 /* Decorator */: + case 152 /* Decorator */: result = reduceNode(node.expression, cbNode, result); break; // Type member - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61548,12 +63847,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 155 /* Constructor */: + case 157 /* Constructor */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61561,7 +63860,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61569,49 +63868,50 @@ var ts; result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 184 /* BindingElement */: + case 186 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 189 /* CallExpression */: + case 191 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 190 /* NewExpression */: + case 192 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNode(node.template, cbNode, result); break; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -61619,123 +63919,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 193 /* ParenthesizedExpression */: - case 196 /* DeleteExpression */: - case 197 /* TypeOfExpression */: - case 198 /* VoidExpression */: - case 199 /* AwaitExpression */: - case 205 /* YieldExpression */: - case 206 /* SpreadElement */: - case 211 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + case 198 /* DeleteExpression */: + case 199 /* TypeOfExpression */: + case 200 /* VoidExpression */: + case 201 /* AwaitExpression */: + case 207 /* YieldExpression */: + case 208 /* SpreadElement */: + case 213 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 210 /* AsExpression */: + case 212 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; // Element - case 216 /* Block */: + case 218 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 221 /* DoStatement */: + case 223 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 222 /* WhileStatement */: - case 229 /* WithStatement */: + case 224 /* WhileStatement */: + case 231 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 223 /* ForStatement */: + case 225 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: + case 230 /* ReturnStatement */: + case 234 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61744,7 +64044,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -61752,139 +64052,140 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 250 /* NamedImports */: - case 254 /* NamedExports */: + case 252 /* NamedImports */: + case 256 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 251 /* ImportSpecifier */: - case 255 /* ExportSpecifier */: + case 253 /* ImportSpecifier */: + case 257 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: result = reduceNode(node.openingFragment, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingFragment, cbNode, result); break; - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.typeArguments, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 261 /* JsxClosingElement */: + case 263 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); // falls through - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 272 /* CatchClause */: + case 274 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 277 /* SourceFile */: + case 279 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -61957,7 +64258,7 @@ var ts; function aggregateTransformFlagsForSubtree(node) { // We do not transform ambient declarations or types, so there is no need to // recursively aggregate transform flags. - if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 209 /* ExpressionWithTypeArguments */)) { + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) { return 0 /* None */; } // Aggregate the transform flags of each child. @@ -62007,7 +64308,7 @@ var ts; }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, - __debugObjectFlags: { get: function () { return this.flags & 131072 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ @@ -62044,288 +64345,623 @@ var ts; /* @internal */ var ts; (function (ts) { - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); + function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var _a = generatorOptions.extendedDiagnostics + ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit; + // Current source map file and its index in the sources list + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = ts.createMap(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappings = ""; + // Last recorded and encoded mappings + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); + getSources: function () { return rawSources; }, + addSource: addSource, + setSourceContent: setSourceContent, + addName: addName, + addMapping: addMapping, + appendSourceMap: appendSourceMap, + toJSON: toJSON, + toString: function () { return JSON.stringify(toJSON()); } + }; + function addSource(fileName) { + enter(); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + var sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) + sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - // And failing that, check the disk - var text = host.readFile(path); // TODO: GH#18217 - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) + nameToNameIndexMap = ts.createMap(); + var nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + var _a; + ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + var sourceIndexToNewSourceIndexMap = []; + var nameIndexToNewNameIndexMap; + var mappingIterator = decodeMappings(map.mappings); + for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + // Then reencode all the updated mappings into the overall map + var newSourceIndex = void 0; + var newSourceLine = void 0; + var newSourceCharacter = void 0; + var newNameIndex = void 0; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + var rawPath = map.sources[raw.sourceIndex]; + var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } } - }; - cached.set(path, file); - return file; + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) + nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + var newGeneratedLine = raw.generatedLine + generatedLine; + var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; + } while (lastGeneratedLine < pendingGeneratedLine); + } + else { + ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } + } + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function toJSON() { + commitPendingMapping(); + return { + version: 3, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings, + sourcesContent: sourcesContent, + }; + } + } + ts.createSourceMapGenerator = createSourceMapGenerator; + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + /** + * Tries to find the sourceMappingURL comment at the end of a file. + * @param text The source text of the file. + * @param lineStarts The line starts of the file. + */ + function tryGetSourceMappingURL(text, lineStarts) { + if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } + for (var index = lineStarts.length - 1; index >= 0; index--) { + var line = text.substring(lineStarts[index], lineStarts[index + 1]); + var comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + ts.tryGetSourceMappingURL = tryGetSourceMappingURL; + function isStringOrNull(x) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + function isRawSourceMap(x) { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && ts.isArray(x.sources) && ts.every(x.sources, ts.isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString)); + } + ts.isRawSourceMap = isRawSourceMap; + function tryParseRawSourceMap(text) { + try { + var parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch (_a) { + // empty + } + return undefined; + } + ts.tryParseRawSourceMap = tryParseRawSourceMap; + function decodeMappings(mappings) { + var done = false; + var pos = 0; + var generatedLine = 0; + var generatedCharacter = 0; + var sourceIndex = 0; + var sourceLine = 0; + var sourceCharacter = 0; + var nameIndex = 0; + var error; + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next: function () { + while (!done && pos < mappings.length) { + var ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + // Next entry is on same line - no action needed + pos++; + continue; + } + var hasSource = false; + var hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (generatedCharacter < 0) + return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceIndex < 0) + return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceLine < 0) + return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (sourceCharacter < 0) + return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) + return stopIterating(); + if (nameIndex < 0) + return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) + return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done: done }; + } + return stopIterating(); } }; + function captureMapping(hasSource, hasName) { + return { + generatedLine: generatedLine, + generatedCharacter: generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined + }; + } + function stopIterating() { + done = true; + return { value: undefined, done: true }; + } + function setError(message) { + if (error === undefined) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== undefined; + } + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === 44 /* comma */ || + mappings.charCodeAt(pos) === 59 /* semicolon */); + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) + return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + // 6 digit number + var currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) + return setError("Invalid character in VLQ"), -1; + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } } - ts.createSourceFileLikeCache = createSourceFileLikeCache; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - var sourcemaps; - (function (sourcemaps) { - sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; - function decode(host, mapPath, map, program, fallbackCache) { - if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } - var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; - var decodedMappings; - var generatedOrderedMappings; - var sourceOrderedMappings; - return { - getOriginalPosition: getOriginalPosition, - getGeneratedPosition: getGeneratedPosition - }; - function getGeneratedPosition(loc) { - var maps = getSourceOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { - return loc; - } - return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos - } - function getOriginalPosition(loc) { - var maps = getGeneratedOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos - } - function getSourceFileLike(fileName, location) { - // Lookup file in program, if provided - var path = ts.toPath(fileName, location, host.getCanonicalFileName); - var file = program && program.getSourceFile(path); - // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file - if (!file || file.resolvedPath !== path) { - // Otherwise check the cache (which may hit disk) - return fallbackCache.get(path); - } - return file; - } - function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { - var file = getSourceFileLike(fileName, directory); - if (!file) { - return -1; - } - return ts.getPositionOfLineAndCharacter(file, line, character); - } - function getDecodedMappings() { - return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host)); - } - function getSourceOrderedMappings() { - return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); - } - function getGeneratedOrderedMappings() { - return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); - } - function compareProcessedPositionSourcePositions(a, b) { - return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || - ts.compareValues(a.sourcePosition, b.sourcePosition); - } - function compareProcessedPositionEmittedPositions(a, b) { - return ts.compareValues(a.emittedPosition, b.emittedPosition); - } - function processPosition(position) { - var sourcePath = map.sources[position.sourceIndex]; - return { - emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), - sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), - sourcePath: sourcePath, - }; - } + ts.decodeMappings = decodeMappings; + function sameMapping(left, right) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; + } + ts.sameMapping = sameMapping; + function isSourceMapping(mapping) { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } + ts.isSourceMapping = isSourceMapping; + function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : + value >= 26 && value < 52 ? 97 /* a */ + value - 26 : + value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : + value === 62 ? 43 /* plus */ : + value === 63 ? 47 /* slash */ : + ts.Debug.fail(value + ": not a base64 value"); + } + function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : + ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : + ch === 43 /* plus */ ? 62 : + ch === 47 /* slash */ ? 63 : + -1; + } + 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; } - sourcemaps.decode = decode; - /*@internal*/ - function decodeMappings(map) { - var state = { - encodedText: map.mappings, - currentNameIndex: undefined, - sourceMapNamesLength: map.names ? map.names.length : undefined, - currentEmittedColumn: 0, - currentEmittedLine: 0, - currentSourceColumn: 0, - currentSourceLine: 0, - currentSourceIndex: 0, - decodingIndex: 0 - }; - function captureSpan() { - return { - emittedColumn: state.currentEmittedColumn, - emittedLine: state.currentEmittedLine, - sourceColumn: state.currentSourceColumn, - sourceIndex: state.currentSourceIndex, - sourceLine: state.currentSourceLine, - nameIndex: state.currentNameIndex - }; + 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 + String.fromCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + return encodedStr; + } + function isSourceMappedPosition(value) { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + function sameMappedPosition(left, right) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + function compareSourcePositions(left, right) { + return ts.compareValues(left.sourceIndex, right.sourceIndex); + } + function compareGeneratedPositions(left, right) { + return ts.compareValues(left.generatedPosition, right.generatedPosition); + } + function getSourcePositionOfMapping(value) { + return value.sourcePosition; + } + function getGeneratedPositionOfMapping(value) { + return value.generatedPosition; + } + function createDocumentPositionMapper(host, map, mapPath) { + var mapDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); + var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); + var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); + var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var decodedMappings; + var generatedMappings; + var sourceMappings; + return { + getSourcePosition: getSourcePosition, + getGeneratedPosition: getGeneratedPosition + }; + function processMapping(mapping) { + var generatedPosition = generatedFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + : -1; + var source; + var sourcePosition; + if (isSourceMapping(mapping)) { + var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + var sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -1; } return { - get decodingIndex() { return state.decodingIndex; }, - get error() { return state.error; }, - get lastSpan() { return captureSpan(); }, - next: function () { - if (hasCompletedDecoding(state) || state.error) - return { done: true, value: undefined }; - if (!decodeSinglePosition(state)) - return { done: true, value: undefined }; - return { done: false, value: captureSpan() }; - } + generatedPosition: generatedPosition, + source: source, + sourceIndex: mapping.sourceIndex, + sourcePosition: sourcePosition, + nameIndex: mapping.nameIndex }; } - sourcemaps.decodeMappings = decodeMappings; - function calculateDecodedMappings(map, processPosition, host) { - var decoder = decodeMappings(map); - var positions = ts.arrayFrom(decoder, processPosition); - if (decoder.error) { - if (host && host.log) { - host.log("Encountered error while decoding sourcemap: " + decoder.error); - } - return []; - } - return positions; - } - function hasCompletedDecoding(state) { - return state.decodingIndex === state.encodedText.length; - } - function decodeSinglePosition(state) { - while (state.decodingIndex < state.encodedText.length) { - var char = state.encodedText.charCodeAt(state.decodingIndex); - if (char === 59 /* semicolon */) { - // New line - state.currentEmittedLine++; - state.currentEmittedColumn = 0; - state.decodingIndex++; - continue; - } - if (char === 44 /* comma */) { - // Next entry is on same line - no action needed - state.decodingIndex++; - continue; - } - // Read the current position - // 1. Column offset from prev read jsColumn - state.currentEmittedColumn += base64VLQFormatDecode(); - // Incorrect emittedColumn dont support this map - if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { - return false; - } - // 2. Relative sourceIndex - state.currentSourceIndex += base64VLQFormatDecode(); - // Incorrect sourceIndex dont support this map - if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { - return false; - } - // Dont support reading mappings that dont have information about original source position - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { - return false; - } - // 3. Relative sourceLine 0 based - state.currentSourceLine += base64VLQFormatDecode(); - // Incorrect sourceLine dont support this map - if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { - return false; - } - // 4. Relative sourceColumn 0 based - state.currentSourceColumn += base64VLQFormatDecode(); - // Incorrect sourceColumn dont support this map - if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { - return false; - } - // 5. Check if there is name: - if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { - if (state.currentNameIndex === undefined) { - state.currentNameIndex = 0; + function getDecodedMappings() { + if (decodedMappings === undefined) { + var decoder = decodeMappings(map.mappings); + var mappings = ts.arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); } - state.currentNameIndex += base64VLQFormatDecode(); - // Incorrect nameIndex dont support this map - // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap - // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { - // return; - // } - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { - return false; - } - // Entry should be complete - return true; - } - createErrorIfCondition(/*condition*/ true, "No encoded entry found"); - return false; - function createErrorIfCondition(condition, errormsg) { - if (state.error) { - // An error was already reported - return true; - } - if (condition) { - state.error = errormsg; - } - return condition; - } - function base64VLQFormatDecode() { - var moreDigits = true; - var shiftCount = 0; - var value = 0; - for (; moreDigits; state.decodingIndex++) { - if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return undefined; // TODO: GH#18217 - } - // 6 digit number - var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); - // If msb is set, we still have more bits to continue - moreDigits = (currentByte & 32) !== 0; - // least significant 5 bits are the next msbs in the final value. - value = value | ((currentByte & 31) << shiftCount); - shiftCount += 5; - } - // Least significant bit if 1 represents negative and rest of the msb is actual absolute value - if ((value & 1) === 0) { - // + number - value = value >> 1; + decodedMappings = ts.emptyArray; } else { - // - number - value = value >> 1; - value = -value; + decodedMappings = mappings; } - return value; } + return decodedMappings; } - function base64FormatDecode(char) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + function getSourceMappings(sourceIndex) { + if (sourceMappings === undefined) { + var lists = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + if (!isSourceMappedPosition(mapping)) + continue; + var list = lists[mapping.sourceIndex]; + if (!list) + lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); }); + } + return sourceMappings[sourceIndex]; } - function isSourceMappingSegmentEnd(encodedText, pos) { - return (pos === encodedText.length || - encodedText.charCodeAt(pos) === 44 /* comma */ || - encodedText.charCodeAt(pos) === 59 /* semicolon */); + function getGeneratedMappings() { + if (generatedMappings === undefined) { + var list = []; + for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) { + var mapping = _a[_i]; + list.push(mapping); + } + generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; } - })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); + function getGeneratedPosition(loc) { + var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) + return loc; + var sourceMappings = getSourceMappings(sourceIndex); + if (!ts.some(sourceMappings)) + return loc; + var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + function getSourcePosition(loc) { + var generatedMappings = getGeneratedMappings(); + if (!ts.some(generatedMappings)) + return loc; + var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + var mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + ts.createDocumentPositionMapper = createDocumentPositionMapper; + ts.identitySourceMapConsumer = { + getSourcePosition: ts.identity, + getGeneratedPosition: ts.identity + }; })(ts || (ts = {})); /* @internal */ var ts; @@ -62348,7 +64984,7 @@ var ts; function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 277 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -62394,7 +65030,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -62402,13 +65038,13 @@ var ts; externalImports.push(node); hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; - case 246 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { + case 248 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 259 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -62438,13 +65074,13 @@ var ts; } } break; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -62452,7 +65088,7 @@ var ts; } } break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default function() { } @@ -62472,7 +65108,7 @@ var ts; } } break; - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default class { } @@ -62824,8 +65460,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62891,7 +65527,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63088,8 +65724,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -63119,14 +65755,14 @@ var ts; var pendingExpressions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 278 /* Bundle */) { + if (node.kind === 280 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280 /* InputFiles */) { + if (prepend.kind === 282 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); } return prepend; @@ -63175,16 +65811,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 277 /* SourceFile */: - case 244 /* CaseBlock */: - case 243 /* ModuleBlock */: - case 216 /* Block */: + case 279 /* SourceFile */: + case 246 /* CaseBlock */: + case 245 /* ModuleBlock */: + case 218 /* Block */: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 238 /* ClassDeclaration */: - case 237 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 239 /* FunctionDeclaration */: if (ts.hasModifier(node, 2 /* Ambient */)) { break; } @@ -63196,7 +65832,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 238 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); } if (ts.isClassDeclaration(node)) { // XXX: should probably also cover interfaces and type aliases that can have type variables? @@ -63244,10 +65880,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 252 /* ExportAssignment */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 254 /* ExportAssignment */: + case 255 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -63268,13 +65904,13 @@ var ts; return node; } switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -63294,11 +65930,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 253 /* ExportDeclaration */ || - node.kind === 247 /* ImportDeclaration */ || - node.kind === 248 /* ImportClause */ || - (node.kind === 246 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 257 /* ExternalModuleReference */)) { + if (node.kind === 255 /* ExportDeclaration */ || + node.kind === 249 /* ImportDeclaration */ || + node.kind === 250 /* ImportClause */ || + (node.kind === 248 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 259 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -63328,19 +65964,19 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 155 /* Constructor */: + case 157 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 152 /* PropertyDeclaration */: - case 160 /* IndexSignature */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 154 /* MethodDeclaration */: + case 154 /* PropertyDeclaration */: + case 162 /* IndexSignature */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 156 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); @@ -63350,7 +65986,7 @@ var ts; if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { return undefined; } - else if (currentNamespace && node.kind === 84 /* ExportKeyword */) { + else if (currentNamespace && node.kind === 85 /* ExportKeyword */) { return undefined; } return node; @@ -63367,67 +66003,67 @@ var ts; return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 132 /* ReadonlyKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 118 /* AbstractKeyword */: + case 77 /* ConstKeyword */: + case 125 /* DeclareKeyword */: + case 133 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 167 /* ArrayType */: - case 168 /* TupleType */: - case 169 /* OptionalType */: - case 170 /* RestType */: - case 166 /* TypeLiteral */: - case 161 /* TypePredicate */: - case 148 /* TypeParameter */: - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 105 /* VoidKeyword */: - case 138 /* SymbolKeyword */: - case 164 /* ConstructorType */: - case 163 /* FunctionType */: - case 165 /* TypeQuery */: - case 162 /* TypeReference */: - case 171 /* UnionType */: - case 172 /* IntersectionType */: - case 173 /* ConditionalType */: - case 175 /* ParenthesizedType */: - case 176 /* ThisType */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 180 /* LiteralType */: + case 169 /* ArrayType */: + case 170 /* TupleType */: + case 171 /* OptionalType */: + case 172 /* RestType */: + case 168 /* TypeLiteral */: + case 163 /* TypePredicate */: + case 150 /* TypeParameter */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 123 /* BooleanKeyword */: + case 138 /* StringKeyword */: + case 135 /* NumberKeyword */: + case 132 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 139 /* SymbolKeyword */: + case 166 /* ConstructorType */: + case 165 /* FunctionType */: + case 167 /* TypeQuery */: + case 164 /* TypeReference */: + case 173 /* UnionType */: + case 174 /* IntersectionType */: + case 175 /* ConditionalType */: + case 177 /* ParenthesizedType */: + case 178 /* ThisType */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 182 /* LiteralType */: // TypeScript type nodes are elided. - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: // TypeScript index signatures are elided. - case 150 /* Decorator */: + case 152 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 155 /* Constructor */: + case 157 /* Constructor */: return visitConstructor(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -63438,7 +66074,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -63449,35 +66085,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 149 /* Parameter */: + case 151 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -63487,35 +66123,35 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 192 /* TypeAssertionExpression */: - case 210 /* AsExpression */: + case 194 /* TypeAssertionExpression */: + case 212 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: @@ -63552,7 +66188,7 @@ var ts; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); - if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) facts |= 2 /* HasConstructorDecorators */; @@ -63621,7 +66257,7 @@ var ts; // return C; // }(); // - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18 /* CloseBraceToken */); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */); var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -63823,7 +66459,7 @@ var ts; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85 /* ExtendsKeyword */; })); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; })); var classExpression = ts.createClassExpression( /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, heritageClauses, members); @@ -63831,7 +66467,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63879,9 +66515,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -63997,7 +66635,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -64068,7 +66706,7 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 152 /* PropertyDeclaration */ + return member.kind === 154 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } @@ -64079,8 +66717,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -64096,8 +66734,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { - var property = properties_11[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var expression = transformInitializedProperty(property, receiver); ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -64208,12 +66846,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -64366,7 +67004,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 152 /* PropertyDeclaration */ + ? member.kind === 154 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? ts.createVoidZero() @@ -64467,13 +67105,13 @@ var ts; if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); } if (properties) { decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); @@ -64489,10 +67127,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */ - || kind === 152 /* PropertyDeclaration */; + return kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */ + || kind === 154 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -64502,7 +67140,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 154 /* MethodDeclaration */; + return node.kind === 156 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -64513,12 +67151,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return true; } return false; @@ -64535,15 +67173,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 152 /* PropertyDeclaration */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 151 /* Parameter */: return serializeTypeNode(node.type); - case 157 /* SetAccessor */: - case 156 /* GetAccessor */: + case 159 /* SetAccessor */: + case 158 /* GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - case 154 /* MethodDeclaration */: + case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: + case 156 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -64580,7 +67218,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 156 /* GetAccessor */) { + if (container && node.kind === 158 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -64625,77 +67263,83 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: + case 106 /* VoidKeyword */: + case 141 /* UndefinedKeyword */: + case 96 /* NullKeyword */: + case 132 /* NeverKeyword */: return ts.createVoidZero(); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 163 /* FunctionType */: - case 164 /* ConstructorType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: return ts.createIdentifier("Function"); - case 167 /* ArrayType */: - case 168 /* TupleType */: + case 169 /* ArrayType */: + case 170 /* TupleType */: return ts.createIdentifier("Array"); - case 161 /* TypePredicate */: - case 122 /* BooleanKeyword */: + case 163 /* TypePredicate */: + case 123 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); - case 137 /* StringKeyword */: + case 138 /* StringKeyword */: return ts.createIdentifier("String"); - case 135 /* ObjectKeyword */: + case 136 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 180 /* LiteralType */: + case 182 /* LiteralType */: switch (node.literal.kind) { - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return ts.createIdentifier("String"); case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: + case 9 /* BigIntLiteral */: + return getGlobalBigIntNameWithFallback(); + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: return ts.Debug.failBadSyntaxKind(node.literal); } - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: return ts.createIdentifier("Number"); - case 138 /* SymbolKeyword */: + case 146 /* BigIntKeyword */: + return getGlobalBigIntNameWithFallback(); + case 139 /* SymbolKeyword */: return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return serializeTypeReferenceNode(node); - case 172 /* IntersectionType */: - case 171 /* UnionType */: - return serializeUnionOrIntersectionType(node); - case 165 /* TypeQuery */: - case 177 /* TypeOperator */: - case 178 /* IndexedAccessType */: - case 179 /* MappedType */: - case 166 /* TypeLiteral */: - case 119 /* AnyKeyword */: - case 142 /* UnknownKeyword */: - case 176 /* ThisType */: - case 181 /* ImportType */: + case 174 /* IntersectionType */: + case 173 /* UnionType */: + return serializeTypeList(node.types); + case 175 /* ConditionalType */: + return serializeTypeList([node.trueType, node.falseType]); + case 167 /* TypeQuery */: + case 179 /* TypeOperator */: + case 180 /* IndexedAccessType */: + case 181 /* MappedType */: + case 168 /* TypeLiteral */: + case 120 /* AnyKeyword */: + case 143 /* UnknownKeyword */: + case 178 /* ThisType */: + case 183 /* ImportType */: break; default: return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } - function serializeUnionOrIntersectionType(node) { + function serializeTypeList(types) { // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, _a = node.types; _i < _a.length; _i++) { - var typeNode = _a[_i]; - while (typeNode.kind === 175 /* ParenthesizedType */) { + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; + while (typeNode.kind === 177 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } - if (typeNode.kind === 131 /* NeverKeyword */) { + if (typeNode.kind === 132 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedIndividual = serializeTypeNode(typeNode); @@ -64731,6 +67375,10 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.createIdentifier("Object"); + } var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); @@ -64738,6 +67386,8 @@ var ts; return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); case ts.TypeReferenceSerializationKind.BooleanType: return ts.createIdentifier("Boolean"); case ts.TypeReferenceSerializationKind.NumberLikeType: @@ -64769,12 +67419,12 @@ var ts; * @param node The entity name to serialize. */ function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { // A -> typeof A !== undefined && A var copied = serializeEntityNameAsExpression(node); return createCheckedValue(copied, copied); } - if (node.left.kind === 71 /* Identifier */) { + if (node.left.kind === 72 /* Identifier */) { // A.B -> typeof A !== undefined && A.B return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); } @@ -64790,7 +67440,7 @@ var ts; */ function serializeEntityNameAsExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were // a source tree node for the purposes of the checker. var name = ts.getMutableClone(node); @@ -64798,7 +67448,7 @@ var ts; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. return name; - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -64819,6 +67469,15 @@ var ts; function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback() { + return languageVersion < 6 /* ESNext */ + ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) + : ts.createIdentifier("BigInt"); + } /** * A simple inlinable expression is an expression which can be copied into multiple locations * without risk of repeating any sideeffects and whose value could not possibly change between @@ -64899,9 +67558,9 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 85 /* ExtendsKeyword */) { + if (node.token === 86 /* ExtendsKeyword */) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(85 /* ExtendsKeyword */, types), node); + return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); } return undefined; } @@ -65297,7 +67956,7 @@ var ts; var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); var valueExpression = transformEnumMemberDeclarationValue(member); var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); - var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? innerAssignment : ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); @@ -65378,12 +68037,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 277 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 241 /* EnumDeclaration */) { + if (node.kind === 243 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -65508,7 +68167,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 243 /* ModuleBlock */) { + if (body.kind === 245 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -65554,13 +68213,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 243 /* ModuleBlock */) { + if (body.kind !== 245 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -65601,7 +68260,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 249 /* NamespaceImport */) { + if (node.kind === 251 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -65795,7 +68454,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65814,7 +68473,7 @@ var ts; function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } function enableSubstitutionForClassAliases() { @@ -65822,7 +68481,7 @@ var ts; enabledSubstitutions |= 1 /* ClassAliases */; // We need to enable substitutions for identifiers. This allows us to // substitute class names inside of a class declaration. - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); // Keep track of class aliases. classAliases = []; } @@ -65832,17 +68491,17 @@ var ts; enabledSubstitutions |= 2 /* NamespaceExports */; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. - context.enableSubstitution(71 /* Identifier */); - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); + context.enableSubstitution(72 /* Identifier */); + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(242 /* ModuleDeclaration */); + context.enableEmitNotification(244 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 242 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 241 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */; } /** * Hook for node emit. @@ -65901,11 +68560,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -65917,7 +68576,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // 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. @@ -65943,9 +68602,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 277 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 242 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 241 /* EnumDeclaration */); + if (container && container.kind !== 279 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), /*location*/ node); @@ -66057,6 +68716,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66077,19 +68744,29 @@ var ts; return node; } switch (node.kind) { - case 120 /* AsyncKeyword */: + case 121 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitAwaitExpression(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66097,27 +68774,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 216 /* Block */: - case 230 /* SwitchStatement */: - case 244 /* CaseBlock */: - case 269 /* CaseClause */: - case 270 /* DefaultClause */: - case 233 /* TryStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: - case 220 /* IfStatement */: - case 229 /* WithStatement */: - case 231 /* LabeledStatement */: + case 218 /* Block */: + case 232 /* SwitchStatement */: + case 246 /* CaseBlock */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: + case 235 /* TryStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: + case 222 /* IfStatement */: + case 231 /* WithStatement */: + case 233 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -66318,7 +68995,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 195 /* ArrowFunction */; + var isArrowFunction = node.kind === 197 /* 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 @@ -66331,23 +69008,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66365,6 +69052,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66391,15 +69080,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(189 /* CallExpression */); - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(238 /* ClassDeclaration */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); } } /** @@ -66422,6 +69113,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66439,24 +69138,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66475,24 +69174,68 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 /* ClassDeclaration */ - || kind === 155 /* Constructor */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66502,7 +69245,7 @@ var ts; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); var generatorFunc = ts.createFunctionExpression( - /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), /*name*/ undefined, /*typeParameters*/ undefined, /*parameters*/ [], @@ -66520,12 +69263,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (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);"], ["\n const ", " = (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);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66548,6 +69291,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66564,7 +69313,7 @@ var ts; return visitorWorker(node, /*noDestructuringValue*/ true); } function visitorNoAsyncModifier(node) { - if (node.kind === 120 /* AsyncKeyword */) { + if (node.kind === 121 /* AsyncKeyword */) { return undefined; } return node; @@ -66574,48 +69323,58 @@ var ts; return node; } switch (node.kind) { - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return visitAwaitExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return visitVoidExpression(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return visitConstructorDeclaration(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 156 /* GetAccessor */: + case 158 /* GetAccessor */: return visitGetAccessorDeclaration(node); - case 157 /* SetAccessor */: + case 159 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitParameter(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitExpressionStatement(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); + case 189 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 190 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66648,7 +69407,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 225 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); @@ -66660,7 +69419,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 275 /* SpreadAssignment */) { + if (e.kind === 277 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -66669,7 +69428,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 273 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */ ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -66680,14 +69439,14 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); // If the first element is a spread element, then the first argument to __assign is {}: // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 186 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -66712,10 +69471,10 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } - else if (node.operatorToken.kind === 26 /* CommaToken */) { + else if (node.operatorToken.kind === 27 /* CommaToken */) { return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); @@ -66727,7 +69486,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66744,7 +69503,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66841,7 +69600,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66938,25 +69697,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( - /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66980,7 +69751,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -67000,15 +69771,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(189 /* CallExpression */); - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(188 /* ElementAccessExpression */); + context.enableSubstitution(191 /* CallExpression */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(190 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(238 /* ClassDeclaration */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(240 /* ClassDeclaration */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(157 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(219 /* VariableStatement */); } } /** @@ -67031,6 +69804,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67048,24 +69829,24 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 98 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67084,19 +69865,19 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 238 /* ClassDeclaration */ - || kind === 155 /* Constructor */ - || kind === 154 /* MethodDeclaration */ - || kind === 156 /* GetAccessor */ - || kind === 157 /* SetAccessor */; + return kind === 240 /* ClassDeclaration */ + || kind === 157 /* Constructor */ + || kind === 156 /* MethodDeclaration */ + || kind === 158 /* GetAccessor */ + || kind === 159 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67197,13 +69978,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67211,15 +69992,15 @@ var ts; } function transformJsxChildToExpression(node) { switch (node.kind) { - case 10 /* JsxText */: + case 11 /* JsxText */: return visitJsxText(node); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return visitJsxExpression(node); - case 258 /* JsxElement */: + case 260 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -67287,14 +70068,14 @@ var ts; if (node === undefined) { return ts.createTrue(); } - else if (node.kind === 9 /* StringLiteral */) { + else if (node.kind === 10 /* StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); return ts.setTextRange(literal, node); } - else if (node.kind === 268 /* JsxExpression */) { + else if (node.kind === 270 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } @@ -67388,7 +70169,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 258 /* JsxElement */) { + if (node.kind === 260 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -67694,7 +70475,7 @@ var ts; return node; } switch (node.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67702,9 +70483,9 @@ var ts; } function visitBinaryExpression(node) { switch (node.operatorToken.kind) { - case 62 /* AsteriskAsteriskEqualsToken */: + case 63 /* AsteriskAsteriskEqualsToken */: return visitExponentiationAssignmentExpression(node); - case 40 /* AsteriskAsteriskToken */: + case 41 /* AsteriskAsteriskToken */: return visitExponentiationExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -67754,6 +70535,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67927,14 +70713,14 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 228 /* ReturnStatement */ + && node.kind === 230 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -67952,104 +70738,104 @@ var ts; return node; } function callExpressionVisitor(node) { - if (node.kind === 97 /* SuperKeyword */) { + if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); } return visitor(node); } function visitJavaScript(node) { switch (node.kind) { - case 115 /* StaticKeyword */: + case 116 /* StaticKeyword */: return undefined; // elide static keyword - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return visitClassExpression(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return visitParameter(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return visitArrowFunction(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 71 /* Identifier */: + case 72 /* Identifier */: return visitIdentifier(node); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitCaseBlock(node); - case 216 /* Block */: + case 218 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 227 /* BreakStatement */: - case 226 /* ContinueStatement */: + case 229 /* BreakStatement */: + case 228 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return visitExpressionStatement(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node, /*needsDestructuringValue*/ true); - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: return visitTemplateLiteral(node); - case 9 /* StringLiteral */: + case 10 /* StringLiteral */: return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return visitTemplateExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return visitSpreadElement(node); - case 97 /* SuperKeyword */: + case 98 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return visitThisKeyword(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return visitMetaProperty(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return visitAccessorDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -68136,14 +70922,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 227 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 227 /* BreakStatement */) { + if (node.kind === 229 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -68154,7 +70940,7 @@ var ts; } } else { - if (node.kind === 227 /* BreakStatement */) { + if (node.kind === 229 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -68173,10 +70959,10 @@ var ts; expr = copyExpr; } else { - expr = ts.createBinary(expr, 26 /* CommaToken */, copyExpr); + expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr); } } - returnExpression = ts.createBinary(expr, 26 /* CommaToken */, returnExpression); + returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression); } return ts.createReturn(returnExpression); } @@ -68310,7 +71096,7 @@ var ts; addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); // Create a synthetic text range for the return statement. - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18 /* CloseBraceToken */); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */); var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -68415,7 +71201,7 @@ var ts; } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); // The last statement expression was replaced. Skip it. if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { @@ -68454,11 +71240,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 228 /* ReturnStatement */) { + if (statement.kind === 230 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 220 /* IfStatement */) { + else if (statement.kind === 222 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -68466,7 +71252,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 216 /* Block */) { + else if (statement.kind === 218 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -68524,7 +71310,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -68532,10 +71318,10 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 202 /* BinaryExpression */ - || superCallExpression.left.kind !== 189 /* CallExpression */) { + if (superCallExpression.kind !== 204 /* BinaryExpression */ + || superCallExpression.left.kind !== 191 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } // Shift comments from the original super call to the return statement. @@ -68603,7 +71389,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68680,7 +71466,7 @@ var ts; * synthesized call to `super` */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 71 /* Identifier */ && !inConstructorWithSynthesizedSuper; + return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; } /** * Adds statements to the body of a function-like node if it contains a rest parameter. @@ -68732,7 +71518,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68751,25 +71537,25 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return statements; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = ts.createVoidZero(); break; - case 155 /* Constructor */: + case 157 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 196 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. - newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); break; default: return ts.Debug.failBadSyntaxKind(node); @@ -68797,20 +71583,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 155 /* Constructor */: + case 157 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -68920,7 +71706,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69002,7 +71788,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 237 /* FunctionDeclaration */ || node.kind === 194 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); @@ -69047,7 +71833,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 195 /* ArrowFunction */); + ts.Debug.assert(node.kind === 197 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -69085,7 +71871,7 @@ var ts; ts.setEmitFlags(block, 1 /* SingleLine */); } if (closeBraceLocation) { - ts.setTokenSourceMapRange(block, 18 /* CloseBraceToken */, closeBraceLocation); + ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -69115,9 +71901,9 @@ var ts; function visitExpressionStatement(node) { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); @@ -69136,9 +71922,9 @@ var ts; // expression. If we are in a state where we do not need the destructuring value, // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } @@ -69173,7 +71959,7 @@ var ts; assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); } else { - assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); @@ -69210,19 +71996,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69270,8 +72064,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69339,14 +72133,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -69526,11 +72320,11 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 147 /* ComputedPropertyName */) { + if (property.name.kind === 149 /* ComputedPropertyName */) { numInitialProperties = i; break; } @@ -69557,7 +72351,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69569,7 +72379,7 @@ var ts; } visit(node.name); function visit(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { state.hoistedLocalVariables.push(node); } else { @@ -69583,7 +72393,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69599,14 +72409,76 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 223 /* ForStatement */: - case 224 /* ForInStatement */: - case 225 /* ForOfStatement */: + case 225 /* ForStatement */: + case 226 /* ForInStatement */: + case 227 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 236 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 238 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -69616,165 +72488,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // 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 - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.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 = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.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'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 58 /* EqualsToken */, source); + return ts.createBinary(target, 59 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69782,38 +72765,38 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield + ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); } if (state.nonLocalJumps & 2 /* Break */) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69853,21 +72836,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69886,20 +72877,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -70007,10 +72998,10 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -70186,15 +73177,15 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || - node.expression.kind === 97 /* SuperKeyword */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70223,7 +73214,7 @@ var ts; resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } - if (node.expression.kind === 97 /* SuperKeyword */) { + if (node.expression.kind === 98 /* SuperKeyword */) { var actualThis = ts.createThis(); ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); var initializer = ts.createLogicalOr(resultingCall, actualThis); @@ -70241,7 +73232,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70288,7 +73279,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 185 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -70405,7 +73396,7 @@ var ts; // thus we need to remove those characters. // First template piece starts with "`", others with "}" // Last template piece ends with "`", others with "${" - var isLast = node.kind === 13 /* NoSubstitutionTemplateLiteral */ || node.kind === 16 /* TemplateTail */; + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; text = text.substring(1, text.length - (isLast ? 1 : 2)); // Newline normalization: // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's @@ -70503,7 +73494,7 @@ var ts; : ts.createFileLevelUniqueName("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") { + if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { if (hierarchyFacts & 8192 /* ComputedPropertyName */) { hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; } @@ -70540,7 +73531,7 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } /** @@ -70550,14 +73541,14 @@ var ts; function enableSubstitutionsForCapturedThis() { if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; - context.enableSubstitution(99 /* ThisKeyword */); - context.enableEmitNotification(155 /* Constructor */); - context.enableEmitNotification(154 /* MethodDeclaration */); - context.enableEmitNotification(156 /* GetAccessor */); - context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(195 /* ArrowFunction */); - context.enableEmitNotification(194 /* FunctionExpression */); - context.enableEmitNotification(237 /* FunctionDeclaration */); + context.enableSubstitution(100 /* ThisKeyword */); + context.enableEmitNotification(157 /* Constructor */); + context.enableEmitNotification(156 /* MethodDeclaration */); + context.enableEmitNotification(158 /* GetAccessor */); + context.enableEmitNotification(159 /* SetAccessor */); + context.enableEmitNotification(197 /* ArrowFunction */); + context.enableEmitNotification(196 /* FunctionExpression */); + context.enableEmitNotification(239 /* FunctionDeclaration */); } } /** @@ -70598,10 +73589,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: - case 241 /* EnumDeclaration */: - case 235 /* VariableDeclaration */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: + case 243 /* EnumDeclaration */: + case 237 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -70614,9 +73605,9 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 99 /* ThisKeyword */: + case 100 /* ThisKeyword */: return substituteThisKeyword(node); } return node; @@ -70683,19 +73674,19 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 219 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 189 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 97 /* SuperKeyword */) { + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) { return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 206 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -70723,7 +73714,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -70748,15 +73739,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(260 /* JsxOpeningElement */); - context.enableEmitNotification(261 /* JsxClosingElement */); - context.enableEmitNotification(259 /* JsxSelfClosingElement */); + context.enableEmitNotification(262 /* JsxOpeningElement */); + context.enableEmitNotification(263 /* JsxClosingElement */); + context.enableEmitNotification(261 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(187 /* PropertyAccessExpression */); - context.enableSubstitution(273 /* PropertyAssignment */); + context.enableSubstitution(189 /* PropertyAccessExpression */); + context.enableSubstitution(275 /* PropertyAssignment */); return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -70775,9 +73766,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 260 /* JsxOpeningElement */: - case 261 /* JsxClosingElement */: - case 259 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: + case 263 /* JsxClosingElement */: + case 261 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -70834,7 +73825,7 @@ var ts; */ function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { + if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -71109,13 +74100,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitWhileStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -71128,30 +74119,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return visitAccessorDeclaration(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return visitBreakStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return visitContinueStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71166,21 +74157,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return visitBinaryExpression(node); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return visitConditionalExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return visitYieldExpression(node); - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return visitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -71193,9 +74184,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -71354,7 +74345,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71394,23 +74385,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 59 /* FirstCompoundAssignment */ - && kind <= 70 /* LastCompoundAssignment */; + return kind >= 60 /* FirstCompoundAssignment */ + && kind <= 71 /* LastCompoundAssignment */; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 59 /* PlusEqualsToken */: return 37 /* PlusToken */; - case 60 /* MinusEqualsToken */: return 38 /* MinusToken */; - case 61 /* AsteriskEqualsToken */: return 39 /* AsteriskToken */; - case 62 /* AsteriskAsteriskEqualsToken */: return 40 /* AsteriskAsteriskToken */; - case 63 /* SlashEqualsToken */: return 41 /* SlashToken */; - case 64 /* PercentEqualsToken */: return 42 /* PercentToken */; - case 65 /* LessThanLessThanEqualsToken */: return 45 /* LessThanLessThanToken */; - case 66 /* GreaterThanGreaterThanEqualsToken */: return 46 /* GreaterThanGreaterThanToken */; - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanGreaterThanToken */; - case 68 /* AmpersandEqualsToken */: return 48 /* AmpersandToken */; - case 69 /* BarEqualsToken */: return 49 /* BarToken */; - case 70 /* CaretEqualsToken */: return 50 /* CaretToken */; + case 60 /* PlusEqualsToken */: return 38 /* PlusToken */; + case 61 /* MinusEqualsToken */: return 39 /* MinusToken */; + case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */; + case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */; + case 64 /* SlashEqualsToken */: return 42 /* SlashToken */; + case 65 /* PercentEqualsToken */: return 43 /* PercentToken */; + case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */; + case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */; + case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */; + case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */; + case 70 /* BarEqualsToken */: return 50 /* BarToken */; + case 71 /* CaretEqualsToken */: return 51 /* CaretToken */; } } /** @@ -71423,7 +74414,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -71435,7 +74426,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -71467,7 +74458,7 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 26 /* CommaToken */) { + else if (node.operatorToken.kind === 27 /* CommaToken */) { return visitCommaExpression(node); } // [source] @@ -71478,10 +74469,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71522,7 +74513,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) { // Logical `&&` shortcuts when the left-hand operand is falsey. emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); } @@ -71553,7 +74544,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { visit(node.left); visit(node.right); } @@ -71742,10 +74733,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -71811,35 +74802,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 216 /* Block */: + case 218 /* Block */: return transformAndEmitBlock(node); - case 219 /* ExpressionStatement */: + case 221 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return transformAndEmitIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return transformAndEmitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return transformAndEmitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return transformAndEmitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -72269,7 +75260,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 270 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -72282,7 +75273,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 269 /* CaseClause */) { + if (clause.kind === 271 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -72412,7 +75403,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72444,10 +75435,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -72594,7 +75585,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = []; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } renamedCatchVariables.set(text, true); renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -73510,12 +76501,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -73529,7 +76520,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73583,6 +76577,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73613,22 +76608,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73837,23 +76834,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return visitExportDeclaration(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 308 /* MergeDeclarationMarker */: + case 310 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 309 /* EndOfDeclarationMarker */: + case 311 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -73862,7 +76859,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73880,24 +76877,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -73929,7 +76926,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74375,7 +77372,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -74430,10 +77427,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -74615,8 +77612,8 @@ var ts; function modifierVisitor(node) { // Elide module-specific modifiers. switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: return undefined; } return node; @@ -74632,7 +77629,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -74694,12 +77691,12 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return substituteBinaryExpression(node); - case 201 /* PostfixUnaryExpression */: - case 200 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -74720,7 +77717,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -74788,15 +77785,15 @@ var ts; // - We do not substitute identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only substitute identifiers that are exported at the top level. - if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 /* PostfixUnaryExpression */ - ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), + var expression = node.kind === 203 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { @@ -74870,12 +77867,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -74894,7 +77891,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75096,7 +78093,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 253 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -75121,7 +78118,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 253 /* ExportDeclaration */) { + if (externalImport.kind !== 255 /* ExportDeclaration */) { continue; } if (!externalImport.exportClause) { @@ -75199,19 +78196,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -75261,15 +78258,15 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return visitImportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: // ExportDeclarations are elided as they are handled via // `appendExportsOfDeclaration`. return undefined; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -75445,7 +78442,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 277 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -75509,7 +78506,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -75571,10 +78568,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -75754,43 +78751,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return visitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return visitForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return visitForOfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return visitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return visitWhileStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return visitLabeledStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return visitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return visitSwitchStatement(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return visitCaseBlock(node); - case 269 /* CaseClause */: + case 271 /* CaseClause */: return visitCaseClause(node); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return visitDefaultClause(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return visitTryStatement(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return visitCatchClause(node); - case 216 /* Block */: + case 218 /* Block */: return visitBlock(node); - case 308 /* MergeDeclarationMarker */: + case 310 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 309 /* EndOfDeclarationMarker */: + case 311 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -75973,13 +78970,13 @@ var ts; */ function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 202 /* BinaryExpression */) { + && node.kind === 204 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76038,7 +79035,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 277 /* SourceFile */; + return container !== undefined && container.kind === 279 /* SourceFile */; } else { return false; @@ -76054,8 +79051,8 @@ var ts; */ function modifierVisitor(node) { switch (node.kind) { - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: return undefined; } return node; @@ -76071,7 +79068,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 277 /* SourceFile */) { + if (node.kind === 279 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -76119,7 +79116,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -76153,12 +79150,12 @@ var ts; */ function substituteExpression(node) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return substituteExpressionIdentifier(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return substituteBinaryExpression(node); - case 200 /* PrefixUnaryExpression */: - case 201 /* PostfixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -76244,22 +79241,22 @@ var ts; // - We do not substitute identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only substitute identifiers that are exported at the top level. - if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) + if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 201 /* PostfixUnaryExpression */ + var expression = node.kind === 203 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 201 /* PostfixUnaryExpression */) { - expression = node.operator === 43 /* PlusPlusToken */ + if (node.kind === 203 /* PostfixUnaryExpression */) { + expression = node.operator === 44 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); } @@ -76280,7 +79277,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -76319,8 +79316,8 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(277 /* SourceFile */); - context.enableSubstitution(71 /* Identifier */); + context.enableEmitNotification(279 /* SourceFile */); + context.enableSubstitution(72 /* Identifier */); var currentSourceFile; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { @@ -76348,10 +79345,10 @@ var ts; } function visitor(node) { switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return visitExportAssignment(node); } return node; @@ -76458,7 +79455,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* 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 : @@ -76487,7 +79484,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -76534,7 +79531,7 @@ var ts; return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { 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 : @@ -76543,8 +79540,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 152 /* PropertyDeclaration */ || node.kind === 151 /* PropertySignature */ || - (node.kind === 149 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -76553,7 +79550,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 238 /* ClassDeclaration */ || node.kind === 149 /* Parameter */) { + else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -76578,7 +79575,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 157 /* SetAccessor */) { + if (node.kind === 159 /* SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.hasModifier(node, 32 /* Static */)) { @@ -76617,26 +79614,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named 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 158 /* CallSignature */: + case 160 /* CallSignature */: // Interfaces cannot have return types that cannot be named 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 160 /* IndexSignature */: + case 162 /* IndexSignature */: // Interfaces cannot have return types that cannot be named 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 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -76644,7 +79641,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.kind === 240 /* 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 : @@ -76658,7 +79655,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 237 /* FunctionDeclaration */: + case 239 /* 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 : @@ -76683,30 +79680,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 155 /* Constructor */: + case 157 /* 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 159 /* ConstructSignature */: - case 164 /* ConstructorType */: + case 161 /* ConstructSignature */: + case 166 /* ConstructorType */: // Interfaces cannot have parameter types that cannot be named 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 158 /* CallSignature */: + case 160 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named 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 160 /* IndexSignature */: + case 162 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -76714,7 +79711,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 240 /* 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 : @@ -76727,8 +79724,8 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 237 /* FunctionDeclaration */: - case 163 /* FunctionType */: + case 239 /* FunctionDeclaration */: + case 165 /* FunctionType */: 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 : @@ -76742,34 +79739,34 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 158 /* CallSignature */: + case 160 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: if (ts.hasModifier(node.parent, 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 === 238 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 240 /* 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 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -76784,9 +79781,9 @@ var ts; function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + if (node.parent.parent.kind === 240 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ? 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; } @@ -76821,11 +79818,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76851,7 +79848,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76862,6 +79859,7 @@ var ts; reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode @@ -76869,6 +79867,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76878,10 +79877,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76949,16 +79948,22 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); + } + } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } - if (node.kind === 278 /* Bundle */) { + if (node.kind === 280 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76970,23 +79975,25 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 280 /* InputFiles */) { + if (prepend.kind === 282 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -77005,8 +80012,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77017,11 +80025,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77051,7 +80062,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77059,13 +80070,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77075,12 +80091,21 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { - if (name.kind === 71 /* Identifier */) { + if (name.kind === 72 /* Identifier */) { return name; } else { - if (name.kind === 183 /* ArrayBindingPattern */) { + if (name.kind === 185 /* ArrayBindingPattern */) { return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -77088,7 +80113,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 208 /* OmittedExpression */) { + if (elem.kind === 210 /* OmittedExpression */) { return elem; } return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -77101,7 +80126,7 @@ var ts; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } var newParam = ts.updateParameter(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -77113,7 +80138,7 @@ var ts; } function ensureNoInitializer(node) { if (shouldPrintWithInitializer(node)) { - return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe + return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe } return undefined; } @@ -77126,19 +80151,19 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 149 /* Parameter */ && + var shouldUseResolverType = node.kind === 151 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { return ts.visitNode(type, visitDeclarationSubtree); } if (!ts.getParseTreeNode(node)) { - return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */); } - if (node.kind === 157 /* SetAccessor */) { + if (node.kind === 159 /* SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) - return ts.createKeywordTypeNode(119 /* AnyKeyword */); + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } errorNameNode = node.name; var oldDiag; @@ -77146,12 +80171,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 149 /* Parameter */ - || node.kind === 152 /* PropertyDeclaration */ - || node.kind === 151 /* PropertySignature */) { + if (node.kind === 151 /* Parameter */ + || node.kind === 154 /* PropertyDeclaration */ + || node.kind === 153 /* PropertySignature */) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -77162,26 +80187,26 @@ var ts; if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } - return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */); + return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */); } } function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 246 /* ImportEqualsDeclaration */: - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: + case 248 /* ImportEqualsDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: return false; } return false; @@ -77235,7 +80260,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -77255,7 +80280,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 257 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return ts.updateImportEqualsDeclaration(decl, @@ -77282,7 +80307,7 @@ var ts; return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 249 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -77387,68 +80412,68 @@ var ts; checkEntityNameVisibility(input.exprName, enclosingDeclaration); } var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 /* TypeLiteral */ || input.kind === 179 /* MappedType */) && input.parent.kind !== 240 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */); if (shouldEnterSuppressNewDiagnosticsContextContext) { // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. suppressNewDiagnosticContexts = true; } if (isProcessedComponent(input)) { switch (input.kind) { - case 209 /* ExpressionWithTypeArguments */: { + case 211 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); } - case 162 /* TypeReference */: { + case 164 /* TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); } - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 155 /* Constructor */: { + case 157 /* Constructor */: { var isPrivate = ts.hasModifier(input, 8 /* Private */); // A constructor declaration may not have a type annotation - var ctor = ts.createSignatureDeclaration(155 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), // TODO: GH#18217 isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), /*type*/ undefined); ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); return cleanup(ctor); } - case 154 /* MethodDeclaration */: { - var sig = ts.createSignatureDeclaration(153 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + case 156 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); sig.name = input.name; sig.modifiers = ts.createNodeArray(ensureModifiers(input)); sig.questionToken = input.questionToken; return cleanup(sig); } - case 156 /* GetAccessor */: { + case 158 /* GetAccessor */: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 157 /* SetAccessor */: { + case 159 /* SetAccessor */: { var newNode = ensureAccessor(input); return cleanup(newNode); } - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return cleanup(ts.updateProperty(input, /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); - case 153 /* MethodSignature */: { + case 155 /* MethodSignature */: { return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); } - case 158 /* CallSignature */: { + case 160 /* CallSignature */: { return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 160 /* IndexSignature */: { + case 162 /* IndexSignature */: { return cleanup(ts.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */))); } - case 235 /* VariableDeclaration */: { + case 237 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -77456,13 +80481,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); } - case 148 /* TypeParameter */: { + case 150 /* TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 173 /* ConditionalType */: { + case 175 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -77474,13 +80499,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 163 /* FunctionType */: { + case 165 /* FunctionType */: { return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 164 /* ConstructorType */: { + case 166 /* ConstructorType */: { return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 181 /* ImportType */: { + case 183 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -77509,7 +80534,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 154 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -77519,7 +80544,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 253 /* ExportDeclaration */: { + case 255 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; @@ -77528,13 +80553,13 @@ var ts; // Rewrite external module names if necessary return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 252 /* ExportAssignment */: { + case 254 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; } - if (input.expression.kind === 71 /* Identifier */) { + if (input.expression.kind === 72 /* Identifier */) { return input; } else { @@ -77544,7 +80569,7 @@ var ts; errorNode: input }); }; var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } @@ -77558,10 +80583,10 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 246 /* ImportEqualsDeclaration */: { + case 248 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 247 /* ImportDeclaration */: { + case 249 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -77582,24 +80607,39 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 240 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(ts.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 239 /* InterfaceDeclaration */: { + case 241 /* InterfaceDeclaration */: { return cleanup(ts.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 237 /* FunctionDeclaration */: { + case 239 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } - case 242 /* ModuleDeclaration */: { + case 244 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 243 /* ModuleBlock */) { + if (inner && inner.kind === 245 /* ModuleBlock */) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; @@ -77620,7 +80660,7 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 238 /* ClassDeclaration */: { + case 240 /* ClassDeclaration */: { var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -77631,7 +80671,7 @@ var ts; if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); - if (param.name.kind === 71 /* Identifier */) { + if (param.name.kind === 72 /* Identifier */) { return preserveJsDoc(ts.createProperty( /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } @@ -77661,7 +80701,7 @@ var ts; } var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); - if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 getSymbolAccessibilityDiagnostic = function () { return ({ @@ -77670,16 +80710,16 @@ var ts; typeName: input.name }); }; var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { - if (clause.token === 85 /* ExtendsKeyword */) { + if (clause.token === 86 /* ExtendsKeyword */) { var oldDiag_2 = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); getSymbolAccessibilityDiagnostic = oldDiag_2; return newClause; } - return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree)); })); return [statement, cleanup(ts.updateClassDeclaration(input, /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 @@ -77690,10 +80730,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 217 /* VariableStatement */: { + case 219 /* VariableStatement */: { return cleanup(transformVariableStatement(input, isPrivate)); } - case 241 /* EnumDeclaration */: { + case 243 /* EnumDeclaration */: { return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -77712,7 +80752,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242 /* ModuleDeclaration */) { + if (input.kind === 244 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -77733,7 +80773,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 208 /* OmittedExpression */) { + if (e.kind === 210 /* OmittedExpression */) { return; } if (e.name) { @@ -77796,7 +80836,7 @@ var ts; function ensureModifierFlags(node, privateDeclaration) { var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 277 /* SourceFile */; + var parentIsFile = node.parent.kind === 279 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; @@ -77817,7 +80857,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77831,20 +80871,20 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; } function transformHeritageClauses(nodes) { return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { - return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */); + return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */); })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); } } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 239 /* InterfaceDeclaration */) { + if (node.kind === 241 /* InterfaceDeclaration */) { return true; } return false; @@ -77869,7 +80909,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 156 /* GetAccessor */ + return accessor.kind === 158 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -77878,51 +80918,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 149 /* Parameter */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); + case 151 /* Parameter */: + case 237 /* VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 237 /* FunctionDeclaration */: - case 242 /* ModuleDeclaration */: - case 246 /* ImportEqualsDeclaration */: - case 239 /* InterfaceDeclaration */: - case 238 /* ClassDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 241 /* EnumDeclaration */: - case 217 /* VariableStatement */: - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: - case 252 /* ExportAssignment */: + case 239 /* FunctionDeclaration */: + case 244 /* ModuleDeclaration */: + case 248 /* ImportEqualsDeclaration */: + case 241 /* InterfaceDeclaration */: + case 240 /* ClassDeclaration */: + case 242 /* TypeAliasDeclaration */: + case 243 /* EnumDeclaration */: + case 219 /* VariableStatement */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: + case 254 /* ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 159 /* ConstructSignature */: - case 155 /* Constructor */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 152 /* PropertyDeclaration */: - case 151 /* PropertySignature */: - case 153 /* MethodSignature */: - case 158 /* CallSignature */: - case 160 /* IndexSignature */: - case 235 /* VariableDeclaration */: - case 148 /* TypeParameter */: - case 209 /* ExpressionWithTypeArguments */: - case 162 /* TypeReference */: - case 173 /* ConditionalType */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 181 /* ImportType */: + case 161 /* ConstructSignature */: + case 157 /* Constructor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 154 /* PropertyDeclaration */: + case 153 /* PropertySignature */: + case 155 /* MethodSignature */: + case 160 /* CallSignature */: + case 162 /* IndexSignature */: + case 237 /* VariableDeclaration */: + case 150 /* TypeParameter */: + case 211 /* ExpressionWithTypeArguments */: + case 164 /* TypeReference */: + case 175 /* ConditionalType */: + case 165 /* FunctionType */: + case 166 /* ConstructorType */: + case 183 /* ImportType */: return true; } return false; @@ -77987,6 +81028,14 @@ var ts; return transformers; } ts.getTransformers = getTransformers; + function noEmitSubstitution(_hint, node) { + return node; + } + ts.noEmitSubstitution = noEmitSubstitution; + function noEmitNotification(hint, node, callback) { + callback(hint, node); + } + ts.noEmitNotification = noEmitNotification; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -77998,7 +81047,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(310 /* Count */); + var enabledSyntaxKindFeatures = new Array(312 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -78006,8 +81055,8 @@ var ts; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; - var onSubstituteNode = function (_, node) { return node; }; - var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; + var onSubstituteNode = noEmitSubstitution; + var onEmitNode = noEmitNotification; var state = 0 /* Uninitialized */; var diagnostics = []; // The transformation context is provided to each transformer as part of transformer @@ -78256,825 +81305,11 @@ var ts; } ts.transformNodes = transformNodes; })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans - var defaultLastEncodedSourceMapSpan = { - emittedLine: 0, - emittedColumn: 0, - sourceLine: 0, - sourceColumn: 0, - sourceIndex: 0 - }; - function createSourceMapWriter(host, writer, compilerOptions) { - if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } - var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSource; - var currentSourceText; - var sourceMapDir; // The directory in which sourcemap will be - // 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; - var sourceMapDataList; - var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); - return { - initialize: initialize, - reset: reset, - setSourceFile: setSourceFile, - emitPos: emitPos, - emitNodeWithSourceMap: emitNodeWithSourceMap, - emitTokenWithSourceMap: emitTokenWithSourceMap, - getText: getText, - getSourceMappingURL: getSourceMappingURL, - }; - /** - * Skips trivia such as comments and white-space that can optionally overriden by the source map source - */ - function skipSourceTrivia(pos) { - return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); - } - /** - * Initialize the SourceMapWriter for a new output file. - * - * @param filePath The path to the generated output file. - * @param sourceMapFilePath The path to the output source map file. - * @param sourceFileOrBundle The input source file or bundle for the program. - */ - function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) { - return; - } - if (sourceMapData) { - reset(); - } - sourceMapDataList = outputSourceMapDataList; - currentSource = undefined; - currentSourceText = 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, - }; - // 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 (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file - // 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(sourceFileOrBundle.fileName, 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)); - } - } - /** - * Reset the SourceMapWriter to an empty state. - */ - function reset() { - if (disabled) { - return; - } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMapData); - } - currentSource = undefined; - sourceMapDir = undefined; - sourceMapSourceIndex = undefined; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = undefined; - lastEncodedNameIndex = undefined; - sourceMapData = undefined; - sourceMapDataList = undefined; - } - function captureSection() { - return { - version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent, - }; - } - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - ts.Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative"); - ts.Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative"); - 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 = 0; - } - // 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; - } - /** - * Emits a mapping. - * - * If the position is synthetic (undefined or a negative value), no mapping will be - * created. - * - * @param pos The position. - */ - function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); - 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 - }; - } - 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; - } - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } - } - function isPossiblySourceMap(x) { - return typeof x === "object" && !!x.mappings && typeof x.mappings === "string" && !!x.sources; - } - /** - * Emits a node with possible leading and trailing source maps. - * - * @param hint A hint as to the intended usage of the node. - * @param node The node to emit. - * @param emitCallback The callback used to emit the node. - */ - function emitNodeWithSourceMap(hint, node, emitCallback) { - var _a; - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(hint, node); - } - if (node) { - if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { - var text = node.sourceMapText; - var parsed = void 0; - try { - parsed = JSON.parse(text); - } - catch (_b) { - // empty - } - if (!parsed || !isPossiblySourceMap(parsed)) { - return emitCallback(hint, node); - } - var offsetLine = writer.getLine(); - var firstLineColumnOffset = writer.getColumn(); - // First, decode the old component sourcemap - var originalMap = parsed; - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var resolvedPathCache = ts.createMap(); - var absolutePathCache = ts.createMap(); - var sourcemapIterator = ts.sourcemaps.decodeMappings(originalMap); - for (var _c = sourcemapIterator.next(), raw = _c.value, done = _c.done; !done; _a = sourcemapIterator.next(), raw = _a.value, done = _a.done, _a) { - var pathCacheKey = "" + raw.sourceIndex; - // Apply offsets to each position and fixup source entries - if (!resolvedPathCache.has(pathCacheKey)) { - var rawPath = originalMap.sources[raw.sourceIndex]; - var relativePath = originalMap.sourceRoot ? ts.combinePaths(originalMap.sourceRoot, rawPath) : rawPath; - var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath); - var resolvedPath_1 = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - resolvedPathCache.set(pathCacheKey, resolvedPath_1); - absolutePathCache.set(pathCacheKey, ts.getNormalizedAbsolutePath(resolvedPath_1, sourcesDirectoryPath)); - } - var resolvedPath = resolvedPathCache.get(pathCacheKey); - var absolutePath = absolutePathCache.get(pathCacheKey); - // tslint:disable-next-line:no-null-keyword - setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); // TODO: Lookup content for inlining? - var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath); - // Then reencode all the updated spans into the overall map - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = __assign({}, raw, { emittedLine: raw.emittedLine + offsetLine, emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, sourceIndex: newIndex }); - } - // And actually emit the text these sourcemaps are for - return emitCallback(hint, node); - } - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0 /* None */; - var range = emitNode && emitNode.sourceMapRange; - var _d = range || node, pos = _d.pos, end = _d.end; - var source = range && range.source; - var oldSource = currentSource; - if (source === oldSource) - source = undefined; - if (source) - setSourceFile(source); - if (node.kind !== 305 /* NotEmittedStatement */ - && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && pos >= 0) { - emitPos(skipSourceTrivia(pos)); - } - if (source) - setSourceFile(oldSource); - if (emitFlags & 64 /* NoNestedSourceMaps */) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - if (source) - setSourceFile(source); - if (node.kind !== 305 /* NotEmittedStatement */ - && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && end >= 0) { - emitPos(end); - } - if (source) - setSourceFile(oldSource); - } - } - /** - * Emits a token of a node with possible leading and trailing source maps. - * - * @param node The node containing the token. - * @param token The token to emit. - * @param tokenStartPos The start pos of the token. - * @param emitCallback The callback used to emit the token. - */ - function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled || ts.isInJsonFile(node)) { - return emitCallback(token, writer, tokenPos); - } - var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0 /* None */; - var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); - if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - tokenPos = emitCallback(token, writer, tokenPos); - if (range) - tokenPos = range.end; - if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - return tokenPos; - } - function isJsonSourceMapSource(sourceFile) { - return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); - } - /** - * Set the current source file. - * - * @param sourceFile The source file. - */ - function setSourceFile(sourceFile) { - if (disabled) { - return; - } - currentSource = sourceFile; - currentSourceText = currentSource.text; - if (isJsonSourceMapSource(sourceFile)) { - return; - } - setupSourceEntry(sourceFile.fileName, sourceFile.text); - } - function setupSourceEntry(fileName, content, source) { - if (!source) { - // 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; - source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(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(fileName); - if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(content); - } - } - } - /** - * Gets the text for the source map. - */ - function getText() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; // TODO: GH#18217 - } - encodeLastRecordedSourceMapSpan(); - return JSON.stringify(captureSection()); - } - /** - * Gets the SourceMappingURL for the source map. - */ - function getSourceMappingURL() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined; // TODO: GH#18217 - } - if (compilerOptions.inlineSourceMap) { - // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.base64encode(ts.sys, 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 createCommentWriter(printerOptions, emitPos) { - var extendedDiagnostics = printerOptions.extendedDiagnostics; - var newLine = ts.getNewLineCharacter(printerOptions); - var writer; - var containerPos = -1; - var containerEnd = -1; - var declarationListContainerEnd = -1; - var currentSourceFile; - var currentText; - var currentLineMap; - var detachedCommentsInfo; - var hasWrittenComment = false; - var disabled = !!printerOptions.removeComments; - return { - reset: reset, - setWriter: setWriter, - setSourceFile: setSourceFile, - emitNodeWithComments: emitNodeWithComments, - emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, - emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, - }; - function emitNodeWithComments(hint, node, emitCallback) { - if (disabled) { - emitCallback(hint, node); - return; - } - if (node) { - hasWrittenComment = false; - var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags || 0; - var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; - if ((pos < 0 && end < 0) || (pos === end)) { - // Both pos and end are synthesized, so just emit the node without comments. - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - } - else { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithComment"); - } - var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */; - // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. - // It is expensive to walk entire tree just to set one kind of node to have no comments. - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; - var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 10 /* JsxText */; - // Emit leading comments if the position is not synthesized and the node - // has not opted out from emitting leading comments. - if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); - } - // Save current container state on the stack. - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { - // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. - containerPos = pos; - } - if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { - // As above. - containerEnd = end; - // To avoid invalid comment emit in a down-level binding pattern, we - // keep track of the last declaration list container's end - if (node.kind === 236 /* VariableDeclarationList */) { - declarationListContainerEnd = end; - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithComment"); - } - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithComment"); - } - // Restore previous container state. - containerPos = savedContainerPos; - containerEnd = savedContainerEnd; - declarationListContainerEnd = savedDeclarationListContainerEnd; - // Emit trailing comments if the position is not synthesized and the node - // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { - emitTrailingComments(end); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithComment"); - } - } - } - } - function emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback) { - var leadingComments = emitNode && emitNode.leadingComments; - if (ts.some(leadingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitNodeWithSynthesizedComments"); - } - ts.forEach(leadingComments, emitLeadingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitNodeWithSynthesizedComments"); - } - } - emitNodeWithNestedComments(hint, node, emitFlags, emitCallback); - var trailingComments = emitNode && emitNode.trailingComments; - if (ts.some(trailingComments)) { - if (extendedDiagnostics) { - ts.performance.mark("postEmitNodeWithSynthesizedComments"); - } - ts.forEach(trailingComments, emitTrailingSynthesizedComment); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "postEmitNodeWithSynthesizedComments"); - } - } - } - function emitLeadingSynthesizedComment(comment) { - if (comment.kind === 2 /* SingleLineCommentTrivia */) { - writer.writeLine(); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function emitTrailingSynthesizedComment(comment) { - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - } - function writeSynthesizedComment(comment) { - var text = formatSynthesizedComment(comment); - var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; - ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); - } - function formatSynthesizedComment(comment) { - return comment.kind === 3 /* MultiLineCommentTrivia */ - ? "/*" + comment.text + "*/" - : "//" + comment.text; - } - function emitNodeWithNestedComments(hint, node, emitFlags, emitCallback) { - if (emitFlags & 2048 /* NoNestedComments */) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - } - function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { - if (extendedDiagnostics) { - ts.performance.mark("preEmitBodyWithDetachedComments"); - } - var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = ts.getEmitFlags(node); - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; - if (!skipLeadingComments) { - emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); - } - if (emitFlags & 2048 /* NoNestedComments */ && !disabled) { - disabled = true; - emitCallback(node); - disabled = false; - } - else { - emitCallback(node); - } - if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); - } - if (!skipTrailingComments) { - emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); - if (hasWrittenComment && !writer.isAtStartOfLine()) { - writer.writeLine(); - } - } - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); - } - } - function emitLeadingComments(pos, isEmittedNode) { - hasWrittenComment = false; - if (isEmittedNode) { - forEachLeadingCommentToEmit(pos, emitLeadingComment); - } - else if (pos === 0) { - // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, - // unless it is a triple slash comment at the top of the file. - // For Example: - // /// - // declare var x; - // /// - // interface F {} - // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted - forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); - } - } - function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (isTripleSlashComment(commentPos, commentEnd)) { - emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); - } - } - function shouldWriteComment(text, pos) { - if (printerOptions.onlyPrintJsDocStyle) { - return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); - } - return true; - } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (!hasWrittenComment) { - ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); - hasWrittenComment = true; - } - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else if (kind === 3 /* MultiLineCommentTrivia */) { - writer.write(" "); - } - } - function emitLeadingCommentsOfPosition(pos) { - if (disabled || pos === -1) { - return; - } - emitLeadingComments(pos, /*isEmittedNode*/ true); - } - function emitTrailingComments(pos) { - forEachTrailingCommentToEmit(pos, emitTrailingComment); - } - function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - } - function emitTrailingCommentsOfPosition(pos, prefixSpace) { - if (disabled) { - return; - } - if (extendedDiagnostics) { - ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); - } - forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); - if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); - } - } - function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { - // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - if (hasTrailingNewLine) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - function forEachLeadingCommentToEmit(pos, cb) { - // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments - if (containerPos === -1 || pos !== containerPos) { - if (hasDetachedComments(pos)) { - forEachLeadingCommentWithoutDetachedComments(cb); - } - else { - ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - } - } - function forEachTrailingCommentToEmit(end, cb) { - // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments - if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { - ts.forEachTrailingCommentRange(currentText, end, cb); - } - } - function reset() { - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - detachedCommentsInfo = undefined; - } - function setWriter(output) { - writer = output; - } - function setSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = currentSourceFile.text; - currentLineMap = ts.getLineStarts(currentSourceFile); - detachedCommentsInfo = undefined; - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; - } - function forEachLeadingCommentWithoutDetachedComments(cb) { - // get the leading comments from detachedPos - var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - function emitDetachedCommentsAndUpdateCommentsInfo(range) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { - if (!shouldWriteComment(currentText, commentPos)) - return; - if (emitPos) - emitPos(commentPos); - ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) - emitPos(commentEnd); - } - /** - * Determine if the given comment is a triple-slash - * - * @return true if the comment is a triple-slash comment else false - */ - function isTripleSlashComment(commentPos, commentEnd) { - return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); - } - } - ts.createCommentWriter = createCommentWriter; -})(ts || (ts = {})); var ts; (function (ts) { var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); + var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ /** * Iterates over the source files that are expected to have an emit output. @@ -79112,21 +81347,26 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + if (sourceFile.kind === 280 /* Bundle */) { + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79149,7 +81389,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79169,22 +81409,16 @@ var ts; var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var newLine = host.getNewLine(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); var writer = ts.createTextWriter(newLine); - var sourceMap = ts.createSourceMapWriter(host, writer); - var declarationSourceMap = ts.createSourceMapWriter(host, writer, { - sourceMap: compilerOptions.declarationMap, - sourceRoot: compilerOptions.sourceRoot, - mapRoot: compilerOptions.mapRoot, - extendedDiagnostics: compilerOptions.extendedDiagnostics, - }); + var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; var exportedModulesFromDeclarationEmit; // Emit each output file - ts.performance.mark("beforePrint"); + enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); - ts.performance.measure("printTime", "beforePrint"); + exit(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -79198,56 +81432,66 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; // Create a printer to print the nodes - var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { + var printer = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, // transform hooks onEmitNode: transform.emitNodeWithNotification, substituteNode: transform.substituteNode, - // sourcemap hooks - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - // emitter hooks - onSetSourceFile: setSourceFile, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79261,14 +81505,20 @@ var ts; emitterDiagnostics.add(diagnostic); } } - var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true, noEmitHelpers: true }), { + var printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + var declarationPrinter = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, - // sourcemap hooks - onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: declarationSourceMap.emitPos, - onSetSourceFile: setSourceFileForDeclarationSourceMaps, // transform hooks onEmitNode: declarationTransform.emitNodeWithNotification, substituteNode: declarationTransform.substituteNode, @@ -79277,8 +81527,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); - if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -79287,7 +81542,7 @@ var ts; } function collectLinkedAliases(node) { if (ts.isExportAssignment(node)) { - if (node.expression.kind === 71 /* Identifier */) { + if (node.expression.kind === 72 /* Identifier */) { resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); } return; @@ -79298,25 +81553,41 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { - var bundle = sourceFileOrBundle.kind === 278 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 277 /* SourceFile */ ? sourceFileOrBundle : undefined; + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); + var sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); + } if (bundle) { - printer.writeBundle(bundle, writer, bundleInfo); + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); } else { - printer.writeFile(sourceFile, writer); + printer.writeFile(sourceFile, writer, sourceMapGenerator); } - writer.writeLine(); - var sourceMappingURL = mapRecorder.getSourceMappingURL(); - if (sourceMappingURL) { - writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) + writer.rawWrite(newLine); + writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (sourceMapFilePath) { + var sourceMap = sourceMapGenerator.toString(); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } } - // Write the source map - if (sourceMapFilePath) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); + else { + writer.writeLine(); } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); @@ -79326,32 +81597,84 @@ var ts; ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); } // Reset state - mapRecorder.reset(); writer.clear(); bundleInfo = createDefaultBundleInfo(); } - function setSourceFile(node) { - sourceMap.setSourceFile(node); + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } - function setSourceFileForDeclarationSourceMaps(node) { - declarationSourceMap.setSourceFile(node); + function getSourceRoot(mapOptions) { + // 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 + var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) + return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return ts.getDirectoryPath(ts.normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var sourceMapText = sourceMapGenerator.toString(); + var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); + return "data:application/json;base64," + base64SourceMapText; + } + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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(sourceFile.fileName, host, sourceMapDir)); + } + if (ts.getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return ts.combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; } } ts.emitFiles = emitFiles; var PipelinePhase; (function (PipelinePhase) { PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; - PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; - PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; - PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); - var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); var currentSourceFile; var nodeIdToGeneratedName; // Map of generated names for specific nodes. var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. @@ -79361,19 +81684,23 @@ var ts; var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; - var ownWriter; + var ownWriter; // Reusable `EmitTextWriter` for basic printing. var write = writeBase; - var commitPendingSemicolon = ts.noop; - var writeSemicolon = writeSemicolonInternal; - var pendingSemicolon = false; - if (printerOptions.omitTrailingSemicolon) { - commitPendingSemicolon = commitPendingSemicolonInternal; - writeSemicolon = deferWriteSemicolon; - } - var syntheticParent = { pos: -1, end: -1 }; - var moduleKind = ts.getEmitModuleKind(printerOptions); - var bundledHelpers = ts.createMap(); var isOwnFileEmit; + // Source Maps + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + // Comments + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; reset(); return { // public API @@ -79400,9 +81727,9 @@ var ts; break; } switch (node.kind) { - case 277 /* SourceFile */: return printFile(node); - case 278 /* Bundle */: return printBundle(node); - case 279 /* UnparsedSource */: return printUnparsedSource(node); + case 279 /* SourceFile */: return printFile(node); + case 280 /* Bundle */: return printBundle(node); + case 281 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -79412,11 +81739,11 @@ var ts; return endPrint(); } function printBundle(bundle) { - writeBundle(bundle, beginPrint()); + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printFile(sourceFile) { - writeFile(sourceFile, beginPrint()); + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printUnparsedSource(unparsed) { @@ -79425,14 +81752,14 @@ var ts; } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(hint, node, sourceFile); reset(); writer = previousWriter; } function writeList(format, nodes, sourceFile, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); if (sourceFile) { setSourceFile(sourceFile); } @@ -79440,18 +81767,18 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output, bundleInfo) { + function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { isOwnFileEmit = false; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { var prepend = _b[_a]; - print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); writeLine(); + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); } if (bundleInfo) { bundleInfo.originalOffset = writer.getTextPos(); @@ -79465,15 +81792,15 @@ var ts; } function writeUnparsedSource(unparsed, output) { var previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); reset(); writer = previousWriter; } - function writeFile(sourceFile, output) { + function writeFile(sourceFile, output, sourceMapGenerator) { isOwnFileEmit = true; var previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(sourceFile); emitPrologueDirectivesIfNeeded(sourceFile); print(0 /* SourceFile */, sourceFile, sourceFile); @@ -79492,19 +81819,24 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - var pipelinePhase = getPipelinePhase(0 /* Notification */, hint); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; - comments.setSourceFile(sourceFile); - if (onSetSourceFile) { - onSetSourceFile(sourceFile); + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); } } - function setWriter(output) { - writer = output; // TODO: GH#18217 - comments.setWriter(output); + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = ts.getTrailingSemicolonOmittingWriter(_writer); + } + writer = _writer; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; } function reset() { nodeIdToGeneratedName = []; @@ -79513,68 +81845,66 @@ var ts; tempFlagsStack = []; tempFlags = 0 /* Auto */; reservedNamesStack = []; - comments.reset(); - setWriter(/*output*/ undefined); + currentSourceFile = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } function emit(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(4 /* Unspecified */, node); } function emitIdentifierName(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(2 /* IdentifierName */, node); } function emitExpression(node) { - if (!node) + if (node === undefined) return; - var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(1 /* Expression */, node); } - function getPipelinePhase(phase, hint) { + function getPipelinePhase(phase, node) { switch (phase) { case 0 /* Notification */: - if (onEmitNode) { + if (onEmitNode !== ts.noEmitNotification) { return pipelineEmitWithNotification; } // falls through - case 1 /* Comments */: - if (emitNodeWithComments && hint !== 0 /* SourceFile */) { + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { return pipelineEmitWithComments; } - return pipelineEmitWithoutComments; - case 2 /* SourceMaps */: - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */) { + // falls through + case 3 /* SourceMaps */: + if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { return pipelineEmitWithSourceMap; } // falls through - case 3 /* Emit */: + case 4 /* Emit */: return pipelineEmitWithHint; default: - return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + return ts.Debug.assertNever(phase); } } - function getNextPipelinePhase(currentPhase, hint) { - return getPipelinePhase(currentPhase + 1, hint); + function getNextPipelinePhase(currentPhase, node) { + return getPipelinePhase(currentPhase + 1, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); - } - function pipelineEmitWithComments(hint, node) { - ts.Debug.assertDefined(emitNodeWithComments); - ts.Debug.assert(hint !== 0 /* SourceFile */); - emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint)); - } - function pipelineEmitWithoutComments(hint, node) { - var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint); - pipelinePhase(hint, trySubstituteNode(hint, node)); - } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(hint !== 0 /* SourceFile */); - ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node); + onEmitNode(hint, node, pipelinePhase); } function pipelineEmitWithHint(hint, node) { if (hint === 0 /* SourceFile */) @@ -79583,254 +81913,285 @@ var ts; return emitIdentifier(ts.cast(node, ts.isIdentifier)); if (hint === 3 /* MappedTypeParameter */) return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } if (hint === 4 /* Unspecified */) { if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); switch (node.kind) { // Pseudo-literals - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: return emitLiteral(node); - case 279 /* UnparsedSource */: + case 281 /* UnparsedSource */: return emitUnparsedSource(node); // Identifiers - case 71 /* Identifier */: + case 72 /* Identifier */: return emitIdentifier(node); // Parse tree nodes // Names - case 146 /* QualifiedName */: + case 148 /* QualifiedName */: return emitQualifiedName(node); - case 147 /* ComputedPropertyName */: + case 149 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 148 /* TypeParameter */: + case 150 /* TypeParameter */: return emitTypeParameter(node); - case 149 /* Parameter */: + case 151 /* Parameter */: return emitParameter(node); - case 150 /* Decorator */: + case 152 /* Decorator */: return emitDecorator(node); // Type members - case 151 /* PropertySignature */: + case 153 /* PropertySignature */: return emitPropertySignature(node); - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 153 /* MethodSignature */: + case 155 /* MethodSignature */: return emitMethodSignature(node); - case 154 /* MethodDeclaration */: + case 156 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 155 /* Constructor */: + case 157 /* Constructor */: return emitConstructor(node); - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return emitAccessorDeclaration(node); - case 158 /* CallSignature */: + case 160 /* CallSignature */: return emitCallSignature(node); - case 159 /* ConstructSignature */: + case 161 /* ConstructSignature */: return emitConstructSignature(node); - case 160 /* IndexSignature */: + case 162 /* IndexSignature */: return emitIndexSignature(node); // Types - case 161 /* TypePredicate */: + case 163 /* TypePredicate */: return emitTypePredicate(node); - case 162 /* TypeReference */: + case 164 /* TypeReference */: return emitTypeReference(node); - case 163 /* FunctionType */: + case 165 /* FunctionType */: return emitFunctionType(node); - case 287 /* JSDocFunctionType */: + case 289 /* JSDocFunctionType */: return emitJSDocFunctionType(node); - case 164 /* ConstructorType */: + case 166 /* ConstructorType */: return emitConstructorType(node); - case 165 /* TypeQuery */: + case 167 /* TypeQuery */: return emitTypeQuery(node); - case 166 /* TypeLiteral */: + case 168 /* TypeLiteral */: return emitTypeLiteral(node); - case 167 /* ArrayType */: + case 169 /* ArrayType */: return emitArrayType(node); - case 168 /* TupleType */: + case 170 /* TupleType */: return emitTupleType(node); - case 169 /* OptionalType */: + case 171 /* OptionalType */: return emitOptionalType(node); - case 171 /* UnionType */: + case 173 /* UnionType */: return emitUnionType(node); - case 172 /* IntersectionType */: + case 174 /* IntersectionType */: return emitIntersectionType(node); - case 173 /* ConditionalType */: + case 175 /* ConditionalType */: return emitConditionalType(node); - case 174 /* InferType */: + case 176 /* InferType */: return emitInferType(node); - case 175 /* ParenthesizedType */: + case 177 /* ParenthesizedType */: return emitParenthesizedType(node); - case 209 /* ExpressionWithTypeArguments */: + case 211 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 176 /* ThisType */: + case 178 /* ThisType */: return emitThisType(); - case 177 /* TypeOperator */: + case 179 /* TypeOperator */: return emitTypeOperator(node); - case 178 /* IndexedAccessType */: + case 180 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 179 /* MappedType */: + case 181 /* MappedType */: return emitMappedType(node); - case 180 /* LiteralType */: + case 182 /* LiteralType */: return emitLiteralType(node); - case 181 /* ImportType */: + case 183 /* ImportType */: return emitImportTypeNode(node); - case 282 /* JSDocAllType */: - write("*"); + case 284 /* JSDocAllType */: + writePunctuation("*"); return; - case 283 /* JSDocUnknownType */: - write("?"); + case 285 /* JSDocUnknownType */: + writePunctuation("?"); return; - case 284 /* JSDocNullableType */: + case 286 /* JSDocNullableType */: return emitJSDocNullableType(node); - case 285 /* JSDocNonNullableType */: + case 287 /* JSDocNonNullableType */: return emitJSDocNonNullableType(node); - case 286 /* JSDocOptionalType */: + case 288 /* JSDocOptionalType */: return emitJSDocOptionalType(node); - case 170 /* RestType */: - case 288 /* JSDocVariadicType */: + case 172 /* RestType */: + case 290 /* JSDocVariadicType */: return emitRestOrJSDocVariadicType(node); // Binding patterns - case 182 /* ObjectBindingPattern */: + case 184 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 183 /* ArrayBindingPattern */: + case 185 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 184 /* BindingElement */: + case 186 /* BindingElement */: return emitBindingElement(node); // Misc - case 214 /* TemplateSpan */: + case 216 /* TemplateSpan */: return emitTemplateSpan(node); - case 215 /* SemicolonClassElement */: + case 217 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 216 /* Block */: + case 218 /* Block */: return emitBlock(node); - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: return emitVariableStatement(node); - case 218 /* EmptyStatement */: - return emitEmptyStatement(); - case 219 /* ExpressionStatement */: + case 220 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 221 /* ExpressionStatement */: return emitExpressionStatement(node); - case 220 /* IfStatement */: + case 222 /* IfStatement */: return emitIfStatement(node); - case 221 /* DoStatement */: + case 223 /* DoStatement */: return emitDoStatement(node); - case 222 /* WhileStatement */: + case 224 /* WhileStatement */: return emitWhileStatement(node); - case 223 /* ForStatement */: + case 225 /* ForStatement */: return emitForStatement(node); - case 224 /* ForInStatement */: + case 226 /* ForInStatement */: return emitForInStatement(node); - case 225 /* ForOfStatement */: + case 227 /* ForOfStatement */: return emitForOfStatement(node); - case 226 /* ContinueStatement */: + case 228 /* ContinueStatement */: return emitContinueStatement(node); - case 227 /* BreakStatement */: + case 229 /* BreakStatement */: return emitBreakStatement(node); - case 228 /* ReturnStatement */: + case 230 /* ReturnStatement */: return emitReturnStatement(node); - case 229 /* WithStatement */: + case 231 /* WithStatement */: return emitWithStatement(node); - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: return emitSwitchStatement(node); - case 231 /* LabeledStatement */: + case 233 /* LabeledStatement */: return emitLabeledStatement(node); - case 232 /* ThrowStatement */: + case 234 /* ThrowStatement */: return emitThrowStatement(node); - case 233 /* TryStatement */: + case 235 /* TryStatement */: return emitTryStatement(node); - case 234 /* DebuggerStatement */: + case 236 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 235 /* VariableDeclaration */: + case 237 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 238 /* ClassDeclaration */: + case 240 /* ClassDeclaration */: return emitClassDeclaration(node); - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 243 /* ModuleBlock */: + case 245 /* ModuleBlock */: return emitModuleBlock(node); - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: return emitCaseBlock(node); - case 245 /* NamespaceExportDeclaration */: + case 247 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: return emitImportDeclaration(node); - case 248 /* ImportClause */: + case 250 /* ImportClause */: return emitImportClause(node); - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: return emitNamespaceImport(node); - case 250 /* NamedImports */: + case 252 /* NamedImports */: return emitNamedImports(node); - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: return emitImportSpecifier(node); - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: return emitExportAssignment(node); - case 253 /* ExportDeclaration */: + case 255 /* ExportDeclaration */: return emitExportDeclaration(node); - case 254 /* NamedExports */: + case 256 /* NamedExports */: return emitNamedExports(node); - case 255 /* ExportSpecifier */: + case 257 /* ExportSpecifier */: return emitExportSpecifier(node); - case 256 /* MissingDeclaration */: + case 258 /* MissingDeclaration */: return; // Module references - case 257 /* ExternalModuleReference */: + case 259 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) - case 10 /* JsxText */: + case 11 /* JsxText */: return emitJsxText(node); - case 260 /* JsxOpeningElement */: - case 263 /* JsxOpeningFragment */: + case 262 /* JsxOpeningElement */: + case 265 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 261 /* JsxClosingElement */: - case 264 /* JsxClosingFragment */: + case 263 /* JsxClosingElement */: + case 266 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 265 /* JsxAttribute */: + case 267 /* JsxAttribute */: return emitJsxAttribute(node); - case 266 /* JsxAttributes */: + case 268 /* JsxAttributes */: return emitJsxAttributes(node); - case 267 /* JsxSpreadAttribute */: + case 269 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 268 /* JsxExpression */: + case 270 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 269 /* CaseClause */: + case 271 /* CaseClause */: return emitCaseClause(node); - case 270 /* DefaultClause */: + case 272 /* DefaultClause */: return emitDefaultClause(node); - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: return emitHeritageClause(node); - case 272 /* CatchClause */: + case 274 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 273 /* PropertyAssignment */: + case 275 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 276 /* EnumMember */: + case 278 /* EnumMember */: return emitEnumMember(node); - // JSDoc nodes (ignored) + // JSDoc nodes (only used in codefixes currently) + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 300 /* JSDocReturnTag */: + case 302 /* JSDocTypeTag */: + case 301 /* JSDocThisTag */: + case 298 /* JSDocEnumTag */: + return emitJSDocSimpleTypedTag(node); + case 295 /* JSDocAugmentsTag */: + return emitJSDocAugmentsTag(node); + case 303 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 304 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 297 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 293 /* JSDocSignature */: + return emitJSDocSignature(node); + case 292 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 296 /* JSDocClassTag */: + case 294 /* JSDocTag */: + return emitJSDocSimpleTag(node); + case 291 /* JSDocComment */: + return emitJSDoc(node); // Transformation nodes (ignored) } if (ts.isExpression(node)) { hint = 1 /* Expression */; - node = trySubstituteNode(1 /* Expression */, node); + if (substituteNode !== ts.noEmitSubstitution) { + node = substituteNode(hint, node); + } } else if (ts.isToken(node)) { return writeTokenNode(node, writePunctuation); @@ -79840,89 +82201,90 @@ var ts; switch (node.kind) { // Literals case 8 /* NumericLiteral */: - return emitNumericLiteral(node); - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: return emitLiteral(node); // Identifiers - case 71 /* Identifier */: + case 72 /* Identifier */: return emitIdentifier(node); // Reserved words - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 101 /* TrueKeyword */: - case 99 /* ThisKeyword */: - case 91 /* ImportKeyword */: + case 87 /* FalseKeyword */: + case 96 /* NullKeyword */: + case 98 /* SuperKeyword */: + case 102 /* TrueKeyword */: + case 100 /* ThisKeyword */: + case 92 /* ImportKeyword */: writeTokenNode(node, writeKeyword); return; // Expressions - case 185 /* ArrayLiteralExpression */: + case 187 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 186 /* ObjectLiteralExpression */: + case 188 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 187 /* PropertyAccessExpression */: + case 189 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 188 /* ElementAccessExpression */: + case 190 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 189 /* CallExpression */: + case 191 /* CallExpression */: return emitCallExpression(node); - case 190 /* NewExpression */: + case 192 /* NewExpression */: return emitNewExpression(node); - case 191 /* TaggedTemplateExpression */: + case 193 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 193 /* ParenthesizedExpression */: + case 195 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 194 /* FunctionExpression */: + case 196 /* FunctionExpression */: return emitFunctionExpression(node); - case 195 /* ArrowFunction */: + case 197 /* ArrowFunction */: return emitArrowFunction(node); - case 196 /* DeleteExpression */: + case 198 /* DeleteExpression */: return emitDeleteExpression(node); - case 197 /* TypeOfExpression */: + case 199 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 198 /* VoidExpression */: + case 200 /* VoidExpression */: return emitVoidExpression(node); - case 199 /* AwaitExpression */: + case 201 /* AwaitExpression */: return emitAwaitExpression(node); - case 200 /* PrefixUnaryExpression */: + case 202 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 201 /* PostfixUnaryExpression */: + case 203 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 202 /* BinaryExpression */: + case 204 /* BinaryExpression */: return emitBinaryExpression(node); - case 203 /* ConditionalExpression */: + case 205 /* ConditionalExpression */: return emitConditionalExpression(node); - case 204 /* TemplateExpression */: + case 206 /* TemplateExpression */: return emitTemplateExpression(node); - case 205 /* YieldExpression */: + case 207 /* YieldExpression */: return emitYieldExpression(node); - case 206 /* SpreadElement */: + case 208 /* SpreadElement */: return emitSpreadExpression(node); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return emitClassExpression(node); - case 208 /* OmittedExpression */: + case 210 /* OmittedExpression */: return; - case 210 /* AsExpression */: + case 212 /* AsExpression */: return emitAsExpression(node); - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: return emitNonNullExpression(node); - case 212 /* MetaProperty */: + case 214 /* MetaProperty */: return emitMetaProperty(node); // JSX - case 258 /* JsxElement */: + case 260 /* JsxElement */: return emitJsxElement(node); - case 259 /* JsxSelfClosingElement */: + case 261 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 262 /* JsxFragment */: + case 264 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 307 /* CommaListExpression */: + case 309 /* CommaListExpression */: return emitCommaList(node); } } @@ -79934,12 +82296,13 @@ var ts; writeSpace(); emit(node.constraint); } - function trySubstituteNode(hint, node) { - return node && substituteNode && substituteNode(hint, node) || node; + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); + pipelinePhase(hint, substituteNode(hint, node)); } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 278 /* Bundle */ ? node : undefined; + var bundle = node.kind === 280 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -79976,7 +82339,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79988,7 +82351,8 @@ var ts; // Literals/Pseudo-literals // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } // SyntaxKind.StringLiteral @@ -79998,9 +82362,9 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) - && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); } else { @@ -80018,7 +82382,7 @@ var ts; function emitIdentifier(node) { var writeText = node.symbol ? writeSymbol : write; writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); - emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments + emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names @@ -80029,7 +82393,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -80065,7 +82429,7 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 287 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { @@ -80087,7 +82451,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -80097,7 +82461,7 @@ var ts; emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); - writeSemicolon(); + writeTrailingSemicolon(); } function emitMethodSignature(node) { pushNameGenerationScope(node); @@ -80108,7 +82472,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -80127,7 +82491,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 156 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -80139,7 +82503,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -80151,7 +82515,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -80159,10 +82523,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // // Types @@ -80189,22 +82553,22 @@ var ts; popNameGenerationScope(node); } function emitJSDocFunctionType(node) { - write("function"); + writeKeyword("function"); emitParameters(node, node.parameters); - write(":"); + writePunctuation(":"); emit(node.type); } function emitJSDocNullableType(node) { - write("?"); + writePunctuation("?"); emit(node.type); } function emitJSDocNonNullableType(node) { - write("!"); + writePunctuation("!"); emit(node.type); } function emitJSDocOptionalType(node) { emit(node.type); - write("="); + writePunctuation("="); } function emitConstructorType(node) { pushNameGenerationScope(node); @@ -80225,8 +82589,8 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */; - emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); writePunctuation("}"); } function emitArrayType(node) { @@ -80235,23 +82599,23 @@ var ts; writePunctuation("]"); } function emitRestOrJSDocVariadicType(node) { - write("..."); + writePunctuation("..."); emit(node.type); } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 272 /* TupleTypeElements */); + emitList(node, node.elementTypes, 528 /* TupleTypeElements */); writePunctuation("]"); } function emitOptionalType(node) { emit(node.type); - write("?"); + writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 260 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */); } function emitIntersectionType(node) { - emitList(node, node.types, 264 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */); } function emitConditionalType(node) { emit(node.checkType); @@ -80304,25 +82668,25 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) { + if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) { writeKeyword("readonly"); } writeSpace(); } writePunctuation("["); - var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */); + var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter); pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); - if (node.questionToken.kind !== 55 /* QuestionToken */) { + if (node.questionToken.kind !== 56 /* QuestionToken */) { writePunctuation("?"); } } writePunctuation(":"); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); if (emitFlags & 1 /* SingleLine */) { writeSpace(); } @@ -80355,12 +82719,12 @@ var ts; // function emitObjectBindingPattern(node) { writePunctuation("{"); - emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); writePunctuation("}"); } function emitArrayBindingPattern(node) { writePunctuation("["); - emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); writePunctuation("]"); } function emitBindingElement(node) { @@ -80378,8 +82742,8 @@ var ts; // function emitArrayLiteralExpression(node) { var elements = node.elements; - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -80387,9 +82751,9 @@ var ts; if (indentedFlag) { increaseIndent(); } - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */; - emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); } @@ -80400,20 +82764,20 @@ var ts; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = ts.createToken(23 /* DotToken */); + var dotToken = ts.createToken(24 /* DotToken */); dotToken.pos = dotRangeStart; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); - increaseIndentIf(indentBeforeDot); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); if (shouldEmitDotDot) { writePunctuation("."); } - emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node); - increaseIndentIf(indentAfterDot); + emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); } @@ -80423,9 +82787,9 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); + && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -80438,21 +82802,21 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); } function emitNewExpression(node) { - emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); @@ -80467,9 +82831,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node); + var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { generateNameIfNeeded(node.name); @@ -80488,22 +82852,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -80528,24 +82892,24 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 200 /* PrefixUnaryExpression */ - && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) - || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); + return operand.kind === 202 /* PrefixUnaryExpression */ + && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */)) + || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; + var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); - increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + increaseIndentIf(indentBeforeOperator, isCommaOperator); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, writeOperator); + writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - increaseIndentIf(indentAfterOperator, " "); + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); } @@ -80555,28 +82919,28 @@ var ts; var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); - increaseIndentIf(indentBeforeQuestion, " "); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); - increaseIndentIf(indentAfterQuestion, " "); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); - increaseIndentIf(indentBeforeColon, " "); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); - increaseIndentIf(indentAfterColon, " "); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); } function emitTemplateExpression(node) { emit(node.head); - emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - writePunctuation("..."); + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); emitExpression(node.expression); } function emitClassExpression(node) { @@ -80619,36 +82983,45 @@ var ts; emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); } function emitBlockStatements(node, forceSingleLine) { - emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); - var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; emitList(node, node.statements, format); - emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); + emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - writeSemicolon(); + writeTrailingSemicolon(); } - function emitEmptyStatement() { - writeSemicolon(); + function emitEmptyStatement(isEmbeddedStatement) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { - writeSemicolon(); + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); } } function emitIfStatement(node) { - var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 220 /* IfStatement */) { + emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 222 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -80658,14 +83031,14 @@ var ts; } } function emitWhileClause(node, startPos) { - var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node); + var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { - emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -80681,45 +83054,45 @@ var ts; emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.condition); - pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.incrementor); - emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(145 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 236 /* VariableDeclarationList */) { + if (node.kind === 238 /* VariableDeclarationList */) { emit(node); } else { @@ -80728,14 +83101,14 @@ var ts; } } function emitContinueStatement(node) { - emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitBreakStatement(node) { - emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { var node = ts.getParseTreeNode(contextNode); @@ -80761,40 +83134,40 @@ var ts; return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitWithStatement(node) { - var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node); + emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTryStatement(node) { - emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -80803,14 +83176,14 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); - writeSemicolon(); + writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); } // // Declarations @@ -80823,7 +83196,7 @@ var ts; function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); writeSpace(); - emitList(node, node.declarations, 272 /* VariableDeclarationList */); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { emitFunctionDeclarationOrExpression(node); @@ -80871,7 +83244,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -80923,7 +83296,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -80935,7 +83308,7 @@ var ts; emitHelpers(body); if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { decreaseIndent(); - emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); increaseIndent(); } else { @@ -80962,7 +83335,7 @@ var ts; emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65 /* ClassMembers */); + emitList(node, node.members, 129 /* ClassMembers */); writePunctuation("}"); if (indentedFlag) { decreaseIndent(); @@ -80975,10 +83348,10 @@ var ts; writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256 /* HeritageClauses */); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 65 /* InterfaceMembers */); + emitList(node, node.members, 129 /* InterfaceMembers */); writePunctuation("}"); } function emitTypeAliasDeclaration(node) { @@ -80992,7 +83365,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -81001,7 +83374,7 @@ var ts; emit(node.name); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 81 /* EnumMembers */); + emitList(node, node.members, 145 /* EnumMembers */); writePunctuation("}"); } function emitModuleDeclaration(node) { @@ -81013,8 +83386,8 @@ var ts; emit(node.name); var body = node.body; if (!body) - return writeSemicolon(); - while (body.kind === 242 /* ModuleDeclaration */) { + return writeTrailingSemicolon(); + while (body.kind === 244 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); body = body.body; @@ -81029,23 +83402,23 @@ var ts; popNameGenerationScope(node); } function emitCaseBlock(node) { - emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node); - emitList(node, node.clauses, 65 /* CaseBlockClauses */); - emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node); + emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); - writeSemicolon(); + writeTrailingSemicolon(); } function emitModuleReference(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81054,29 +83427,29 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - emitTokenWithComment(143 /* FromKeyword */, node.importClause.end, writeKeyword, node); + emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); - writeSemicolon(); + writeTrailingSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); + var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node); writeSpace(); - emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node); + emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -81087,45 +83460,45 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node); + emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node); } else { - emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node); + emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitExportDeclaration(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node); + nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); var fromPos = node.exportClause ? node.exportClause.end : nextPos; - emitTokenWithComment(143 /* FromKeyword */, fromPos, writeKeyword, node); + emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamespaceExportDeclaration(node) { - var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); + var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node); writeSpace(); emit(node.name); - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -81135,14 +83508,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -81161,7 +83534,7 @@ var ts; // function emitJsxElement(node) { emit(node.openingElement); - emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); emit(node.closingElement); } function emitJsxSelfClosingElement(node) { @@ -81173,7 +83546,7 @@ var ts; } function emitJsxFragment(node) { emit(node.openingFragment); - emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { @@ -81188,7 +83561,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { @@ -81199,7 +83571,7 @@ var ts; writePunctuation(">"); } function emitJsxAttributes(node) { - emitList(node, node.properties, 131328 /* JsxElementAttributes */); + emitList(node, node.properties, 262656 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); @@ -81219,7 +83591,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81230,13 +83602,13 @@ var ts; // Clauses // function emitCaseClause(node) { - emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node); + var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node); emitCaseOrDefaultClauseRest(node, node.statements, pos); } function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { @@ -81246,14 +83618,14 @@ var ts; ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); - var format = 81985 /* CaseOrDefaultClauseStatements */; + var format = 163969 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode); writeSpace(); - format &= ~(1 /* MultiLine */ | 64 /* Indented */); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); } else { - emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode); } emitList(parentNode, statements, format); } @@ -81261,15 +83633,15 @@ var ts; writeSpace(); writeTokenText(node.token, writeKeyword); writeSpace(); - emitList(node, node.types, 272 /* HeritageClauseTypes */); + emitList(node, node.types, 528 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -81306,7 +83678,7 @@ var ts; } function emitSpreadAssignment(node) { if (node.expression) { - writePunctuation("..."); + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); emitExpression(node.expression); } } @@ -81318,6 +83690,142 @@ var ts; emitInitializer(node.initializer, node.name.end, node); } // + // JSDoc + // + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + var lines = node.comment.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocAugmentsTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + if (comment) { + writeSpace(); + write(comment); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // // Top-level nodes // function emitSourceFile(node) { @@ -81337,41 +83845,46 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.moduleName) { - write("/// "); + writeComment("/// "); writeLine(); } if (currentSourceFile && currentSourceFile.amdDependencies) { for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { var dep = _b[_a]; if (dep.name) { - write("/// "); + writeComment("/// "); } else { - write("/// "); + writeComment("/// "); } writeLine(); } } for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { var directive = files_1[_c]; - write("/// "); + writeComment("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; - write("/// "); + for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { + var directive = types_18[_d]; + writeComment("/// "); + writeLine(); + } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + writeComment("/// "); writeLine(); } } @@ -81390,7 +83903,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 272 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -81430,13 +83943,14 @@ var ts; setSourceFile(sourceFile); emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); } + setSourceFile(undefined); } } function emitShebangIfNeeded(sourceFileOrBundle) { if (ts.isSourceFile(sourceFileOrBundle)) { var shebang = ts.getShebang(sourceFileOrBundle.text); if (shebang) { - write(shebang); + writeComment(shebang); writeLine(); return true; } @@ -81464,7 +83978,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328 /* Modifiers */); + emitList(node, modifiers, 262656 /* Modifiers */); writeSpace(); } } @@ -81478,7 +83992,7 @@ var ts; function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -81515,30 +84029,37 @@ var ts; else { writeLine(); increaseIndent(); - emit(node); + if (ts.isEmptyStatement(node)) { + var pipelinePhase = getPipelinePhase(0 /* Notification */, node); + pipelinePhase(5 /* EmbeddedStatement */, node); + } + else { + emit(node); + } decreaseIndent(); } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 24577 /* Decorators */); + emitList(parentNode, decorators, 49153 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26896 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures return emitTypeArguments(parentNode, parentNode.typeArguments); } - emitList(parentNode, typeParameters, 26896 /* TypeParameters */); + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1296 /* Parameters */); + emitList(parentNode, parameters, 2576 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81552,14 +84073,14 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); } else { emitParameters(parentNode, parameters); } } function emitParametersForIndexSignature(parentNode, parameters) { - emitList(parentNode, parameters, 4432 /* IndexSignatureParameters */); + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } function emitList(parentNode, children, format, start, count) { emitNodeList(emit, parentNode, children, format, start, count); @@ -81568,7 +84089,7 @@ var ts; emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 } function writeDelimiter(format) { - switch (format & 28 /* DelimitersMask */) { + switch (format & 60 /* DelimitersMask */) { case 0 /* None */: break; case 16 /* CommaDelimited */: @@ -81578,6 +84099,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8 /* AmpersandDelimited */: writeSpace(); writePunctuation("&"); @@ -81588,11 +84114,11 @@ var ts; if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; - if (isUndefined && format & 8192 /* OptionalIfUndefined */) { + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { return; } var isEmpty = children === undefined || start >= children.length || count === 0; - if (isEmpty && format & 16384 /* OptionalIfEmpty */) { + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); } @@ -81601,7 +84127,7 @@ var ts; } return; } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { // TODO: GH#18217 @@ -81616,23 +84142,23 @@ var ts; if (format & 1 /* MultiLine */) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { + else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { writeSpace(); } } else { // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; + var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 writeLine(); shouldEmitInterveningComments = false; } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 256 /* SpaceBetweenBraces */) { writeSpace(); } // Increase the indent, if requested. - if (format & 64 /* Indented */) { + if (format & 128 /* Indented */) { increaseIndent(); } // Emit each child. @@ -81641,14 +84167,19 @@ var ts; for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. - if (previousSibling) { + if (format & 32 /* AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { // i.e // function commentedParameters( // /* Parameter a */ // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -81656,14 +84187,14 @@ var ts; if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new // line, we should increase the indent. - if ((format & (3 /* LinesMask */ | 64 /* Indented */)) === 0 /* SingleLine */) { + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { increaseIndent(); shouldDecreaseIndentAfterEmit = true; } writeLine(); shouldEmitInterveningComments = false; } - else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { + else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { writeSpace(); } } @@ -81685,7 +84216,7 @@ var ts; previousSibling = child; } // Write a trailing comma, if requested. - var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; + var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { writePunctuation(","); } @@ -81695,25 +84226,25 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. - if (format & 64 /* Indented */) { + if (format & 128 /* Indented */) { decreaseIndent(); } // Write the closing line terminator or closing whitespace. if (shouldWriteClosingLineTerminator(parentNode, children, format)) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 256 /* SpaceBetweenBraces */) { writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { if (isEmpty && !isUndefined) { // TODO: GH#18217 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists @@ -81721,73 +84252,55 @@ var ts; writePunctuation(getClosingBracket(format)); } } - function commitPendingSemicolonInternal() { - if (pendingSemicolon) { - writeSemicolonInternal(); - pendingSemicolon = false; - } - } + // Writers function writeLiteral(s) { - commitPendingSemicolon(); writer.writeLiteral(s); } function writeStringLiteral(s) { - commitPendingSemicolon(); writer.writeStringLiteral(s); } function writeBase(s) { - commitPendingSemicolon(); writer.write(s); } function writeSymbol(s, sym) { - commitPendingSemicolon(); writer.writeSymbol(s, sym); } function writePunctuation(s) { - commitPendingSemicolon(); writer.writePunctuation(s); } - function deferWriteSemicolon() { - pendingSemicolon = true; - } - function writeSemicolonInternal() { - writer.writePunctuation(";"); + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); } function writeKeyword(s) { - commitPendingSemicolon(); writer.writeKeyword(s); } function writeOperator(s) { - commitPendingSemicolon(); writer.writeOperator(s); } function writeParameter(s) { - commitPendingSemicolon(); writer.writeParameter(s); } + function writeComment(s) { + writer.writeComment(s); + } function writeSpace() { - commitPendingSemicolon(); writer.writeSpace(" "); } function writeProperty(s) { - commitPendingSemicolon(); writer.writeProperty(s); } function writeLine() { - commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { - commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { - commitPendingSemicolon(); writer.decreaseIndent(); } function writeToken(token, pos, writer, contextNode) { - return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) : writeTokenText(token, writer, pos); } function writeTokenNode(node, writer) { @@ -81815,23 +84328,23 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = ts.guessIndentation(lines); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var lineText = lines_2[_a]; + for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) { + var lineText = lines_3[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); - writeLine(); + writer.rawWrite(newLine); } } } - function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + function increaseIndentIf(value, writeSpaceIfNotIndenting) { if (value) { increaseIndent(); writeLine(); } - else if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); + else if (writeSpaceIfNotIndenting) { + writeSpace(); } } // Helper function to decrease the indent if we previously indented. Allows multiple @@ -81851,7 +84364,7 @@ var ts; return true; } if (format & 2 /* PreserveLines */) { - if (format & 32768 /* PreferNewLine */) { + if (format & 65536 /* PreferNewLine */) { return true; } var firstChild = children[0]; @@ -81890,10 +84403,10 @@ var ts; } function shouldWriteClosingLineTerminator(parentNode, children, format) { if (format & 1 /* MultiLine */) { - return (format & 65536 /* NoTrailingNewLine */) === 0; + return (format & 131072 /* NoTrailingNewLine */) === 0; } else if (format & 2 /* PreserveLines */) { - if (format & 32768 /* PreferNewLine */) { + if (format & 65536 /* PreferNewLine */) { return true; } var lastChild = ts.lastOrUndefined(children); @@ -81915,11 +84428,11 @@ var ts; if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { - return (format & 32768 /* PreferNewLine */) !== 0; + return (format & 65536 /* PreferNewLine */) !== 0; } return startsOnNewLine; } - return (format & 32768 /* PreferNewLine */) !== 0; + return (format & 65536 /* PreferNewLine */) !== 0; } function needsIndentation(parent, node1, node2) { parent = skipSynthesizedParentheses(parent); @@ -81939,7 +84452,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -81951,7 +84464,7 @@ var ts; else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } - else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); } else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { @@ -81959,19 +84472,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { - if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + function getLiteralTextOfNode(node, neverAsciiEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82004,81 +84517,81 @@ var ts; if (!node) return; switch (node.kind) { - case 216 /* Block */: + case 218 /* Block */: ts.forEach(node.statements, generateNames); break; - case 231 /* LabeledStatement */: - case 229 /* WithStatement */: - case 221 /* DoStatement */: - case 222 /* WhileStatement */: + case 233 /* LabeledStatement */: + case 231 /* WithStatement */: + case 223 /* DoStatement */: + case 224 /* WhileStatement */: generateNames(node.statement); break; - case 220 /* IfStatement */: + case 222 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 223 /* ForStatement */: - case 225 /* ForOfStatement */: - case 224 /* ForInStatement */: + case 225 /* ForStatement */: + case 227 /* ForOfStatement */: + case 226 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 230 /* SwitchStatement */: + case 232 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 244 /* CaseBlock */: + case 246 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 269 /* CaseClause */: - case 270 /* DefaultClause */: + case 271 /* CaseClause */: + case 272 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 233 /* TryStatement */: + case 235 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 272 /* CatchClause */: + case 274 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: generateNames(node.declarationList); break; - case 236 /* VariableDeclarationList */: + case 238 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 235 /* VariableDeclaration */: - case 149 /* Parameter */: - case 184 /* BindingElement */: - case 238 /* ClassDeclaration */: + case 237 /* VariableDeclaration */: + case 151 /* Parameter */: + case 186 /* BindingElement */: + case 240 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 237 /* FunctionDeclaration */: + case 239 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 182 /* ObjectBindingPattern */: - case 183 /* ArrayBindingPattern */: + case 184 /* ObjectBindingPattern */: + case 185 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 247 /* ImportDeclaration */: + case 249 /* ImportDeclaration */: generateNames(node.importClause); break; - case 248 /* ImportClause */: + case 250 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 250 /* NamedImports */: + case 252 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 251 /* ImportSpecifier */: + case 253 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -82087,12 +84600,12 @@ var ts; if (!node) return; switch (node.kind) { - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 152 /* PropertyDeclaration */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 275 /* PropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: + case 154 /* PropertyDeclaration */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: generateNameIfNeeded(node.name); break; } @@ -82150,7 +84663,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82229,7 +84742,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82272,23 +84785,23 @@ var ts; */ function generateNameForNode(node, flags) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 242 /* ModuleDeclaration */: - case 241 /* EnumDeclaration */: + case 244 /* ModuleDeclaration */: + case 243 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 247 /* ImportDeclaration */: - case 253 /* ExportDeclaration */: + case 249 /* ImportDeclaration */: + case 255 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 237 /* FunctionDeclaration */: - case 238 /* ClassDeclaration */: - case 252 /* ExportAssignment */: + case 239 /* FunctionDeclaration */: + case 240 /* ClassDeclaration */: + case 254 /* ExportAssignment */: return generateNameForExportDefault(); - case 207 /* ClassExpression */: + case 209 /* ClassExpression */: return generateNameForClassExpression(); - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0 /* Auto */); @@ -82329,21 +84842,396 @@ var ts; // otherwise, return the original node for the source; return node; } + // Comments + function pipelineEmitWithComments(hint, node) { + enterComment(); + hasWrittenComment = false; + var emitFlags = ts.getEmitFlags(node); + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 238 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + enterComment(); + ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + var text = formatSynthesizedComment(comment); + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; + ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ + ? "/*" + comment.text + "*/" + : "//" + comment.text; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos, commentEnd) { + return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + // Source Maps + function pipelineEmitWithSourceMap(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var parsed = ts.tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + } + pipelinePhase(hint, node); + } + else { + var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; + var emitFlags = ts.getEmitFlags(node); + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + if (node.kind !== 307 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(sourceMapSource.text, pos); + } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos) { + if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, + /*nameIndex*/ undefined); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + var savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && ts.isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + var source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } } ts.createPrinter = createPrinter; function createBracketsMap() { var brackets = []; - brackets[512 /* Braces */] = ["{", "}"]; - brackets[1024 /* Parenthesis */] = ["(", ")"]; - brackets[2048 /* AngleBrackets */] = ["<", ">"]; - brackets[4096 /* SquareBrackets */] = ["[", "]"]; + brackets[1024 /* Braces */] = ["{", "}"]; + brackets[2048 /* Parenthesis */] = ["(", ")"]; + brackets[4096 /* AngleBrackets */] = ["<", ">"]; + brackets[8192 /* SquareBrackets */] = ["[", "]"]; return brackets; } function getOpeningBracket(format) { - return brackets[format & 7680 /* BracketsMask */][0]; + return brackets[format & 15360 /* BracketsMask */][0]; } function getClosingBracket(format) { - return brackets[format & 7680 /* BracketsMask */][1]; + return brackets[format & 15360 /* BracketsMask */][1]; } // Flags enum to track count of temp variables and a few dedicated names var TempFlags; @@ -82743,17 +85631,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82769,7 +85664,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82779,7 +85674,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82787,8 +85682,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82799,8 +85694,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82811,11 +85706,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82827,36 +85722,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(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); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82864,8 +85756,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82891,7 +85783,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82979,8 +85871,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82995,11 +85887,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83034,7 +85926,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -83047,7 +85939,7 @@ var ts; result = cache.get(name); } else { - cache.set(name, result = loader(name, containingFile)); + cache.set(name, result = loader(name, containingFile, redirectedReference)); } resolutions.push(result); } @@ -83057,7 +85949,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83066,6 +85958,11 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + var seenResolvedRefs; + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83086,9 +85983,39 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || + return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolution(sourceFile.path); } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + // If child project references are upto date, this project reference is uptodate + return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { + return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); + }); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { @@ -83097,21 +86024,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83134,7 +86057,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var modifiedFilePaths; + var ambientModuleNameToUnmodifiedFileName = ts.createMap(); var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -83162,16 +86085,15 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; - var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; @@ -83183,16 +86105,16 @@ var ts; } else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217 - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; + var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); }; } else { - var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217 - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). @@ -83208,30 +86130,34 @@ var ts; // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files - var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var resolvedProjectReferences; + var projectReferenceRedirects; + var mapFromFileToProjectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; if (projectReferences) { - for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { - var ref = projectReferences_1[_i]; - var parsedRef = parseProjectReferenceConfigFile(ref); - resolvedProjectReferences.push(parsedRef); - if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); - processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var parsedRef = resolvedProjectReferences_1[_i]; + if (parsedRef) { + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); } } } ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); @@ -83245,7 +86171,7 @@ var ts; // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. - if (!skipDefaultLib) { + if (rootNames.length && !skipDefaultLib) { // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file var defaultLibraryFileName = getDefaultLibraryFileName(); @@ -83270,10 +86196,18 @@ var ts; var oldSourceFiles = oldProgram.getSourceFiles(); for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { var oldSourceFile = oldSourceFiles_1[_a]; - if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { - host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); } // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; @@ -83312,7 +86246,12 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83346,9 +86285,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83375,13 +86314,13 @@ var ts; } return classifiableNames; } - function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) { if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, // the best we can do is fallback to the default logic. - return resolveModuleNamesWorker(moduleNames, containingFile); + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); } - var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { // `file` was created for the new program. // @@ -83391,13 +86330,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83444,7 +86383,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -83455,7 +86394,7 @@ var ts; } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) : ts.emptyArray; // Combine results of resolutions and predicted results if (!result) { @@ -83481,9 +86420,9 @@ var ts; return result; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { + var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83491,24 +86430,35 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); - if (!firstUnmodifiedFile) { + var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); + if (!unmodifiedFile) { return false; } if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); } return true; } } + function canReuseProjectReferences() { + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) { + var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, function (oldProjectReferences, parent) { + // If array of references is changed, we cant resue old program + var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo); + }); + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return 0 /* Not */; @@ -83529,36 +86479,14 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); - if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } - for (var i = 0; i < projectReferences.length; i++) { - var oldRef = oldRefs[i]; - if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); - if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { - // Resolved project reference has gone missing or changed - return oldProgram.structureIsReused = 0 /* Not */; - } - } - else { - // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { - return oldProgram.structureIsReused = 0 /* Not */; - } - } - } + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = 0 /* Not */; } - else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; - var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2 /* Completely */; // If the missing file paths are now present, it can change the progam structure, @@ -83577,7 +86505,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83604,8 +86532,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; - filePaths.push(newSourceFile.path); + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { // If there are 2 different source files for the same package name and at least one of them changes, @@ -83666,15 +86597,23 @@ var ts; if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } - modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); + for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) { + var oldFile = oldSourceFiles_3[_a]; + if (!ts.contains(modifiedFiles, oldFile)) { + for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) { + var moduleName = _c[_b]; + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } // try to verify results of module resolution - for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { - var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) { + var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { @@ -83686,8 +86625,9 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -83707,28 +86647,29 @@ var ts; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping - for (var i = 0; i < newSourceFiles.length; i++) { - filesByName.set(filePaths[i], newSourceFiles[i]); + for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) { + var newSourceFile = newSourceFiles_1[_f]; + var filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); // Set the file as found during node modules search if it was found that way in old progra, - if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { - sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { - var modifiedFile = modifiedSourceFiles_2[_c]; + for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) { + var modifiedFile = modifiedSourceFiles_2[_g]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83739,11 +86680,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83753,12 +86695,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83815,7 +86758,7 @@ var ts; // get any preEmit diagnostics, not just the ones 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) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83881,9 +86824,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83972,7 +86915,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -83982,22 +86925,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 149 /* Parameter */: - case 152 /* PropertyDeclaration */: + case 151 /* Parameter */: + case 154 /* PropertyDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } // falls through - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: - case 235 /* VariableDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 237 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -84005,41 +86948,41 @@ var ts; } } switch (node.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 252 /* ExportAssignment */: + case 254 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 271 /* HeritageClause */: + case 273 /* HeritageClause */: var heritageClause = node; - if (heritageClause.token === 108 /* ImplementsKeyword */) { + if (heritageClause.token === 109 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 239 /* InterfaceDeclaration */: + case 241 /* InterfaceDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 242 /* ModuleDeclaration */: + case 244 /* ModuleDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 240 /* TypeAliasDeclaration */: + case 242 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 241 /* EnumDeclaration */: + case 243 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 211 /* NonNullExpression */: + case 213 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 210 /* AsExpression */: + case 212 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 192 /* TypeAssertionExpression */: + case 194 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; @@ -84052,51 +86995,51 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, 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)); } switch (parent.kind) { - case 238 /* ClassDeclaration */: - case 154 /* MethodDeclaration */: - case 153 /* MethodSignature */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 194 /* FunctionExpression */: - case 237 /* FunctionDeclaration */: - case 195 /* ArrowFunction */: + case 240 /* ClassDeclaration */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } // falls through - case 217 /* VariableStatement */: + case 219 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 217 /* VariableStatement */); + return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */); } break; - case 152 /* PropertyDeclaration */: + case 154 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 115 /* StaticKeyword */) { + if (modifier.kind !== 116 /* StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } return; } break; - case 149 /* Parameter */: + case 151 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 189 /* CallExpression */: - case 190 /* NewExpression */: - case 209 /* ExpressionWithTypeArguments */: - case 259 /* JsxSelfClosingElement */: - case 260 /* JsxOpeningElement */: + case 191 /* CallExpression */: + case 192 /* NewExpression */: + case 211 /* ExpressionWithTypeArguments */: + case 261 /* JsxSelfClosingElement */: + case 262 /* JsxOpeningElement */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -84113,24 +87056,24 @@ var ts; for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { var modifier = modifiers_1[_i]; switch (modifier.kind) { - case 76 /* ConstKeyword */: + case 77 /* ConstKeyword */: if (isConstValid) { continue; } // to report error, // falls through - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 124 /* DeclareKeyword */: - case 117 /* AbstractKeyword */: + case 115 /* PublicKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 133 /* ReadonlyKeyword */: + case 125 /* DeclareKeyword */: + case 118 /* AbstractKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. - case 115 /* StaticKeyword */: - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: + case 116 /* StaticKeyword */: + case 85 /* ExportKeyword */: + case 80 /* DefaultKeyword */: } } } @@ -84178,10 +87121,22 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()))); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { + return ts.emptyArray; + } + var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(function (resolvedRef) { + if (resolvedRef) { + diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; } function getGlobalDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); + return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray; } function getConfigFileParsingDiagnostics() { return configFileParsingDiagnostics || ts.emptyArray; @@ -84193,15 +87148,15 @@ var ts; return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 71 /* Identifier */ - ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText - : b.kind === 9 /* StringLiteral */ && a.text === b.text; + return a.kind === 72 /* Identifier */ + ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 10 /* StringLiteral */ && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84223,12 +87178,9 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, /*inAmbientModule*/ false); - if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(node); - } } if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(file.endOfFileToken); + collectDynamicImportOrRequireCalls(file); } file.imports = imports || ts.emptyArray; file.moduleAugmentations = moduleAugmentations || ts.emptyArray; @@ -84276,24 +87228,37 @@ var ts; } } } - function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { - imports = ts.append(imports, node.arguments[0]); - } - // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. - else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { - imports = ts.append(imports, node.arguments[0]); - } - else if (ts.isLiteralImportTypeNode(node)) { - imports = ts.append(imports, node.argument.literal); - } - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); + function collectDynamicImportOrRequireCalls(file) { + var r = /import|require/g; + while (r.exec(file.text) !== null) { + var node = getNodeAtPosition(file, r.lastIndex); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } } } - function collectDynamicImportOrRequireCallsForEachChild(node) { - ts.forEachChild(node, collectDynamicImportOrRequireCalls); + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + var getContainingChild = function (child) { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) { + return child; + } + }; + while (true) { + var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } } } function getLibFileFromReference(ref) { @@ -84309,7 +87274,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84365,11 +87330,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84384,6 +87352,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84449,9 +87418,9 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); - filesByName.set(path, dupFile); + addFileToFilesByName(dupFile, path, redirectedPath); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); return dupFile; @@ -84462,14 +87431,12 @@ var ts; sourceFileToPackageName.set(path, packageId.name); } } - filesByName.set(path, file); - if (redirectedPath) { - filesByName.set(redirectedPath, file); - } + addFileToFilesByName(file, path, redirectedPath); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84498,25 +87465,90 @@ var ts; } return file; } + function addFileToFilesByName(file, path, redirectedPath) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { - return undefined; - } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = ts.createMap(); + forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(function (f) { + return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath); + }); + } + }); + } + var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference(cb) { + return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); }); - return result; + } + function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + var seenResolvedRefs; + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) { + // Visit project references first + if (cbRef) { + var result = cbRef(projectReferences, parent); + if (result) { + return result; + } + } + return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) { + if (ts.contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + var result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + if (!resolvedRef) + return undefined; + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return undefined; + } + return projectReferenceRedirects.get(projectReferencePath) || undefined; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84526,7 +87558,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84544,6 +87576,8 @@ var ts; } var saveResolution = true; if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth++; if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 @@ -84568,6 +87602,8 @@ var ts; processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } + if (resolvedTypeReferenceDirective.isExternalLibraryImport) + currentNodeModulesDepth--; } else { fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 @@ -84612,8 +87648,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84622,7 +87657,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84642,7 +87677,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84662,61 +87697,61 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } return allFilesBelongToPath; } function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = ts.createMap(); + } // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); + var sourceFilePath = toPath(refPath); + var fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); return undefined; } - sourceFile.path = toPath(refPath); + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); - return { commandLine: commandLine, sourceFile: sourceFile }; - } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84744,41 +87779,18 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); } } - if (projectReferences) { - for (var i = 0; i < projectReferences.length; i++) { - var ref = projectReferences[i]; - var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; - if (resolvedRefOpts === undefined) { - createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); - continue; - } - if (!resolvedRefOpts.composite) { - createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - } - if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); - } - } - else { - createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); - } - } - } - } + verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84828,15 +87840,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84846,12 +87858,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -84863,7 +87875,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84876,9 +87888,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84889,19 +87901,19 @@ var ts; // 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; })) { + if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) { createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -84959,6 +87971,35 @@ var ts; } } } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { + var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + var parentFile = parent && parent.sourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path); + return; + } + var options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + var inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + var out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { var needCompilerDiagnostic = true; var pathsSyntax = getOptionPathsSyntax(); @@ -85009,10 +88050,10 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } - function createDiagnosticForReference(index, message, arg0, arg1) { - var referencesSyntax = getProjectReferencesSyntax(); + function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { + var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); if (referencesSyntax && referencesSyntax.elements.length > index) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); } else { programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); @@ -85026,22 +88067,6 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } - function getProjectReferencesSyntax() { - if (_referencesArrayLiteralSyntax === undefined) { - _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile) { - var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217 - for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { - var prop = _a[_i]; - if (ts.isArrayLiteralExpression(prop.initializer)) { - _referencesArrayLiteralSyntax = prop.initializer; - break; - } - } - } - } - return _referencesArrayLiteralSyntax; - } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword @@ -85092,7 +88117,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85109,25 +88134,26 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85166,7 +88192,7 @@ var ts; var res = imports.map(function (i) { return i.text; }); for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9 /* StringLiteral */) { + if (aug.kind === 10 /* StringLiteral */) { res.push(aug.text); } // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. @@ -85197,7 +88223,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85207,6 +88233,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85230,7 +88262,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85241,11 +88273,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85351,6 +88417,11 @@ var ts; var latestSignature; if (sourceFile.isDeclarationFile) { latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } } else { var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); @@ -85416,7 +88487,7 @@ var ts; return getAllFileNames(state, programOfThisState); } // If this is non module emit, or its a global file, it depends on all the source files - if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { return getAllFileNames(state, programOfThisState); } // Get the references, traversing deep from the referenceMap @@ -85475,6 +88546,20 @@ var ts; } return true; } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile) { + return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); }); + } + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } /** * Gets all files of the program excluding the default library file */ @@ -85515,7 +88600,7 @@ var ts; * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { - if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } var compilerOptions = programOfThisState.getCompilerOptions(); @@ -85565,8 +88650,9 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && - !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { @@ -85581,6 +88667,8 @@ var ts; // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -85598,6 +88686,13 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { + var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { + return; + } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { + return; + } // Unchanged file copy diagnostics var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { @@ -85681,18 +88776,31 @@ var ts; // If there are no more diagnostics from old cache, done return; } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + var options_2 = state.program.getCompilerOptions(); + if (ts.forEach(state.program.getSourceFiles(), function (f) { + return state.program.isSourceFileDefaultLibrary(f) && + !ts.skipTypeChecking(f, options_2) && + removeSemanticDiagnosticsOf(state, f.path); + })) { + return; + } + } // If there was change in signature for the changed file, // then delete the semantic diagnostics for files that are affected by using exports of this module if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { return; } ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + var seenFileAndExportsOfFile = ts.createMap(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { return exportedModules && exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); })) { return; } @@ -85700,16 +88808,44 @@ var ts; ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile); }); } /** * removes the semantic diagnostics of files referencing referencedPath and * returns true if there are no more semantic diagnostics from old state */ - function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) { return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { - return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile); + }); + } + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) { + if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); }); } /** @@ -85718,7 +88854,7 @@ var ts; */ function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -85765,7 +88901,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85778,7 +88914,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85952,16 +89095,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -85984,6 +89127,10 @@ var ts; /*@internal*/ var ts; (function (ts) { + function isPathInNodeModulesStartingWithDot(path) { + return ts.stringContains(path, "/node_modules/."); + } + ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; ts.maxNumberOfFilesToIterateForInvalidation = 256; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; @@ -85997,11 +89144,11 @@ var ts; // The key in the map is source file's path. // The values are Map of resolutions with key being name lookedup. var resolvedModuleNames = ts.createMap(); - var perDirectoryResolvedModuleNames = ts.createMap(); - var nonRelaticeModuleNameCache = ts.createMap(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); + var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); var resolvedTypeReferenceDirectives = ts.createMap(); - var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -86025,6 +89172,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -86086,7 +89234,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -86102,15 +89250,15 @@ var ts; } }); } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); + function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { return primaryResult; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86121,10 +89269,11 @@ var ts; // Default return the result from the first pass return primaryResult; } - function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { var path = resolutionHost.toPath(containingFile); var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); var dirPath = ts.getDirectoryPath(path); + var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); var perDirectoryResolution = perDirectoryCache.get(dirPath); if (!perDirectoryResolution) { perDirectoryResolution = ts.createMap(); @@ -86133,22 +89282,28 @@ var ts; var resolvedModules = []; var compilerOptions = resolutionHost.getCompilationSettings(); var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + var program = resolutionHost.getCurrentProgram(); + var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + var unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; var seenNamesInFile = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { var name = names_2[_i]; var resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { var existingResolution = resolution; var resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { resolution = resolutionInDirectory; } else { - resolution = loader(name, containingFile, compilerOptions, resolutionHost); + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); @@ -86164,7 +89319,7 @@ var ts; } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217 + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); } // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { @@ -86192,12 +89347,14 @@ var ts; return oldResult.resolvedFileName === newResult.resolvedFileName; } } - function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { - return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, /*reusedNames*/ undefined, /*logChanges*/ false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); + function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { + return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); } function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); @@ -86240,15 +89397,10 @@ var ts; } return true; } - function filterFSRootDirectoriesToWatch(watchPath, dirPath) { - if (!canWatchDirectory(dirPath)) { - watchPath.ignore = true; - } - return watchPath; - } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86264,13 +89416,13 @@ var ts; } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // If directory path contains node module, get the most parent node_modules directory for watching - while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { + while (ts.pathContainsNodeModules(dirPath)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } // If the directory is node_modules use it to watch, always watch it recursively if (isNodeModulesDirectory(dirPath)) { - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -86288,7 +89440,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive }, dirPath); + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -86317,8 +89469,9 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, nonRecursive = _a.nonRecursive, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive; // If the failed lookup location path is not one of the supported extensions, // store it in the custom path if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { @@ -86371,8 +89524,9 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; - if (!ignore) { + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { if (refCount === 1) { @@ -86420,6 +89574,22 @@ var ts; cache.delete(filePath); } } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) { + return; + } + var program = resolutionHost.getCurrentProgram(); + if (!program) { + return; + } + // If this file is input file for the referenced project, get it + var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { + return; + } + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); + } function removeResolutionsOfFile(filePath) { removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); @@ -86481,6 +89651,9 @@ var ts; isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; } else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return false; // Some file or directory in the watching directory is created // Return early if it does not have any of the watching extension or not the custom failed lookup path var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); @@ -86521,8 +89694,8 @@ var ts; if (isInDirectoryPath(rootPath, typeRootPath)) { return rootPath; } - var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; + var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info @@ -86588,121 +89761,118 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; + } + return count; + } + moduleSpecifiers.countPathComponents = countPathComponents; function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86766,16 +89936,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86793,7 +89953,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86813,25 +89974,30 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86840,20 +90006,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86868,12 +90032,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86936,13 +90102,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86981,11 +90170,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86994,13 +90178,12 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } return false; } - /** @internal */ ts.screenStartingMessageCodes = [ ts.Diagnostics.Starting_compilation_in_watch_mode.code, ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, @@ -87041,10 +90224,27 @@ var ts; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getErrorCountForSummary(diagnostics) { + return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + ts.getErrorCountForSummary = getErrorCountForSummary; + function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? + ts.Diagnostics.Found_1_error_Watching_for_file_changes : + ts.Diagnostics.Found_0_errors_Watching_for_file_changes; + } + ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; + function getErrorSummaryText(errorCount, newLine) { + if (errorCount === 0) + return ""; + var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); + return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + } + ts.getErrorSummaryText = getErrorSummaryText; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87060,7 +90260,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87079,7 +90279,7 @@ var ts; } } if (reportSummary) { - reportSummary(diagnostics.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length); + reportSummary(getErrorCountForSummary(diagnostics)); } if (emitSkipped && diagnostics.length > 0) { // If the emitter didn't emit anything, then pass that value along. @@ -87094,6 +90294,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87106,7 +90325,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87120,17 +90339,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87146,15 +90358,7 @@ var ts; function emitFilesAndReportErrorUsingBuilder(builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - var reportSummary = function (errorCount) { - if (errorCount === 1) { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions); - } - else { - onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions); - } - }; - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); } } /** @@ -87179,18 +90383,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87213,9 +90418,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87228,7 +90434,8 @@ var ts; fileExists: function (path) { return host.fileExists(path); }, readFile: readFile, getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? function (s) { return host.trace(s); } : undefined }; // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); @@ -87286,7 +90493,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87295,11 +90503,11 @@ var ts; /*logChangesWhenResolvingModule*/ false); // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names compilerHost.resolveModuleNames = host.resolveModuleNames ? - (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : - (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) : + (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }); compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? - (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : - (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : + (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; synchronizeProgram(); // Update the wild card directory watch @@ -87324,9 +90532,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87351,7 +90559,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87473,8 +90681,8 @@ var ts; var hostSourceFile = sourceFilesCache.get(path); return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); } - function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { - var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); // If this is the source file thats in the cache and new program doesnt need it, // remove the cached entry. // Note we arent deleting entry if file became missing in new program or @@ -87488,8 +90696,10 @@ var ts; if (hostSourceFileInfo.fileWatcher) { hostSourceFileInfo.fileWatcher.close(); } - sourceFilesCache.delete(oldSourceFile.path); - resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } } } } @@ -87532,12 +90742,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87563,7 +90768,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87572,6 +90779,7 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { resolutionCache.invalidateResolutionOfFile(path); } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program scheduleProgramUpdate(); @@ -87612,6 +90820,8 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } nextSourceFileVersion(fileOrDirectoryPath); + if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + return; // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { @@ -87650,6 +90860,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87670,7 +90882,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87687,94 +90900,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87787,7 +90971,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87798,13 +90986,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87815,808 +91007,827 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects - }; - } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } - } - ts.performBuild = performBuild; /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary; + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch || host.reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); }); + if (options.watch) { + reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1); + } + else { + host.reportErrorSummary(totalErrors_1); + } + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; + if (host.beforeCreateProgram) { + host.beforeCreateProgram(options); + } var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88652,7 +91863,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88660,6 +91873,144 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + var members = ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.js.map "use strict"; /* @internal */ @@ -88671,6 +92022,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88699,7 +92051,6 @@ var ts; : undefined; } server.findArgument = findArgument; - /*@internal*/ function nowString() { // E.g. "12:34:56.789" var d = new Date(); @@ -88713,13 +92064,11 @@ var ts; (function (ts) { var JsTyping; (function (JsTyping) { - /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; - /* @internal */ JsTyping.nodeCoreModuleList = [ "assert", "async_hooks", @@ -88758,7 +92107,6 @@ var ts; "vm", "zlib" ]; - /* @internal */ JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); @@ -88791,7 +92139,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88876,7 +92224,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -89005,71 +92353,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); //# sourceMappingURL=jsTyping.js.map "use strict"; var ts; @@ -89277,8 +92560,10 @@ var ts; } var info = ts.getProperty(npmLock.dependencies, key); var version_1 = info && info.version; - var semver = ts.Semver.parse(version_1); // TODO: GH#18217 - var newTyping = { typingLocation: typingFile, version: semver }; + if (!version_1) { + continue; + } + var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) }; this.packageNameToTypingLocation.set(packageName, newTyping); } } @@ -89380,7 +92665,7 @@ var ts; } // packageName is guaranteed to exist in typesRegistry by filterTypings var distTags = _this.typesRegistry.get(packageName); - var newVersion = ts.Semver.parse(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]); + var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]); var newTyping = { typingLocation: typingFile, version: newVersion }; _this.packageNameToTypingLocation.set(packageName, newTyping); installedTypingFiles.push(typingFile); @@ -89559,16 +92844,17 @@ var ts; function FileLog(logFile) { var _this = this; this.logFile = logFile; - this.logEnabled = true; this.isEnabled = function () { - return _this.logEnabled && _this.logFile !== undefined; + return typeof _this.logFile === "string"; }; this.writeLine = function (text) { + if (typeof _this.logFile !== "string") + return; try { fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine); } catch (e) { - _this.logEnabled = false; + _this.logFile = undefined; } }; } @@ -89678,6 +92964,11 @@ var ts; } break; } + case "inspectValue": { + var response = { kind: server.ActionValueInspected, result: ts.inspectModule(req.options.fileNameToRequire) }; + _this.sendResponse(response); + break; + } default: ts.Debug.assertNever(req); } diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index aaf6a7101a8..23d0bae7b27 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -68,7 +68,7 @@ "A_rest_parameter_cannot_have_an_initializer_1048": "rest 参数不能具有初始化表达式。", "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 参数必须是参数列表中的最后一个参数。", "A_rest_parameter_must_be_of_an_array_type_2370": "rest 参数必须是数组类型。", - "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式可能不具有尾随逗号。", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式不可带尾随逗号。", "A_return_statement_can_only_be_used_within_a_function_body_1108": "\"return\" 语句只能在函数体中使用。", "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "一系列条目,这些条目将重新映射导入内容,以查找与 \"baseUrl\" 有关的位置。", "A_set_accessor_cannot_have_a_return_type_annotation_1095": "\"set\" 访问器不能具有返回类型批注。", @@ -161,7 +161,7 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引签名参数不能具有可访问性修饰符。", "An_index_signature_parameter_cannot_have_an_initializer_1020": "索引签名参数不能具有初始化表达式。", "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引签名参数必须具有类型批注。", - "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改而编写“[{0}: {1}]:{2}”。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改为编写“[{0}: {1}]:{2}”。", "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引签名参数类型不能为联合类型。请考虑改用映射的对象类型。", "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引签名参数类型必须为 \"string\" 或 \"number\"。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "接口只能扩展具有可选类型参数的标识符/限定名称。", @@ -628,7 +628,7 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "选项 \"isolatedModules\" 只可在提供了选项 \"--module\" 或者选项 \"target\" 是 \"ES2015\" 或更高版本时使用。", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "选项 \"project\" 在命令行上不能与源文件混合使用。", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "在没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。", "Options_0_and_1_cannot_be_combined_6370": "选项“{0}”与“{1}”不能组合在一起。", "Options_Colon_6027": "选项:", "Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。", diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json index 0ffe456d728..bc7bc2fccf4 100644 --- a/lib/zh-tw/diagnosticMessages.generated.json +++ b/lib/zh-tw/diagnosticMessages.generated.json @@ -406,11 +406,11 @@ "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "運算式會解析成變數宣告 '{0}',而編譯器會使用此宣告支援非同步函式。", "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "運算式將解析成變數宣告 '_newTarget',而供編譯器用來擷取 'new.target' 中繼屬性參考。", "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "運算式會解析成變數宣告 '_this',而編譯器會使用此宣告來擷取 'this' 參考 。", - "Extract_constant_95006": "解壓縮常數", - "Extract_function_95005": "解壓縮函式", - "Extract_to_0_in_1_95004": "解壓縮至 {1} 中的 {0}", - "Extract_to_0_in_1_scope_95008": "解壓縮至 {1} 範圍中的 {0}", - "Extract_to_0_in_enclosing_scope_95007": "解壓縮至封閉式範圍中的 {0}", + "Extract_constant_95006": "擷取常數", + "Extract_function_95005": "擷取函式", + "Extract_to_0_in_1_95004": "擷取至 {1} 中的 {0}", + "Extract_to_0_in_1_scope_95008": "擷取至 {1} 範圍中的 {0}", + "Extract_to_0_in_enclosing_scope_95007": "擷取至封閉式範圍中的 {0}", "FILE_6035": "檔案", "FILE_OR_DIRECTORY_6040": "檔案或目錄", "Failed_to_parse_file_0_Colon_1_5014": "無法剖析檔案 '{0}': {1}。", @@ -584,7 +584,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== 模組名稱 '{0}' 已成功解析為 '{1}'。========", "Module_resolution_kind_is_not_specified_using_0_6088": "未指定模組解析種類,將使用 '{0}'。", "Module_resolution_using_rootDirs_has_failed_6111": "使用 'rootDirs' 解析模組失敗。", - "Move_to_a_new_file_95049": "移至新行", + "Move_to_a_new_file_95049": "移至新檔", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允許多個連續的數字分隔符號。", "Multiple_constructor_implementations_are_not_allowed_2392": "不允許多個建構函式實作。", "NEWLINE_6061": "新行", diff --git a/package.json b/package.json index 55acc40268d..d8c514363e5 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "typescript", "author": "Microsoft Corp.", - "homepage": "http://typescriptlang.org/", - "version": "3.1.0", + "homepage": "https://www.typescriptlang.org/", + "version": "3.3.0", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ @@ -75,12 +75,14 @@ "gulp-typescript": "latest", "istanbul": "latest", "jake": "latest", + "lodash": "4.17.10", "merge2": "latest", "minimist": "latest", "mkdirp": "latest", "mocha": "latest", "mocha-fivemat-progress-reporter": "latest", "plugin-error": "latest", + "pretty-hrtime": "^1.0.3", "prex": "^0.4.3", "q": "latest", "remove-internal": "^2.9.2", diff --git a/scripts/build/baselineAccept.js b/scripts/build/baselineAccept.js index 4710161027e..df61b87cd32 100644 --- a/scripts/build/baselineAccept.js +++ b/scripts/build/baselineAccept.js @@ -12,7 +12,7 @@ function baselineAccept(subfolder = "") { } function baselineCopy(subfolder = "") { - return gulp.src([`${localBaseline}${subfolder ? `${subfolder}/` : ``}**`, `!${localBaseline}${subfolder}/**/*.delete`], { base: localBaseline, read: false }) + return gulp.src([`${localBaseline}${subfolder ? `${subfolder}/` : ``}**`, `!${localBaseline}${subfolder}/**/*.delete`], { base: localBaseline }) .pipe(gulp.dest(refBaseline)); } @@ -21,4 +21,4 @@ function baselineDelete(subfolder = "") { .pipe(rm()) .pipe(rename({ extname: "" })) .pipe(rm(refBaseline)); -} \ No newline at end of file +} diff --git a/scripts/build/gulp-typescript-oop/index.js b/scripts/build/gulp-typescript-oop/index.js index 3ef5effaf5a..ed7a7d64a03 100644 --- a/scripts/build/gulp-typescript-oop/index.js +++ b/scripts/build/gulp-typescript-oop/index.js @@ -1,6 +1,7 @@ // @ts-check const path = require("path"); const child_process = require("child_process"); +const fs = require("fs"); const tsc = require("gulp-typescript"); const Vinyl = require("vinyl"); const { Duplex, Readable } = require("stream"); @@ -42,7 +43,10 @@ function createProject(tsConfigFileName, settings, options) { getVinyl(path) { return inputs.get(path); }, getSourceFile(fileName) { return sourceFiles.get(fileName); }, createSourceFile(fileName, text, languageVersion) { - if (text === undefined) throw new Error("File not cached."); + if (text === undefined) { + text = fs.readFileSync(fileName, "utf8"); + } + /** @type {protocol.SourceFile} */ let file; if (options.parse) { diff --git a/scripts/build/options.js b/scripts/build/options.js index e9e3bfb7b1b..ba1b669188d 100644 --- a/scripts/build/options.js +++ b/scripts/build/options.js @@ -34,7 +34,7 @@ module.exports = minimist(process.argv.slice(2), { workers: process.env.workerCount || os.cpus().length, failed: false, keepFailed: false, - lkg: false, + lkg: true, dirty: false } }); diff --git a/scripts/build/project.js b/scripts/build/project.js index 0375faa2820..fb193907bbe 100644 --- a/scripts/build/project.js +++ b/scripts/build/project.js @@ -14,71 +14,14 @@ const ts = require("../../lib/typescript"); const del = require("del"); const needsUpdate = require("./needsUpdate"); const mkdirp = require("./mkdirp"); -const prettyTime = require("pretty-hrtime"); const { reportDiagnostics } = require("./diagnostics"); -const { CountdownEvent, ManualResetEvent } = require("prex"); +const { CountdownEvent, ManualResetEvent, Semaphore } = require("prex"); const workStartedEvent = new ManualResetEvent(); const countdown = new CountdownEvent(0); -class CompilationGulp extends gulp.Gulp { - /** - * @param {boolean} [verbose] - */ - fork(verbose) { - const child = new ForkedGulp(this.tasks); - child.on("task_start", e => { - if (countdown.remainingCount === 0) { - countdown.reset(1); - workStartedEvent.set(); - workStartedEvent.reset(); - } - else { - countdown.add(); - } - if (verbose) { - log('Starting', `'${chalk.cyan(e.task)}' ${chalk.gray(`(${countdown.remainingCount} remaining)`)}...`); - } - }); - child.on("task_stop", e => { - countdown.signal(); - if (verbose) { - log('Finished', `'${chalk.cyan(e.task)}' after ${chalk.magenta(prettyTime(/** @type {*}*/(e).hrDuration))} ${chalk.gray(`(${countdown.remainingCount} remaining)`)}`); - } - }); - child.on("task_err", e => { - countdown.signal(); - if (verbose) { - log(`'${chalk.cyan(e.task)}' ${chalk.red("errored after")} ${chalk.magenta(prettyTime(/** @type {*}*/(e).hrDuration))} ${chalk.gray(`(${countdown.remainingCount} remaining)`)}`); - log(e.err ? e.err.stack : e.message); - } - }); - return child; - } - - // @ts-ignore - start() { - throw new Error("Not supported, use fork."); - } -} - -class ForkedGulp extends gulp.Gulp { - /** - * @param {gulp.Gulp["tasks"]} tasks - */ - constructor(tasks) { - super(); - this.tasks = tasks; - } - - // Do not reset tasks - _resetAllTasks() {} - _resetSpecificTasks() {} - _resetTask() {} -} - // internal `Gulp` instance for compilation artifacts. -const compilationGulp = new CompilationGulp(); +const compilationGulp = new gulp.Gulp(); /** @type {Map} */ const projectGraphCache = new Map(); @@ -86,6 +29,39 @@ const projectGraphCache = new Map(); /** @type {Map} */ const typescriptAliasMap = new Map(); +// TODO: allow concurrent outer builds to be run in parallel +const sem = new Semaphore(1); + +/** + * @param {string|string[]} taskName + * @param {() => any} [cb] + */ +function start(taskName, cb) { + return sem.wait().then(() => new Promise((resolve, reject) => { + compilationGulp.start(taskName, err => { + if (err) { + reject(err); + } + else if (cb) { + try { + resolve(cb()); + } + catch (e) { + reject(err); + } + } + else { + resolve(); + } + }); + })).then(() => { + sem.release() + }, e => { + sem.release(); + throw e; + }); +} + /** * Defines a gulp orchestration for a TypeScript project, returning a callback that can be used to trigger compilation. * @param {string} projectSpec The path to a tsconfig.json file or its containing directory. @@ -98,9 +74,7 @@ function createCompiler(projectSpec, options) { const projectGraph = getOrCreateProjectGraph(resolvedProjectSpec, resolvedOptions.paths); projectGraph.isRoot = true; const taskName = compileTaskName(ensureCompileTask(projectGraph, resolvedOptions), resolvedOptions.typescript); - return () => new Promise((resolve, reject) => compilationGulp - .fork(resolvedOptions.verbose) - .start(taskName, err => err ? reject(err) : resolve())); + return () => start(taskName); } exports.createCompiler = createCompiler; @@ -139,9 +113,7 @@ function createCleaner(projectSpec, options) { const projectGraph = getOrCreateProjectGraph(resolvedProjectSpec, paths); projectGraph.isRoot = true; const taskName = cleanTaskName(ensureCleanTask(projectGraph)); - return () => new Promise((resolve, reject) => compilationGulp - .fork() - .start(taskName, err => err ? reject(err) : resolve())); + return () => start(taskName); } exports.createCleaner = createCleaner; @@ -683,11 +655,17 @@ function ensureCompileTask(projectGraph, options) { } }); } - const js = (projectGraphConfig.resolvedOptions.js ? projectGraphConfig.resolvedOptions.js(stream.js) : stream.js) + + const additionalJsOutputs = projectGraphConfig.resolvedOptions.js ? projectGraphConfig.resolvedOptions.js(stream.js) + .pipe(gulpif(sourceMap || inlineSourceMap, sourcemaps.write(sourceMapPath, sourceMapOptions))) : undefined; + const additionalDtsOutputs = projectGraphConfig.resolvedOptions.dts ? projectGraphConfig.resolvedOptions.dts(stream.dts) + .pipe(gulpif(declarationMap, sourcemaps.write(sourceMapPath, sourceMapOptions))) : undefined; + + const js = stream.js .pipe(gulpif(sourceMap || inlineSourceMap, sourcemaps.write(sourceMapPath, sourceMapOptions))); - const dts = (projectGraphConfig.resolvedOptions.dts ? projectGraphConfig.resolvedOptions.dts(stream.dts) : stream.dts) + const dts = stream.dts .pipe(gulpif(declarationMap, sourcemaps.write(sourceMapPath, sourceMapOptions))); - return merge2([js, dts]) + return merge2([js, dts, additionalJsOutputs, additionalDtsOutputs].filter(x => !!x)) .pipe(gulp.dest(destPath)); }); } @@ -805,7 +783,7 @@ function possiblyTriggerRecompilation(config, task) { function triggerRecompilation(task, config) { compilationGulp._resetTask(task); if (config.watchers && config.watchers.size) { - compilationGulp.fork().start(task.name, () => { + start(task.name, () => { /** @type {Set} */ const taskNames = new Set(); /** @type {((err?: any) => void)[]} */ @@ -825,7 +803,7 @@ function triggerRecompilation(task, config) { }); } else { - compilationGulp.fork(/*verbose*/ true).start(task.name); + start(task.name); } } diff --git a/scripts/build/upToDate.js b/scripts/build/upToDate.js index f92fd6b503a..c3abb5d1013 100644 --- a/scripts/build/upToDate.js +++ b/scripts/build/upToDate.js @@ -4,7 +4,7 @@ const fs = require("fs"); const log = require("fancy-log"); // was `require("gulp-util").log (see https://github.com/gulpjs/gulp-util) const ts = require("../../lib/typescript"); const { Duplex } = require("stream"); -const chalk = require("./chalk"); +const chalk = /**@type {*} */(require("chalk")); const Vinyl = require("vinyl"); /** @@ -14,7 +14,7 @@ const Vinyl = require("vinyl"); * @param {UpToDateOptions} [options] * * @typedef UpToDateOptions - * @property {boolean} [verbose] + * @property {boolean | "minimal"} [verbose] * @property {(configFilePath: string) => ParsedCommandLine | undefined} [parseProject] */ function upToDate(parsedProject, options) { @@ -47,9 +47,9 @@ function upToDate(parsedProject, options) { cb(); }, final(cb) { - const status = ts.getUpToDateStatus(upToDateHost, parsedProject); + const status = getUpToDateStatus(upToDateHost, parsedProject); reportStatus(parsedProject, status, options); - if (status.type !== ts.UpToDateStatusType.UpToDate) { + if (status.type !== UpToDateStatusType.UpToDate) { for (const input of inputs) duplex.push(input); } duplex.push(null); @@ -88,11 +88,25 @@ function formatMessage(message, ...args) { /** * @param {ParsedCommandLine} project * @param {UpToDateStatus} status - * @param {{verbose?: boolean}} options + * @param {{verbose?: boolean | "minimal"}} options */ function reportStatus(project, status, options) { + switch (options.verbose) { + case "minimal": + switch (status.type) { + case UpToDateStatusType.UpToDate: + log.info(`Project '${fileName(project.options.configFilePath)}' is up to date.`); + break; + default: + log.info(`Project '${fileName(project.options.configFilePath)}' is out of date, rebuilding...`); + break; + } + break; + case true: + /**@type {*}*/(ts).formatUpToDateStatus(project.options.configFilePath, status, fileName, formatMessage); + break; + } if (!options.verbose) return; - ts.formatUpToDateStatus(project.options.configFilePath, status, fileName, formatMessage); } /** @@ -120,12 +134,302 @@ function formatStringFromArgs(text, args, baseIndex = 0) { return text.replace(/{(\d+)}/g, (_match, index) => args[+index + baseIndex]); } +const minimumDate = new Date(-8640000000000000); +const maximumDate = new Date(8640000000000000); +const missingFileModifiedTime = new Date(0); + +/** + * @typedef {0} UpToDateStatusType.Unbuildable + * @typedef {1} UpToDateStatusType.UpToDate + * @typedef {2} UpToDateStatusType.UpToDateWithUpstreamTypes + * @typedef {3} UpToDateStatusType.OutputMissing + * @typedef {4} UpToDateStatusType.OutOfDateWithSelf + * @typedef {5} UpToDateStatusType.OutOfDateWithUpstream + * @typedef {6} UpToDateStatusType.UpstreamOutOfDate + * @typedef {7} UpToDateStatusType.UpstreamBlocked + * @typedef {8} UpToDateStatusType.ComputingUpstream + * @typedef {9} UpToDateStatusType.ContainerOnly + * @enum {UpToDateStatusType.Unbuildable | UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes | UpToDateStatusType.OutputMissing | UpToDateStatusType.OutOfDateWithSelf | UpToDateStatusType.OutOfDateWithUpstream | UpToDateStatusType.UpstreamOutOfDate | UpToDateStatusType.UpstreamBlocked | UpToDateStatusType.ComputingUpstream | UpToDateStatusType.ContainerOnly} + */ +const UpToDateStatusType = { + Unbuildable: /** @type {0} */(0), + UpToDate: /** @type {1} */(1), + UpToDateWithUpstreamTypes: /** @type {2} */(2), + OutputMissing: /** @type {3} */(3), + OutOfDateWithSelf: /** @type {4} */(4), + OutOfDateWithUpstream: /** @type {5} */(5), + UpstreamOutOfDate: /** @type {6} */(6), + UpstreamBlocked: /** @type {7} */(7), + ComputingUpstream: /** @type {8} */(8), + ContainerOnly: /** @type {9} */(9), +}; + +/** + * @param {Date} date1 + * @param {Date} date2 + * @returns {Date} + */ +function newer(date1, date2) { + return date2 > date1 ? date2 : date1; +} + +/** + * @param {UpToDateHost} host + * @param {ParsedCommandLine | undefined} project + * @returns {UpToDateStatus} + */ +function getUpToDateStatus(host, project) { + if (project === undefined) return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + const prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; + if (prior !== undefined) { + return prior; + } + const actual = getUpToDateStatusWorker(host, project); + if (host.setLastStatus) { + host.setLastStatus(project.options.configFilePath, actual); + } + return actual; +} + +/** + * @param {UpToDateHost} host + * @param {ParsedCommandLine | undefined} project + * @returns {UpToDateStatus} + */ +function getUpToDateStatusWorker(host, project) { + /** @type {string} */ + let newestInputFileName = undefined; + let newestInputFileTime = minimumDate; + // Get timestamps of input files + for (const inputFile of project.fileNames) { + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: `${inputFile} does not exist` + }; + } + + const inputTime = host.getModifiedTime(inputFile) || missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + + // Collect the expected outputs of this project + const outputs = /**@type {string[]}*/(/**@type {*}*/(ts).getAllProjectOutputs(project)); + + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + + // Now see if all outputs are newer than the newest input + let oldestOutputFileName = "(none)"; + let oldestOutputFileTime = maximumDate; + let newestOutputFileName = "(none)"; + let newestOutputFileTime = minimumDate; + /** @type {string | undefined} */ + let missingOutputFileName; + let newestDeclarationFileContentChangedTime = minimumDate; + let isOutOfDateWithInputs = false; + for (const output of outputs) { + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + + const outputTime = host.getModifiedTime(output) || missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (path.extname(output) === ".d.ts") { + const unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + const outputModifiedTime = host.getModifiedTime(output) || missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + + let pseudoUpToDate = false; + let usesPrepend = false; + /** @type {string | undefined} */ + let upstreamChangedProject; + if (project.projectReferences) { + if (host.setLastStatus) host.setLastStatus(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (const ref of project.projectReferences) { + usesPrepend = usesPrepend || !!(ref.prepend); + const resolvedRef = ts.resolveProjectReferencePath(host, ref); + const parsedRef = host.parseConfigFile ? host.parseConfigFile(resolvedRef) : ts.getParsedCommandLineOfConfigFile(resolvedRef, {}, parseConfigHost); + const refStatus = getUpToDateStatus(host, parsedRef); + + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + + // We have an output older than an upstream output - we are out of date + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName + }; + } + + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime, + newestInputFileTime, + newestOutputFileTime, + newestInputFileName, + newestOutputFileName, + oldestOutputFileName + }; +} + +const parseConfigHost = { + useCaseSensitiveFileNames: true, + getCurrentDirectory: () => process.cwd(), + readDirectory: (file) => fs.readdirSync(file), + fileExists: file => fs.existsSync(file) && fs.statSync(file).isFile(), + readFile: file => fs.readFileSync(file, "utf8"), + onUnRecoverableConfigFileDiagnostic: () => undefined +}; + /** * @typedef {import("vinyl")} File * @typedef {import("../../lib/typescript").ParsedCommandLine & { options: CompilerOptions }} ParsedCommandLine * @typedef {import("../../lib/typescript").CompilerOptions & { configFilePath?: string }} CompilerOptions - * @typedef {import("../../lib/typescript").UpToDateHost} UpToDateHost - * @typedef {import("../../lib/typescript").UpToDateStatus} UpToDateStatus * @typedef {import("../../lib/typescript").DiagnosticMessage} DiagnosticMessage + * @typedef UpToDateHost + * @property {(fileName: string) => boolean} fileExists + * @property {(fileName: string) => Date} getModifiedTime + * @property {(fileName: string) => Date} [getUnchangedTime] + * @property {(configFilePath: string) => ParsedCommandLine | undefined} parseConfigFile + * @property {(configFilePath: string) => UpToDateStatus} [getLastStatus] + * @property {(configFilePath: string, status: UpToDateStatus) => void} [setLastStatus] + * + * @typedef Status.Unbuildable + * @property {UpToDateStatusType.Unbuildable} type + * @property {string} reason + * + * @typedef Status.ContainerOnly + * @property {UpToDateStatusType.ContainerOnly} type + * + * @typedef Status.UpToDate + * @property {UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes} type + * @property {Date} [newestInputFileTime] + * @property {string} [newestInputFileName] + * @property {Date} [newestDeclarationFileContentChangedTime] + * @property {Date} [newestOutputFileTime] + * @property {string} [newestOutputFileName] + * @property {string} [oldestOutputFileName] + * + * @typedef Status.OutputMissing + * @property {UpToDateStatusType.OutputMissing} type + * @property {string} missingOutputFileName + * + * @typedef Status.OutOfDateWithSelf + * @property {UpToDateStatusType.OutOfDateWithSelf} type + * @property {string} outOfDateOutputFileName + * @property {string} newerInputFileName + * + * @typedef Status.UpstreamOutOfDate + * @property {UpToDateStatusType.UpstreamOutOfDate} type + * @property {string} upstreamProjectName + * + * @typedef Status.UpstreamBlocked + * @property {UpToDateStatusType.UpstreamBlocked} type + * @property {string} upstreamProjectName + * + * @typedef Status.ComputingUpstream + * @property {UpToDateStatusType.ComputingUpstream} type + * + * @typedef Status.OutOfDateWithUpstream + * @property {UpToDateStatusType.OutOfDateWithUpstream} type + * @property {string} outOfDateOutputFileName + * @property {string} newerProjectName + + * @typedef {Status.Unbuildable | Status.ContainerOnly | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ComputingUpstream | Status.OutOfDateWithUpstream} UpToDateStatus */ void 0; \ No newline at end of file diff --git a/scripts/generateLocalizedDiagnosticMessages.ts b/scripts/generateLocalizedDiagnosticMessages.ts index 09d117d533b..a9183c8ddbe 100644 --- a/scripts/generateLocalizedDiagnosticMessages.ts +++ b/scripts/generateLocalizedDiagnosticMessages.ts @@ -36,7 +36,7 @@ function main(): void { console.error("Unexpected XML file structure. Expected to find result.LCX.$.TgtCul."); process.exit(1); } - const outputDirectoryName = getPreferedLocaleName(result.LCX.$.TgtCul); + const outputDirectoryName = getPreferedLocaleName(result.LCX.$.TgtCul).toLowerCase(); if (!outputDirectoryName) { console.error(`Invalid output locale name for '${result.LCX.$.TgtCul}'.`); process.exit(1); diff --git a/scripts/tslint/tsconfig.json b/scripts/tslint/tsconfig.json index 045abc24f6b..e9f90ad4266 100644 --- a/scripts/tslint/tsconfig.json +++ b/scripts/tslint/tsconfig.json @@ -12,6 +12,7 @@ "module": "commonjs", "outDir": "../../built/local/tslint", "baseUrl": "../..", + "types": ["node"], "paths": { "typescript": ["lib/typescript.d.ts"] } diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index ea8fb3eea8d..27f85896a3b 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -100,6 +100,8 @@ namespace ts { IsObjectLiteralOrClassExpressionMethod = 1 << 7, } + let flowNodeCreated: (node: T) => T = identity; + const binder = createBinder(); export function bindSourceFile(file: SourceFile, options: CompilerOptions) { @@ -143,7 +145,7 @@ namespace ts { let symbolCount = 0; - let Symbol: { new (flags: SymbolFlags, name: __String): Symbol }; // tslint:disable-line variable-name + let Symbol: new (flags: SymbolFlags, name: __String) => Symbol; // tslint:disable-line variable-name let classifiableNames: UnderscoreEscapedMap; const unreachableFlow: FlowNode = { flags: FlowFlags.Unreachable }; @@ -233,14 +235,23 @@ namespace ts { symbol.members = createSymbolTable(); } + // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate) + if (symbol.constEnumOnlyModule && (symbol.flags & (SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.RegularEnum))) { + symbol.constEnumOnlyModule = false; + } + if (symbolFlags & SymbolFlags.Value) { - const { valueDeclaration } = symbol; - if (!valueDeclaration || - (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - symbol.valueDeclaration = node; - } + setValueDeclaration(symbol, node); + } + } + + function setValueDeclaration(symbol: Symbol, node: Declaration): void { + const { valueDeclaration } = symbol; + if (!valueDeclaration || + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } @@ -288,7 +299,7 @@ namespace ts { // module.exports = ... return InternalSymbolName.ExportEquals; case SyntaxKind.BinaryExpression: - if (getSpecialPropertyAssignmentKind(node as BinaryExpression) === SpecialPropertyAssignmentKind.ModuleExports) { + if (getAssignmentDeclarationKind(node as BinaryExpression) === AssignmentDeclarationKind.ModuleExports) { // module.exports = ... return InternalSymbolName.ExportEquals; } @@ -374,8 +385,8 @@ namespace ts { // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name)); } - else if (!(includes & SymbolFlags.Variable && symbol.flags & SymbolFlags.JSContainer)) { - // JSContainers are allowed to merge with variables, no matter what other flags they have. + else if (!(includes & SymbolFlags.Variable && symbol.flags & SymbolFlags.Assignment)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (isNamedDeclaration(node)) { node.name.parent = node; } @@ -461,7 +472,7 @@ namespace ts { // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (isJSDocTypeAlias(node)) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypeAlias(node)) { if (hasModifier(node, ModifierFlags.Default) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! @@ -521,6 +532,7 @@ namespace ts { blockScopeContainer.locals = undefined; } if (containerFlags & ContainerFlags.IsControlFlowContainer) { + const saveFlowNodeCreated = flowNodeCreated; const saveCurrentFlow = currentFlow; const saveBreakTarget = currentBreakTarget; const saveContinueTarget = currentContinueTarget; @@ -544,6 +556,7 @@ namespace ts { currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; + flowNodeCreated = identity; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~NodeFlags.ReachabilityAndEmitFlags; @@ -570,6 +583,7 @@ namespace ts { currentReturnTarget = saveReturnTarget; activeLabels = saveActiveLabels; hasExplicitReturn = saveHasExplicitReturn; + flowNodeCreated = saveFlowNodeCreated; } else if (containerFlags & ContainerFlags.IsInterface) { seenThisKeyword = false; @@ -636,6 +650,7 @@ namespace ts { function bindChildrenWorker(node: Node): void { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -743,7 +758,7 @@ namespace ts { function isNarrowableReference(expr: Expression): boolean { return expr.kind === SyntaxKind.Identifier || expr.kind === SyntaxKind.ThisKeyword || expr.kind === SyntaxKind.SuperKeyword || - isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + (isPropertyAccessExpression(expr) || isNonNullExpression(expr) || isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || isElementAccessExpression(expr) && expr.argumentExpression && (isStringLiteral(expr.argumentExpression) || isNumericLiteral(expr.argumentExpression)) && isNarrowableReference(expr.expression); @@ -848,7 +863,7 @@ namespace ts { return antecedent; } setFlowNodeReferenced(antecedent); - return { flags, expression, antecedent }; + return flowNodeCreated({ flags, expression, antecedent }); } function createFlowSwitchClause(antecedent: FlowNode, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): FlowNode { @@ -856,17 +871,17 @@ namespace ts { return antecedent; } setFlowNodeReferenced(antecedent); - return { flags: FlowFlags.SwitchClause, switchStatement, clauseStart, clauseEnd, antecedent }; + return flowNodeCreated({ flags: FlowFlags.SwitchClause, switchStatement, clauseStart, clauseEnd, antecedent }); } function createFlowAssignment(antecedent: FlowNode, node: Expression | VariableDeclaration | BindingElement): FlowNode { setFlowNodeReferenced(antecedent); - return { flags: FlowFlags.Assignment, antecedent, node }; + return flowNodeCreated({ flags: FlowFlags.Assignment, antecedent, node }); } function createFlowArrayMutation(antecedent: FlowNode, node: CallExpression | BinaryExpression): FlowNode { setFlowNodeReferenced(antecedent); - const res: FlowArrayMutation = { flags: FlowFlags.ArrayMutation, antecedent, node }; + const res: FlowArrayMutation = flowNodeCreated({ flags: FlowFlags.ArrayMutation, antecedent, node }); return res; } @@ -1070,8 +1085,16 @@ namespace ts { function bindTryStatement(node: TryStatement): void { const preFinallyLabel = createBranchLabel(); const preTryFlow = currentFlow; - // TODO: Every statement in try block is potentially an exit point! + const tryPriors: FlowNode[] = []; + const oldFlowNodeCreated = flowNodeCreated; + // We hook the creation of all flow nodes within the `try` scope and store them so we can add _all_ of them + // as possible antecedents of the start of the `catch` or `finally` blocks. + // Don't bother intercepting the call if there's no finally or catch block that needs the information + if (node.catchClause || node.finallyBlock) { + flowNodeCreated = node => (tryPriors.push(node), node); + } bind(node.tryBlock); + flowNodeCreated = oldFlowNodeCreated; addAntecedent(preFinallyLabel, currentFlow); const flowAfterTry = currentFlow; @@ -1079,12 +1102,32 @@ namespace ts { if (node.catchClause) { currentFlow = preTryFlow; + if (tryPriors.length) { + const preCatchFlow = createBranchLabel(); + addAntecedent(preCatchFlow, currentFlow); + for (const p of tryPriors) { + addAntecedent(preCatchFlow, p); + } + currentFlow = finishFlowLabel(preCatchFlow); + } + bind(node.catchClause); addAntecedent(preFinallyLabel, currentFlow); flowAfterCatch = currentFlow; } if (node.finallyBlock) { + // We add the nodes within the `try` block to the `finally`'s antecedents if there's no catch block + // (If there is a `catch` block, it will have all these antecedents instead, and the `finally` will + // have the end of the `try` block and the end of the `catch` block) + if (!node.catchClause) { + if (tryPriors.length) { + for (const p of tryPriors) { + addAntecedent(preFinallyLabel, p); + } + } + } + // in finally flow is combined from pre-try/flow from try/flow from catch // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable @@ -1132,7 +1175,7 @@ namespace ts { } } if (!(currentFlow.flags & FlowFlags.Unreachable)) { - const afterFinallyFlow: AfterFinallyFlow = { flags: FlowFlags.AfterFinally, antecedent: currentFlow }; + const afterFinallyFlow: AfterFinallyFlow = flowNodeCreated({ flags: FlowFlags.AfterFinally, antecedent: currentFlow }); preFinallyFlow.lock = afterFinallyFlow; currentFlow = afterFinallyFlow; } @@ -1176,7 +1219,6 @@ namespace ts { } const preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow!, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow!, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); const clause = clauses[i]; @@ -1375,6 +1417,7 @@ namespace ts { } function bindJSDocTypeAlias(node: JSDocTypedefTag | JSDocCallbackTag) { + node.tagName.parent = node; if (node.fullName) { setParentPointers(node, node.fullName); } @@ -2009,7 +2052,7 @@ namespace ts { function bindJSDoc(node: Node) { if (hasJSDocNodes(node)) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { for (const j of node.jsDoc!) { bind(j); } @@ -2075,7 +2118,7 @@ namespace ts { if (isSpecialPropertyDeclaration(node as PropertyAccessExpression)) { bindSpecialPropertyDeclaration(node as PropertyAccessExpression); } - if (isInJavaScriptFile(node) && + if (isInJSFile(node) && file.commonJsModuleIndicator && isModuleExportsPropertyAccessExpression(node as PropertyAccessExpression) && !lookupSymbolForNameWorker(blockScopeContainer, "module" as __String)) { @@ -2084,31 +2127,31 @@ namespace ts { } break; case SyntaxKind.BinaryExpression: - const specialKind = getSpecialPropertyAssignmentKind(node as BinaryExpression); + const specialKind = getAssignmentDeclarationKind(node as BinaryExpression); switch (specialKind) { - case SpecialPropertyAssignmentKind.ExportsProperty: + case AssignmentDeclarationKind.ExportsProperty: bindExportsPropertyAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.ModuleExports: + case AssignmentDeclarationKind.ModuleExports: bindModuleExportsAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.PrototypeProperty: bindPrototypePropertyAssignment((node as BinaryExpression).left as PropertyAccessEntityNameExpression, node); break; - case SpecialPropertyAssignmentKind.Prototype: + case AssignmentDeclarationKind.Prototype: bindPrototypeAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ThisProperty: bindThisPropertyAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.Property: + case AssignmentDeclarationKind.Property: bindSpecialPropertyAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.None: // Nothing to do break; default: - Debug.fail("Unknown special property assignment kind"); + Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); case SyntaxKind.CatchClause: @@ -2184,7 +2227,20 @@ namespace ts { return bindFunctionExpression(node); case SyntaxKind.CallExpression: - if (isInJavaScriptFile(node)) { + const assignmentKind = getAssignmentDeclarationKind(node as CallExpression); + switch (assignmentKind) { + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + return bindObjectDefinePropertyAssignment(node as BindableObjectDefinePropertyCall); + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + return bindObjectDefinePropertyExport(node as BindableObjectDefinePropertyCall); + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: + return bindObjectDefinePrototypeProperty(node as BindableObjectDefinePropertyCall); + case AssignmentDeclarationKind.None: + break; // Nothing to do + default: + return Debug.fail("Unknown call expression assignment declaration kind"); + } + if (isInJSFile(node)) { bindCallExpression(node); } break; @@ -2286,14 +2342,19 @@ namespace ts { bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node)!); } else { - const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) + const flags = exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? SymbolFlags.Alias // An export default clause with any other expression exports a value : SymbolFlags.Property; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.All); + const symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.All); + + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } @@ -2301,27 +2362,17 @@ namespace ts { 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; + const diag = !isSourceFile(node.parent) ? Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !isExternalModule(node.parent) ? Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } 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 || createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); } - - file.symbol.globalExports = file.symbol.globalExports || createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); } function bindExportDeclaration(node: ExportDeclaration) { @@ -2352,6 +2403,22 @@ namespace ts { return true; } + function bindObjectDefinePropertyExport(node: BindableObjectDefinePropertyCall) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + const symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, (id, symbol) => { + if (symbol) { + addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.Assignment); + } + return symbol; + }); + if (symbol) { + const flags = SymbolFlags.Property | SymbolFlags.ExportValue; + declareSymbol(symbol.exports!, symbol, node, flags, SymbolFlags.None); + } + } + function bindExportsPropertyAssignment(node: BinaryExpression) { // When we create a property via 'exports.foo = bar', the 'exports.foo' property access // expression is the declaration @@ -2361,7 +2428,7 @@ namespace ts { const lhs = node.left as PropertyAccessEntityNameExpression; const symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, (id, symbol) => { if (symbol) { - addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.JSContainer); + addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.Assignment); } return symbol; }); @@ -2390,11 +2457,11 @@ namespace ts { const flags = exportAssignmentIsAlias(node) ? SymbolFlags.Alias // An export= with an EntityNameExpression or a ClassExpression exports all meanings of that identifier or class : SymbolFlags.Property | SymbolFlags.ExportValue | SymbolFlags.ValueModule; - declareSymbol(file.symbol.exports!, file.symbol, node, flags, SymbolFlags.None); + declareSymbol(file.symbol.exports!, file.symbol, node, flags | SymbolFlags.Assignment, SymbolFlags.None); } function bindThisPropertyAssignment(node: BinaryExpression | PropertyAccessExpression) { - Debug.assert(isInJavaScriptFile(node)); + Debug.assert(isInJSFile(node)); const thisContainer = getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case SyntaxKind.FunctionDeclaration: @@ -2456,7 +2523,12 @@ namespace ts { node.left.parent = node; node.right.parent = node; const lhs = node.left as PropertyAccessEntityNameExpression; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); + } + + function bindObjectDefinePrototypeProperty(node: BindableObjectDefinePropertyCall) { + const namespaceSymbol = lookupSymbolForPropertyAccess((node.arguments[0] as PropertyAccessExpression).expression as EntityNameExpression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -2477,12 +2549,18 @@ namespace ts { bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); } + function bindObjectDefinePropertyAssignment(node: BindableObjectDefinePropertyCall) { + let namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + const isToplevel = node.parent.parent.kind === SyntaxKind.SourceFile; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } function bindSpecialPropertyAssignment(node: BinaryExpression) { const lhs = node.left as PropertyAccessEntityNameExpression; // Class declarations in Typescript do not allow property declarations const parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!isInJavaScriptFile(node) && !isFunctionSymbol(parentSymbol)) { + if (!isInJSFile(node) && !isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -2508,26 +2586,28 @@ namespace ts { bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); } - function bindPropertyAssignment(name: EntityNameExpression, propertyAccess: PropertyAccessEntityNameExpression, isPrototypeProperty: boolean) { - let namespaceSymbol = lookupSymbolForPropertyAccess(name); - const isToplevel = isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === SyntaxKind.SourceFile - : propertyAccess.parent.parent.kind === SyntaxKind.SourceFile; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & SymbolFlags.Namespace)) && isToplevel) { + function bindPotentiallyMissingNamespaces(namespaceSymbol: Symbol | undefined, entityName: EntityNameExpression, isToplevel: boolean, isPrototypeProperty: boolean) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & SymbolFlags.Namespace))) { // make symbols or add declarations for intermediate containers - const flags = SymbolFlags.Module | SymbolFlags.JSContainer; - const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.JSContainer; - namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, (id, symbol, parent) => { + const flags = SymbolFlags.Module | SymbolFlags.Assignment; + const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.Assignment; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, (id, symbol, parent) => { if (symbol) { addDeclarationToSymbol(symbol, id, flags); return symbol; } else { - return declareSymbol(parent ? parent.exports! : container.locals!, parent, id, flags, excludeFlags); + const table = parent ? parent.exports! : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = createSymbolTable()); + return declareSymbol(table, parent, id, flags, excludeFlags); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + return namespaceSymbol; + } + + function bindPotentiallyNewExpandoMemberToNamespace(declaration: PropertyAccessEntityNameExpression | CallExpression, namespaceSymbol: Symbol | undefined, isPrototypeProperty: boolean) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } @@ -2536,14 +2616,23 @@ namespace ts { (namespaceSymbol.members || (namespaceSymbol.members = createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = createSymbolTable())); - const isMethod = isFunctionLikeDeclaration(getAssignedJavascriptInitializer(propertyAccess)!); + const isMethod = isFunctionLikeDeclaration(getAssignedExpandoInitializer(declaration)!); const includes = isMethod ? SymbolFlags.Method : SymbolFlags.Property; const excludes = isMethod ? SymbolFlags.MethodExcludes : SymbolFlags.PropertyExcludes; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | SymbolFlags.JSContainer, excludes & ~SymbolFlags.JSContainer); + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | SymbolFlags.Assignment, excludes & ~SymbolFlags.Assignment); + } + + function bindPropertyAssignment(name: EntityNameExpression, propertyAccess: PropertyAccessEntityNameExpression, isPrototypeProperty: boolean) { + let namespaceSymbol = lookupSymbolForPropertyAccess(name); + const isToplevel = isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === SyntaxKind.SourceFile + : propertyAccess.parent.parent.kind === SyntaxKind.SourceFile; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -2552,11 +2641,14 @@ namespace ts { * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol: Symbol): boolean { + function isExpandoSymbol(symbol: Symbol): boolean { if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.NamespaceModule)) { return true; } const node = symbol.valueDeclaration; + if (node && isCallExpression(node)) { + return !!getAssignedExpandoInitializer(node); + } let init = !node ? undefined : isVariableDeclaration(node) ? node.initializer : isBinaryExpression(node) ? node.right : @@ -2565,7 +2657,7 @@ namespace ts { init = init && getRightMostAssignedExpression(init); if (init) { const isPrototypeAssignment = isPrototypeAccess(isVariableDeclaration(node) ? node.name : isBinaryExpression(node) ? node.left : node); - return !!getJavascriptInitializer(isBinaryExpression(init) && init.operatorToken.kind === SyntaxKind.BarBarToken ? init.right : init, isPrototypeAssignment); + return !!getExpandoInitializer(isBinaryExpression(init) && init.operatorToken.kind === SyntaxKind.BarBarToken ? init.right : init, isPrototypeAssignment); } return false; } @@ -2657,7 +2749,7 @@ namespace ts { } if (!isBindingPattern(node.name)) { - const isEnum = !!getJSDocEnumTag(node); + const isEnum = isInJSFile(node) && !!getJSDocEnumTag(node); const enumFlags = (isEnum ? SymbolFlags.RegularEnum : SymbolFlags.None); const enumExcludes = (isEnum ? SymbolFlags.RegularEnumExcludes : SymbolFlags.None); if (isBlockOrCatchScoped(node)) { @@ -2868,7 +2960,6 @@ namespace ts { } } - /* @internal */ export function isExportsOrModuleExportsOrAlias(sourceFile: SourceFile, node: Expression): boolean { return isExportsIdentifier(node) || isModuleExportsPropertyAccessExpression(node) || @@ -2892,6 +2983,9 @@ namespace ts { if (local) { return local.exportSymbol || local; } + if (isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } @@ -2996,7 +3090,7 @@ namespace ts { transformFlags |= TransformFlags.AssertTypeScript; } - if (subtreeFlags & TransformFlags.ContainsSpread + if (subtreeFlags & TransformFlags.ContainsRestOrSpread || (expression.transformFlags & (TransformFlags.Super | TransformFlags.ContainsSuper))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. @@ -3027,7 +3121,7 @@ namespace ts { if (node.typeArguments) { transformFlags |= TransformFlags.AssertTypeScript; } - if (subtreeFlags & TransformFlags.ContainsSpread) { + if (subtreeFlags & TransformFlags.ContainsRestOrSpread) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= TransformFlags.AssertES2015; @@ -3070,18 +3164,18 @@ namespace ts { // syntax. if (node.questionToken || node.type - || subtreeFlags & TransformFlags.ContainsDecorators + || (subtreeFlags & TransformFlags.ContainsTypeScriptClassSyntax && some(node.decorators)) || isThisIdentifier(name)) { transformFlags |= TransformFlags.AssertTypeScript; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (hasModifier(node, ModifierFlags.ParameterPropertyModifier)) { - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsParameterPropertyAssignments; + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsTypeScriptClassSyntax; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3134,7 +3228,7 @@ namespace ts { // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) + if ((subtreeFlags & TransformFlags.ContainsTypeScriptClassSyntax) || node.typeParameters) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -3156,7 +3250,7 @@ namespace ts { // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask + if (subtreeFlags & TransformFlags.ContainsTypeScriptClassSyntax || node.typeParameters) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -3233,7 +3327,7 @@ namespace ts { } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3257,7 +3351,7 @@ namespace ts { } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3288,7 +3382,7 @@ namespace ts { } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3303,7 +3397,7 @@ namespace ts { // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || isComputedPropertyName(node.name)) { - transformFlags |= TransformFlags.ContainsPropertyInitializer; + transformFlags |= TransformFlags.ContainsTypeScriptClassSyntax; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -3337,7 +3431,7 @@ namespace ts { } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3379,7 +3473,7 @@ namespace ts { } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3420,7 +3514,7 @@ namespace ts { } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3440,7 +3534,9 @@ namespace ts { // ES6 syntax, and requires a lexical `this` binding. if (transformFlags & TransformFlags.Super) { transformFlags ^= TransformFlags.Super; - transformFlags |= TransformFlags.ContainsSuper; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= TransformFlags.ContainsSuper | TransformFlags.ContainsES2017 | TransformFlags.ContainsESNext; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -3456,7 +3552,9 @@ namespace ts { // ES6 syntax, and requires a lexical `this` binding. if (expressionFlags & TransformFlags.Super) { transformFlags &= ~TransformFlags.Super; - transformFlags |= TransformFlags.ContainsSuper; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= TransformFlags.ContainsSuper | TransformFlags.ContainsES2017 | TransformFlags.ContainsESNext; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -3468,7 +3566,7 @@ namespace ts { transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3642,6 +3740,10 @@ namespace ts { } break; + case SyntaxKind.BigIntLiteral: + transformFlags |= TransformFlags.AssertESNext; + break; + case SyntaxKind.ForOfStatement: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if ((node).awaitModifier) { @@ -3658,6 +3760,7 @@ namespace ts { case SyntaxKind.AnyKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.NeverKeyword: case SyntaxKind.ObjectKeyword: case SyntaxKind.StringKeyword: @@ -3717,11 +3820,11 @@ namespace ts { break; case SyntaxKind.SpreadElement: - transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsSpread; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsRestOrSpread; break; case SyntaxKind.SpreadAssignment: - transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectSpread; + transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRestOrSpread; break; case SyntaxKind.SuperKeyword: @@ -3737,8 +3840,8 @@ namespace ts { case SyntaxKind.ObjectBindingPattern: transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; - if (subtreeFlags & TransformFlags.ContainsRest) { - transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRest; + if (subtreeFlags & TransformFlags.ContainsRestOrSpread) { + transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRestOrSpread; } excludeFlags = TransformFlags.BindingPatternExcludes; break; @@ -3751,13 +3854,13 @@ namespace ts { case SyntaxKind.BindingElement: transformFlags |= TransformFlags.AssertES2015; if ((node).dotDotDotToken) { - transformFlags |= TransformFlags.ContainsRest; + transformFlags |= TransformFlags.ContainsRestOrSpread; } break; case SyntaxKind.Decorator: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsDecorators; + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsTypeScriptClassSyntax; break; case SyntaxKind.ObjectLiteralExpression: @@ -3774,7 +3877,7 @@ namespace ts { transformFlags |= TransformFlags.ContainsLexicalThis; } - if (subtreeFlags & TransformFlags.ContainsObjectSpread) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= TransformFlags.AssertESNext; @@ -3785,7 +3888,7 @@ namespace ts { case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.NewExpression: excludeFlags = TransformFlags.ArrayLiteralOrCallOrNewExcludes; - if (subtreeFlags & TransformFlags.ContainsSpread) { + if (subtreeFlags & TransformFlags.ContainsRestOrSpread) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= TransformFlags.AssertES2015; @@ -3833,7 +3936,6 @@ namespace ts { * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather * than calling this function. */ - /* @internal */ export function getTransformFlagsSubtreeExclusions(kind: SyntaxKind) { if (kind >= SyntaxKind.FirstTypeNode && kind <= SyntaxKind.LastTypeNode) { return TransformFlags.TypeExcludes; @@ -3866,6 +3968,7 @@ namespace ts { return TransformFlags.MethodOrAccessorExcludes; case SyntaxKind.AnyKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.NeverKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.ObjectKeyword: diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index f4a61267144..44ae6a299d8 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -38,6 +38,10 @@ namespace ts { * Already seen affected files */ seenAffectedFiles: Map | undefined; + /** + * whether this program has cleaned semantic diagnostics cache for lib files + */ + cleanedDiagnosticsOfLibFiles?: boolean; /** * True if the semantic diagnostics were copied from the old state */ @@ -45,7 +49,27 @@ namespace ts { /** * program corresponding to this state */ - program: Program; + program: Program | undefined; + /** + * compilerOptions for the program + */ + compilerOptions: CompilerOptions; + /** + * Files pending to be emitted + */ + affectedFilesPendingEmit: ReadonlyArray | undefined; + /** + * Current index to retrieve pending affected file + */ + affectedFilesPendingEmitIndex: number | undefined; + /** + * Already seen affected files + */ + seenEmittedFiles: Map | undefined; + /** + * true if program has been emitted + */ + programEmitComplete?: true; } function hasSameKeys(map1: ReadonlyMap | undefined, map2: ReadonlyMap | undefined): boolean { @@ -60,17 +84,23 @@ namespace ts { const state = BuilderState.create(newProgram, getCanonicalFileName, oldState) as BuilderProgramState; state.program = newProgram; const compilerOptions = newProgram.getCompilerOptions(); - if (!compilerOptions.outFile && !compilerOptions.out) { + state.compilerOptions = compilerOptions; + // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them + // With --isolatedModules, emitting changed file doesnt emit dependent files so we cant know of dependent files to retrieve errors so dont cache the errors + if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) { state.semanticDiagnosticsPerFile = createMap>(); } state.changedFilesSet = createMap(); + const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState); + const oldCompilerOptions = useOldState ? oldState!.compilerOptions : undefined; const canCopySemanticDiagnostics = useOldState && oldState!.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && - !compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState!.program.getCompilerOptions()); + !compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions!); if (useOldState) { // Verify the sanity of old state if (!oldState!.currentChangedFilePath) { - Debug.assert(!oldState!.affectedFiles && (!oldState!.currentAffectedFilesSignatures || !oldState!.currentAffectedFilesSignatures!.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + const affectedSignatures = oldState!.currentAffectedFilesSignatures; + Debug.assert(!oldState!.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); } if (canCopySemanticDiagnostics) { Debug.assert(!forEachKey(oldState!.changedFilesSet, path => oldState!.semanticDiagnosticsPerFile!.has(path)), "Semantic diagnostics shouldnt be available for changed files"); @@ -78,11 +108,17 @@ namespace ts { // Copy old state's changed files set copyEntries(oldState!.changedFilesSet, state.changedFilesSet); + if (!compilerOptions.outFile && !compilerOptions.out && oldState!.affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = oldState!.affectedFilesPendingEmit; + state.affectedFilesPendingEmitIndex = oldState!.affectedFilesPendingEmitIndex; + } } // Update changed files and copy semantic diagnostics if we can const referencedMap = state.referencedMap; const oldReferencedMap = useOldState ? oldState!.referencedMap : undefined; + const copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions!.skipLibCheck; + const copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions!.skipDefaultLibCheck; state.fileInfos.forEach((info, sourceFilePath) => { let oldInfo: Readonly | undefined; let newReferences: BuilderState.ReferencedSet | undefined; @@ -101,6 +137,11 @@ namespace ts { state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { + const sourceFile = newProgram.getSourceFileByPath(sourceFilePath as Path)!; + + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { return; } + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { return; } + // Unchanged file copy diagnostics const diagnostics = oldState!.semanticDiagnosticsPerFile!.get(sourceFilePath); if (diagnostics) { @@ -116,6 +157,38 @@ namespace ts { return state; } + /** + * Releases program and other related not needed properties + */ + function releaseCache(state: BuilderProgramState) { + BuilderState.releaseCache(state); + state.program = undefined; + } + + /** + * Creates a clone of the state + */ + function cloneBuilderProgramState(state: Readonly): BuilderProgramState { + const newState = BuilderState.clone(state) as BuilderProgramState; + newState.semanticDiagnosticsPerFile = cloneMapOrUndefined(state.semanticDiagnosticsPerFile); + newState.changedFilesSet = cloneMap(state.changedFilesSet); + newState.affectedFiles = state.affectedFiles; + newState.affectedFilesIndex = state.affectedFilesIndex; + newState.currentChangedFilePath = state.currentChangedFilePath; + newState.currentAffectedFilesSignatures = cloneMapOrUndefined(state.currentAffectedFilesSignatures); + newState.currentAffectedFilesExportedModulesMap = cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap); + newState.seenAffectedFiles = cloneMapOrUndefined(state.seenAffectedFiles); + newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; + newState.semanticDiagnosticsFromOldState = cloneMapOrUndefined(state.semanticDiagnosticsFromOldState); + newState.program = state.program; + newState.compilerOptions = state.compilerOptions; + newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit; + newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; + newState.seenEmittedFiles = cloneMapOrUndefined(state.seenEmittedFiles); + newState.programEmitComplete = state.programEmitComplete; + return newState; + } + /** * Verifies that source file is ok to be used in calls that arent handled by next */ @@ -166,10 +239,11 @@ namespace ts { // With --out or --outFile all outputs go into single file // so operations are performed directly on program, return program - const compilerOptions = state.program.getCompilerOptions(); + const program = Debug.assertDefined(state.program); + const compilerOptions = program.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { Debug.assert(!state.semanticDiagnosticsPerFile); - return state.program; + return program; } // Get next batch of affected files @@ -177,13 +251,34 @@ namespace ts { if (state.exportedModulesMap) { state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || createMap(); } - state.affectedFiles = BuilderState.getFilesAffectedBy(state, state.program, nextKey.value as Path, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = BuilderState.getFilesAffectedBy(state, program, nextKey.value as Path, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value as Path; state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || createMap(); } } + /** + * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet + */ + function getNextAffectedFilePendingEmit(state: BuilderProgramState): SourceFile | undefined { + const { affectedFilesPendingEmit } = state; + if (affectedFilesPendingEmit) { + const seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = createMap()); + for (let i = state.affectedFilesPendingEmitIndex!; i < affectedFilesPendingEmit.length; i++) { + const affectedFile = Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]); + if (affectedFile && !seenEmittedFiles.has(affectedFile.path)) { + // emit this file + state.affectedFilesPendingEmitIndex = i; + return affectedFile; + } + } + state.affectedFilesPendingEmit = undefined; + state.affectedFilesPendingEmitIndex = undefined; + } + return undefined; + } + /** * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file */ @@ -193,6 +288,20 @@ namespace ts { return; } + // Clean lib file diagnostics if its all files excluding default files to emit + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + const program = Debug.assertDefined(state.program); + const options = program.getCompilerOptions(); + if (forEach(program.getSourceFiles(), f => + program.isSourceFileDefaultLibrary(f) && + !skipTypeChecking(f, options) && + removeSemanticDiagnosticsOf(state, f.path) + )) { + return; + } + } + // If there was change in signature for the changed file, // then delete the semantic diagnostics for files that are affected by using exports of this module @@ -201,12 +310,13 @@ namespace ts { } Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + const seenFileAndExportsOfFile = createMap(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) => exportedModules && exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath as Path) + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile) )) { return; } @@ -215,7 +325,7 @@ namespace ts { forEachEntry(state.exportedModulesMap, (exportedModules, exportedFromPath) => !state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath as Path) + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile) ); } @@ -223,9 +333,50 @@ namespace ts { * removes the semantic diagnostics of files referencing referencedPath and * returns true if there are no more semantic diagnostics from old state */ - function removeSemanticDiagnosticsOfFilesReferencingPath(state: BuilderProgramState, referencedPath: Path) { + function removeSemanticDiagnosticsOfFilesReferencingPath(state: BuilderProgramState, referencedPath: Path, seenFileAndExportsOfFile: Map) { return forEachEntry(state.referencedMap!, (referencesInFile, filePath) => - referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath as Path) + referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath as Path, seenFileAndExportsOfFile) + ); + } + + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state: BuilderProgramState, filePath: Path, seenFileAndExportsOfFile: Map): boolean { + if (!addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + + Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) => + exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile) + )) { + return true; + } + + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + if (forEachEntry(state.exportedModulesMap!, (exportedModules, exportedFromPath) => + !state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile) + )) { + return true; + } + + // Remove diagnostics of files that import this file (without going to exports of referencing files) + return !!forEachEntry(state.referencedMap!, (referencesInFile, referencingFilePath) => + referencesInFile.has(filePath) && + !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file + removeSemanticDiagnosticsOf(state, referencingFilePath as Path) // Dont add to seen since this is not yet done with the export removal ); } @@ -235,7 +386,7 @@ namespace ts { */ function removeSemanticDiagnosticsOf(state: BuilderProgramState, path: Path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile!.delete(path); @@ -246,21 +397,27 @@ namespace ts { * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly */ - function doneWithAffectedFile(state: BuilderProgramState, affected: SourceFile | Program) { + function doneWithAffectedFile(state: BuilderProgramState, affected: SourceFile | Program, isPendingEmit?: boolean) { if (affected === state.program) { state.changedFilesSet.clear(); + state.programEmitComplete = true; } else { state.seenAffectedFiles!.set((affected as SourceFile).path, true); - state.affectedFilesIndex!++; + if (isPendingEmit) { + state.affectedFilesPendingEmitIndex!++; + } + else { + state.affectedFilesIndex!++; + } } } /** * Returns the result with affected file */ - function toAffectedFileResult(state: BuilderProgramState, result: T, affected: SourceFile | Program): AffectedFileResult { - doneWithAffectedFile(state, affected); + function toAffectedFileResult(state: BuilderProgramState, result: T, affected: SourceFile | Program, isPendingEmit?: boolean): AffectedFileResult { + doneWithAffectedFile(state, affected, isPendingEmit); return { result, affected }; } @@ -270,15 +427,19 @@ namespace ts { */ function getSemanticDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray { const path = sourceFile.path; - const cachedDiagnostics = state.semanticDiagnosticsPerFile!.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; + if (state.semanticDiagnosticsPerFile) { + const cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } } // Diagnostics werent cached, get them from program, and cache the result - const diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - state.semanticDiagnosticsPerFile!.set(path, diagnostics); + const diagnostics = Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); + if (state.semanticDiagnosticsPerFile) { + state.semanticDiagnosticsPerFile.set(path, diagnostics); + } return diagnostics; } @@ -294,7 +455,7 @@ namespace ts { configFileParsingDiagnostics: ReadonlyArray; } - export function getBuilderCreationParameters(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderCreationParameters { + export function getBuilderCreationParameters(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderCreationParameters { let host: BuilderProgramHost; let newProgram: Program; let oldProgram: BuilderProgram; @@ -307,7 +468,14 @@ namespace ts { } else if (isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram as BuilderProgram; - newProgram = createProgram(newProgramOrRootNames, hostOrOptions as CompilerOptions, oldProgramOrHost as CompilerHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions as CompilerOptions, + host: oldProgramOrHost as CompilerHost, + oldProgram: oldProgram && oldProgram.getProgramOrUndefined(), + configFileParsingDiagnostics, + projectReferences + }); host = oldProgramOrHost as CompilerHost; } else { @@ -337,28 +505,31 @@ namespace ts { /** * Computing hash to for signature verification */ - const computeHash = host.createHash || identity; - const state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + const computeHash = host.createHash || generateDjb2Hash; + let state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + let backupState: BuilderProgramState | undefined; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined!; // TODO: GH#18217 oldProgram = undefined; oldState = undefined; - const result: BuilderProgram = { - getState: () => state, - getProgram: () => state.program, - getCompilerOptions: () => state.program.getCompilerOptions(), - getSourceFile: fileName => state.program.getSourceFile(fileName), - getSourceFiles: () => state.program.getSourceFiles(), - getOptionsDiagnostics: cancellationToken => state.program.getOptionsDiagnostics(cancellationToken), - getGlobalDiagnostics: cancellationToken => state.program.getGlobalDiagnostics(cancellationToken), - getConfigFileParsingDiagnostics: () => configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(), - getSyntacticDiagnostics: (sourceFile, cancellationToken) => state.program.getSyntacticDiagnostics(sourceFile, cancellationToken), - getSemanticDiagnostics, - emit, - getAllDependencies: sourceFile => BuilderState.getAllDependencies(state, state.program, sourceFile), - getCurrentDirectory: () => state.program.getCurrentDirectory() + const result = createRedirectedBuilderProgram(state, configFileParsingDiagnostics); + result.getState = () => state; + result.backupState = () => { + Debug.assert(backupState === undefined); + backupState = cloneBuilderProgramState(state); + }; + result.restoreState = () => { + state = Debug.assertDefined(backupState); + backupState = undefined; + }; + result.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.assertDefined(state.program), sourceFile); + result.getSemanticDiagnostics = getSemanticDiagnostics; + result.emit = emit; + result.releaseProgram = () => { + releaseCache(state); + backupState = undefined; }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { @@ -379,18 +550,39 @@ namespace ts { * in that order would be used to write the files */ function emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult { - const affected = getNextAffectedFile(state, cancellationToken, computeHash); + let affected = getNextAffectedFile(state, cancellationToken, computeHash); + let isPendingEmitFile = false; if (!affected) { - // Done - return undefined; + if (!state.compilerOptions.out && !state.compilerOptions.outFile) { + affected = getNextAffectedFilePendingEmit(state); + if (!affected) { + return undefined; + } + isPendingEmitFile = true; + } + else { + const program = Debug.assertDefined(state.program); + // Check if program uses any prepend project references, if thats the case we cant track of the js files of those, so emit even though there are no changes + if (state.programEmitComplete || !some(program.getProjectReferences(), ref => !!ref.prepend)) { + state.programEmitComplete = true; + return undefined; + } + affected = program; + } + } + + // Mark seen emitted files if there are pending files to be emitted + if (state.affectedFilesPendingEmit && state.program !== affected) { + (state.seenEmittedFiles || (state.seenEmittedFiles = createMap())).set((affected as SourceFile).path, true); } return toAffectedFileResult( state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - state.program.emit(affected === state.program ? undefined : affected as SourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), - affected + Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected as SourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), + affected, + isPendingEmitFile ); } @@ -410,7 +602,7 @@ namespace ts { assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); if (!targetSourceFile) { // Emit and report any errors we ran into. - let sourceMaps: SourceMapData[] = []; + let sourceMaps: SourceMapEmitResult[] = []; let emitSkipped = false; let diagnostics: Diagnostic[] | undefined; let emittedFiles: string[] = []; @@ -430,7 +622,7 @@ namespace ts { }; } } - return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); } /** @@ -478,33 +670,74 @@ namespace ts { */ function getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray { assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - const compilerOptions = state.program.getCompilerOptions(); + const compilerOptions = Debug.assertDefined(state.program).getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { Debug.assert(!state.semanticDiagnosticsPerFile); // We dont need to cache the diagnostics just return them from program - return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + return Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); } if (sourceFile) { return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); } - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - // When semantic builder asks for diagnostics of the whole program, - // ensure that all the affected files are handled - let affected: SourceFile | Program | undefined; - while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { - doneWithAffectedFile(state, affected); + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + let affected: SourceFile | Program | undefined; + let affectedFilesPendingEmit: Path[] | undefined; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + if (affected !== state.program && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push((affected as SourceFile).path); + } + doneWithAffectedFile(state, affected); + } + + // In case of emit builder, cache the files to be emitted + if (affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit); + // affectedFilesPendingEmitIndex === undefined + // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files + // so start from 0 as array would be affectedFilesPendingEmit + // else, continue to iterate from existing index, the current set is appended to existing files + if (state.affectedFilesPendingEmitIndex === undefined) { + state.affectedFilesPendingEmitIndex = 0; } } let diagnostics: Diagnostic[] | undefined; - for (const sourceFile of state.program.getSourceFiles()) { + for (const sourceFile of Debug.assertDefined(state.program).getSourceFiles()) { diagnostics = addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken)); } return diagnostics || emptyArray; } } + + export function createRedirectedBuilderProgram(state: { program: Program | undefined; compilerOptions: CompilerOptions; }, configFileParsingDiagnostics: ReadonlyArray): BuilderProgram { + return { + getState: notImplemented, + backupState: noop, + restoreState: noop, + getProgram, + getProgramOrUndefined: () => state.program, + releaseProgram: () => state.program = undefined, + getCompilerOptions: () => state.compilerOptions, + getSourceFile: fileName => getProgram().getSourceFile(fileName), + getSourceFiles: () => getProgram().getSourceFiles(), + getOptionsDiagnostics: cancellationToken => getProgram().getOptionsDiagnostics(cancellationToken), + getGlobalDiagnostics: cancellationToken => getProgram().getGlobalDiagnostics(cancellationToken), + getConfigFileParsingDiagnostics: () => configFileParsingDiagnostics, + getSyntacticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken), + getDeclarationDiagnostics: (sourceFile, cancellationToken) => getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken), + getSemanticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSemanticDiagnostics(sourceFile, cancellationToken), + emit: (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) => getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers), + getAllDependencies: notImplemented, + getCurrentDirectory: () => getProgram().getCurrentDirectory() + }; + + function getProgram() { + return Debug.assertDefined(state.program); + } + } } namespace ts { @@ -532,10 +765,24 @@ namespace ts { export interface BuilderProgram { /*@internal*/ getState(): BuilderProgramState; + /*@internal*/ + backupState(): void; + /*@internal*/ + restoreState(): void; /** * Returns current program */ getProgram(): Program; + /** + * Returns current program that could be undefined if the program was released + */ + /*@internal*/ + getProgramOrUndefined(): Program | undefined; + /** + * Releases reference to the program, making all the other operations that need program to fail. + */ + /*@internal*/ + releaseProgram(): void; /** * Get compiler options of the program */ @@ -564,10 +811,15 @@ namespace ts { * Get the syntax diagnostics, for all source files if source file is not supplied */ getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the declaration diagnostics, for all source files if source file is not supplied + */ + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; /** * Get all the dependencies of the file */ getAllDependencies(sourceFile: SourceFile): ReadonlyArray; + /** * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program * The semantic diagnostics are cached and managed here @@ -623,9 +875,9 @@ namespace ts { * Create the builder to manage semantic diagnostics and cache them */ export function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - export function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray) { - return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + export function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray) { + return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } /** @@ -633,33 +885,18 @@ namespace ts { * to emit the those files and manage semantic diagnostics cache as well */ export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray) { - return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray) { + return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } /** * Creates a builder thats just abstraction over program and can be used with watch */ export function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - export function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - export function createAbstractBuilder(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram { - const { newProgram: program } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics); - return { - // Only return program, all other methods are not implemented - getProgram: () => program, - getState: notImplemented, - getCompilerOptions: notImplemented, - getSourceFile: notImplemented, - getSourceFiles: notImplemented, - getOptionsDiagnostics: notImplemented, - getGlobalDiagnostics: notImplemented, - getConfigFileParsingDiagnostics: notImplemented, - getSyntacticDiagnostics: notImplemented, - getSemanticDiagnostics: notImplemented, - emit: notImplemented, - getAllDependencies: notImplemented, - getCurrentDirectory: notImplemented - }; + export function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; + export function createAbstractBuilder(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram { + const { newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); + return createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics); } } diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index 12936e5b2e8..552f46c378d 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -50,11 +50,15 @@ namespace ts { /** * Cache of all files excluding default library file for the current program */ - allFilesExcludingDefaultLibraryFile: ReadonlyArray | undefined; + allFilesExcludingDefaultLibraryFile?: ReadonlyArray; /** * Cache of all the file names */ - allFileNames: ReadonlyArray | undefined; + allFileNames?: ReadonlyArray; + } + + export function cloneMapOrUndefined(map: ReadonlyMap | undefined) { + return map ? cloneMap(map) : undefined; } } @@ -88,7 +92,7 @@ namespace ts.BuilderState { function getReferencedFileFromImportedModuleSymbol(symbol: Symbol) { if (symbol.declarations && symbol.declarations[0]) { const declarationSourceFile = getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } @@ -100,6 +104,13 @@ namespace ts.BuilderState { return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program: Program, fileName: string, sourceFileDirectory: Path, getCanonicalFileName: GetCanonicalFileName): Path { + return toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } + /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -123,7 +134,7 @@ namespace ts.BuilderState { // Handle triple slash references if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (const referencedFile of sourceFile.referencedFiles) { - const referencedPath = toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + const referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -136,13 +147,44 @@ namespace ts.BuilderState { } const fileName = resolvedTypeReferenceDirective.resolvedFileName!; // TODO: GH#18217 - const typeFilePath = toPath(fileName, sourceFileDirectory, getCanonicalFileName); + const typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + const checker = program.getTypeChecker(); + for (const moduleName of sourceFile.moduleAugmentations) { + if (!isStringLiteral(moduleName)) { continue; } + const symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { continue; } + + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + + // From ambient modules + for (const ambientModule of program.getTypeChecker().getAmbientModules()) { + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } + return referencedFiles; + function addReferenceFromAmbientModule(symbol: Symbol) { + // Add any file other than our own as reference + for (const declaration of symbol.declarations) { + const declarationSourceFile = getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } + function addReferencedFile(referencedPath: Path) { if (!referencedFiles) { referencedFiles = createMap(); @@ -192,9 +234,32 @@ namespace ts.BuilderState { fileInfos, referencedMap, exportedModulesMap, - hasCalledUpdateShapeSignature, - allFilesExcludingDefaultLibraryFile: undefined, - allFileNames: undefined + hasCalledUpdateShapeSignature + }; + } + + /** + * Releases needed properties + */ + export function releaseCache(state: BuilderState) { + state.allFilesExcludingDefaultLibraryFile = undefined; + state.allFileNames = undefined; + } + + /** + * Creates a clone of the state + */ + export function clone(state: Readonly): BuilderState { + const fileInfos = createMap(); + state.fileInfos.forEach((value, key) => { + fileInfos.set(key, { ...value }); + }); + // Dont need to backup allFiles info since its cache anyway + return { + fileInfos, + referencedMap: cloneMapOrUndefined(state.referencedMap), + exportedModulesMap: cloneMapOrUndefined(state.exportedModulesMap), + hasCalledUpdateShapeSignature: cloneMap(state.hasCalledUpdateShapeSignature), }; } @@ -254,6 +319,11 @@ namespace ts.BuilderState { let latestSignature: string; if (sourceFile.isDeclarationFile) { latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + const references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } } else { const emitOutput = getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); @@ -325,7 +395,7 @@ namespace ts.BuilderState { } // If this is non module emit, or its a global file, it depends on all the source files - if (!state.referencedMap || (!isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { return getAllFileNames(state, programOfThisState); } @@ -387,6 +457,22 @@ namespace ts.BuilderState { return true; } + /** + * Return true if file contains anything that augments to global scope we need to build them as if + * they are global files as well as module + */ + function containsGlobalScopeAugmentation(sourceFile: SourceFile) { + return some(sourceFile.moduleAugmentations, augmentation => isGlobalScopeAugmentation(augmentation.parent as ModuleDeclaration)); + } + + /** + * Return true if the file will invalidate all files because it affectes global scope + */ + function isFileAffectingGlobalScope(sourceFile: SourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || + !isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } + /** * Gets all files of the program excluding the default library file */ @@ -430,7 +516,7 @@ namespace ts.BuilderState { * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ function getFilesAffectedByUpdatedShapeWhenModuleEmit(state: BuilderState, programOfThisState: Program, sourceFileWithUpdatedShape: SourceFile, cacheToUpdateSignature: Map, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash | undefined, exportedModulesMapCache: ComputingExportedModulesMap | undefined) { - if (!isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -446,14 +532,14 @@ namespace ts.BuilderState { // Start with the paths this file was referenced by seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); - const queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + const queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath); while (queue.length > 0) { const currentPath = queue.pop()!; if (!seenFileNamesMap.has(currentPath)) { const currentSourceFile = programOfThisState.getSourceFileByPath(currentPath)!; seenFileNamesMap.set(currentPath, currentSourceFile); if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash!, exportedModulesMapCache)) { // TODO: GH#18217 - queue.push(...getReferencedByPaths(state, currentPath)); + queue.push(...getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 91985bbc64d..ac069d95fac 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -77,10 +77,12 @@ namespace ts { const allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions); const strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks"); const strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + const strictBindCallApply = getStrictOptionValue(compilerOptions, "strictBindCallApply"); const strictPropertyInitialization = getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); const noImplicitAny = getStrictOptionValue(compilerOptions, "noImplicitAny"); const noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis"); const keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : ObjectFlags.FreshLiteral; const emitResolver = createResolver(); const nodeBuilder = createNodeBuilder(); @@ -240,17 +242,7 @@ namespace ts { const parsed = getParseTreeNode(node, isFunctionLike); return parsed ? isImplementationOfOverload(parsed) : undefined; }, - getImmediateAliasedSymbol: symbol => { - Debug.assert((symbol.flags & SymbolFlags.Alias) !== 0, "Should only get Alias here."); - const links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - const node = getDeclarationOfAliasSymbol(symbol); - if (!node) return Debug.fail(); - links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); - } - - return links.immediateTarget; - }, + getImmediateAliasedSymbol, getAliasedSymbol: resolveAlias, getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, @@ -268,10 +260,6 @@ namespace ts { getFirstIdentifier, ), getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: nodeIn => { - const node = getParseTreeNode(nodeIn, isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, getJsxIntrinsicTagNamesAt, isOptionalParameter: nodeIn => { const node = getParseTreeNode(nodeIn, isParameter); @@ -295,15 +283,17 @@ namespace ts { getNumberType: () => numberType, createPromiseType, createArrayType, + getElementTypeOfArrayType, getBooleanType: () => booleanType, - getFalseType: () => falseType, - getTrueType: () => trueType, + getFalseType: (fresh?) => fresh ? falseType : regularFalseType, + getTrueType: (fresh?) => fresh ? trueType : regularTrueType, getVoidType: () => voidType, getUndefinedType: () => undefinedType, getNullType: () => nullType, getESSymbolType: () => esSymbolType, getNeverType: () => neverType, isSymbolAccessible, + getObjectFlags, isArrayLikeType, isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes, @@ -405,9 +395,25 @@ namespace ts { const nullWideningType = strictNullChecks ? nullType : createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsWideningType, "null"); const stringType = createIntrinsicType(TypeFlags.String, "string"); const numberType = createIntrinsicType(TypeFlags.Number, "number"); - const falseType = createIntrinsicType(TypeFlags.BooleanLiteral, "false"); - const trueType = createIntrinsicType(TypeFlags.BooleanLiteral, "true"); - const booleanType = createBooleanType([falseType, trueType]); + const bigintType = createIntrinsicType(TypeFlags.BigInt, "bigint"); + const falseType = createIntrinsicType(TypeFlags.BooleanLiteral, "false") as FreshableIntrinsicType; + const regularFalseType = createIntrinsicType(TypeFlags.BooleanLiteral, "false") as FreshableIntrinsicType; + const trueType = createIntrinsicType(TypeFlags.BooleanLiteral, "true") as FreshableIntrinsicType; + const regularTrueType = createIntrinsicType(TypeFlags.BooleanLiteral, "true") as FreshableIntrinsicType; + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + const booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); const esSymbolType = createIntrinsicType(TypeFlags.ESSymbol, "symbol"); const voidType = createIntrinsicType(TypeFlags.Void, "void"); const neverType = createIntrinsicType(TypeFlags.Never, "never"); @@ -416,8 +422,11 @@ namespace ts { const nonPrimitiveType = createIntrinsicType(TypeFlags.NonPrimitive, "object"); const stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); const keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + const numberOrBigIntType = getUnionType([numberType, bigintType]); const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + emptyJsxObjectType.objectFlags |= ObjectFlags.JsxAttributes; const emptyTypeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type); emptyTypeLiteralSymbol.members = createSymbolTable(); @@ -435,10 +444,10 @@ namespace ts { const circularConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); const resolvingDefaultType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - const markerSuperType = createType(TypeFlags.TypeParameter); - const markerSubType = createType(TypeFlags.TypeParameter); + const markerSuperType = createTypeParameter(); + const markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; - const markerOtherType = createType(TypeFlags.TypeParameter); + const markerOtherType = createTypeParameter(); const noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); @@ -446,12 +455,23 @@ namespace ts { const unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); const resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); const silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - const resolvingSignaturesArray = [resolvingSignature]; const enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); const globals = createSymbolTable(); - let amalgamatedDuplicates: Map<{ firstFile: SourceFile, secondFile: SourceFile, firstFileInstances: Map<{ instances: Node[], blockScoped: boolean }>, secondFileInstances: Map<{ instances: Node[], blockScoped: boolean }> }> | undefined; + interface DuplicateInfoForSymbol { + readonly firstFileLocations: Node[]; + readonly secondFileLocations: Node[]; + readonly isBlockScoped: boolean; + } + interface DuplicateInfoForFiles { + readonly firstFile: SourceFile; + readonly secondFile: SourceFile; + /** Key is symbol name. */ + readonly conflictingSymbols: Map; + } + /** Key is "/path/to/a.ts|/path/to/b.ts". */ + let amalgamatedDuplicates: Map | undefined; const reverseMappedCache = createMap(); let ambientModulesCache: Symbol[] | undefined; /** @@ -463,6 +483,8 @@ namespace ts { let globalObjectType: ObjectType; let globalFunctionType: ObjectType; + let globalCallableFunctionType: ObjectType; + let globalNewableFunctionType: ObjectType; let globalArrayType: GenericType; let globalReadonlyArrayType: GenericType; let globalStringType: ObjectType; @@ -482,6 +504,7 @@ namespace ts { let deferredGlobalESSymbolType: ObjectType; let deferredGlobalTypedPropertyDescriptorType: GenericType; let deferredGlobalPromiseType: GenericType; + let deferredGlobalPromiseLikeType: GenericType; let deferredGlobalPromiseConstructorSymbol: Symbol | undefined; let deferredGlobalPromiseConstructorLikeType: ObjectType; let deferredGlobalIterableType: GenericType; @@ -493,8 +516,10 @@ namespace ts { let deferredGlobalTemplateStringsArrayType: ObjectType; let deferredGlobalImportMetaType: ObjectType; let deferredGlobalExtractSymbol: Symbol; + let deferredGlobalExcludeSymbol: Symbol; + let deferredGlobalPickSymbol: Symbol; + let deferredGlobalBigIntType: ObjectType; - let deferredNodes: Map | undefined; const allPotentiallyUnusedIdentifiers = createMap(); // key is file name let flowLoopStart = 0; @@ -504,6 +529,7 @@ namespace ts { const emptyStringType = getLiteralType(""); const zeroType = getLiteralType(0); + const zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); const resolutionTargets: TypeSystemEntity[] = []; const resolutionResults: boolean[] = []; @@ -532,31 +558,33 @@ namespace ts { None = 0, TypeofEQString = 1 << 0, // typeof x === "string" TypeofEQNumber = 1 << 1, // typeof x === "number" - TypeofEQBoolean = 1 << 2, // typeof x === "boolean" - TypeofEQSymbol = 1 << 3, // typeof x === "symbol" - TypeofEQObject = 1 << 4, // typeof x === "object" - TypeofEQFunction = 1 << 5, // typeof x === "function" - TypeofEQHostObject = 1 << 6, // typeof x === "xxx" - TypeofNEString = 1 << 7, // typeof x !== "string" - TypeofNENumber = 1 << 8, // typeof x !== "number" - TypeofNEBoolean = 1 << 9, // typeof x !== "boolean" - TypeofNESymbol = 1 << 10, // typeof x !== "symbol" - TypeofNEObject = 1 << 11, // typeof x !== "object" - TypeofNEFunction = 1 << 12, // typeof x !== "function" - TypeofNEHostObject = 1 << 13, // typeof x !== "xxx" - EQUndefined = 1 << 14, // x === undefined - EQNull = 1 << 15, // x === null - EQUndefinedOrNull = 1 << 16, // x === undefined / x === null - NEUndefined = 1 << 17, // x !== undefined - NENull = 1 << 18, // x !== null - NEUndefinedOrNull = 1 << 19, // x != undefined / x != null - Truthy = 1 << 20, // x - Falsy = 1 << 21, // !x - All = (1 << 22) - 1, + TypeofEQBigInt = 1 << 2, // typeof x === "bigint" + TypeofEQBoolean = 1 << 3, // typeof x === "boolean" + TypeofEQSymbol = 1 << 4, // typeof x === "symbol" + TypeofEQObject = 1 << 5, // typeof x === "object" + TypeofEQFunction = 1 << 6, // typeof x === "function" + TypeofEQHostObject = 1 << 7, // typeof x === "xxx" + TypeofNEString = 1 << 8, // typeof x !== "string" + TypeofNENumber = 1 << 9, // typeof x !== "number" + TypeofNEBigInt = 1 << 10, // typeof x !== "bigint" + TypeofNEBoolean = 1 << 11, // typeof x !== "boolean" + TypeofNESymbol = 1 << 12, // typeof x !== "symbol" + TypeofNEObject = 1 << 13, // typeof x !== "object" + TypeofNEFunction = 1 << 14, // typeof x !== "function" + TypeofNEHostObject = 1 << 15, // typeof x !== "xxx" + EQUndefined = 1 << 16, // x === undefined + EQNull = 1 << 17, // x === null + EQUndefinedOrNull = 1 << 18, // x === undefined / x === null + NEUndefined = 1 << 19, // x !== undefined + NENull = 1 << 20, // x !== null + NEUndefinedOrNull = 1 << 21, // x != undefined / x != null + Truthy = 1 << 22, // x + Falsy = 1 << 23, // !x + All = (1 << 24) - 1, // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. - BaseStringStrictFacts = TypeofEQString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, + BaseStringStrictFacts = TypeofEQString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, BaseStringFacts = BaseStringStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, StringStrictFacts = BaseStringStrictFacts | Truthy | Falsy, StringFacts = BaseStringFacts | Truthy, @@ -564,15 +592,23 @@ namespace ts { EmptyStringFacts = BaseStringFacts, NonEmptyStringStrictFacts = BaseStringStrictFacts | Truthy, NonEmptyStringFacts = BaseStringFacts | Truthy, - BaseNumberStrictFacts = TypeofEQNumber | TypeofNEString | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, + BaseNumberStrictFacts = TypeofEQNumber | TypeofNEString | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, BaseNumberFacts = BaseNumberStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, NumberStrictFacts = BaseNumberStrictFacts | Truthy | Falsy, NumberFacts = BaseNumberFacts | Truthy, - ZeroStrictFacts = BaseNumberStrictFacts | Falsy, - ZeroFacts = BaseNumberFacts, - NonZeroStrictFacts = BaseNumberStrictFacts | Truthy, - NonZeroFacts = BaseNumberFacts | Truthy, - BaseBooleanStrictFacts = TypeofEQBoolean | TypeofNEString | TypeofNENumber | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, + ZeroNumberStrictFacts = BaseNumberStrictFacts | Falsy, + ZeroNumberFacts = BaseNumberFacts, + NonZeroNumberStrictFacts = BaseNumberStrictFacts | Truthy, + NonZeroNumberFacts = BaseNumberFacts | Truthy, + BaseBigIntStrictFacts = TypeofEQBigInt | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, + BaseBigIntFacts = BaseBigIntStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, + BigIntStrictFacts = BaseBigIntStrictFacts | Truthy | Falsy, + BigIntFacts = BaseBigIntFacts | Truthy, + ZeroBigIntStrictFacts = BaseBigIntStrictFacts | Falsy, + ZeroBigIntFacts = BaseBigIntFacts, + NonZeroBigIntStrictFacts = BaseBigIntStrictFacts | Truthy, + NonZeroBigIntFacts = BaseBigIntFacts | Truthy, + BaseBooleanStrictFacts = TypeofEQBoolean | TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, BaseBooleanFacts = BaseBooleanStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, BooleanStrictFacts = BaseBooleanStrictFacts | Truthy | Falsy, BooleanFacts = BaseBooleanFacts | Truthy, @@ -580,19 +616,22 @@ namespace ts { FalseFacts = BaseBooleanFacts, TrueStrictFacts = BaseBooleanStrictFacts | Truthy, TrueFacts = BaseBooleanFacts | Truthy, - SymbolStrictFacts = TypeofEQSymbol | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull | Truthy, + SymbolStrictFacts = TypeofEQSymbol | TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull | Truthy, SymbolFacts = SymbolStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, - ObjectStrictFacts = TypeofEQObject | TypeofEQHostObject | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEFunction | NEUndefined | NENull | NEUndefinedOrNull | Truthy, + ObjectStrictFacts = TypeofEQObject | TypeofEQHostObject | TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEFunction | NEUndefined | NENull | NEUndefinedOrNull | Truthy, ObjectFacts = ObjectStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, - FunctionStrictFacts = TypeofEQFunction | TypeofEQHostObject | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | NEUndefined | NENull | NEUndefinedOrNull | Truthy, + FunctionStrictFacts = TypeofEQFunction | TypeofEQHostObject | TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | NEUndefined | NENull | NEUndefinedOrNull | Truthy, FunctionFacts = FunctionStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, - UndefinedFacts = TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | EQUndefined | EQUndefinedOrNull | NENull | Falsy, - NullFacts = TypeofEQObject | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEFunction | TypeofNEHostObject | EQNull | EQUndefinedOrNull | NEUndefined | Falsy, + UndefinedFacts = TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | EQUndefined | EQUndefinedOrNull | NENull | Falsy, + NullFacts = TypeofEQObject | TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEFunction | TypeofNEHostObject | EQNull | EQUndefinedOrNull | NEUndefined | Falsy, + EmptyObjectStrictFacts = All & ~(EQUndefined | EQNull | EQUndefinedOrNull), + EmptyObjectFacts = All, } const typeofEQFacts = createMapFromTemplate({ string: TypeFacts.TypeofEQString, number: TypeFacts.TypeofEQNumber, + bigint: TypeFacts.TypeofEQBigInt, boolean: TypeFacts.TypeofEQBoolean, symbol: TypeFacts.TypeofEQSymbol, undefined: TypeFacts.EQUndefined, @@ -602,6 +641,7 @@ namespace ts { const typeofNEFacts = createMapFromTemplate({ string: TypeFacts.TypeofNEString, number: TypeFacts.TypeofNENumber, + bigint: TypeFacts.TypeofNEBigInt, boolean: TypeFacts.TypeofNEBoolean, symbol: TypeFacts.TypeofNESymbol, undefined: TypeFacts.NEUndefined, @@ -611,6 +651,7 @@ namespace ts { const typeofTypesByName = createMapFromTemplate({ string: stringType, number: numberType, + bigint: bigintType, boolean: booleanType, symbol: esSymbolType, undefined: undefinedType @@ -622,12 +663,11 @@ namespace ts { const subtypeRelation = createMap(); const assignableRelation = createMap(); - const definitelyAssignableRelation = createMap(); const comparableRelation = createMap(); const identityRelation = createMap(); const enumRelation = createMap(); - type TypeSystemEntity = Symbol | Type | Signature; + type TypeSystemEntity = Node | Symbol | Type | Signature; const enum TypeSystemPropertyName { Type, @@ -635,6 +675,8 @@ namespace ts { DeclaredType, ResolvedReturnType, ImmediateBaseConstraint, + EnumTagType, + JSDocTypeReference, } const enum CheckMode { @@ -824,10 +866,14 @@ namespace ts { */ function mergeSymbol(target: Symbol, source: Symbol): Symbol { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & SymbolFlags.JSContainer) { + (source.flags | target.flags) & SymbolFlags.Assignment) { Debug.assert(source !== target); if (!(target.flags & SymbolFlags.Transient)) { - target = cloneSymbol(target); + const resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + target = cloneSymbol(resolvedTarget); } // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & SymbolFlags.ValueModule && target.flags & SymbolFlags.ValueModule && target.constEnumOnlyModule && !source.constEnumOnlyModule) { @@ -837,7 +883,7 @@ namespace ts { target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - isAssignmentDeclaration(target.valueDeclaration) || + isAssignmentDeclaration(target.valueDeclaration) && !isAssignmentDeclaration(source.valueDeclaration) || isEffectiveModuleDeclaration(target.valueDeclaration) && !isEffectiveModuleDeclaration(source.valueDeclaration))) { // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; @@ -856,7 +902,7 @@ namespace ts { else if (target.flags & SymbolFlags.NamespaceModule) { error(getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } - else { + else { // error const isEitherEnum = !!(target.flags & SymbolFlags.Enum || source.flags & SymbolFlags.Enum); const isEitherBlockScoped = !!(target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable); const message = isEitherEnum @@ -866,50 +912,45 @@ namespace ts { : Diagnostics.Duplicate_identifier_0; const sourceSymbolFile = source.declarations && getSourceFileOfNode(source.declarations[0]); const targetSymbolFile = target.declarations && getSourceFileOfNode(target.declarations[0]); + const symbolName = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { const firstFile = comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === Comparison.LessThan ? sourceSymbolFile : targetSymbolFile; const secondFile = firstFile === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; - const cacheKey = `${firstFile.path}|${secondFile.path}`; - const existing = amalgamatedDuplicates.get(cacheKey) || { firstFile, secondFile, firstFileInstances: createMap(), secondFileInstances: createMap() }; - const symbolName = symbolToString(source); - const firstInstanceList = existing.firstFileInstances.get(symbolName) || { instances: [], blockScoped: isEitherBlockScoped }; - const secondInstanceList = existing.secondFileInstances.get(symbolName) || { instances: [], blockScoped: isEitherBlockScoped }; - - forEach(source.declarations, node => { - const errorNode = (getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? getOuterNameOfJsInitializer(node) : getNameOfDeclaration(node)) || node; - const targetList = sourceSymbolFile === firstFile ? firstInstanceList : secondInstanceList; - targetList.instances.push(errorNode); - }); - forEach(target.declarations, node => { - const errorNode = (getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? getOuterNameOfJsInitializer(node) : getNameOfDeclaration(node)) || node; - const targetList = targetSymbolFile === firstFile ? firstInstanceList : secondInstanceList; - targetList.instances.push(errorNode); - }); - - existing.firstFileInstances.set(symbolName, firstInstanceList); - existing.secondFileInstances.set(symbolName, secondInstanceList); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + const filesDuplicates = getOrUpdate(amalgamatedDuplicates, `${firstFile.path}|${secondFile.path}`, () => + ({ firstFile, secondFile, conflictingSymbols: createMap() })); + const conflictingSymbolInfo = getOrUpdate(filesDuplicates.conflictingSymbols, symbolName, () => + ({ isBlockScoped: isEitherBlockScoped, firstFileLocations: [], secondFileLocations: [] })); + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source); } - const symbolName = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source); } return target; + + function addDuplicateLocations(locs: Node[], symbol: Symbol): void { + for (const decl of symbol.declarations) { + pushIfUnique(locs, (getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? getNameOfExpando(decl) : getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target: Symbol, message: DiagnosticMessage, symbolName: string, source: Symbol) { forEach(target.declarations, node => { - const errorNode = (getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? getOuterNameOfJsInitializer(node) : getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + const errorNode = (getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode: Node, message: DiagnosticMessage, symbolName: string, relatedNode: Node | undefined) { + function addDuplicateDeclarationError(errorNode: Node, message: DiagnosticMessage, symbolName: string, relatedNodes: ReadonlyArray | undefined) { const err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && length(err.relatedInformation) < 5) { + for (const relatedNode of relatedNodes || emptyArray) { + err.relatedInformation = err.relatedInformation || []; + if (length(err.relatedInformation) >= 5) continue; addRelatedInfo(err, !length(err.relatedInformation) ? createDiagnosticForNode(relatedNode, Diagnostics._0_was_also_declared_here, symbolName) : createDiagnosticForNode(relatedNode, Diagnostics.and_here)); } } @@ -925,7 +966,8 @@ namespace ts { function mergeSymbolTable(target: SymbolTable, source: SymbolTable) { source.forEach((sourceSymbol, id) => { - target.set(id, target.has(id) ? mergeSymbol(target.get(id)!, sourceSymbol) : sourceSymbol); + const targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); }); } @@ -1211,17 +1253,25 @@ namespace ts { // 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 && - !!findAncestor(result.valueDeclaration, isParameter) - ); + if (meaning & result.flags & SymbolFlags.Variable) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + const functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= ScriptTarget.ES2015 && isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (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 && + !!findAncestor(result.valueDeclaration, isParameter) + ); + } } } else if (location.kind === SyntaxKind.ConditionalType) { @@ -1312,7 +1362,10 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location as ClassLikeDeclaration | InterfaceDeclaration)), name, meaning & SymbolFlags.Type)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location as ClassLikeDeclaration | InterfaceDeclaration).members || emptySymbols, name, meaning & SymbolFlags.Type)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -1365,13 +1418,18 @@ namespace ts { } } break; + case SyntaxKind.ArrowFunction: + // when targeting ES6 or higher there is no 'arguments' in an arrow function + // for lower compile targets the resolved symbol is used to emit an error + if (compilerOptions.target! >= ScriptTarget.ES2015) { + break; + } + // falls through case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.FunctionDeclaration: - case SyntaxKind.ArrowFunction: if (meaning & SymbolFlags.Variable && name === "arguments") { result = argumentsSymbol; break loop; @@ -1436,7 +1494,7 @@ namespace ts { if (!result) { if (lastLocation) { Debug.assert(lastLocation.kind === SyntaxKind.SourceFile); - if ((lastLocation as SourceFile).commonJsModuleIndicator && name === "exports") { + if ((lastLocation as SourceFile).commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -1446,7 +1504,7 @@ namespace ts { } } if (!result) { - if (originalLocation && isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && isInJSFile(originalLocation) && originalLocation.parent) { if (isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -1516,8 +1574,8 @@ namespace ts { // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value && !(originalLocation!.flags & NodeFlags.JSDoc)) { - const decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === SyntaxKind.NamespaceExportDeclaration) { + const merged = getMergedSymbol(result); + if (length(merged.declarations) && every(merged.declarations, d => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) { error(errorLocation!, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -1622,7 +1680,7 @@ namespace ts { } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation: Node, name: __String, meaning: SymbolFlags): boolean { - const namespaceMeaning = SymbolFlags.Namespace | (isInJavaScriptFile(errorLocation) ? SymbolFlags.Value : 0); + const namespaceMeaning = SymbolFlags.Namespace | (isInJSFile(errorLocation) ? SymbolFlags.Value : 0); if (meaning === namespaceMeaning) { const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~namespaceMeaning, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false)); const parent = errorLocation.parent; @@ -1657,7 +1715,10 @@ namespace ts { } const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & SymbolFlags.NamespaceModule)) { - error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, unescapeLeadingUnderscores(name)); + const message = (name === "Promise" || name === "Symbol") + ? Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, unescapeLeadingUnderscores(name)); return true; } } @@ -1685,7 +1746,9 @@ namespace ts { function checkResolvedBlockScopedVariable(result: Symbol, errorLocation: Node): void { Debug.assert(!!(result.flags & SymbolFlags.BlockScopedVariable || result.flags & SymbolFlags.Class || result.flags & SymbolFlags.Enum)); // Block-scoped variables cannot be used before their definition - const declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) || isClassLike(d) || (d.kind === SyntaxKind.EnumDeclaration) ? d : undefined); + const declaration = find( + result.declarations, + d => isBlockOrCatchScoped(d) || isClassLike(d) || (d.kind === SyntaxKind.EnumDeclaration) || isInJSFile(d) && !!getJSDocEnumTag(d)); if (declaration === undefined) return Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); @@ -1785,7 +1848,7 @@ namespace ts { return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!isSourceFileJavaScript(file)) { + if (!isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -1900,7 +1963,7 @@ namespace ts { combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - const moduleName = getFullyQualifiedName(moduleSymbol); + const moduleName = getFullyQualifiedName(moduleSymbol, node); const declarationName = declarationNameToString(name); const suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -1976,7 +2039,7 @@ namespace ts { */ function isNonLocalAlias(symbol: Symbol | undefined, excludes = SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace): symbol is Symbol { if (!symbol) return false; - return (symbol.flags & (SymbolFlags.Alias | excludes)) === SymbolFlags.Alias || !!(symbol.flags & SymbolFlags.Alias && symbol.flags & SymbolFlags.JSContainer); + return (symbol.flags & (SymbolFlags.Alias | excludes)) === SymbolFlags.Alias || !!(symbol.flags & SymbolFlags.Alias && symbol.flags & SymbolFlags.Assignment); } function resolveSymbol(symbol: Symbol, dontResolveAlias?: boolean): Symbol; @@ -2066,8 +2129,8 @@ namespace ts { } } - function getFullyQualifiedName(symbol: Symbol): string { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol: Symbol, containingLocation?: Node): string { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, SymbolFormatFlags.DoNotIncludeSymbolChain | SymbolFormatFlags.AllowAnyNodeKind); } /** @@ -2078,11 +2141,11 @@ namespace ts { return undefined; } - const namespaceMeaning = SymbolFlags.Namespace | (isInJavaScriptFile(name) ? meaning & SymbolFlags.Value : 0); + const namespaceMeaning = SymbolFlags.Namespace | (isInJSFile(name) ? meaning & SymbolFlags.Value : 0); let symbol: Symbol | undefined; if (name.kind === SyntaxKind.Identifier) { - const message = meaning === namespaceMeaning ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0; - const symbolFromJSPrototype = isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + const message = meaning === namespaceMeaning ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + const symbolFromJSPrototype = isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -2098,7 +2161,7 @@ namespace ts { else if (namespace === unknownSymbol) { return namespace; } - if (isInJavaScriptFile(name)) { + if (isInJSFile(name)) { if (namespace.valueDeclaration && isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -2134,16 +2197,16 @@ namespace ts { * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name: Identifier, meaning: SymbolFlags) { + function resolveEntityNameFromAssignmentDeclaration(name: Identifier, meaning: SymbolFlags) { if (isJSDocTypeReference(name.parent)) { - const secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + const secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node: TypeReferenceNode): Node | undefined { + function getAssignmentDeclarationLocation(node: TypeReferenceNode): Node | undefined { const typeAlias = findAncestor(node, node => !(isJSDocNode(node) || node.flags & NodeFlags.JSDoc) ? "quit" : isJSDocTypeAlias(node)); if (typeAlias) { return; @@ -2151,7 +2214,7 @@ namespace ts { const host = getJSDocHost(node); if (isExpressionStatement(host) && isBinaryExpression(host.expression) && - getSpecialPropertyAssignmentKind(host.expression) === SpecialPropertyAssignmentKind.PrototypeProperty) { + getAssignmentDeclarationKind(host.expression) === AssignmentDeclarationKind.PrototypeProperty) { // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration const symbol = getSymbolOfNode(host.expression.left); if (symbol) { @@ -2160,7 +2223,7 @@ namespace ts { } if ((isObjectLiteralMethod(host) || isPropertyAssignment(host)) && isBinaryExpression(host.parent.parent) && - getSpecialPropertyAssignmentKind(host.parent.parent) === SpecialPropertyAssignmentKind.Prototype) { + getAssignmentDeclarationKind(host.parent.parent) === AssignmentDeclarationKind.Prototype) { // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration const symbol = getSymbolOfNode(host.parent.parent.left); if (symbol) { @@ -2176,14 +2239,17 @@ namespace ts { function getDeclarationOfJSPrototypeContainer(symbol: Symbol) { const decl = symbol.parent!.valueDeclaration; - const initializer = isAssignmentDeclaration(decl) ? getAssignedJavascriptInitializer(decl) : - hasOnlyExpressionInitializer(decl) ? getDeclaredJavascriptInitializer(decl) : + if (!decl) { + return undefined; + } + const initializer = isAssignmentDeclaration(decl) ? getAssignedExpandoInitializer(decl) : + hasOnlyExpressionInitializer(decl) ? getDeclaredExpandoInitializer(decl) : undefined; return initializer || decl; } - function resolveExternalModuleName(location: Node, moduleReferenceExpression: Expression): Symbol | undefined { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, Diagnostics.Cannot_find_module_0); + function resolveExternalModuleName(location: Node, moduleReferenceExpression: Expression, ignoreErrors?: boolean): Symbol | undefined { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : Diagnostics.Cannot_find_module_0); } function resolveExternalModuleNameWorker(location: Node, moduleReferenceExpression: Expression, moduleNotFoundError: DiagnosticMessage | undefined, isForAugmentation = false): Symbol | undefined { @@ -2213,7 +2279,7 @@ namespace ts { const sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -2234,7 +2300,7 @@ namespace ts { } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { const diag = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -2267,7 +2333,7 @@ namespace ts { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - const tsExtension = tryExtractTypeScriptExtension(moduleReference); + const tsExtension = tryExtractTSExtension(moduleReference); if (tsExtension) { const diag = Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, removeExtension(moduleReference, tsExtension)); @@ -2292,12 +2358,12 @@ namespace ts { ? chainDiagnosticMessages( /*details*/ undefined, Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, - packageId.name, getMangledNameForScopedPackage(packageId.name)) + packageId.name, mangleScopedPackageName(packageId.name)) : chainDiagnosticMessages( /*details*/ undefined, Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, - getMangledNameForScopedPackage(packageId.name)) + mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, chainDiagnosticMessages( errorInfo, @@ -2312,11 +2378,16 @@ namespace ts { function resolveExternalModuleSymbol(moduleSymbol: Symbol, dontResolveAlias?: boolean): Symbol; function resolveExternalModuleSymbol(moduleSymbol: Symbol | undefined, dontResolveAlias?: boolean): Symbol | undefined; function resolveExternalModuleSymbol(moduleSymbol: Symbol, dontResolveAlias?: boolean): Symbol { - return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports!.get(InternalSymbolName.ExportEquals), dontResolveAlias), moduleSymbol)) || moduleSymbol; + if (moduleSymbol) { + const exportEquals = resolveSymbol(moduleSymbol.exports!.get(InternalSymbolName.ExportEquals), dontResolveAlias); + const exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined!; } function getCommonJsExportEquals(exported: Symbol | undefined, moduleSymbol: Symbol): Symbol | undefined { - if (!exported || moduleSymbol.exports!.size === 1) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports!.size === 1 || exported.flags & SymbolFlags.Alias) { return exported; } const merged = cloneSymbol(exported); @@ -2336,11 +2407,18 @@ namespace ts { // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol: Symbol | undefined, referencingLocation: Node, dontResolveAlias: boolean): Symbol | undefined { const symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); + if (!dontResolveAlias && symbol) { if (!(symbol.flags & (SymbolFlags.Module | SymbolFlags.Variable)) && !getDeclarationOfKind(symbol, SyntaxKind.SourceFile)) { - error(referencingLocation, Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol!)); + const compilerOptionName = moduleKind >= ModuleKind.ES2015 + ? "allowSyntheticDefaultImports" + : "esModuleInterop"; + + error(referencingLocation, Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); + return symbol; } + if (compilerOptions.esModuleInterop) { const referenceParent = referencingLocation.parent; if ( @@ -2528,6 +2606,44 @@ namespace ts { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + function getAlternativeContainingModules(symbol: Symbol, enclosingDeclaration: Node): Symbol[] { + const containingFile = getSourceFileOfNode(enclosingDeclaration); + const id = "" + getNodeId(containingFile); + const links = getSymbolLinks(symbol); + let results: Symbol[] | undefined; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + // Try to make an import using an import already in the enclosing file, if possible + for (const importRef of containingFile.imports) { + if (nodeIsSynthesized(importRef)) continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error + const resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true); + if (!resolvedModule) continue; + const ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) continue; + results = append(results, resolvedModule); + } + if (length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = createMap())).set(id, results!); + return results!; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached) + const otherFiles = host.getSourceFiles(); + for (const file of otherFiles) { + if (!isExternalModule(file)) continue; + const sym = getSymbolOfNode(file); + const ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) continue; + results = append(results, sym); + } + return links.extendedContainers = results || emptyArray; + } + /** * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` @@ -2536,10 +2652,12 @@ namespace ts { const container = getParentOfSymbol(symbol); if (container) { const additionalContainers = mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + const reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, SymbolFlags.Namespace, /*externalOnly*/ false)) { - return concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + return concatenate(concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope } - return append(additionalContainers, container); + const res = append(additionalContainers, container); + return concatenate(res, reexportContainers); } const candidates = mapDefined(symbol.declarations, d => !isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined); if (!length(candidates)) { @@ -2633,6 +2751,12 @@ namespace ts { return getUnionType(arrayFrom(typeofEQFacts.keys(), getLiteralType)); } + function createTypeParameter(symbol?: Symbol) { + const type = createType(TypeFlags.TypeParameter); + if (symbol) type.symbol = symbol; + return type; + } + // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started // with at least two underscores. The @ character indicates that the name is denoted by a well known ES @@ -3043,6 +3167,9 @@ namespace ts { if (flags & SymbolFormatFlags.UseAliasDefinedOutsideCurrentScope) { nodeFlags |= NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope; } + if (flags & SymbolFormatFlags.DoNotIncludeSymbolChain) { + nodeFlags |= NodeBuilderFlags.DoNotIncludeSymbolChain; + } const builder = flags & SymbolFormatFlags.AllowAnyNodeKind ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); @@ -3069,7 +3196,7 @@ namespace ts { const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName); const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(EmitHint.Unspecified, sig!, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 + printer.writeNode(EmitHint.Unspecified, sig!, /*sourceFile*/ sourceFile, getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217 return writer; } } @@ -3120,9 +3247,15 @@ namespace ts { const context: NodeBuilderContext = { enclosingDeclaration, flags: flags || NodeBuilderFlags.None, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: noop, moduleResolverHost: flags! & NodeBuilderFlags.DoNotIncludeSymbolChain ? { + getCommonSourceDirectory: (host as Program).getCommonSourceDirectory ? () => (host as Program).getCommonSourceDirectory() : () => "", + getSourceFiles: () => host.getSourceFiles(), + getCurrentDirectory: host.getCurrentDirectory && (() => host.getCurrentDirectory!()) + } : undefined }, encounteredError: false, - visitedSymbols: undefined, + visitedTypes: undefined, + symbolDepth: undefined, inferTypeParameters: undefined, approximateLength: 0 }; @@ -3162,21 +3295,27 @@ namespace ts { context.approximateLength += 6; return createKeywordTypeNode(SyntaxKind.NumberKeyword); } + if (type.flags & TypeFlags.BigInt) { + context.approximateLength += 6; + return createKeywordTypeNode(SyntaxKind.BigIntKeyword); + } if (type.flags & TypeFlags.Boolean) { context.approximateLength += 7; return createKeywordTypeNode(SyntaxKind.BooleanKeyword); } if (type.flags & TypeFlags.EnumLiteral && !(type.flags & TypeFlags.Union)) { const parentSymbol = getParentOfSymbol(type.symbol)!; - const parentName = symbolToName(parentSymbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); - const enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : createQualifiedName(parentName, symbolName(type.symbol)); - context.approximateLength += symbolName(type.symbol).length; - return createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + const parentName = symbolToTypeNode(parentSymbol, context, SymbolFlags.Type); + const enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType( + parentName as TypeReferenceNode | ImportTypeNode, + createTypeReferenceNode(symbolName(type.symbol), /*typeArguments*/ undefined) + ); + return enumLiteralName; } if (type.flags & TypeFlags.EnumLike) { - const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); - context.approximateLength += symbolName(type.symbol).length; - return createTypeReferenceNode(name, /*typeArguments*/ undefined); + return symbolToTypeNode(type.symbol, context, SymbolFlags.Type); } if (type.flags & TypeFlags.StringLiteral) { context.approximateLength += ((type).value.length + 2); @@ -3186,6 +3325,10 @@ namespace ts { context.approximateLength += (("" + (type).value).length); return createLiteralTypeNode((createLiteral((type).value))); } + if (type.flags & TypeFlags.BigIntLiteral) { + context.approximateLength += (pseudoBigIntToString((type).value).length) + 1; + return createLiteralTypeNode((createLiteral((type).value))); + } if (type.flags & TypeFlags.BooleanLiteral) { context.approximateLength += (type).intrinsicName.length; return (type).intrinsicName === "true" ? createTrue() : createFalse(); @@ -3273,6 +3416,9 @@ namespace ts { } if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { const types = type.flags & TypeFlags.Union ? formatUnionTypes((type).types) : (type).types; + if (length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } const typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { const unionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode(type.flags & TypeFlags.Union ? SyntaxKind.UnionType : SyntaxKind.IntersectionType, typeNodes); @@ -3340,12 +3486,13 @@ namespace ts { } function createAnonymousTypeNode(type: ObjectType): TypeNode { + const typeId = "" + type.id; const symbol = type.symbol; let id: string; if (symbol) { const isConstructorObject = getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & SymbolFlags.Class; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. const isInstanceType = type === getInferredClassType(symbol) ? SymbolFlags.Type : SymbolFlags.Value; return symbolToTypeNode(symbol, context, isInstanceType); @@ -3356,7 +3503,7 @@ namespace ts { shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, SymbolFlags.Value); } - else if (context.visitedSymbols && context.visitedSymbols.has(id)) { + else if (context.visitedTypes && context.visitedTypes.has(typeId)) { // If type is an anonymous type literal in a type alias declaration, use type alias name const typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { @@ -3364,20 +3511,28 @@ namespace ts { return symbolToTypeNode(typeAlias, context, SymbolFlags.Type); } else { - context.approximateLength += 3; - return createKeywordTypeNode(SyntaxKind.AnyKeyword); + return createElidedInformationPlaceholder(context); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.visitedSymbols) { - context.visitedSymbols = createMap(); + if (!context.visitedTypes) { + context.visitedTypes = createMap(); + } + if (!context.symbolDepth) { + context.symbolDepth = createMap(); } - context.visitedSymbols.set(id, true); + const depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + context.visitedTypes.set(typeId, true); const result = createTypeNodeFromObjectType(type); - context.visitedSymbols.delete(id); + context.visitedTypes.delete(typeId); + context.symbolDepth.set(id, depth); return result; } } @@ -3394,7 +3549,7 @@ namespace ts { declaration.parent.kind === SyntaxKind.SourceFile || declaration.parent.kind === SyntaxKind.ModuleBlock)); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & NodeBuilderFlags.UseTypeOfFunction) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively + return (!!(context.flags & NodeBuilderFlags.UseTypeOfFunction) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively (!(context.flags & NodeBuilderFlags.UseStructuralFallback) || isValueSymbolAccessible(symbol, context.enclosingDeclaration!)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } @@ -3451,8 +3606,8 @@ namespace ts { const arity = getTypeReferenceArity(type); const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); const hasRestElement = (type.target).hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (let i = (type.target).minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (let i = (type.target).minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? createRestTypeNode(createArrayTypeNode(tupleConstituentNodes[i])) : createOptionalTypeNode(tupleConstituentNodes[i]); @@ -3564,10 +3719,15 @@ namespace ts { typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructSignature, context)); } if (resolvedType.stringIndexInfo) { - const indexInfo = resolvedType.objectFlags & ObjectFlags.ReverseMapped ? - createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : - resolvedType.stringIndexInfo; - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, IndexKind.String, context)); + let indexSignature: IndexSignatureDeclaration; + if (resolvedType.objectFlags & ObjectFlags.ReverseMapped) { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), IndexKind.String, context); + indexSignature.type = createElidedInformationPlaceholder(context); + } + else { + indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, IndexKind.String, context); + } + typeElements.push(indexSignature); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, IndexKind.Number, context)); @@ -3601,8 +3761,17 @@ namespace ts { } } + function createElidedInformationPlaceholder(context: NodeBuilderContext) { + context.approximateLength += 3; + if (!(context.flags & NodeBuilderFlags.NoTruncation)) { + return createTypeReferenceNode(createIdentifier("..."), /*typeArguments*/ undefined); + } + return createKeywordTypeNode(SyntaxKind.AnyKeyword); + } + function addPropertyToElementList(propertySymbol: Symbol, context: NodeBuilderContext, typeElements: TypeElement[]) { - const propertyType = getCheckFlags(propertySymbol) & CheckFlags.ReverseMapped && context.flags & NodeBuilderFlags.InReverseMappedType ? + const propertyIsReverseMapped = !!(getCheckFlags(propertySymbol) & CheckFlags.ReverseMapped); + const propertyType = propertyIsReverseMapped && context.flags & NodeBuilderFlags.InReverseMappedType ? anyType : getTypeOfSymbol(propertySymbol); const saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; @@ -3631,8 +3800,14 @@ namespace ts { } else { const savedFlags = context.flags; - context.flags |= !!(getCheckFlags(propertySymbol) & CheckFlags.ReverseMapped) ? NodeBuilderFlags.InReverseMappedType : 0; - const propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : createKeywordTypeNode(SyntaxKind.AnyKeyword); + context.flags |= propertyIsReverseMapped ? NodeBuilderFlags.InReverseMappedType : 0; + let propertyTypeNode: TypeNode; + if (propertyIsReverseMapped && !!(savedFlags & NodeBuilderFlags.InReverseMappedType)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } + else { + propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : createKeywordTypeNode(SyntaxKind.AnyKeyword); + } context.flags = savedFlags; const modifiers = isReadonlySymbol(propertySymbol) ? [createToken(SyntaxKind.ReadonlyKeyword)] : undefined; @@ -3847,7 +4022,7 @@ namespace ts { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. let chain: Symbol[]; const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & NodeBuilderFlags.UseFullyQualifiedType) && !(context.flags & NodeBuilderFlags.DoNotIncludeSymbolChain)) { chain = Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); Debug.assert(chain && chain.length > 0); } @@ -3859,14 +4034,21 @@ namespace ts { /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol: Symbol, meaning: SymbolFlags, endOfChain: boolean): Symbol[] | undefined { let accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & NodeBuilderFlags.UseOnlyExternalAliasing)); - + let parentSpecifiers: (string | undefined)[]; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. const parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); if (length(parents)) { - for (const parent of parents!) { + parentSpecifiers = parents!.map(symbol => + some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) + ? getSpecifierForModuleSymbol(symbol, context) + : undefined); + const indices = parents!.map((_, i) => i); + indices.sort(sortByBestName); + const sortedParents = indices.map(i => parents![i]); + for (const parent of sortedParents) { const parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); @@ -3890,6 +4072,25 @@ namespace ts { } return [symbol]; } + + function sortByBestName(a: number, b: number) { + const specifierA = parentSpecifiers[a]; + const specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + const isBRelative = pathIsRelative(specifierB); + if (pathIsRelative(specifierA) === isBRelative) { + // Both relative or both non-relative, sort by number of parts + return moduleSpecifiers.countPathComponents(specifierA) - moduleSpecifiers.countPathComponents(specifierB); + } + if (isBRelative) { + // A is non-relative, B is relative: prefer A + return -1; + } + // A is relative, B is non-relative: prefer B + return 1; + } + return 0; + } } } @@ -3993,6 +4194,14 @@ namespace ts { const nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; const typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); const specifier = getSpecifierForModuleSymbol(chain[0], context); + if (!(context.flags & NodeBuilderFlags.AllowNodeModulesRelativePaths) && getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) { + // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error + // since declaration files with these kinds of references are liable to fail when published :( + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(specifier); + } + } const lit = createLiteralTypeNode(createLiteral(specifier)); if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); context.approximateLength += specifier.length + 10; // specifier + import("") @@ -4102,6 +4311,9 @@ namespace ts { function createExpressionFromSymbolChain(chain: Symbol[], index: number): Expression { const typeParameterNodes = lookupTypeParameterNodes(chain, index, context); const symbol = chain[index]; + if (some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= NodeBuilderFlags.InInitialEntityName; @@ -4167,7 +4379,7 @@ namespace ts { const baseType = t.flags & TypeFlags.BooleanLiteral ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & TypeFlags.Union) { const count = (baseType).types.length; - if (i + count <= types.length && types[i + count - 1] === (baseType).types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType((baseType).types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -4215,7 +4427,8 @@ namespace ts { // State encounteredError: boolean; - visitedSymbols: Map | undefined; + visitedTypes: Map | undefined; + symbolDepth: Map | undefined; inferTypeParameters: TypeParameter[] | undefined; approximateLength: number; truncating?: boolean; @@ -4225,6 +4438,22 @@ namespace ts { return location.kind === SyntaxKind.SourceFile || isAmbientModule(location); } + function getNameOfSymbolFromNameType(symbol: Symbol, context?: NodeBuilderContext) { + const nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & TypeFlags.StringOrNumberLiteral) { + const name = "" + (nameType).value; + if (!isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { + return `"${escapeString(name, CharacterCodes.doubleQuote)}"`; + } + return name; + } + if (nameType.flags & TypeFlags.UniqueESSymbol) { + return `[${getNameOfSymbolAsWritten((nameType).symbol, context)}]`; + } + } + } + /** * Gets a human-readable name for a symbol. * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. @@ -4246,6 +4475,16 @@ namespace ts { const declaration = symbol.declarations[0]; const name = getNameOfDeclaration(declaration); if (name) { + if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) { + return symbolName(symbol); + } + if (isComputedPropertyName(name) && !(getCheckFlags(symbol) & CheckFlags.Late) && symbol.nameType && symbol.nameType.flags & TypeFlags.StringOrNumberLiteral) { + // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name + const result = getNameOfSymbolFromNameType(symbol, context); + if (result !== undefined) { + return result; + } + } return declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { @@ -4261,16 +4500,8 @@ namespace ts { return declaration.kind === SyntaxKind.ClassExpression ? "(Anonymous class)" : "(Anonymous function)"; } } - const nameType = symbol.nameType; - if (nameType) { - if (nameType.flags & TypeFlags.StringLiteral && !isIdentifierText((nameType).value, compilerOptions.target)) { - return `"${escapeString((nameType).value, CharacterCodes.doubleQuote)}"`; - } - if (nameType && nameType.flags & TypeFlags.UniqueESSymbol) { - return `[${getNameOfSymbolAsWritten((nameType).symbol, context)}]`; - } - } - return symbolName(symbol); + const name = getNameOfSymbolFromNameType(symbol, context); + return name !== undefined ? name : symbolName(symbol); } function isDeclarationVisible(node: Node): boolean { @@ -4456,6 +4687,8 @@ namespace ts { switch (propertyName) { case TypeSystemPropertyName.Type: return !!getSymbolLinks(target).type; + case TypeSystemPropertyName.EnumTagType: + return !!(getNodeLinks(target as JSDocEnumTag).resolvedEnumType); case TypeSystemPropertyName.DeclaredType: return !!getSymbolLinks(target).declaredType; case TypeSystemPropertyName.ResolvedBaseConstructorType: @@ -4464,6 +4697,8 @@ namespace ts { return !!(target).resolvedReturnType; case TypeSystemPropertyName.ImmediateBaseConstraint: return !!(target).immediateBaseConstraint; + case TypeSystemPropertyName.JSDocTypeReference: + return !!getSymbolLinks(target as Symbol).resolvedJSDocType; } return Debug.assertNever(propertyName); } @@ -4507,6 +4742,10 @@ namespace ts { return prop ? getTypeOfSymbol(prop) : undefined; } + function getTypeOfPropertyOrIndexSignature(type: Type, name: __String): Type { + return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, IndexKind.Number) || getIndexTypeOfType(type, IndexKind.String) || unknownType; + } + function isTypeAny(type: Type | undefined) { return type && (type.flags & TypeFlags.Any) !== 0; } @@ -4527,21 +4766,28 @@ namespace ts { if (source.flags & TypeFlags.Never) { return emptyObjectType; } - if (source.flags & TypeFlags.Union) { return mapType(source, t => getRestType(t, properties, symbol)); } - - const members = createSymbolTable(); - const names = createUnderscoreEscapedMap(); - for (const name of properties) { - names.set(getTextOfPropertyName(name), true); + const omitKeyType = getUnionType(map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (omitKeyType.flags & TypeFlags.Never) { + return source; + } + const pickTypeAlias = getGlobalPickSymbol(); + const excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + const pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); } + const members = createSymbolTable(); for (const prop of getPropertiesOfType(source)) { - if (!names.has(prop.escapedName) + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, TypeFlags.StringOrNumberLiteralOrUnique), omitKeyType) && !(getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected)) && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getNonReadonlySymbol(prop)); + members.set(prop.escapedName, getSpreadSymbol(prop)); } } const stringIndexInfo = getIndexInfoOfType(source, IndexKind.String); @@ -4549,6 +4795,69 @@ namespace ts { return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); } + // Determine the control flow type associated with a destructuring declaration or assignment. The following + // forms of destructuring are possible: + // let { x } = obj; // BindingElement + // let [ x ] = obj; // BindingElement + // { x } = obj; // ShorthandPropertyAssignment + // { x: v } = obj; // PropertyAssignment + // [ x ] = obj; // Expression + // We construct a synthetic element access expression corresponding to 'obj.x' such that the control + // flow analyzer doesn't have to handle all the different syntactic forms. + function getFlowTypeOfDestructuring(node: BindingElement | PropertyAssignment | ShorthandPropertyAssignment | Expression, declaredType: Type) { + const reference = getSyntheticElementAccess(node); + return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType; + } + + function getSyntheticElementAccess(node: BindingElement | PropertyAssignment | ShorthandPropertyAssignment | Expression): ElementAccessExpression | undefined { + const parentAccess = getParentElementAccess(node); + if (parentAccess && parentAccess.flowNode) { + const propName = getDestructuringPropertyName(node); + if (propName) { + const result = createNode(SyntaxKind.ElementAccessExpression, node.pos, node.end); + result.parent = node; + result.expression = parentAccess; + const literal = createNode(SyntaxKind.StringLiteral, node.pos, node.end); + literal.parent = result; + literal.text = propName; + result.argumentExpression = literal; + result.flowNode = parentAccess.flowNode; + return result; + } + } + } + + function getParentElementAccess(node: BindingElement | PropertyAssignment | ShorthandPropertyAssignment | Expression) { + const ancestor = node.parent.parent; + switch (ancestor.kind) { + case SyntaxKind.BindingElement: + case SyntaxKind.PropertyAssignment: + return getSyntheticElementAccess(ancestor); + case SyntaxKind.ArrayLiteralExpression: + return getSyntheticElementAccess(node.parent); + case SyntaxKind.VariableDeclaration: + return (ancestor).initializer; + case SyntaxKind.BinaryExpression: + return (ancestor).right; + } + } + + function getDestructuringPropertyName(node: BindingElement | PropertyAssignment | ShorthandPropertyAssignment | Expression) { + const parent = node.parent; + if (node.kind === SyntaxKind.BindingElement && parent.kind === SyntaxKind.ObjectBindingPattern) { + return getLiteralPropertyNameText((node).propertyName || (node).name); + } + if (node.kind === SyntaxKind.PropertyAssignment || node.kind === SyntaxKind.ShorthandPropertyAssignment) { + return getLiteralPropertyNameText((node).name); + } + return "" + (>(parent).elements).indexOf(node); + } + + function getLiteralPropertyNameText(name: PropertyName) { + const type = getLiteralTypeFromPropertyName(name); + return type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral) ? "" + (type).value : undefined; + } + /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration: BindingElement): Type | undefined { const pattern = declaration.parent; @@ -4566,6 +4875,10 @@ namespace ts { if (isTypeAny(parentType)) { return parentType; } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & NodeFlags.Ambient && isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } let type: Type | undefined; if (pattern.kind === SyntaxKind.ObjectBindingPattern) { @@ -4585,53 +4898,9 @@ namespace ts { else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) const name = declaration.propertyName || declaration.name; - const isLate = isLateBindableName(name); - const isWellKnown = isComputedPropertyName(name) && isWellKnownSymbolSyntactically(name.expression); - if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { - const exprType = checkExpression((name as ComputedPropertyName).expression); - if (isTypeAssignableToKind(exprType, TypeFlags.ESSymbolLike)) { - if (noImplicitAny) { - error(declaration, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); - } - return anyType; - } - const indexerType = isTypeAssignableToKind(exprType, TypeFlags.NumberLike) && getIndexTypeOfType(parentType, IndexKind.Number) || getIndexTypeOfType(parentType, IndexKind.String); - if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(parentType, IndexKind.Number)) { - error(declaration, Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(declaration, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType)); - } - } - return indexerType || 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. - const nameType = isLate ? checkComputedPropertyName(name as ComputedPropertyName) as LiteralType | UniqueESSymbolType : undefined; - const text = isLate ? getLateBoundNameFromType(nameType!) : - isWellKnown ? getPropertyNameForKnownSymbolName(idText(((name as ComputedPropertyName).expression as PropertyAccessExpression).name)) : - getTextOfPropertyName(name); - - // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation - if (strictNullChecks && declaration.flags & NodeFlags.Ambient && isParameterDeclaration(declaration)) { - parentType = getNonNullableType(parentType); - } - if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, TypeFlags.ESSymbolLike)) { - if (noImplicitAny) { - error(declaration, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType)); - } - return anyType; - } - const declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); - type = declaredType && getFlowTypeOfReference(declaration, declaredType) || - 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)); - return errorType; - } + const indexType = getLiteralTypeFromPropertyName(name); + const declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); } } else { @@ -4641,37 +4910,29 @@ namespace ts { const elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); const index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, t => sliceTupleType(t, index)) : createArrayType(elementType); } + else if (isArrayLikeType(parentType)) { + const indexType = getLiteralType(index); + const declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, declaration.name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); + } else { - // Use specific property type when parent is a tuple or numeric index type when parent is an array - const index = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index) || declaration.initializer && checkDeclarationInitializer(declaration) : - elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index); - } - return errorType; - } + type = 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 && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & TypeFlags.Undefined)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & TypeFlags.Undefined)) { type = getTypeWithFacts(type, TypeFacts.NEUndefined); } return declaration.initializer && !getEffectiveTypeAnnotationNode(walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], UnionReduction.Subtype) : + getUnionType([type, checkDeclarationInitializer(declaration)], UnionReduction.Subtype) : type; } @@ -4702,7 +4963,7 @@ namespace ts { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === SyntaxKind.ForInStatement) { - const indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + const indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); return indexType.flags & (TypeFlags.TypeParameter | TypeFlags.Index) ? getExtractStringType(indexType) : stringType; } @@ -4729,7 +4990,7 @@ namespace ts { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || isInJavaScriptFile(declaration)) && + if ((noImplicitAny || isInJSFile(declaration)) && declaration.kind === SyntaxKind.VariableDeclaration && !isBindingPattern(declaration.name) && !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -4761,7 +5022,7 @@ namespace ts { return getReturnTypeOfSignature(getterSignature); } } - if (isInJavaScriptFile(declaration)) { + if (isInJSFile(declaration)) { const typeTag = getJSDocType(func); if (typeTag && isFunctionTypeNode(typeTag)) { return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); @@ -4773,10 +5034,10 @@ namespace ts { return addOptionality(type, isOptional); } } - else if (isInJavaScriptFile(declaration)) { - const expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (isInJSFile(declaration)) { + const containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } @@ -4801,31 +5062,31 @@ namespace ts { return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol: Symbol, resolvedSymbol?: Symbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - const specialDeclaration = getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - const tag = getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol: Symbol, resolvedSymbol?: Symbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + const container = getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + const tag = getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - const expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + const containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } let definedInConstructor = false; let definedInMethod = false; let jsdocType: Type | undefined; let types: Type[] | undefined; for (const declaration of symbol.declarations) { - const expression = isBinaryExpression(declaration) ? declaration : + const expression = (isBinaryExpression(declaration) || isCallExpression(declaration)) ? declaration : isPropertyAccessExpression(declaration) ? isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { return errorType; } - const special = isPropertyAccessExpression(expression) ? getSpecialPropertyAccessKind(expression) : getSpecialPropertyAssignmentKind(expression); - if (special === SpecialPropertyAssignmentKind.ThisProperty) { + const kind = isPropertyAccessExpression(expression) ? getAssignmentDeclarationPropertyAccessKind(expression) : getAssignmentDeclarationKind(expression); + if (kind === AssignmentDeclarationKind.ThisProperty) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -4833,9 +5094,11 @@ namespace ts { definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } if (!jsdocType) { - (types || (types = [])).push(isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push((isBinaryExpression(expression) || isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } let type = jsdocType; @@ -4843,7 +5106,7 @@ namespace ts { let constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types!, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - const propType = getTypeOfSpecialPropertyOfBaseType(symbol); + const propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -4854,16 +5117,14 @@ namespace ts { } const widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, t => !!(t.flags & ~TypeFlags.Nullable)) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl: Node, symbol: Symbol, init: Expression | undefined): Type | undefined { - if (!isInJavaScriptFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl: Node, symbol: Symbol, init: Expression | undefined): Type | undefined { + if (!isInJSFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) { return undefined; } const exports = createSymbolTable(); @@ -4883,7 +5144,7 @@ namespace ts { return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType: Type | undefined, expression: Expression, _symbol: Symbol, declaration: Declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType: Type | undefined, expression: Expression, _symbol: Symbol, declaration: Declaration) { const typeNode = getJSDocType(expression.parent); if (typeNode) { const type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -4898,10 +5159,35 @@ namespace ts { } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol: Symbol, resolvedSymbol: Symbol | undefined, expression: BinaryExpression, special: SpecialPropertyAssignmentKind) { + function getInitializerTypeFromAssignmentDeclaration(symbol: Symbol, resolvedSymbol: Symbol | undefined, expression: BinaryExpression | CallExpression, kind: AssignmentDeclarationKind) { + if (isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + const objectLitType = checkExpressionCached((expression as BindableObjectDefinePropertyCall).arguments[2]); + const valueType = getTypeOfPropertyOfType(objectLitType, "value" as __String); + if (valueType) { + return valueType; + } + const getFunc = getTypeOfPropertyOfType(objectLitType, "get" as __String); + if (getFunc) { + const getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + const setFunc = getTypeOfPropertyOfType(objectLitType, "set" as __String); + if (setFunc) { + const setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } const type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & TypeFlags.Object && - special === SpecialPropertyAssignmentKind.ModuleExports && + kind === AssignmentDeclarationKind.ModuleExports && symbol.escapedName === InternalSymbolName.ExportEquals) { const exportedType = resolveStructuredTypeMembers(type as ObjectType); const members = createSymbolTable(); @@ -4931,9 +5217,7 @@ namespace ts { return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -4959,8 +5243,8 @@ namespace ts { } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty: Symbol) { - const parentDeclaration = forEach(specialProperty.declarations, d => { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property: Symbol) { + const parentDeclaration = forEach(property.declarations, d => { const parent = getThisContainer(d, /*includeArrowFunctions*/ false).parent; return isClassLike(parent) && parent; }); @@ -4968,7 +5252,7 @@ namespace ts { const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)) as InterfaceType; const baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -4983,8 +5267,8 @@ namespace ts { if (isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -5084,9 +5368,9 @@ namespace ts { type = isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -5131,29 +5415,32 @@ namespace ts { return anyType; } // Handle export default expressions - if (isSourceFile(declaration)) { - const jsonSourceFile = cast(declaration, isJsonSourceFile); - if (!jsonSourceFile.statements.length) { + if (isSourceFile(declaration) && isJsonSourceFile(declaration)) { + if (!declaration.statements.length) { return emptyObjectType; } - const type = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + const type = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); if (type.flags & TypeFlags.Object) { return getRegularTypeOfObjectLiteral(type); } return type; } if (declaration.kind === SyntaxKind.ExportAssignment) { - return checkExpression((declaration).expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached((declaration).expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & SymbolFlags.ValueModule) { + return getTypeOfFuncClassEnumModule(symbol); + } return errorType; } let type: Type | undefined; - if (isInJavaScriptFile(declaration) && - (isBinaryExpression(declaration) || isPropertyAccessExpression(declaration) && isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + if (isInJSFile(declaration) && + (isCallExpression(declaration) || isBinaryExpression(declaration) || isPropertyAccessExpression(declaration) && isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (isJSDocPropertyLikeTag(declaration) || isPropertyAccessExpression(declaration) @@ -5161,13 +5448,14 @@ namespace ts { || isClassDeclaration(declaration) || isFunctionDeclaration(declaration) || (isMethodDeclaration(declaration) && !isObjectLiteralMethod(declaration)) - || isMethodSignature(declaration)) { + || isMethodSignature(declaration) + || isSourceFile(declaration)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)) { return getTypeOfFuncClassEnumModule(symbol); } type = isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (isPropertyAssignment(declaration)) { @@ -5189,11 +5477,23 @@ namespace ts { || isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } else { return Debug.fail("Unhandled declaration kind! " + Debug.showSyntaxKind(declaration) + " for " + Debug.showSymbol(symbol)); } if (!popTypeResolution()) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & SymbolFlags.ValueModule) { + return getTypeOfFuncClassEnumModule(symbol); + } type = reportCircularityError(symbol); } return type; @@ -5236,7 +5536,7 @@ namespace ts { const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); - if (getter && isInJavaScriptFile(getter)) { + if (getter && isInJSFile(getter)) { const jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -5267,14 +5567,12 @@ namespace ts { } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter!, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -5299,7 +5597,7 @@ namespace ts { let links = getSymbolLinks(symbol); const originalLinks = links; if (!links.type) { - const jsDeclaration = getDeclarationOfJSInitializer(symbol.valueDeclaration); + const jsDeclaration = getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { const jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (hasEntries(jsSymbol.exports) || hasEntries(jsSymbol.members))) { @@ -5328,7 +5626,7 @@ namespace ts { } else if (declaration.kind === SyntaxKind.BinaryExpression || declaration.kind === SyntaxKind.PropertyAccessExpression && declaration.parent.kind === SyntaxKind.BinaryExpression) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & SymbolFlags.ValueModule && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) { const resolvedModule = resolveExternalModuleSymbol(symbol); @@ -5337,7 +5635,7 @@ namespace ts { return errorType; } const exportEquals = getMergedSymbol(symbol.exports!.get(InternalSymbolName.ExportEquals)!); - const type = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + const type = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } @@ -5557,7 +5855,7 @@ namespace ts { const constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type: InterfaceType): ExpressionWithTypeArguments | undefined { @@ -5566,10 +5864,7 @@ namespace ts { function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { const typeArgCount = length(typeArgumentNodes); - const isJavascript = isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, SignatureKind.Call); - } + const isJavascript = isInJSFile(location); return filter(getSignaturesOfType(type, SignatureKind.Construct), sig => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); } @@ -5577,7 +5872,7 @@ namespace ts { function getInstantiatedConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { const signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); - return sameMap(signatures, sig => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJavaScriptFile(location)) : sig); + return sameMap(signatures, sig => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJSFile(location)) : sig); } /** @@ -5614,7 +5909,18 @@ namespace ts { return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & TypeFlags.Any) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + const err = error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & TypeFlags.TypeParameter) { + const constraint = getConstraintFromTypeParameter(baseConstructorType); + let ctorReturn: Type = unknownType; + if (constraint) { + const ctorSig = getSignaturesOfType(constraint, SignatureKind.Construct); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } return type.resolvedBaseConstructorType = errorType; } type.resolvedBaseConstructorType = baseConstructorType; @@ -5651,7 +5957,9 @@ namespace ts { const baseTypeNode = getBaseTypeNodeOfClass(type)!; const typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); let baseType: Type; - const originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + const originalBaseType = isJSConstructorType(baseConstructorType) ? 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 @@ -5662,8 +5970,8 @@ namespace ts { else if (baseConstructorType.flags & TypeFlags.Any) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -5681,7 +5989,7 @@ namespace ts { return type.resolvedBaseTypes = emptyArray; } if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + error(baseTypeNode.expression, Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); return type.resolvedBaseTypes = emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { @@ -5739,7 +6047,7 @@ namespace ts { } } else { - error(node, Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + error(node, Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -5797,9 +6105,8 @@ namespace ts { (type).instantiations.set(getTypeListId(type.typeParameters), type); (type).target = type; (type).typeArguments = type.typeParameters; - type.thisType = createType(TypeFlags.TypeParameter); + type.thisType = createTypeParameter(symbol); type.thisType.isThisType = true; - type.thisType.symbol = symbol; type.thisType.constraint = type; } } @@ -5907,9 +6214,9 @@ namespace ts { for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.EnumDeclaration) { for (const member of (declaration).members) { - const memberType = getLiteralType(getEnumMemberValue(member)!, enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + const memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member)!, enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -5940,20 +6247,12 @@ namespace ts { function getDeclaredTypeOfTypeParameter(symbol: Symbol): TypeParameter { const links = getSymbolLinks(symbol); - if (!links.declaredType) { - const type = createType(TypeFlags.TypeParameter); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; + return links.declaredType || (links.declaredType = createTypeParameter(symbol)); } function getDeclaredTypeOfAlias(symbol: Symbol): Type { const links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; + return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol))); } function getDeclaredTypeOfSymbol(symbol: Symbol): Type { @@ -5993,6 +6292,7 @@ namespace ts { case SyntaxKind.UnknownKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.ObjectKeyword: @@ -6154,7 +6454,7 @@ namespace ts { if (type.flags & TypeFlags.UniqueESSymbol) { return `__@${type.symbol.escapedName}@${getSymbolId(type.symbol)}` as __String; } - if (type.flags & TypeFlags.StringOrNumberLiteral) { + if (type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { return escapeLeadingUnderscores("" + (type).value); } return Debug.fail(); @@ -6453,7 +6753,7 @@ namespace ts { return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } const baseTypeNode = getBaseTypeNodeOfClass(classType)!; - const isJavaScript = isInJavaScriptFile(baseTypeNode); + const isJavaScript = isInJSFile(baseTypeNode); const typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); const typeArgCount = length(typeArguments); const result: Signature[] = []; @@ -6472,7 +6772,7 @@ namespace ts { function findMatchingSignature(signatureList: ReadonlyArray, signature: Signature, partialMatch: boolean, ignoreThisTypes: boolean, ignoreReturnTypes: boolean): Signature | undefined { for (const s of signatureList) { - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { return s; } } @@ -6508,10 +6808,14 @@ namespace ts { // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional // parameters and may differ in return types. When signatures differ in return types, the resulting return // type is the union of the constituent return types. - function getUnionSignatures(types: ReadonlyArray, kind: SignatureKind): Signature[] { - const signatureLists = map(types, t => getSignaturesOfType(t, kind)); + function getUnionSignatures(signatureLists: ReadonlyArray>): Signature[] { let result: Signature[] | undefined; + let indexWithLengthOverOne: number | undefined; for (let i = 0; i < signatureLists.length; i++) { + if (signatureLists[i].length === 0) return emptyArray; + if (signatureLists[i].length > 1) { + indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets + } for (const signature of signatureLists[i]) { // Only process signatures with parameter lists that aren't already in the result list if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { @@ -6535,9 +6839,91 @@ namespace ts { } } } + if (!length(result) && indexWithLengthOverOne !== -1) { + // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single + // signature that handles all over them. We only do this when there are overloads in only one constituent. + // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of + // signatures from the type, whose ordering would be non-obvious) + const masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; + let results: Signature[] | undefined = masterList.slice(); + for (const signatures of signatureLists) { + if (signatures !== masterList) { + const signature = signatures[0]; + Debug.assert(!!signature, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); + results = signature.typeParameters && some(results, s => !!s.typeParameters) ? undefined : map(results, sig => combineSignaturesOfUnionMembers(sig, signature)); + if (!results) { + break; + } + } + } + result = results; + } return result || emptyArray; } + function combineUnionThisParam(left: Symbol | undefined, right: Symbol | undefined): Symbol | undefined { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // permissive when calling, for now, we'll union the `this` types just like the overlapping-union-signature check does + const thisType = getUnionType([getTypeOfSymbol(left), getTypeOfSymbol(right)], UnionReduction.Subtype); + return createSymbolWithType(left, thisType); + } + + function combineUnionParameters(left: Signature, right: Signature) { + const longest = getParameterCount(left) >= getParameterCount(right) ? left : right; + const shorter = longest === left ? right : left; + const longestCount = getParameterCount(longest); + const eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (let i = 0; i < longestCount; i++) { + const longestParamType = tryGetTypeAtPosition(longest, i)!; + const shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + const unionParamType = getIntersectionType([longestParamType, shorterParamType]); + const isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + const isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + const leftName = getParameterNameAtPosition(left, i); + const rightName = getParameterNameAtPosition(right, i); + const paramSymbol = createSymbol( + SymbolFlags.FunctionScopedVariable | (isOptional && !isRestParam ? SymbolFlags.Optional : 0), + leftName === rightName ? leftName : `arg${i}` as __String + ); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + const restParamSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, "args" as __String); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + params[longestCount] = restParamSymbol; + } + return params; + } + + function combineSignaturesOfUnionMembers(left: Signature, right: Signature): Signature { + const declaration = left.declaration; + const params = combineUnionParameters(left, right); + const thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); + const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + const hasRestParam = left.hasRestParameter || right.hasRestParameter; + const hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; + const result = createSignature( + declaration, + left.typeParameters || right.typeParameters, + thisParam, + params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, + minArgCount, + hasRestParam, + hasLiteralTypes + ); + result.unionSignatures = concatenate(left.unionSignatures || [left], [right]); + return result; + } + function getUnionIndexInfo(types: ReadonlyArray, kind: IndexKind): IndexInfo | undefined { const indexTypes: Type[] = []; let isAnyReadonly = false; @@ -6555,8 +6941,8 @@ namespace ts { function resolveUnionTypeMembers(type: UnionType) { // 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). - const callSignatures = getUnionSignatures(type.types, SignatureKind.Call); - const constructSignatures = getUnionSignatures(type.types, SignatureKind.Construct); + const callSignatures = getUnionSignatures(map(type.types, t => t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, SignatureKind.Call))); + const constructSignatures = getUnionSignatures(map(type.types, t => getSignaturesOfType(t, SignatureKind.Construct))); const stringIndexInfo = getUnionIndexInfo(type.types, IndexKind.String); const numberIndexInfo = getUnionIndexInfo(type.types, IndexKind.Number); setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -6675,6 +7061,7 @@ namespace ts { // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = filter(type.callSignatures, sig => isJSConstructor(sig.declaration)); } // And likewise for construct signatures for classes if (symbol.flags & SymbolFlags.Class) { @@ -6693,7 +7080,7 @@ namespace ts { const modifiers = getMappedTypeModifiers(type.mappedType); const readonlyMask = modifiers & MappedTypeModifiers.IncludeReadonly ? false : true; const optionalMask = modifiers & MappedTypeModifiers.IncludeOptional ? 0 : SymbolFlags.Optional; - const stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + const stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); const members = createSymbolTable(); for (const prop of getPropertiesOfType(type.source)) { const checkFlags = CheckFlags.ReverseMapped | (readonlyMask && isReadonlySymbol(prop) ? CheckFlags.Readonly : 0); @@ -6702,11 +7089,45 @@ namespace ts { inferredProp.nameType = prop.nameType; inferredProp.propertyType = getTypeOfSymbol(prop); inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); } + // Return the lower bound of the key type in a mapped type. Intuitively, the lower + // bound includes those keys that are known to always be present, for example because + // because of constraints on type parameters (e.g. 'keyof T' for a constrained T). + function getLowerBoundOfKeyType(type: Type): Type { + if (type.flags & (TypeFlags.Any | TypeFlags.Primitive)) { + return type; + } + if (type.flags & TypeFlags.Index) { + return getIndexType(getApparentType((type).type)); + } + if (type.flags & TypeFlags.Conditional) { + return getLowerBoundOfConditionalType(type); + } + if (type.flags & TypeFlags.Union) { + return getUnionType(sameMap((type).types, getLowerBoundOfKeyType)); + } + if (type.flags & TypeFlags.Intersection) { + return getIntersectionType(sameMap((type).types, getLowerBoundOfKeyType)); + } + return neverType; + } + + function getLowerBoundOfConditionalType(type: ConditionalType) { + if (type.root.isDistributive) { + const constraint = getLowerBoundOfKeyType(type.checkType); + if (constraint !== type.checkType) { + const mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } + /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type: MappedType) { const members: SymbolTable = createSymbolTable(); @@ -6725,7 +7146,7 @@ namespace ts { if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (const prop of getPropertiesOfType(modifiersType)) { - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); } if (modifiersType.flags & TypeFlags.Any || getIndexInfoOfType(modifiersType, IndexKind.String)) { addMemberForKeyType(stringType); @@ -6735,12 +7156,7 @@ namespace ts { } } else { - // First, if the constraint type is a type parameter, obtain the base constraint. Then, - // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Finally, iterate over the constituents of the resulting iteration type. - const keyType = constraintType.flags & TypeFlags.InstantiableNonPrimitive ? getApparentType(constraintType) : constraintType; - const iterationType = keyType.flags & TypeFlags.Index ? getIndexType(getApparentType((keyType).type)) : keyType; - forEachType(iterationType, addMemberForKeyType); + forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType); } setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); @@ -6789,7 +7205,7 @@ namespace ts { function getConstraintTypeFromMappedType(type: MappedType) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type: MappedType) { @@ -6935,11 +7351,12 @@ namespace ts { getPropertiesOfObjectType(type); } - function isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression): boolean { - return obj.properties.some(property => { + function isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes): boolean { + const list = obj.properties as NodeArray; + return list.some(property => { const name = property.name && getTextOfPropertyName(property.name); const expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } @@ -6988,7 +7405,11 @@ namespace ts { function getDefaultConstraintOfConditionalType(type: ConditionalType) { if (!type.resolvedDefaultConstraint) { const rootTrueType = type.root.trueType; - const rootTrueConstraint = rootTrueType.flags & TypeFlags.Substitution ? (rootTrueType).substitute : rootTrueType; + const rootTrueConstraint = !(rootTrueType.flags & TypeFlags.Substitution) + ? rootTrueType + : ((rootTrueType).substitute).flags & TypeFlags.AnyOrUnknown + ? (rootTrueType).typeVariable + : getIntersectionType([(rootTrueType).substitute, (rootTrueType).typeVariable]); type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); } return type.resolvedDefaultConstraint; @@ -7003,7 +7424,7 @@ namespace ts { if (type.root.isDistributive) { const simplified = getSimplifiedType(type.checkType); const constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; - if (constraint) { + if (constraint && constraint !== type.checkType) { const mapper = makeUnaryTypeMapper(type.root.checkType, constraint); const instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & TypeFlags.Never)) { @@ -7236,6 +7657,7 @@ namespace ts { t.flags & TypeFlags.Intersection ? getApparentTypeOfIntersectionType(t) : t.flags & TypeFlags.StringLike ? globalStringType : t.flags & TypeFlags.NumberLike ? globalNumberType : + t.flags & TypeFlags.BigIntLike ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= ScriptTarget.ESNext) : t.flags & TypeFlags.BooleanLike ? globalBooleanType : t.flags & TypeFlags.ESSymbolLike ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= ScriptTarget.ES2015) : t.flags & TypeFlags.NonPrimitive ? emptyObjectType : @@ -7270,10 +7692,10 @@ namespace ts { } } else if (isUnion) { - const index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, IndexKind.Number)) || getIndexInfoOfType(type, IndexKind.String)); - if (index) { - checkFlags |= index.isReadonly ? CheckFlags.Readonly : 0; - indexTypes = append(indexTypes, index.type); + const indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, IndexKind.Number) || getIndexInfoOfType(type, IndexKind.String)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? CheckFlags.Readonly : 0; + indexTypes = append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= CheckFlags.Partial; @@ -7288,39 +7710,44 @@ namespace ts { return props[0]; } let declarations: Declaration[] | undefined; - let commonType: Type | undefined; + let firstType: Type | undefined; let nameType: Type | undefined; const propTypes: Type[] = []; - let first = true; - let commonValueDeclaration: Declaration | undefined; + let firstValueDeclaration: Declaration | undefined; let hasNonUniformValueDeclaration = false; for (const prop of props) { - if (!commonValueDeclaration) { - commonValueDeclaration = prop.valueDeclaration; + if (!firstValueDeclaration) { + firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== commonValueDeclaration) { + else if (prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = addRange(declarations, prop.declarations); const type = getTypeOfSymbol(prop); - if (first) { - commonType = type; + if (!firstType) { + firstType = type; nameType = prop.nameType; - first = false; } - else { - if (type !== commonType) { - checkFlags |= CheckFlags.HasNonUniformType; - } + else if (type !== firstType) { + checkFlags |= CheckFlags.HasNonUniformType; + } + if (isLiteralType(type)) { + checkFlags |= CheckFlags.HasLiteralType; } propTypes.push(type); } addRange(propTypes, indexTypes); const result = createSymbol(SymbolFlags.Property | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; - if (!hasNonUniformValueDeclaration && commonValueDeclaration) { - result.valueDeclaration = commonValueDeclaration; + if (!hasNonUniformValueDeclaration && firstValueDeclaration) { + result.valueDeclaration = firstValueDeclaration; + + // Inherit information about parent type. + if (firstValueDeclaration.symbol.parent) { + result.parent = firstValueDeclaration.symbol.parent; + } } + result.declarations = declarations!; result.nameType = nameType; result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -7366,8 +7793,12 @@ namespace ts { if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - const symbol = getPropertyOfObjectType(globalFunctionType, name); + const functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + const symbol = getPropertyOfObjectType(functionType, name); if (symbol) { return symbol; } @@ -7456,7 +7887,7 @@ namespace ts { } function isJSDocOptionalParameter(node: ParameterDeclaration) { - return isInJavaScriptFile(node) && ( + return isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === SyntaxKind.JSDocOptionalType || getJSDocParameterTags(node).some(({ isBracketed, typeExpression }) => @@ -7533,35 +7964,32 @@ namespace ts { * @param typeParameters The requested type parameters. * @param minTypeArgumentCount The minimum number of required type arguments. */ - function fillMissingTypeArguments(typeArguments: Type[], typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[]; - function fillMissingTypeArguments(typeArguments: Type[] | undefined, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[] | undefined; - function fillMissingTypeArguments(typeArguments: Type[] | undefined, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean) { + function fillMissingTypeArguments(typeArguments: ReadonlyArray, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[]; + function fillMissingTypeArguments(typeArguments: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[] | undefined; + function fillMissingTypeArguments(typeArguments: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean) { const numTypeParameters = length(typeParameters); - if (numTypeParameters) { - const numTypeArguments = length(typeArguments); - if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { - if (!typeArguments) { - typeArguments = []; - } - - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - for (let i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - for (let i = numTypeArguments; i < numTypeParameters; i++) { - const mapper = createTypeMapper(typeParameters!, typeArguments); - let defaultType = getDefaultFromTypeParameter(typeParameters![i]); - if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { - defaultType = anyType; - } - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - typeArguments.length = typeParameters!.length; - } + if (!numTypeParameters) { + return []; } - return typeArguments; + const numTypeArguments = length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + const result = typeArguments ? typeArguments.slice() : []; + // Map invalid forward references in default types to the error type + for (let i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = errorType; + } + const baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + for (let i = numTypeArguments; i < numTypeParameters; i++) { + let defaultType = getDefaultFromTypeParameter(typeParameters![i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters!, result)) : baseDefaultType; + } + result.length = typeParameters!.length; + return result; + } + return typeArguments && typeArguments.slice(); } function getSignatureFromDeclaration(declaration: SignatureDeclaration | JSDocSignature): Signature { @@ -7575,7 +8003,7 @@ namespace ts { const iife = getImmediatelyInvokedFunctionExpression(declaration); const isJSConstructSignature = isJSDocConstructSignature(declaration); const isUntypedSignatureInJSFile = !iife && - isInJavaScriptFile(declaration) && + isInJSFile(declaration) && isValueSignatureDeclaration(declaration) && !hasJSDocParameterTags(declaration) && !getJSDocType(declaration); @@ -7631,7 +8059,7 @@ namespace ts { getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)) : undefined; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - const hasRestLikeParameter = hasRestParameter(declaration) || isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + const hasRestLikeParameter = hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); @@ -7665,7 +8093,7 @@ namespace ts { } function getSignatureOfTypeTag(node: SignatureDeclaration | JSDocSignature) { - const typeTag = isInJavaScriptFile(node) ? getJSDocTypeTag(node) : undefined; + const typeTag = isInJSFile(node) ? getJSDocTypeTag(node) : undefined; const signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -7760,7 +8188,7 @@ namespace ts { else { const type = signature.declaration && getEffectiveReturnTypeNode(signature.declaration); let jsdocPredicate: TypePredicate | undefined; - if (!type && isInJavaScriptFile(signature.declaration)) { + if (!type && isInJSFile(signature.declaration)) { const jsdocSignature = getSignatureOfTypeTag(signature.declaration!); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -7807,6 +8235,7 @@ namespace ts { let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper!) : signature.unionSignatures ? getUnionType(map(signature.unionSignatures, getReturnTypeOfSignature), UnionReduction.Subtype) : getReturnTypeFromAnnotation(signature.declaration!) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration!)) || (nodeIsMissing((signature.declaration).body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -7844,7 +8273,7 @@ namespace ts { return getTypeFromTypeNode(typeNode); } if (declaration.kind === SyntaxKind.GetAccessor && !hasNonBindableDynamicName(declaration)) { - const jsDocType = isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + const jsDocType = isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -7921,7 +8350,7 @@ namespace ts { return getSignatureInstantiation( signature, map(signature.typeParameters, tp => tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp), - isInJavaScriptFile(signature.declaration)); + isInJSFile(signature.declaration)); } function getBaseSignature(signature: Signature) { @@ -8131,10 +8560,10 @@ namespace ts { if (typeParameters) { const numTypeArguments = length(node.typeArguments); const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - const isJs = isInJavaScriptFile(node); + const isJs = isInJSFile(node); const isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - const missingAugmentsTag = isJs && node.parent.kind !== SyntaxKind.JSDocAugmentsTag; + const missingAugmentsTag = isJs && isExpressionWithTypeArguments(node) && !isJSDocAugmentsTag(node.parent); const diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -8158,14 +8587,14 @@ namespace ts { return checkNoTypeArguments(node, symbol) ? type : errorType; } - function getTypeAliasInstantiation(symbol: Symbol, typeArguments: Type[] | undefined): Type { + function getTypeAliasInstantiation(symbol: Symbol, typeArguments: ReadonlyArray | undefined): Type { const type = getDeclaredTypeOfSymbol(symbol); const links = getSymbolLinks(symbol); const typeParameters = links.typeParameters!; const id = getTypeListId(typeArguments); let instantiation = links.instantiations!.get(id); if (!instantiation) { - links.instantiations!.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations!.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -8232,17 +8661,26 @@ namespace ts { return type; } - // JS are 'string' or 'number', not an enum type. - const enumTag = symbol.valueDeclaration && getJSDocEnumTag(symbol.valueDeclaration); + // JS enums are 'string' or 'number', not an enum type. + const enumTag = isInJSFile(node) && symbol.valueDeclaration && getJSDocEnumTag(symbol.valueDeclaration); if (enumTag) { - return enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + const links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, TypeSystemPropertyName.EnumTagType)) { + return errorType; + } + let type = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type = errorType; + error(node, Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type); } // Get type from reference to named type that cannot be generic (enum or type parameter) const res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & TypeFlags.TypeParameter ? getConstrainedTypeVariable(res, node) : res : + res.flags & TypeFlags.TypeParameter ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } @@ -8266,12 +8704,17 @@ namespace ts { * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node: NodeWithTypeArguments, symbol: Symbol, typeArguments: Type[] | undefined): Type | undefined { - const assignedType = getAssignedClassType(symbol); - const valueType = getTypeOfSymbol(symbol); - const referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType || assignedType) { - // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType)!; + // In the case of an assignment of a function expression (binary expressions, variable declarations, etc.), we will get the + // correct instance type for the symbol on the LHS by finding the type for RHS. For example if we want to get the type of the symbol `foo`: + // var foo = function() {} + // We will find the static type of the assigned anonymous function. + const staticType = getTypeOfSymbol(symbol); + const instanceType = + staticType.symbol && + staticType.symbol !== symbol && // Make sure this is an assignment like expression by checking that symbol -> type -> symbol doesn't roundtrips. + getTypeReferenceTypeWorker(node, staticType.symbol, typeArguments); // Get the instance type of the RHS symbol. + if (instanceType) { + return getSymbolLinks(symbol).resolvedJSDocType = instanceType; } } @@ -8292,8 +8735,11 @@ namespace ts { if (symbol.flags & SymbolFlags.Function && isJSDocTypeReference(node) && - (symbol.members || getJSDocClassTag(symbol.valueDeclaration))) { - return getInferredClassType(symbol); + isJSConstructor(symbol.valueDeclaration)) { + const resolved = resolveStructuredTypeMembers(getTypeOfSymbol(symbol)); + if (resolved.callSignatures.length === 1) { + return getReturnTypeOfSignature(resolved.callSignatures[0]); + } } } @@ -8408,7 +8854,7 @@ namespace ts { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -8505,6 +8951,10 @@ namespace ts { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise" as __String, /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors: boolean) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike" as __String, /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors: boolean): Symbol | undefined { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise" as __String, reportErrors)); } @@ -8546,6 +8996,18 @@ namespace ts { return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract" as __String, SymbolFlags.TypeAlias, Diagnostics.Cannot_find_global_type_0)!); // TODO: GH#18217 } + function getGlobalExcludeSymbol(): Symbol { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude" as __String, SymbolFlags.TypeAlias, Diagnostics.Cannot_find_global_type_0)!); // TODO: GH#18217 + } + + function getGlobalPickSymbol(): Symbol { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick" as __String, SymbolFlags.TypeAlias, Diagnostics.Cannot_find_global_type_0)!); // TODO: GH#18217 + } + + function getGlobalBigIntType(reportErrors: boolean) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt" as __String, /*arity*/ 0, reportErrors)) || emptyObjectType; + } + /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -8603,7 +9065,7 @@ namespace ts { if (arity) { typeParameters = new Array(arity); for (let i = 0; i < arity; i++) { - const typeParameter = typeParameters[i] = createType(TypeFlags.TypeParameter); + const typeParameter = typeParameters[i] = createTypeParameter(); if (i < maxLength) { const property = createSymbol(SymbolFlags.Property | (i >= minLength ? SymbolFlags.Optional : 0), "" + i as __String); property.type = typeParameter; @@ -8624,7 +9086,7 @@ namespace ts { type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(TypeFlags.TypeParameter); + type.thisType = createTypeParameter(); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -8671,6 +9133,20 @@ namespace ts { return links.resolvedType; } + function sliceTupleType(type: TupleTypeReference, index: number) { + const tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType( + (type.typeArguments || emptyArray).slice(index), + Math.max(0, tuple.minLength - index), + tuple.hasRestElement, + tuple.associatedNames && tuple.associatedNames.slice(index), + ); + } + function getTypeFromOptionalTypeNode(node: OptionalTypeNode): Type { const type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -8712,6 +9188,7 @@ namespace ts { combined & TypeFlags.NonPrimitive && combined & (TypeFlags.DisjointDomains & ~TypeFlags.NonPrimitive) || combined & TypeFlags.StringLike && combined & (TypeFlags.DisjointDomains & ~TypeFlags.StringLike) || combined & TypeFlags.NumberLike && combined & (TypeFlags.DisjointDomains & ~TypeFlags.NumberLike) || + combined & TypeFlags.BigIntLike && combined & (TypeFlags.DisjointDomains & ~TypeFlags.BigIntLike) || combined & TypeFlags.ESSymbolLike && combined & (TypeFlags.DisjointDomains & ~TypeFlags.ESSymbolLike) || combined & TypeFlags.VoidLike && combined & (TypeFlags.DisjointDomains & ~TypeFlags.VoidLike)) { return true; @@ -8731,10 +9208,8 @@ namespace ts { // easier to reason about their origin. if (!(flags & TypeFlags.Never || flags & TypeFlags.Intersection && isEmptyIntersectionType(type))) { includes |= flags & ~TypeFlags.ConstructionFlags; - if (flags & TypeFlags.AnyOrUnknown) { - if (type === wildcardType) includes |= TypeFlags.Wildcard; - } - else if (!strictNullChecks && flags & TypeFlags.Nullable) { + if (type === wildcardType) includes |= TypeFlags.Wildcard; + if (!strictNullChecks && flags & TypeFlags.Nullable) { if (!(flags & TypeFlags.ContainsWideningType)) includes |= TypeFlags.NonWideningType; } else { @@ -8806,8 +9281,9 @@ namespace ts { const remove = t.flags & TypeFlags.StringLiteral && includes & TypeFlags.String || t.flags & TypeFlags.NumberLiteral && includes & TypeFlags.Number || + t.flags & TypeFlags.BigIntLiteral && includes & TypeFlags.BigInt || t.flags & TypeFlags.UniqueESSymbol && includes & TypeFlags.ESSymbol || - t.flags & TypeFlags.StringOrNumberLiteral && t.flags & TypeFlags.FreshLiteral && containsType(types, (t).regularType); + isFreshLiteralType(t) && containsType(types, (t).regularType); if (remove) { orderedRemoveItemAt(types, i); } @@ -8830,25 +9306,27 @@ namespace ts { } const typeSet: Type[] = []; const includes = addTypesToUnion(typeSet, 0, types); - if (includes & TypeFlags.AnyOrUnknown) { - return includes & TypeFlags.Any ? includes & TypeFlags.Wildcard ? wildcardType : anyType : unknownType; + if (unionReduction !== UnionReduction.None) { + if (includes & TypeFlags.AnyOrUnknown) { + return includes & TypeFlags.Any ? includes & TypeFlags.Wildcard ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case UnionReduction.Literal: + if (includes & TypeFlags.StringOrNumberLiteralOrUnique | TypeFlags.BooleanLiteral) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case UnionReduction.Subtype: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & TypeFlags.Null ? includes & TypeFlags.NonWideningType ? nullType : nullWideningType : + includes & TypeFlags.Undefined ? includes & TypeFlags.NonWideningType ? undefinedType : undefinedWideningType : + neverType; + } } - switch (unionReduction) { - case UnionReduction.Literal: - if (includes & TypeFlags.StringOrNumberLiteralOrUnique) { - removeRedundantLiteralTypes(typeSet, includes); - } - break; - case UnionReduction.Subtype: - removeSubtypes(typeSet); - break; - } - if (typeSet.length === 0) { - return includes & TypeFlags.Null ? includes & TypeFlags.NonWideningType ? nullType : nullWideningType : - includes & TypeFlags.Undefined ? includes & TypeFlags.NonWideningType ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, includes & TypeFlags.NotPrimitiveUnion ? 0 : TypeFlags.UnionOfPrimitiveTypes, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, !(includes & TypeFlags.NotPrimitiveUnion), aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures: ReadonlyArray): TypePredicate | undefined { @@ -8888,7 +9366,7 @@ namespace ts { } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types: Type[], unionOfUnitTypes: TypeFlags, aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray): Type { + function getUnionTypeFromSortedList(types: Type[], primitiveTypesOnly: boolean, aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray): Type { if (types.length === 0) { return neverType; } @@ -8899,9 +9377,10 @@ namespace ts { let type = unionTypes.get(id); if (!type) { const propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ TypeFlags.Nullable); - type = createType(TypeFlags.Union | propagatedFlags | unionOfUnitTypes); + type = createType(TypeFlags.Union | propagatedFlags); unionTypes.set(id, type); type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; /* Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. @@ -8929,8 +9408,11 @@ namespace ts { if (flags & TypeFlags.Intersection) { return addTypesToIntersection(typeSet, includes, (type).types); } - if (getObjectFlags(type) & ObjectFlags.Anonymous && isEmptyObjectType(type)) { - includes |= TypeFlags.EmptyObject; + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & TypeFlags.EmptyObject)) { + includes |= TypeFlags.EmptyObject; + typeSet.push(type); + } } else { includes |= flags & ~TypeFlags.ConstructionFlags; @@ -8961,6 +9443,7 @@ namespace ts { const remove = t.flags & TypeFlags.String && includes & TypeFlags.StringLiteral || t.flags & TypeFlags.Number && includes & TypeFlags.NumberLiteral || + t.flags & TypeFlags.BigInt && includes & TypeFlags.BigIntLiteral || t.flags & TypeFlags.ESSymbol && includes & TypeFlags.UniqueESSymbol; if (remove) { orderedRemoveItemAt(types, i); @@ -8976,6 +9459,7 @@ namespace ts { if (!containsType(u.types, type)) { const primitive = type.flags & TypeFlags.StringLiteral ? stringType : type.flags & TypeFlags.NumberLiteral ? numberType : + type.flags & TypeFlags.BigIntLiteral ? bigintType : type.flags & TypeFlags.UniqueESSymbol ? esSymbolType : undefined; if (!primitive || !containsType(u.types, primitive)) { @@ -8991,13 +9475,16 @@ namespace ts { // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types: Type[]) { let unionTypes: UnionType[] | undefined; - const index = findIndex(types, t => (t.flags & TypeFlags.UnionOfPrimitiveTypes) !== 0); + const index = findIndex(types, t => !!(t.flags & TypeFlags.Union) && (t).primitiveTypesOnly); + if (index < 0) { + return false; + } let i = index + 1; // Remove all but the first union of primitive types and collect them in // the unionTypes array. while (i < types.length) { const t = types[i]; - if (t.flags & TypeFlags.UnionOfPrimitiveTypes) { + if (t.flags & TypeFlags.Union && (t).primitiveTypesOnly) { (unionTypes || (unionTypes = [types[index]])).push(t); orderedRemoveItemAt(types, i); } @@ -9024,7 +9511,7 @@ namespace ts { } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, TypeFlags.UnionOfPrimitiveTypes); + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); return true; } @@ -9052,11 +9539,12 @@ namespace ts { } if (includes & TypeFlags.String && includes & TypeFlags.StringLiteral || includes & TypeFlags.Number && includes & TypeFlags.NumberLiteral || + includes & TypeFlags.BigInt && includes & TypeFlags.BigIntLiteral || includes & TypeFlags.ESSymbol && includes & TypeFlags.UniqueESSymbol) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & TypeFlags.EmptyObject && !(includes & TypeFlags.Object)) { - typeSet.push(emptyObjectType); + if (includes & TypeFlags.EmptyObject && includes & TypeFlags.Object) { + orderedRemoveItemAt(typeSet, findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { return unknownType; @@ -9065,7 +9553,7 @@ namespace ts { return typeSet[0]; } if (includes & TypeFlags.Union) { - if (includes & TypeFlags.UnionOfPrimitiveTypes && intersectUnionsOfPrimitiveTypes(typeSet)) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -9114,14 +9602,29 @@ namespace ts { type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } - function getLiteralTypeFromPropertyName(prop: Symbol, include: TypeFlags) { + function getLiteralTypeFromPropertyName(name: PropertyName) { + return isIdentifier(name) ? getLiteralType(unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + } + + function getBigIntLiteralType(node: BigIntLiteral): LiteralType { + return getLiteralType({ + negative: false, + base10Value: parsePseudoBigInt(node.text) + }); + } + + function getLiteralTypeFromProperty(prop: Symbol, include: TypeFlags) { if (!(getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier)) { let type = getLateBoundSymbol(prop).nameType; if (!type && !isKnownSymbol(prop)) { - const name = prop.valueDeclaration && getNameOfDeclaration(prop.valueDeclaration); - type = name && isNumericLiteral(name) ? getLiteralType(+name.text) : - name && name.kind === SyntaxKind.ComputedPropertyName && isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : - getLiteralType(symbolName(prop)); + if (prop.escapedName === InternalSymbolName.Default) { + type = getLiteralType("default"); + } + else { + const name = prop.valueDeclaration && getNameOfDeclaration(prop.valueDeclaration) as PropertyName; + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(symbolName(prop)); + } } if (type && type.flags & include) { return type; @@ -9130,8 +9633,8 @@ namespace ts { return neverType; } - function getLiteralTypeFromPropertyNames(type: Type, include: TypeFlags) { - return getUnionType(map(getPropertiesOfType(type), t => getLiteralTypeFromPropertyName(t, include))); + function getLiteralTypeFromProperties(type: Type, include: TypeFlags) { + return getUnionType(map(getPropertiesOfType(type), t => getLiteralTypeFromProperty(t, include))); } function getNonEnumNumberIndexInfo(type: Type) { @@ -9146,10 +9649,10 @@ namespace ts { getObjectFlags(type) & ObjectFlags.Mapped ? getConstraintTypeFromMappedType(type) : type === wildcardType ? wildcardType : type.flags & TypeFlags.Any ? keyofConstraintType : - stringsOnly ? getIndexInfoOfType(type, IndexKind.String) ? stringType : getLiteralTypeFromPropertyNames(type, TypeFlags.StringLiteral) : - getIndexInfoOfType(type, IndexKind.String) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, TypeFlags.UniqueESSymbol)]) : - getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, TypeFlags.StringLiteral | TypeFlags.UniqueESSymbol)]) : - getLiteralTypeFromPropertyNames(type, TypeFlags.StringOrNumberLiteralOrUnique); + stringsOnly ? getIndexInfoOfType(type, IndexKind.String) ? stringType : getLiteralTypeFromProperties(type, TypeFlags.StringLiteral) : + getIndexInfoOfType(type, IndexKind.String) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, TypeFlags.UniqueESSymbol)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, TypeFlags.StringLiteral | TypeFlags.UniqueESSymbol)]) : + getLiteralTypeFromProperties(type, TypeFlags.StringOrNumberLiteralOrUnique); } function getExtractStringType(type: Type) { @@ -9217,19 +9720,23 @@ namespace ts { return false; } - function getPropertyTypeForIndexType(objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode | undefined, cacheSymbol: boolean, missingType: Type) { + function getPropertyTypeForIndexType(objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression | undefined, cacheSymbol: boolean, missingType: Type) { const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; - const propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : + const propName = isTypeUsableAsLateBoundName(indexType) ? + getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? getPropertyNameForKnownSymbolName(idText((accessExpression.argumentExpression).name)) : - undefined; + accessNode && isPropertyName(accessNode) ? + // late bound names are handled in the first branch, so here we only need to handle normal names + getPropertyNameForPropertyNameNode(accessNode) : + undefined; if (propName !== undefined) { const prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === SyntaxKind.ThisKeyword); if (isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + error(accessExpression.argumentExpression, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); return missingType; } if (cacheSymbol) { @@ -9237,13 +9744,22 @@ namespace ts { } } const propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && getAssignmentTargetKind(accessExpression) !== AssignmentKind.Definite ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - const restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, t => !(t).target.hasRestElement)) { + const indexNode = getIndexNodeForAccessExpression(accessNode); + if (isTupleType(objectType)) { + error(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, + typeToString(objectType), getTypeReferenceArity(objectType), unescapeLeadingUnderscores(propName)); + } + else { + error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); + } } + return mapType(objectType, t => getRestTypeOfTupleType(t) || undefinedType); } } if (!(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike)) { @@ -9255,7 +9771,7 @@ namespace ts { undefined; if (indexInfo) { if (accessNode && !isTypeAssignableToKind(indexType, TypeFlags.String | TypeFlags.Number)) { - const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.indexType; + const indexNode = getIndexNodeForAccessExpression(accessNode); error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } else if (accessExpression && indexInfo.isReadonly && (isAssignmentTarget(accessExpression) || isDeleteTarget(accessExpression))) { @@ -9296,7 +9812,7 @@ namespace ts { return anyType; } if (accessNode) { - const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.indexType; + const indexNode = getIndexNodeForAccessExpression(accessNode); if (indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + (indexType).value, typeToString(objectType)); } @@ -9313,6 +9829,16 @@ namespace ts { return missingType; } + function getIndexNodeForAccessExpression(accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression) { + return accessNode.kind === SyntaxKind.ElementAccessExpression + ? accessNode.argumentExpression + : accessNode.kind === SyntaxKind.IndexedAccessType + ? accessNode.indexType + : accessNode.kind === SyntaxKind.ComputedPropertyName + ? accessNode.expression + : accessNode; + } + function isGenericObjectType(type: Type): boolean { return maybeTypeOfKind(type, TypeFlags.InstantiableNonPrimitive | TypeFlags.GenericMappedType); } @@ -9325,6 +9851,17 @@ namespace ts { return type.flags & TypeFlags.IndexedAccess ? getSimplifiedIndexedAccessType(type) : type; } + function distributeIndexOverObjectType(objectType: Type, indexType: Type) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & TypeFlags.Union) { + return mapType(objectType, t => getSimplifiedType(getIndexedAccessType(t, indexType))); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & TypeFlags.Intersection) { + return getIntersectionType(map((objectType as IntersectionType).types, t => getSimplifiedType(getIndexedAccessType(t, indexType)))); + } + } + // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // the type itself if no transformation is possible. function getSimplifiedIndexedAccessType(type: IndexedAccessType): Type { @@ -9336,35 +9873,32 @@ namespace ts { // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. const objectType = getSimplifiedType(type.objectType); const indexType = getSimplifiedType(type.indexType); - if (objectType.flags & TypeFlags.Union) { - return type.simplified = mapType(objectType, t => getSimplifiedType(getIndexedAccessType(t, indexType))); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & TypeFlags.Union) { + return type.simplified = mapType(indexType, t => getSimplifiedType(getIndexedAccessType(objectType, t))); } - if (objectType.flags & TypeFlags.Intersection) { - return type.simplified = getIntersectionType(map((objectType as IntersectionType).types, t => getSimplifiedType(getIndexedAccessType(t, indexType)))); + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & TypeFlags.Instantiable)) { + const simplified = distributeIndexOverObjectType(objectType, indexType); + if (simplified) { + return type.simplified = simplified; + } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] + // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we - // construct the type Box. We do not further simplify the result because mapped types can be recursive - // and we might never terminate. + // construct the type Box. if (isGenericMappedType(objectType)) { - return type.simplified = substituteIndexedMappedType(objectType, type); - } - if (objectType.flags & TypeFlags.TypeParameter) { - const constraint = getConstraintOfTypeParameter(objectType as TypeParameter); - if (constraint && isGenericMappedType(constraint)) { - return type.simplified = substituteIndexedMappedType(constraint, type); - } + const mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + const templateMapper = combineTypeMappers(objectType.mapper, mapper); + return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType); } return type.simplified = type; } - function substituteIndexedMappedType(objectType: MappedType, type: IndexedAccessType) { - const mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - const templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); - } - - function getIndexedAccessType(objectType: Type, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode, missingType = accessNode ? errorType : unknownType): Type { + function getIndexedAccessType(objectType: Type, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression, missingType = accessNode ? errorType : unknownType): Type { if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -9373,7 +9907,7 @@ namespace ts { // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== SyntaxKind.IndexedAccessType) && isGenericObjectType(objectType)) { if (objectType.flags & TypeFlags.AnyOrUnknown) { return objectType; } @@ -9453,14 +9987,11 @@ namespace ts { if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } - // If this is a distributive conditional type and the check type is generic we need to defer - // resolution of the conditional type such that a later instantiation will properly distribute - // over union types. - const isDeferred = root.isDistributive && maybeTypeOfKind(checkType, TypeFlags.Instantiable); + const checkTypeInstantiable = maybeTypeOfKind(checkType, TypeFlags.Instantiable | TypeFlags.GenericMappedType); let combinedMapper: TypeMapper | undefined; if (root.inferTypeParameters) { const context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, InferenceFlags.None); - if (!isDeferred) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -9468,28 +9999,30 @@ namespace ts { } combinedMapper = combineTypeMappers(mapper, context); } - if (!isDeferred) { - if (extendsType.flags & TypeFlags.AnyOrUnknown) { + // Instantiate the extends type including inferences for 'infer T' type parameters + const inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // We attempt to resolve the conditional type only when the check and extends types are non-generic + if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, TypeFlags.Instantiable | TypeFlags.GenericMappedType)) { + if (inferredExtendsType.flags & TypeFlags.AnyOrUnknown) { return instantiateType(root.trueType, mapper); } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & TypeFlags.Any) { return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); } - // Instantiate the extends type including inferences for 'infer T' type parameters - const inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; // Return falseType for a definitely false extends check. We check an instantations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instatiations will be and we can just return the false branch type. - if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { return instantiateType(root.falseType, mapper); } - // Return trueType for a definitely true extends check. The definitely assignable relation excludes - // type variable constraints from consideration. Without the definitely assignable relation, the type + // Return trueType for a definitely true extends check. We check instantiations of the two + // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter + // that has no constraint. This ensures that, for example, the type // type Foo = T extends { x: string } ? string : number - // would immediately resolve to 'string' instead of being deferred. - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + // doesn't immediately resolve to 'string' instead of being deferred. + if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { return instantiateType(root.trueType, combinedMapper || mapper); } } @@ -9685,6 +10218,10 @@ namespace ts { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } + function isNonGenericObjectType(type: Type) { + return !!(type.flags & TypeFlags.Object) && !isGenericMappedType(type); + } + /** * Since the source of spread types are object literals, which are not binary, * this function should be called in a left folding style, with left = previous result of getSpreadType @@ -9709,10 +10246,27 @@ namespace ts { if (right.flags & TypeFlags.Union) { return mapType(right, t => getSpreadType(left, t, symbol, typeFlags, objectFlags)); } - if (right.flags & (TypeFlags.BooleanLike | TypeFlags.NumberLike | TypeFlags.StringLike | TypeFlags.EnumLike | TypeFlags.NonPrimitive | TypeFlags.Index)) { + if (right.flags & (TypeFlags.BooleanLike | TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.StringLike | TypeFlags.EnumLike | TypeFlags.NonPrimitive | TypeFlags.Index)) { return left; } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & TypeFlags.Intersection) { + const types = (left).types; + const lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } + const members = createSymbolTable(); const skippedPrivateMembers = createUnderscoreEscapedMap(); let stringIndexInfo: IndexInfo | undefined; @@ -9732,7 +10286,7 @@ namespace ts { skippedPrivateMembers.set(rightProp.escapedName, true); } else if (isSpreadableProperty(rightProp)) { - members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); } } @@ -9756,7 +10310,7 @@ namespace ts { } } else { - members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); } } @@ -9767,25 +10321,26 @@ namespace ts { emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= typeFlags | TypeFlags.ContainsObjectLiteral; - (spread as ObjectType).objectFlags |= objectFlags | (ObjectFlags.ObjectLiteral | ObjectFlags.ContainsSpread); + spread.flags |= TypeFlags.ContainsObjectLiteral | typeFlags; + spread.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.ContainsSpread | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop: Symbol): boolean { - return prop.flags & (SymbolFlags.Method | SymbolFlags.GetAccessor) - ? !prop.declarations.some(decl => isClassLike(decl.parent)) - : !(prop.flags & SymbolFlags.SetAccessor); // Setter without getter is not spreadable + return !(prop.flags & (SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor)) || + !prop.declarations.some(decl => isClassLike(decl.parent)); } - function getNonReadonlySymbol(prop: Symbol) { - if (!isReadonlySymbol(prop)) { + function getSpreadSymbol(prop: Symbol) { + const isReadonly = isReadonlySymbol(prop); + const isSetonlyAccessor = prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor); + if (!isReadonly && !isSetonlyAccessor) { return prop; } const flags = SymbolFlags.Property | (prop.flags & SymbolFlags.Optional); const result = createSymbol(flags, prop.escapedName); - result.type = getTypeOfSymbol(prop); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); result.declarations = prop.declarations; result.nameType = prop.nameType; result.syntheticOrigin = prop; @@ -9799,7 +10354,7 @@ namespace ts { return index; } - function createLiteralType(flags: TypeFlags, value: string | number, symbol: Symbol | undefined) { + function createLiteralType(flags: TypeFlags, value: string | number | PseudoBigInt, symbol: Symbol | undefined) { const type = createType(flags); type.symbol = symbol!; type.value = value; @@ -9807,10 +10362,11 @@ namespace ts { } function getFreshTypeOfLiteralType(type: Type): Type { - if (type.flags & TypeFlags.StringOrNumberLiteral && !(type.flags & TypeFlags.FreshLiteral)) { + if (type.flags & TypeFlags.Literal) { if (!(type).freshType) { - const freshType = createLiteralType(type.flags | TypeFlags.FreshLiteral, (type).value, (type).symbol); + const freshType = createLiteralType(type.flags, (type).value, (type).symbol); freshType.regularType = type; + freshType.freshType = freshType; (type).freshType = freshType; } return (type).freshType; @@ -9819,22 +10375,29 @@ namespace ts { } function getRegularTypeOfLiteralType(type: Type): Type { - return type.flags & TypeFlags.StringOrNumberLiteral && type.flags & TypeFlags.FreshLiteral ? (type).regularType : + return type.flags & TypeFlags.Literal ? (type).regularType : type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getRegularTypeOfLiteralType)) : type; } - function getLiteralType(value: string | number, enumId?: number, symbol?: Symbol) { + function isFreshLiteralType(type: Type) { + return !!(type.flags & TypeFlags.Literal) && (type).freshType === type; + } + + function getLiteralType(value: string | number | PseudoBigInt, enumId?: number, symbol?: Symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', // where NNN is the text representation of a numeric literal and SSS are the characters // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where // EEE is a unique id for the containing enum type. - const qualifier = typeof value === "number" ? "#" : "@"; - const key = enumId ? enumId + qualifier + value : qualifier + value; + const qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + const key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? pseudoBigIntToString(value) : value); let type = literalTypes.get(key); if (!type) { - const flags = (typeof value === "number" ? TypeFlags.NumberLiteral : TypeFlags.StringLiteral) | (enumId ? TypeFlags.EnumLiteral : 0); + const flags = (typeof value === "number" ? TypeFlags.NumberLiteral : + typeof value === "string" ? TypeFlags.StringLiteral : TypeFlags.BigIntLiteral) | + (enumId ? TypeFlags.EnumLiteral : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; } return type; } @@ -9895,6 +10458,8 @@ namespace ts { return stringType; case SyntaxKind.NumberKeyword: return numberType; + case SyntaxKind.BigIntKeyword: + return bigintType; case SyntaxKind.BooleanKeyword: return booleanType; case SyntaxKind.SymbolKeyword: @@ -10063,13 +10628,20 @@ namespace ts { return t => t === source ? target : baseMapper(t); } - function wildcardMapper(type: Type) { + function permissiveMapper(type: Type) { return type.flags & TypeFlags.TypeParameter ? wildcardType : type; } + function getRestrictiveTypeParameter(tp: TypeParameter) { + return !tp.constraint ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol)); + } + + function restrictiveMapper(type: Type) { + return type.flags & TypeFlags.TypeParameter ? getRestrictiveTypeParameter(type) : type; + } + function cloneTypeParameter(typeParameter: TypeParameter): TypeParameter { - const result = createType(TypeFlags.TypeParameter); - result.symbol = typeParameter.symbol; + const result = createTypeParameter(typeParameter.symbol); result.target = typeParameter; return result; } @@ -10160,7 +10732,7 @@ namespace ts { // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. let declaration = symbol.declarations[0]; - if (isInJavaScriptFile(declaration)) { + if (isInJSFile(declaration)) { const paramTag = findAncestor(declaration, isJSDocParameterTag); if (paramTag) { const paramSymbol = getParameterSymbolFromJSDoc(paramTag); @@ -10170,7 +10742,7 @@ namespace ts { } } let outerTypeParameters = getOuterTypeParameters(declaration, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration)) { + if (isJSConstructor(declaration)) { const templateTagParameters = getTypeParametersFromDeclaration(declaration as DeclarationWithTypeParameters); outerTypeParameters = addRange(outerTypeParameters, templateTagParameters); } @@ -10258,7 +10830,15 @@ namespace ts { if (typeVariable) { const mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(mappedTypeVariable, t => { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; + } + type.instantiating = true; + const result = mapType(mappedTypeVariable, t => { if (t.flags & (TypeFlags.AnyOrUnknown | TypeFlags.InstantiableNonPrimitive | TypeFlags.Object | TypeFlags.Intersection) && t !== wildcardType) { const replacementMapper = createReplacementMapper(typeVariable, t, mapper); return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : @@ -10268,6 +10848,8 @@ namespace ts { } return t; }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); @@ -10297,6 +10879,12 @@ namespace ts { const result = createObjectType(type.objectFlags | ObjectFlags.Instantiated, type.symbol); if (type.objectFlags & ObjectFlags.Mapped) { (result).declaration = (type).declaration; + // C.f. instantiateSignature + const origTypeParameter = getTypeParameterFromMappedType(type); + const freshTypeParameter = cloneTypeParameter(origTypeParameter); + (result).typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -10405,9 +10993,14 @@ namespace ts { return type; } - function getWildcardInstantiation(type: Type) { + function getPermissiveInstantiation(type: Type) { return type.flags & (TypeFlags.Primitive | TypeFlags.AnyOrUnknown | TypeFlags.Never) ? type : - type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); + } + + function getRestrictiveInstantiation(type: Type) { + return type.flags & (TypeFlags.Primitive | TypeFlags.AnyOrUnknown | TypeFlags.Never) ? type : + type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); } function instantiateIndexInfo(info: IndexInfo | undefined, mapper: TypeMapper): IndexInfo | undefined { @@ -10416,7 +11009,7 @@ namespace ts { // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. - function isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike): boolean { + function isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike | JsxChild): boolean { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); switch (node.kind) { case SyntaxKind.FunctionExpression: @@ -10438,7 +11031,7 @@ namespace ts { case SyntaxKind.ParenthesizedExpression: return isContextSensitive((node).expression); case SyntaxKind.JsxAttributes: - return some((node).properties, isContextSensitive); + return some((node).properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive); case SyntaxKind.JsxAttribute: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. const { initializer } = node as JsxAttribute; @@ -10476,12 +11069,11 @@ namespace ts { function hasContextSensitiveReturnExpression(node: FunctionLikeDeclaration) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - const body = node.body!; - return body.kind === SyntaxKind.Block ? false : isContextSensitive(body); + return !!node.body && node.body.kind !== SyntaxKind.Block && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func: Node): func is FunctionExpression | ArrowFunction | MethodDeclaration { - return (isInJavaScriptFile(func) && isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) && + return (isInJSFile(func) && isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } @@ -10517,6 +11109,10 @@ namespace ts { return isTypeRelatedTo(source, target, assignableRelation) ? Ternary.True : Ternary.False; } + function compareTypesSubtypeOf(source: Type, target: Type): Ternary { + return isTypeRelatedTo(source, target, subtypeRelation) ? Ternary.True : Ternary.False; + } + function isTypeSubtypeOf(source: Type, target: Type): boolean { return isTypeRelatedTo(source, target, subtypeRelation); } @@ -10537,7 +11133,8 @@ namespace ts { return source.flags & TypeFlags.Union ? every((source).types, t => isTypeDerivedFrom(t, target)) : target.flags & TypeFlags.Union ? some((target).types, t => isTypeDerivedFrom(source, t)) : source.flags & TypeFlags.InstantiableNonPrimitive ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : + target === globalObjectType ? !!(source.flags & (TypeFlags.Object | TypeFlags.NonPrimitive)) : + target === globalFunctionType ? !!(source.flags & TypeFlags.Object) && isFunctionObjectType(source as ObjectType) : hasBaseType(source, getTargetType(target)); } @@ -10573,7 +11170,7 @@ namespace ts { function checkTypeRelatedToAndOptionallyElaborate(source: Type, target: Type, relation: Map, errorNode: Node | undefined, expr: Expression | undefined, headMessage?: DiagnosticMessage, containingMessageChain?: () => DiagnosticMessageChain | undefined): boolean { if (isTypeRelatedTo(source, target, relation)) return true; - if (!errorNode || !elaborateError(expr, source, target)) { + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; @@ -10583,25 +11180,91 @@ namespace ts { return !!(type.flags & TypeFlags.Conditional || (type.flags & TypeFlags.Intersection && some((type as IntersectionType).types, isOrHasGenericConditional))); } - function elaborateError(node: Expression | undefined, source: Type, target: Type): boolean { + function elaborateError(node: Expression | undefined, source: Type, target: Type, relation: Map, headMessage: DiagnosticMessage | undefined): boolean { if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case SyntaxKind.JsxExpression: case SyntaxKind.ParenthesizedExpression: - return elaborateError((node as ParenthesizedExpression | JsxExpression).expression, source, target); + return elaborateError((node as ParenthesizedExpression | JsxExpression).expression, source, target, relation, headMessage); case SyntaxKind.BinaryExpression: switch ((node as BinaryExpression).operatorToken.kind) { case SyntaxKind.EqualsToken: case SyntaxKind.CommaToken: - return elaborateError((node as BinaryExpression).right, source, target); + return elaborateError((node as BinaryExpression).right, source, target, relation, headMessage); } break; case SyntaxKind.ObjectLiteralExpression: - return elaborateObjectLiteral(node as ObjectLiteralExpression, source, target); + return elaborateObjectLiteral(node as ObjectLiteralExpression, source, target, relation); case SyntaxKind.ArrayLiteralExpression: - return elaborateArrayLiteral(node as ArrayLiteralExpression, source, target); + return elaborateArrayLiteral(node as ArrayLiteralExpression, source, target, relation); case SyntaxKind.JsxAttributes: - return elaborateJsxAttributes(node as JsxAttributes, source, target); + return elaborateJsxComponents(node as JsxAttributes, source, target, relation); + case SyntaxKind.ArrowFunction: + return elaborateArrowFunction(node as ArrowFunction, source, target, relation); + } + return false; + } + + function elaborateDidYouMeanToCallOrConstruct(node: Expression, source: Type, target: Type, relation: Map, headMessage: DiagnosticMessage | undefined): boolean { + const callSignatures = getSignaturesOfType(source, SignatureKind.Call); + const constructSignatures = getSignaturesOfType(source, SignatureKind.Construct); + for (const signatures of [constructSignatures, callSignatures]) { + if (some(signatures, s => { + const returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (TypeFlags.Any | TypeFlags.Never)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + const resultObj: { error?: Diagnostic } = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + const diagnostic = resultObj.error!; + addRelatedInfo(diagnostic, createDiagnosticForNode( + node, + signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression + )); + return true; + } + } + return false; + } + + function elaborateArrowFunction(node: ArrowFunction, source: Type, target: Type, relation: Map): boolean { + // Don't elaborate blocks + if (isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (some(node.parameters, ts.hasType)) { + return false; + } + const sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + const targetSignatures = getSignaturesOfType(target, SignatureKind.Call); + if (!length(targetSignatures)) { + return false; + } + const returnExpression = node.body; + const sourceReturn = getReturnTypeOfSignature(sourceSig); + const targetReturn = getUnionType(map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + const elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + const resultObj: { error?: Diagnostic } = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, createDiagnosticForNode( + target.symbol.declarations[0], + Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature, + )); + } + return true; + } } return false; } @@ -10612,15 +11275,16 @@ namespace ts { * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator: ElaborationIterator, source: Type, target: Type) { + function elaborateElementwise(iterator: ElaborationIterator, source: Type, target: Type, relation: Map) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span let reportedError = false; for (let status = iterator.next(); !status.done; status = iterator.next()) { const { errorNode: prop, innerExpression: next, nameType, errorMessage } = status.value; - const sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); const targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); - if (sourcePropType !== errorType && targetPropType !== errorType && !isTypeAssignableTo(sourcePropType, targetPropType)) { - const elaborated = next && elaborateError(next, sourcePropType, targetPropType); + if (targetPropType === errorType || targetPropType.flags & TypeFlags.IndexedAccess) continue; // Don't elaborate on indexes on generic variables + const sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + const elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -10629,10 +11293,10 @@ namespace ts { const resultObj: { error?: Diagnostic } = {}; // Use the expression type, if available const specificSource = next ? checkExpressionForMutableLocation(next, CheckMode.Normal, sourcePropType) : sourcePropType; - const result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { const reportedDiag = resultObj.error; @@ -10644,19 +11308,22 @@ namespace ts { const indexInfo = isTypeAssignableToKind(nameType, TypeFlags.NumberLike) && getIndexInfoOfType(target, IndexKind.Number) || getIndexInfoOfType(target, IndexKind.String) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, createDiagnosticForNode(indexInfo.declaration, Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && length(targetProp.declarations) || target.symbol && length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, createDiagnosticForNode( - targetProp && length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], - Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, - propertyName && !(nameType.flags & TypeFlags.UniqueESSymbol) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), - typeToString(target) - )); + const targetNode = targetProp && length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, createDiagnosticForNode( + targetNode, + Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, + propertyName && !(nameType.flags & TypeFlags.UniqueESSymbol) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), + typeToString(target) + )); + } } } reportedError = true; @@ -10674,8 +11341,113 @@ namespace ts { } } - function elaborateJsxAttributes(node: JsxAttributes, source: Type, target: Type) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function *generateJsxChildren(node: JsxElement, getInvalidTextDiagnostic: () => DiagnosticMessage): ElaborationIterator { + if (!length(node.children)) return; + let memberOffset = 0; + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + const nameType = getLiteralType(i - memberOffset); + const elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic); + if (elem) { + yield elem; + } + else { + memberOffset++; + } + } + } + + function getElaborationElementForJsxChild(child: JsxChild, nameType: LiteralType, getInvalidTextDiagnostic: () => DiagnosticMessage) { + switch (child.kind) { + case SyntaxKind.JsxExpression: + // child is of the type of the expression + return { errorNode: child, innerExpression: child.expression, nameType }; + case SyntaxKind.JsxText: + if (child.containsOnlyWhiteSpaces) { + break; // Whitespace only jsx text isn't real jsx text + } + // child is a string + return { errorNode: child, innerExpression: undefined, nameType, errorMessage: getInvalidTextDiagnostic() }; + case SyntaxKind.JsxElement: + case SyntaxKind.JsxSelfClosingElement: + case SyntaxKind.JsxFragment: + // child is of type JSX.Element + return { errorNode: child, innerExpression: child, nameType }; + default: + return Debug.assertNever(child, "Found invalid jsx child"); + } + } + + function elaborateJsxComponents(node: JsxAttributes, source: Type, target: Type, relation: Map) { + let result = elaborateElementwise(generateJsxAttributes(node), source, target, relation); + let invalidTextDiagnostic: DiagnosticMessage | undefined; + if (isJsxOpeningElement(node.parent) && isJsxElement(node.parent.parent)) { + const containingElement = node.parent.parent; + const childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + const childrenPropName = childPropName === undefined ? "children" : unescapeLeadingUnderscores(childPropName); + const childrenNameType = getLiteralType(childrenPropName); + const childrenTargetType = getIndexedAccessType(target, childrenNameType); + const validChildren = filter(containingElement.children, i => !isJsxText(i) || !i.containsOnlyWhiteSpaces); + if (!length(validChildren)) { + return result; + } + const moreThanOneRealChildren = length(validChildren) > 1; + const arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType); + const nonArrayLikeTargetParts = filterType(childrenTargetType, t => !isArrayOrTupleLikeType(t)); + if (moreThanOneRealChildren) { + if (arrayLikeTargetParts !== neverType) { + const realSource = createTupleType(checkJsxChildren(containingElement, CheckMode.Normal)); + result = elaborateElementwise(generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic), realSource, arrayLikeTargetParts, relation) || result; + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error( + containingElement.openingElement.tagName, + Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, + childrenPropName, + typeToString(childrenTargetType) + ); + } + } + else { + if (nonArrayLikeTargetParts !== neverType) { + const child = validChildren[0]; + const elem = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); + if (elem) { + result = elaborateElementwise( + (function*() { yield elem; })(), + source, + target, + relation + ) || result; + } + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error( + containingElement.openingElement.tagName, + Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, + childrenPropName, + typeToString(childrenTargetType) + ); + } + } + } + return result; + + function getInvalidTextualChildDiagnostic() { + if (!invalidTextDiagnostic) { + const tagNameText = getTextOfNode(node.parent.tagName); + const childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + const childrenPropName = childPropName === undefined ? "children" : unescapeLeadingUnderscores(childPropName); + const childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName)); + const diagnostic = Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; + invalidTextDiagnostic = { ...diagnostic, key: "!!ALREADY FORMATTED!!", message: formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }; + } + return invalidTextDiagnostic; + } } function *generateLimitedTupleElements(node: ArrayLiteralExpression, target: Type): ElaborationIterator { @@ -10691,9 +11463,14 @@ namespace ts { } } - function elaborateArrayLiteral(node: ArrayLiteralExpression, source: Type, target: Type) { + function elaborateArrayLiteral(node: ArrayLiteralExpression, source: Type, target: Type, relation: Map) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + const tupleizedType = checkArrayLiteral(node, CheckMode.Contextual, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -10702,7 +11479,7 @@ namespace ts { if (!length(node.properties)) return; for (const prop of node.properties) { if (isSpreadAssignment(prop)) continue; - const type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), TypeFlags.StringOrNumberLiteralOrUnique); + const type = getLiteralTypeFromProperty(getSymbolOfNode(prop), TypeFlags.StringOrNumberLiteralOrUnique); if (!type || (type.flags & TypeFlags.Never)) { continue; } @@ -10722,8 +11499,8 @@ namespace ts { } } - function elaborateObjectLiteral(node: ObjectLiteralExpression, source: Type, target: Type) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node: ObjectLiteralExpression, source: Type, target: Type, relation: Map) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** @@ -10832,13 +11609,13 @@ namespace ts { } if (!ignoreReturnTypes) { - const targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol)! : getReturnTypeOfSignature(target); + const targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol)! : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - const sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol)! : getReturnTypeOfSignature(source); + const sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol)! : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions const targetTypePredicate = getTypePredicateOfSignature(target); @@ -10929,13 +11706,17 @@ namespace ts { } function isEmptyObjectType(type: Type): boolean { - return type.flags & TypeFlags.Object ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + return type.flags & TypeFlags.Object ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & TypeFlags.NonPrimitive ? true : type.flags & TypeFlags.Union ? some((type).types, isEmptyObjectType) : type.flags & TypeFlags.Intersection ? every((type).types, isEmptyObjectType) : false; } + function isEmptyAnonymousObjectType(type: Type) { + return !!(getObjectFlags(type) & ObjectFlags.Anonymous) && isEmptyObjectType(type); + } + function isEnumTypeRelatedTo(sourceSymbol: Symbol, targetSymbol: Symbol, errorReporter?: ErrorReporter) { if (sourceSymbol === targetSymbol) { return true; @@ -10983,6 +11764,7 @@ namespace ts { if (s & TypeFlags.NumberLiteral && s & TypeFlags.EnumLiteral && t & TypeFlags.NumberLiteral && !(t & TypeFlags.EnumLiteral) && (source).value === (target).value) return true; + if (s & TypeFlags.BigIntLike && t & TypeFlags.BigInt) return true; if (s & TypeFlags.BooleanLike && t & TypeFlags.Boolean) return true; if (s & TypeFlags.ESSymbolLike && t & TypeFlags.ESSymbol) return true; if (s & TypeFlags.Enum && t & TypeFlags.Enum && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; @@ -10995,8 +11777,7 @@ namespace ts { if (s & TypeFlags.Undefined && (!strictNullChecks || t & (TypeFlags.Undefined | TypeFlags.Void))) return true; if (s & TypeFlags.Null && (!strictNullChecks || t & TypeFlags.Null)) return true; if (s & TypeFlags.Object && t & TypeFlags.NonPrimitive) return true; - if (s & TypeFlags.UniqueESSymbol || t & TypeFlags.UniqueESSymbol) return false; - if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (relation === assignableRelation || relation === comparableRelation) { if (s & TypeFlags.Any) return true; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because @@ -11008,11 +11789,11 @@ namespace ts { } function isTypeRelatedTo(source: Type, target: Type, relation: Map) { - if (source.flags & TypeFlags.StringOrNumberLiteral && source.flags & TypeFlags.FreshLiteral) { - source = (source).regularType; + if (isFreshLiteralType(source)) { + source = (source).regularType; } - if (target.flags & TypeFlags.StringOrNumberLiteral && target.flags & TypeFlags.FreshLiteral) { - target = (target).regularType; + if (isFreshLiteralType(target)) { + target = (target).regularType; } if (source === target || relation === comparableRelation && !(target.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(target, source, relation) || @@ -11056,6 +11837,7 @@ namespace ts { ): boolean { let errorInfo: DiagnosticMessageChain | undefined; + let relatedInfo: [DiagnosticRelatedInformation, ...DiagnosticRelatedInformation[]] | undefined; let maybeKeys: string[]; let sourceStack: Type[]; let targetStack: Type[]; @@ -11063,7 +11845,7 @@ namespace ts { let depth = 0; let expandingFlags = ExpandingFlags.None; let overflow = false; - let isIntersectionConstituent = false; + let suppressNextError = false; Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); @@ -11094,6 +11876,9 @@ namespace ts { } const diag = createDiagnosticForNodeFromMessageChain(errorNode!, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo(diag, ...relatedInfo); + } if (errorOutputContainer) { errorOutputContainer.error = diag; } @@ -11101,9 +11886,19 @@ namespace ts { } return result !== Ternary.False; - function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): void { + function reportError(message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number, arg3?: string | number): void { Debug.assert(!!errorNode); - errorInfo = chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + errorInfo = chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + } + + function associateRelatedInfo(info: DiagnosticRelatedInformation) { + Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } + else { + relatedInfo.push(info); + } } function reportRelationError(message: DiagnosticMessage | undefined, source: Type, target: Type) { @@ -11166,15 +11961,15 @@ namespace ts { * * Ternary.Maybe if they are related with assumptions of other relationships, or * * Ternary.False if they are not related. */ - function isRelatedTo(source: Type, target: Type, reportErrors = false, headMessage?: DiagnosticMessage): Ternary { - if (source.flags & TypeFlags.StringOrNumberLiteral && source.flags & TypeFlags.FreshLiteral) { - source = (source).regularType; + function isRelatedTo(source: Type, target: Type, reportErrors = false, headMessage?: DiagnosticMessage, isApparentIntersectionConstituent?: boolean): Ternary { + if (isFreshLiteralType(source)) { + source = (source).regularType; } - if (target.flags & TypeFlags.StringOrNumberLiteral && target.flags & TypeFlags.FreshLiteral) { - target = (target).regularType; + if (isFreshLiteralType(target)) { + target = (target).regularType; } if (source.flags & TypeFlags.Substitution) { - source = relation === definitelyAssignableRelation ? (source).typeVariable : (source).substitute; + source = (source).substitute; } if (target.flags & TypeFlags.Substitution) { target = (target).typeVariable; @@ -11213,7 +12008,8 @@ namespace ts { if (relation === comparableRelation && !(target.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return Ternary.True; - if (isObjectLiteralType(source) && source.flags & TypeFlags.FreshLiteral) { + const isComparingJsxAttributes = !!(getObjectFlags(source) & ObjectFlags.JsxAttributes); + if (isObjectLiteralType(source) && getObjectFlags(source) & ObjectFlags.FreshLiteral) { const discriminantType = target.flags & TypeFlags.Union ? findMatchingDiscriminantType(source, target as UnionType) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { if (reportErrors) { @@ -11230,11 +12026,11 @@ namespace ts { } } - if (relation !== comparableRelation && !isIntersectionConstituent && + if (relation !== comparableRelation && !isApparentIntersectionConstituent && source.flags & (TypeFlags.Primitive | TypeFlags.Object | TypeFlags.Intersection) && source !== globalObjectType && target.flags & (TypeFlags.Object | TypeFlags.Intersection) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - !hasCommonProperties(source, target)) { + !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { const calls = getSignaturesOfType(source, SignatureKind.Call); const constructs = getSignaturesOfType(source, SignatureKind.Construct); @@ -11251,8 +12047,7 @@ namespace ts { let result = Ternary.False; const saveErrorInfo = errorInfo; - const saveIsIntersectionConstituent = isIntersectionConstituent; - isIntersectionConstituent = false; + let isIntersectionConstituent = !!isApparentIntersectionConstituent; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), @@ -11267,7 +12062,7 @@ namespace ts { result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & TypeFlags.Primitive) && !(target.flags & TypeFlags.Primitive)); } else if (target.flags & TypeFlags.Intersection) { - isIntersectionConstituent = true; + isIntersectionConstituent = true; // set here to affect the following trio of checks result = typeRelatedToEachType(source, target as IntersectionType, reportErrors); } else if (source.flags & TypeFlags.Intersection) { @@ -11287,7 +12082,7 @@ namespace ts { result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } if (!result && (source.flags & TypeFlags.StructuredOrInstantiable || target.flags & TypeFlags.StructuredOrInstantiable)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } @@ -11304,22 +12099,22 @@ namespace ts { // 'string & number | number & number' which reduces to just 'number'. const constraint = getUnionConstraintOfIntersection(source, !!(target.flags & TypeFlags.Union)); if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - isIntersectionConstituent = saveIsIntersectionConstituent; - if (!result && reportErrors) { + const maybeSuppress = suppressNextError; + suppressNextError = false; if (source.flags & TypeFlags.Object && target.flags & TypeFlags.Primitive) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } else if (source.symbol && source.flags & TypeFlags.Object && globalObjectType === source) { reportError(Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } - else if (getObjectFlags(source) & ObjectFlags.JsxAttributes && target.flags & TypeFlags.Intersection) { + else if (isComparingJsxAttributes && target.flags & TypeFlags.Intersection) { const targetTypes = (target as IntersectionType).types; const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); const intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); @@ -11329,6 +12124,10 @@ namespace ts { return result; } } + if (!headMessage && maybeSuppress) { + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return result; + } reportRelationError(headMessage, source, target); } return result; @@ -11338,7 +12137,7 @@ namespace ts { let result: Ternary; const flags = source.flags & target.flags; if (flags & TypeFlags.Object || flags & TypeFlags.IndexedAccess || flags & TypeFlags.Conditional || flags & TypeFlags.Index || flags & TypeFlags.Substitution) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); } if (flags & (TypeFlags.Union | TypeFlags.Intersection)) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -11354,9 +12153,9 @@ namespace ts { if (!noImplicitAny && getObjectFlags(target) & ObjectFlags.JSLiteral) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, TypeFlags.Object) && !(getObjectFlags(target) & ObjectFlags.ObjectLiteralPatternWithComputedProperties)) { + if (isExcessPropertyCheckTarget(target)) { const isComparingJsxAttributes = !!(getObjectFlags(source) & ObjectFlags.JsxAttributes); - if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } @@ -11365,16 +12164,20 @@ namespace ts { return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } for (const prop of getPropertiesOfObjectType(source)) { - if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { + // Report error in terms of object types in the target as those are the only ones + // we check in isKnownProperty. + const errorTarget = filterType(target, isExcessPropertyCheckTarget); // 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. if (!errorNode) return Debug.fail(); - if (isJsxAttributes(errorNode) || isJsxOpeningLikeElement(errorNode)) { + if (isJsxAttributes(errorNode) || isJsxOpeningLikeElement(errorNode) || isJsxOpeningLikeElement(errorNode.parent)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. - reportError(Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) + reportError(Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget)); } else { // use the property's value declaration if the property is assigned inside the literal itself @@ -11388,17 +12191,17 @@ namespace ts { const name = propDeclaration.name!; if (isIdentifier(name)) { - suggestion = getSuggestionForNonexistentProperty(name, target); + suggestion = getSuggestionForNonexistentProperty(name, errorTarget); } } if (suggestion !== undefined) { reportError(Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, - symbolToString(prop), typeToString(target), suggestion); + symbolToString(prop), typeToString(errorTarget), suggestion); } else { reportError(Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, - symbolToString(prop), typeToString(target)); + symbolToString(prop), typeToString(errorTarget)); } } } @@ -11409,8 +12212,8 @@ namespace ts { return false; } - function isPropertyFromSpread(prop: Symbol, container: Symbol) { - return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + function shouldCheckAsExcessProperty(prop: Symbol, container: Symbol) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; } function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType): Ternary { @@ -11441,7 +12244,9 @@ namespace ts { const bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } @@ -11472,36 +12277,62 @@ namespace ts { } } + function findBestTypeForInvokable(source: Type, unionTarget: UnionOrIntersectionType) { + let signatureKind = SignatureKind.Call; + const hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = SignatureKind.Construct, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return find(unionTarget.types, t => getSignaturesOfType(t, signatureKind).length > 0); + } + } + + function findMostOverlappyType(source: Type, unionTarget: UnionOrIntersectionType) { + let bestMatch: Type | undefined; + let matchingCount = 0; + for (const target of unionTarget.types) { + const overlap = getIntersectionType([getIndexType(source), getIndexType(target)]); + if (overlap.flags & TypeFlags.Index) { + // perfect overlap of keys + bestMatch = target; + matchingCount = Infinity; + } + else if (overlap.flags & TypeFlags.Union) { + // We only want to account for literal types otherwise. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + const len = length(filter((overlap as UnionType).types, isUnitType)); + if (len >= matchingCount) { + bestMatch = target; + matchingCount = len; + } + } + else if (isUnitType(overlap) && 1 >= matchingCount) { + bestMatch = target; + matchingCount = 1; + } + } + return bestMatch; + } + // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly - function findMatchingDiscriminantType(source: Type, target: UnionOrIntersectionType) { - let match: Type | undefined; - const sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); - if (sourcePropertiesFiltered) { - for (const sourceProperty of sourcePropertiesFiltered) { - const sourceType = getTypeOfSymbol(sourceProperty); - for (const type of target.types) { - const targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } + function findMatchingDiscriminantType(source: Type, target: Type) { + if (target.flags & TypeFlags.Union) { + const sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, p => ([() => getTypeOfSymbol(p), p.escapedName] as [() => Type, __String])), isRelatedTo); } } } - return match; + return undefined; } function typeRelatedToEachType(source: Type, target: IntersectionType, reportErrors: boolean): Ternary { let result = Ternary.True; const targetTypes = target.types; for (const targetType of targetTypes) { - const related = isRelatedTo(source, targetType, reportErrors); + const related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); if (!related) { return Ternary.False; } @@ -11538,9 +12369,7 @@ namespace ts { return result; } - function typeArgumentsRelatedTo(source: TypeReference, target: TypeReference, variances: Variance[], reportErrors: boolean): Ternary { - const sources = source.typeArguments || emptyArray; - const targets = target.typeArguments || emptyArray; + function typeArgumentsRelatedTo(sources: ReadonlyArray = emptyArray, targets: ReadonlyArray = emptyArray, variances: ReadonlyArray = emptyArray, reportErrors: boolean): Ternary { if (sources.length !== targets.length && relation === identityRelation) { return Ternary.False; } @@ -11595,7 +12424,7 @@ namespace ts { // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function recursiveTypeRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary { + function recursiveTypeRelatedTo(source: Type, target: Type, reportErrors: boolean, isIntersectionConstituent: boolean): Ternary { if (overflow) { return Ternary.False; } @@ -11636,7 +12465,7 @@ namespace ts { const saveExpandingFlags = expandingFlags; if (!(expandingFlags & ExpandingFlags.Source) && isDeeplyNestedType(source, sourceStack, depth)) expandingFlags |= ExpandingFlags.Source; if (!(expandingFlags & ExpandingFlags.Target) && isDeeplyNestedType(target, targetStack, depth)) expandingFlags |= ExpandingFlags.Target; - const result = expandingFlags !== ExpandingFlags.Both ? structuredTypeRelatedTo(source, target, reportErrors) : Ternary.Maybe; + const result = expandingFlags !== ExpandingFlags.Both ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : Ternary.Maybe; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -11657,11 +12486,7 @@ namespace ts { return result; } - function getConstraintForRelation(type: Type) { - return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); - } - - function structuredTypeRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary { + function structuredTypeRelatedTo(source: Type, target: Type, reportErrors: boolean, isIntersectionConstituent: boolean): Ternary { const flags = source.flags & target.flags; if (relation === identityRelation && !(flags & TypeFlags.Object)) { if (flags & TypeFlags.Index) { @@ -11693,12 +12518,28 @@ namespace ts { } return Ternary.False; } + let result: Ternary; let originalErrorInfo: DiagnosticMessageChain | undefined; const saveErrorInfo = errorInfo; + + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (TypeFlags.Object | TypeFlags.Conditional) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + const variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & TypeFlags.TypeParameter) { - // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (getObjectFlags(source) & ObjectFlags.Mapped && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (getObjectFlags(source) & ObjectFlags.Mapped && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { if (!(getMappedTypeModifiers(source) & MappedTypeModifiers.IncludeOptional)) { const templateType = getTemplateTypeFromMappedType(source); const indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -11717,19 +12558,23 @@ namespace ts { } // A type S is assignable to keyof T if S is assignable to keyof C, where C is the // simplified form of T or, if T doesn't simplify, the constraint of T. - if (relation !== definitelyAssignableRelation) { - const simplified = getSimplifiedType((target).type); - const constraint = simplified !== (target).type ? simplified : getConstraintOfType((target).type); - if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, (target as IndexType).stringsOnly), reportErrors)) { - return result; - } + const simplified = getSimplifiedType((target).type); + const constraint = simplified !== (target).type ? simplified : getConstraintOfType((target).type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, (target as IndexType).stringsOnly), reportErrors) === Ternary.True) { + return Ternary.True; } } } else if (target.flags & TypeFlags.IndexedAccess) { - // A type S is related to a type T[K] if S is related to C, where C is the base constraint of T[K] - if (relation !== identityRelation) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && + !(isGenericObjectType((target).objectType) && isGenericIndexType((target).indexType))) { const constraint = getBaseConstraintOfType(target); if (constraint && constraint !== target) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -11747,14 +12592,16 @@ namespace ts { (template).indexType === getTypeParameterFromMappedType(target)) { return Ternary.True; } - // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { const indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); const templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { return result; } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } } @@ -11769,20 +12616,23 @@ namespace ts { return result; } } - const constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & TypeFlags.TypeParameter && constraint.flags & TypeFlags.AnyOrUnknown)) { + const constraint = getConstraintOfType(source); + if (!constraint || (source.flags & TypeFlags.TypeParameter && constraint.flags & TypeFlags.Any)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~TypeFlags.NonPrimitive))) { errorInfo = saveErrorInfo; return result; } } - else { - const instantiated = getTypeWithThisArgument(constraint, source); - if (result = isRelatedTo(instantiated, target, reportErrors)) { + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; return result; - } + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; } } else if (source.flags & TypeFlags.Index) { @@ -11807,7 +12657,7 @@ namespace ts { } } } - else if (relation !== definitelyAssignableRelation) { + else { const distributiveConstraint = getConstraintOfDistributiveConditionalType(source); if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { @@ -11826,7 +12676,7 @@ namespace ts { } else { // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + if (relation !== subtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) { return Ternary.True; } if (isGenericMappedType(target)) { @@ -11838,9 +12688,6 @@ namespace ts { } return Ternary.False; } - if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { - return Ternary.False; - } const sourceIsPrimitive = !!(source.flags & TypeFlags.Primitive); if (relation !== identityRelation) { source = getApparentType(source); @@ -11851,7 +12698,7 @@ namespace ts { // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. const variances = getVariances((source).target); - if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { + if (result = typeArgumentsRelatedTo((source).typeArguments, (target).typeArguments, variances, reportErrors)) { return result; } // The type arguments did not relate appropriately, but it may be because we have no variance @@ -11935,10 +12782,27 @@ namespace ts { return propertiesIdenticalTo(source, target); } const requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); - const unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + const unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false); if (unmatchedProperty) { if (reportErrors) { - reportError(Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + const props = arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false)); + if (!headMessage || (headMessage.code !== Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it + } + if (props.length === 1) { + const propName = symbolToString(unmatchedProperty); + reportError(Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + if (length(unmatchedProperty.declarations)) { + associateRelatedInfo(createDiagnosticForNode(unmatchedProperty.declarations[0], Diagnostics._0_is_declared_here, propName)); + } + } + else if (props.length > 5) { // arbitrary cutoff for too-long list form + reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), map(props.slice(0, 4), p => symbolToString(p)).join(", "), props.length - 4); + } + else { + reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), map(props, p => symbolToString(p)).join(", ")); + } } return Ternary.False; } @@ -12092,8 +12956,8 @@ namespace ts { return Ternary.True; } - const sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - const targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + const sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + const targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); const sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === SignatureKind.Construct) ? SignatureKind.Call : kind); @@ -12304,6 +13168,25 @@ namespace ts { } } + function discriminateTypeByDiscriminableItems(target: UnionType, discriminators: [() => Type, __String][], related: (source: Type, target: Type) => boolean | Ternary): Type | undefined; + function discriminateTypeByDiscriminableItems(target: UnionType, discriminators: [() => Type, __String][], related: (source: Type, target: Type) => boolean | Ternary, defaultValue: Type): Type; + function discriminateTypeByDiscriminableItems(target: UnionType, discriminators: [() => Type, __String][], related: (source: Type, target: Type) => boolean | Ternary, defaultValue?: Type) { + let match: Type | undefined; + for (const [getDiscriminatingType, propertyName] of discriminators) { + for (const type of target.types) { + const targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** * A type is 'weak' if it is an object type with at least one optional property * and no required properties, call/construct signatures or index signatures @@ -12322,8 +13205,7 @@ namespace ts { return false; } - function hasCommonProperties(source: Type, target: Type) { - const isComparingJsxAttributes = !!(getObjectFlags(source) & ObjectFlags.JsxAttributes); + function hasCommonProperties(source: Type, target: Type, isComparingJsxAttributes: boolean) { for (const prop of getPropertiesOfType(source)) { if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { return true; @@ -12340,48 +13222,58 @@ namespace ts { return result; } + function getAliasVariances(symbol: Symbol) { + const links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, (_links, param, marker) => { + const type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters!, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } + // Return an array containing the variance of each type parameter. The variance is effectively // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters: ReadonlyArray = emptyArray, cache: TCache, createMarkerType: (input: TCache, param: TypeParameter, marker: Type) => Type): Variance[] { + let variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = emptyArray; + variances = []; + for (const tp of typeParameters) { + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + const typeWithSuper = createMarkerType(cache, tp, markerSuperType); + const typeWithSub = createMarkerType(cache, tp, markerSubType); + let variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? Variance.Covariant : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? Variance.Contravariant : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === Variance.Bivariant && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = Variance.Independent; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } + function getVariances(type: GenericType): Variance[] { if (!strictFunctionTypes) { return emptyArray; } - const typeParameters = type.typeParameters || emptyArray; - let variances = type.variances; - if (!variances) { - if (type === globalArrayType || type === globalReadonlyArrayType) { - // Arrays are known to be covariant, no need to spend time computing this - variances = [Variance.Covariant]; - } - else { - // The emptyArray singleton is used to signal a recursive invocation. - type.variances = emptyArray; - variances = []; - for (const tp of typeParameters) { - // We first compare instantiations where the type parameter is replaced with - // marker types that have a known subtype relationship. From this we can infer - // invariance, covariance, contravariance or bivariance. - const typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); - const typeWithSub = getMarkerTypeReference(type, tp, markerSubType); - let variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? Variance.Covariant : 0) | - (isTypeAssignableTo(typeWithSuper, typeWithSub) ? Variance.Contravariant : 0); - // If the instantiations appear to be related bivariantly it may be because the - // type parameter is independent (i.e. it isn't witnessed anywhere in the generic - // type). To determine this we compare instantiations where the type parameter is - // replaced with marker types that are known to be unrelated. - if (variance === Variance.Bivariant && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { - variance = Variance.Independent; - } - variances.push(variance); - } - } - type.variances = variances; + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return emptyArray; } - return variances; + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } // Return true if the given type reference has a 'void' type argument for a covariant type parameter. @@ -12558,13 +13450,8 @@ namespace ts { 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). - const sourceRestCount = sourceHasRestParameter ? 1 : 0; - const targetRestCount = targetHasRestParameter ? 1 : 0; - if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && ( - sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) { + // parameters + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { return true; } return false; @@ -12613,7 +13500,7 @@ namespace ts { for (let i = 0; i < targetLen; i++) { const s = getTypeAtPosition(source, i); const t = getTypeAtPosition(target, i); - const related = compareTypes(s, t); + const related = compareTypes(t, s); if (!related) { return Ternary.False; } @@ -12680,6 +13567,10 @@ namespace ts { return !!(getObjectFlags(type) & ObjectFlags.Reference) && (type).target === globalReadonlyArrayType; } + function getElementTypeOfArrayType(type: Type): Type | undefined { + return isArrayType(type) && (type as TypeReference).typeArguments ? (type as TypeReference).typeArguments![0] : undefined; + } + function isArrayLikeType(type: Type): boolean { // 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 @@ -12696,10 +13587,19 @@ namespace ts { return isTupleType(type) || !!getPropertyOfType(type, "0" as __String); } + function isArrayOrTupleLikeType(type: Type): boolean { + return isArrayLikeType(type) || isTupleLikeType(type); + } + function getTupleElementType(type: Type, index: number) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments![index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index as __String); + const propType = getTypeOfPropertyOfType(type, "" + index as __String); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, t => !(t).target.hasRestElement)) { + return mapType(type, t => getRestTypeOfTupleType(t) || undefinedType); + } + return undefined; } function isNeitherUnitTypeNorNever(type: Type): boolean { @@ -12720,16 +13620,18 @@ namespace ts { return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : type.flags & TypeFlags.StringLiteral ? stringType : type.flags & TypeFlags.NumberLiteral ? numberType : + type.flags & TypeFlags.BigIntLiteral ? bigintType : type.flags & TypeFlags.BooleanLiteral ? booleanType : type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type: Type): Type { - return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : - type.flags & TypeFlags.StringLiteral && type.flags & TypeFlags.FreshLiteral ? stringType : - type.flags & TypeFlags.NumberLiteral && type.flags & TypeFlags.FreshLiteral ? numberType : - type.flags & TypeFlags.BooleanLiteral ? booleanType : + return type.flags & TypeFlags.EnumLiteral && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & TypeFlags.StringLiteral && isFreshLiteralType(type) ? stringType : + type.flags & TypeFlags.NumberLiteral && isFreshLiteralType(type) ? numberType : + type.flags & TypeFlags.BigIntLiteral && isFreshLiteralType(type) ? bigintType : + type.flags & TypeFlags.BooleanLiteral && isFreshLiteralType(type) ? booleanType : type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getWidenedLiteralType)) : type; } @@ -12768,6 +13670,10 @@ namespace ts { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } + function isZeroBigInt({value}: BigIntLiteralType) { + return value.base10Value === "0"; + } + function getFalsyFlagsOfTypes(types: Type[]): TypeFlags { let result: TypeFlags = 0; for (const t of types) { @@ -12783,7 +13689,8 @@ namespace ts { return type.flags & TypeFlags.Union ? getFalsyFlagsOfTypes((type).types) : type.flags & TypeFlags.StringLiteral ? (type).value === "" ? TypeFlags.StringLiteral : 0 : type.flags & TypeFlags.NumberLiteral ? (type).value === 0 ? TypeFlags.NumberLiteral : 0 : - type.flags & TypeFlags.BooleanLiteral ? type === falseType ? TypeFlags.BooleanLiteral : 0 : + type.flags & TypeFlags.BigIntLiteral ? isZeroBigInt(type) ? TypeFlags.BigIntLiteral : 0 : + type.flags & TypeFlags.BooleanLiteral ? (type === falseType || type === regularFalseType) ? TypeFlags.BooleanLiteral : 0 : type.flags & TypeFlags.PossiblyFalsy; } @@ -12800,10 +13707,13 @@ namespace ts { function getDefinitelyFalsyPartOfType(type: Type): Type { return type.flags & TypeFlags.String ? emptyStringType : type.flags & TypeFlags.Number ? zeroType : - type.flags & TypeFlags.Boolean || type === falseType ? falseType : + type.flags & TypeFlags.BigInt ? zeroBigIntType : + type === regularFalseType || + type === falseType || type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null) || type.flags & TypeFlags.StringLiteral && (type).value === "" || - type.flags & TypeFlags.NumberLiteral && (type).value === 0 ? type : + type.flags & TypeFlags.NumberLiteral && (type).value === 0 || + type.flags & TypeFlags.BigIntLiteral && isZeroBigInt(type) ? type : neverType; } @@ -12880,7 +13790,7 @@ namespace ts { * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type: Type): Type { - if (!(isObjectLiteralType(type) && type.flags & TypeFlags.FreshLiteral)) { + if (!(isObjectLiteralType(type) && getObjectFlags(type) & ObjectFlags.FreshLiteral)) { return type; } const regularType = (type).regularType; @@ -12896,7 +13806,7 @@ namespace ts { resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~TypeFlags.FreshLiteral; + regularNew.flags = resolved.flags; regularNew.objectFlags |= ObjectFlags.ObjectLiteral | (getObjectFlags(resolved) & ObjectFlags.JSLiteral); (type).regularType = regularNew; return regularNew; @@ -13003,6 +13913,9 @@ namespace ts { // union includes empty object types (e.g. reducing {} | string to just {}). return getUnionType(widenedTypes, some(widenedTypes, isEmptyObjectType) ? UnionReduction.Subtype : UnionReduction.Literal); } + if (type.flags & TypeFlags.Intersection) { + return getIntersectionType(sameMap((type).types, getWidenedType)); + } if (isArrayType(type) || isTupleType(type)) { return createTypeReference((type).target, sameMap((type).typeArguments, getWidenedType)); } @@ -13058,23 +13971,44 @@ namespace ts { return errorReported; } - function reportImplicitAnyError(declaration: Declaration, type: Type) { + function reportImplicitAny(declaration: Declaration, type: Type) { const typeAsString = typeToString(getWidenedType(type)); + if (isInJSFile(declaration) && !isCheckJsEnabledForFile(getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } let diagnostic: DiagnosticMessage; switch (declaration.kind) { case SyntaxKind.BinaryExpression: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - diagnostic = Diagnostics.Member_0_implicitly_has_an_1_type; + diagnostic = noImplicitAny ? Diagnostics.Member_0_implicitly_has_an_1_type : Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; case SyntaxKind.Parameter: + const param = declaration as ParameterDeclaration; + if (isIdentifier(param.name) && + (isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && + param.parent.parameters.indexOf(param) > -1 && + (resolveName(param, param.name.escapedText, SymbolFlags.Type, undefined, param.name.escapedText, /*isUse*/ true) || + param.name.originalKeywordKind && isTypeNodeKind(param.name.originalKeywordKind))) { + const newName = "arg" + param.parent.parameters.indexOf(param); + errorOrSuggestion(noImplicitAny, declaration, Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, declarationNameToString(param.name)); + return; + } diagnostic = (declaration).dotDotDotToken ? - Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - Diagnostics.Parameter_0_implicitly_has_an_1_type; + noImplicitAny ? Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? Diagnostics.Parameter_0_implicitly_has_an_1_type : Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; case SyntaxKind.BindingElement: diagnostic = Diagnostics.Binding_element_0_implicitly_has_an_1_type; + if (!noImplicitAny) { + // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. + return; + } break; + case SyntaxKind.JSDocFunctionType: + error(declaration, Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: @@ -13082,26 +14016,28 @@ namespace ts { case SyntaxKind.SetAccessor: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - if (!(declaration as NamedDeclaration).name) { + if (noImplicitAny && !(declaration as NamedDeclaration).name) { error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } - diagnostic = Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + diagnostic = noImplicitAny ? Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; break; case SyntaxKind.MappedType: - error(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: - diagnostic = Diagnostics.Variable_0_implicitly_has_an_1_type; + diagnostic = noImplicitAny ? Diagnostics.Variable_0_implicitly_has_an_1_type : Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; } - error(declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration: Declaration, type: Type) { if (produceDiagnostics && noImplicitAny && type.flags & TypeFlags.ContainsWideningType) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } @@ -13111,10 +14047,8 @@ namespace ts { const targetCount = getParameterCount(target); const sourceRestType = getEffectiveRestType(source); const targetRestType = getEffectiveRestType(target); - const paramCount = targetRestType ? Math.min(targetCount - 1, sourceCount) : - sourceRestType ? targetCount : - Math.min(sourceCount, targetCount); - + const targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + const paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); const sourceThisType = getThisTypeOfSignature(source); if (sourceThisType) { const targetThisType = getThisTypeOfSignature(target); @@ -13224,18 +14158,18 @@ namespace ts { * property is computed by inferring from the source property type to X for the type * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ - function inferTypeForHomomorphicMappedType(source: Type, target: MappedType): Type | undefined { - const key = source.id + "," + target.id; + function inferTypeForHomomorphicMappedType(source: Type, target: MappedType, constraint: IndexType): Type | undefined { + const key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } reverseMappedCache.set(key, undefined); - const type = createReverseMappedType(source, target); + const type = createReverseMappedType(source, target, constraint); reverseMappedCache.set(key, type); return type; } - function createReverseMappedType(source: Type, target: MappedType) { + function createReverseMappedType(source: Type, target: MappedType, constraint: IndexType) { const properties = getPropertiesOfType(source); if (properties.length === 0 && !getIndexInfoOfType(source, IndexKind.String)) { return undefined; @@ -13250,13 +14184,13 @@ namespace ts { // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been // applied to the element type(s). if (isArrayType(source)) { - return createArrayType(inferReverseMappedType((source).typeArguments![0], target)); + return createArrayType(inferReverseMappedType((source).typeArguments![0], target, constraint)); } if (isReadonlyArrayType(source)) { - return createReadonlyArrayType(inferReverseMappedType((source).typeArguments![0], target)); + return createReadonlyArrayType(inferReverseMappedType((source).typeArguments![0], target, constraint)); } if (isTupleType(source)) { - const elementTypes = map(source.typeArguments || emptyArray, t => inferReverseMappedType(t, target)); + const elementTypes = map(source.typeArguments || emptyArray, t => inferReverseMappedType(t, target, constraint)); const minLength = getMappedTypeModifiers(target) & MappedTypeModifiers.IncludeOptional ? getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); @@ -13266,32 +14200,45 @@ namespace ts { const reversed = createObjectType(ObjectFlags.ReverseMapped | ObjectFlags.Anonymous, /*symbol*/ undefined) as ReverseMappedType; reversed.source = source; reversed.mappedType = target; + reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol: ReverseMappedSymbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); } - function inferReverseMappedType(sourceType: Type, target: MappedType): Type { - const typeParameter = getIndexedAccessType((getConstraintTypeFromMappedType(target)).type, getTypeParameterFromMappedType(target)); + function inferReverseMappedType(sourceType: Type, target: MappedType, constraint: IndexType): Type { + const typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); const templateType = getTemplateTypeFromMappedType(target); const inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperty(source: Type, target: Type, requireOptionalProperties: boolean) { + function* getUnmatchedProperties(source: Type, target: Type, requireOptionalProperties: boolean, matchDiscriminantProperties: boolean) { const properties = target.flags & TypeFlags.Intersection ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); for (const targetProp of properties) { if (requireOptionalProperties || !(targetProp.flags & SymbolFlags.Optional)) { const sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!sourceProp) { - return targetProp; + yield targetProp; + } + else if (matchDiscriminantProperties) { + const targetType = getTypeOfSymbol(targetProp); + if (targetType.flags & TypeFlags.Unit) { + const sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType.flags & TypeFlags.Any || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) { + yield targetProp; + } + } } } } - return undefined; + } + + function getUnmatchedProperty(source: Type, target: Type, requireOptionalProperties: boolean, matchDiscriminantProperties: boolean): Symbol | undefined { + return getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next().value; } function tupleTypesDefinitelyUnrelated(source: TupleTypeReference, target: TupleTypeReference) { @@ -13303,7 +14250,8 @@ namespace ts { // Two tuple types with incompatible arities are definitely unrelated. // Two object types that each have a property that is unmatched in the other are definitely unrelated. return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || - !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) && + !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true); } function getTypeFromInference(inference: InferenceInfo) { @@ -13316,10 +14264,12 @@ namespace ts { let symbolStack: Symbol[]; let visited: Map; let contravariant = false; + let bivariant = false; let propagationType: Type; + let allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); - function inferFromTypes(source: Type, target: Type) { + function inferFromTypes(source: Type, target: Type): void { if (!couldContainTypeVariables(target)) { return; } @@ -13388,7 +14338,7 @@ namespace ts { // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & TypeFlags.ContainsAnyFunctionType || source === silentNeverType) { + if (source.flags & TypeFlags.ContainsAnyFunctionType || source === silentNeverType || (priority & InferencePriority.ReturnType && (source === autoType || source === autoArrayType))) { return; } const inference = getInferenceInfoForType(target); @@ -13401,11 +14351,13 @@ namespace ts { } if (priority === inference.priority) { const candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = append(inference.candidates, candidate); + inference.candidates = appendIfUnique(inference.candidates, candidate); } } if (!(priority & InferencePriority.ReturnType) && target.flags & TypeFlags.TypeParameter && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -13414,6 +14366,24 @@ namespace ts { } return; } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + const simplified = getSimplifiedType(target); + if (simplified !== target) { + inferFromTypesOnce(source, simplified); + } + else if (target.flags & TypeFlags.IndexedAccess) { + const indexType = getSimplifiedType((target as IndexedAccessType).indexType); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & TypeFlags.Instantiable) { + const simplified = distributeIndexOverObjectType(getSimplifiedType((target as IndexedAccessType).objectType), indexType); + if (simplified && simplified !== target) { + inferFromTypesOnce(source, simplified); + } + } + } + } } if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) { // If source and target are references to the same generic type, infer from type arguments @@ -13454,6 +14424,9 @@ namespace ts { inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & TypeFlags.Conditional) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & TypeFlags.UnionOrIntersection) { const targetTypes = (target).types; let typeVariableCount = 0; @@ -13487,7 +14460,22 @@ namespace ts { } else { if (!(priority & InferencePriority.NoConstraints && source.flags & (TypeFlags.Intersection | TypeFlags.Instantiable))) { - source = getApparentType(source); + const apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (TypeFlags.Object | TypeFlags.Intersection))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (TypeFlags.Object | TypeFlags.Intersection)) { const key = source.id + "," + target.id; @@ -13515,6 +14503,14 @@ namespace ts { } } } + + function inferFromTypesOnce(source: Type, target: Type) { + const key = source.id + "," + target.id; + if (!visited || !visited.get(key)) { + (visited || (visited = createMap())).set(key, true); + inferFromTypes(source, target); + } + } } function inferFromContravariantTypes(source: Type, target: Type) { @@ -13539,6 +14535,44 @@ namespace ts { return undefined; } + function inferFromMappedTypeConstraint(source: Type, target: Type, constraintType: Type): boolean { + if (constraintType.flags & TypeFlags.Union) { + let result = false; + for (const type of (constraintType as UnionType).types) { + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & TypeFlags.Index) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + const inference = getInferenceInfoForType((constraintType).type); + if (inference && !inference.isFixed) { + const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType as IndexType); + if (inferredType) { + const savePriority = priority; + priority |= InferencePriority.HomomorphicMappedType; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & TypeFlags.TypeParameter) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + const savePriority = priority; + priority |= InferencePriority.MappedTypeConstraint; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } + function inferFromObjectTypes(source: Type, target: Type) { if (isGenericMappedType(source) && isGenericMappedType(target)) { // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer @@ -13548,31 +14582,7 @@ namespace ts { } if (getObjectFlags(target) & ObjectFlags.Mapped) { const constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & TypeFlags.Index) { - // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, - // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source - // type and then make a secondary inference from that type to T. We make a secondary inference - // such that direct inferences to T get priority over inferences to Partial, for example. - const inference = getInferenceInfoForType((constraintType).type); - if (inference && !inference.isFixed) { - const inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - const savePriority = priority; - priority |= InferencePriority.HomomorphicMappedType; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; - } - } - return; - } - if (constraintType.flags & TypeFlags.TypeParameter) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. - const savePriority = priority; - priority |= InferencePriority.MappedTypeConstraint; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; - inferFromTypes(getUnionType(map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { return; } } @@ -13635,7 +14645,12 @@ namespace ts { function inferFromSignature(source: Signature, target: Signature, skipParameters: boolean) { if (!skipParameters) { + const saveBivariant = bivariant; + const kind = target.declaration ? target.declaration.kind : SyntaxKind.Unknown; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === SyntaxKind.MethodDeclaration || kind === SyntaxKind.MethodSignature || kind === SyntaxKind.Constructor; forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; } const sourceTypePredicate = getTypePredicateOfSignature(source); const targetTypePredicate = getTypePredicateOfSignature(target); @@ -13693,7 +14708,7 @@ namespace ts { function hasPrimitiveConstraint(type: TypeParameter): boolean { const constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, TypeFlags.Primitive | TypeFlags.Index); + return !!constraint && maybeTypeOfKind(constraint.flags & TypeFlags.Conditional ? getDefaultConstraintOfConditionalType(constraint as ConditionalType) : constraint, TypeFlags.Primitive | TypeFlags.Index); } function isObjectLiteralType(type: Type) { @@ -13742,15 +14757,17 @@ namespace ts { if (!inferredType) { const signature = context.signature; if (signature) { - if (inference.contraCandidates && (!inference.candidates || inference.candidates.length === 1 && inference.candidates[0].flags & TypeFlags.Never)) { - // If we have contravariant inferences, but no covariant inferences or a single - // covariant inference of 'never', we find the best common subtype and treat that - // as a single covariant candidate. - inference.candidates = [getContravariantInference(inference)]; - inference.contraCandidates = undefined; + const inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + if (inference.contraCandidates) { + const inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & TypeFlags.Never) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } else if (context.flags & InferenceFlags.NoDefault) { // We use silentNeverType as the wildcard that signals no inferences. @@ -13808,6 +14825,36 @@ namespace ts { // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name: __String): DiagnosticMessage { + switch (name) { + case "document": + case "console": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + case "describe": + case "suite": + case "it": + case "test": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + case "process": + case "require": + case "Buffer": + case "module": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return Diagnostics.Cannot_find_name_0; + } + } + function getResolvedSymbol(node: Identifier): Symbol { const links = getNodeLinks(node); if (!links.resolvedSymbol) { @@ -13816,7 +14863,7 @@ namespace ts { node, node.escapedText, SymbolFlags.Value | SymbolFlags.ExportValue, - Diagnostics.Cannot_find_name_0, + getCannotFindNameDiagnosticForName(node.escapedText), node, !isWriteOnlyAccess(node), /*excludeGlobals*/ false, @@ -13841,50 +14888,32 @@ namespace ts { // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node: Node): string | undefined { - if (node.kind === SyntaxKind.Identifier) { - const symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === SyntaxKind.ThisKeyword) { - return "0"; - } - if (node.kind === SyntaxKind.PropertyAccessExpression) { - const key = getFlowCacheKey((node).expression); - return key && key + "." + idText((node).name); - } - if (node.kind === SyntaxKind.BindingElement) { - const container = (node as BindingElement).parent.parent; - const key = container.kind === SyntaxKind.BindingElement ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); - const text = getBindingElementNameText(node as BindingElement); - const result = key && text && (key + "." + text); - return result; + switch (node.kind) { + case SyntaxKind.Identifier: + const symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + case SyntaxKind.ThisKeyword: + return "0"; + case SyntaxKind.NonNullExpression: + case SyntaxKind.ParenthesizedExpression: + return getFlowCacheKey((node).expression); + case SyntaxKind.PropertyAccessExpression: + case SyntaxKind.ElementAccessExpression: + const propName = getAccessedPropertyName(node); + if (propName !== undefined) { + const key = getFlowCacheKey((node).expression); + return key && key + "." + propName; + } } return undefined; } - function getBindingElementNameText(element: BindingElement): string | undefined { - const parent = element.parent; - if (parent.kind === SyntaxKind.ObjectBindingPattern) { - const name = element.propertyName || element.name; - switch (name.kind) { - case SyntaxKind.Identifier: - return idText(name); - case SyntaxKind.ComputedPropertyName: - return isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case SyntaxKind.StringLiteral: - case SyntaxKind.NumericLiteral: - return name.text; - default: - // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined - Debug.fail("Unexpected name kind for binding element name"); - } - } - else { - return "" + parent.elements.indexOf(element); - } - } - function isMatchingReference(source: Node, target: Node): boolean { + switch (target.kind) { + case SyntaxKind.ParenthesizedExpression: + case SyntaxKind.NonNullExpression: + return isMatchingReference(source, (target as NonNullExpression | ParenthesizedExpression).expression); + } switch (source.kind) { case SyntaxKind.Identifier: return target.kind === SyntaxKind.Identifier && getResolvedSymbol(source) === getResolvedSymbol(target) || @@ -13894,35 +14923,27 @@ namespace ts { return target.kind === SyntaxKind.ThisKeyword; case SyntaxKind.SuperKeyword: return target.kind === SyntaxKind.SuperKeyword; + case SyntaxKind.NonNullExpression: + case SyntaxKind.ParenthesizedExpression: + return isMatchingReference((source as NonNullExpression | ParenthesizedExpression).expression, target); case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: - return (isPropertyAccessExpression(target) || isElementAccessExpression(target)) && - getAccessedPropertyName(source as PropertyAccessExpression | ElementAccessExpression) === getAccessedPropertyName(target) && - isMatchingReference((source as PropertyAccessExpression | ElementAccessExpression).expression, target.expression); - case SyntaxKind.BindingElement: - if (target.kind !== SyntaxKind.PropertyAccessExpression) return false; - const t = target as PropertyAccessExpression; - if (t.name.escapedText !== getBindingElementNameText(source as BindingElement)) return false; - if (source.parent.parent.kind === SyntaxKind.BindingElement && isMatchingReference(source.parent.parent, t.expression)) { - return true; - } - if (source.parent.parent.kind === SyntaxKind.VariableDeclaration) { - const maybeId = (source.parent.parent as VariableDeclaration).initializer; - return !!maybeId && isMatchingReference(maybeId, t.expression); - } + return isAccessExpression(target) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && + isMatchingReference((source).expression, target.expression); } return false; } - function getAccessedPropertyName(access: PropertyAccessExpression | ElementAccessExpression): __String | undefined { - return isPropertyAccessExpression(access) ? access.name.escapedText : + function getAccessedPropertyName(access: AccessExpression): __String | undefined { + return access.kind === SyntaxKind.PropertyAccessExpression ? access.name.escapedText : isStringLiteral(access.argumentExpression) || isNumericLiteral(access.argumentExpression) ? escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } function containsMatchingReference(source: Node, target: Node) { - while (source.kind === SyntaxKind.PropertyAccessExpression) { - source = (source).expression; + while (isAccessExpression(source)) { + source = source.expression; if (isMatchingReference(source, target)) { return true; } @@ -13935,35 +14956,52 @@ namespace ts { // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source: Node, target: Node) { - return target.kind === SyntaxKind.PropertyAccessExpression && - containsMatchingReference(source, (target).expression) && - isDiscriminantProperty(getDeclaredTypeOfReference((target).expression), (target).name.escapedText); + let name; + return isAccessExpression(target) && + containsMatchingReference(source, target.expression) && + (name = getAccessedPropertyName(target)) !== undefined && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), name); } function getDeclaredTypeOfReference(expr: Node): Type | undefined { if (expr.kind === SyntaxKind.Identifier) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === SyntaxKind.PropertyAccessExpression) { - const type = getDeclaredTypeOfReference((expr).expression); - return type && getTypeOfPropertyOfType(type, (expr).name.escapedText); + if (isAccessExpression(expr)) { + const type = getDeclaredTypeOfReference(expr.expression); + if (type) { + const propName = getAccessedPropertyName(expr); + return propName !== undefined ? getTypeOfPropertyOfType(type, propName) : undefined; + } } return undefined; } + function isDiscriminantType(type: Type): boolean { + return !!(type.flags & TypeFlags.Union && + (type.flags & (TypeFlags.Boolean | TypeFlags.EnumLiteral) || !isGenericIndexType(type))); + } + function isDiscriminantProperty(type: Type | undefined, name: __String) { if (type && type.flags & TypeFlags.Union) { const prop = getUnionOrIntersectionProperty(type, name); if (prop && getCheckFlags(prop) & CheckFlags.SyntheticProperty) { if ((prop).isDiscriminantProperty === undefined) { - (prop).isDiscriminantProperty = !!((prop).checkFlags & CheckFlags.HasNonUniformType) && isLiteralType(getTypeOfSymbol(prop)); + (prop).isDiscriminantProperty = + ((prop).checkFlags & CheckFlags.Discriminant) === CheckFlags.Discriminant && + isDiscriminantType(getTypeOfSymbol(prop)); } - return (prop).isDiscriminantProperty; + return !!(prop).isDiscriminantProperty; } } return false; } + function hasNarrowableDeclaredType(expr: Node) { + const type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & TypeFlags.Union); + } + function findDiscriminantProperties(sourceProperties: Symbol[], target: Type): Symbol[] | undefined { let result: Symbol[] | undefined; for (const sourceProperty of sourceProperties) { @@ -14025,7 +15063,10 @@ namespace ts { if (assignedType.flags & TypeFlags.Never) { return assignedType; } - const reducedType = filterType(declaredType, t => typeMaybeAssignableTo(assignedType, t)); + let reducedType = filterType(declaredType, t => typeMaybeAssignableTo(assignedType, t)); + if (assignedType.flags & TypeFlags.BooleanLiteral && isFreshLiteralType(assignedType)) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } // Our crude heuristic produces an invalid result in some cases: see GH#26130. // For now, when that happens, we give up and don't narrow at all. (This also // means we'll never narrow for erroneous assignments where the assigned type @@ -14070,21 +15111,32 @@ namespace ts { if (flags & TypeFlags.NumberLiteral) { const isZero = (type).value === 0; return strictNullChecks ? - isZero ? TypeFacts.ZeroStrictFacts : TypeFacts.NonZeroStrictFacts : - isZero ? TypeFacts.ZeroFacts : TypeFacts.NonZeroFacts; + isZero ? TypeFacts.ZeroNumberStrictFacts : TypeFacts.NonZeroNumberStrictFacts : + isZero ? TypeFacts.ZeroNumberFacts : TypeFacts.NonZeroNumberFacts; + } + if (flags & TypeFlags.BigInt) { + return strictNullChecks ? TypeFacts.BigIntStrictFacts : TypeFacts.BigIntFacts; + } + if (flags & TypeFlags.BigIntLiteral) { + const isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? TypeFacts.ZeroBigIntStrictFacts : TypeFacts.NonZeroBigIntStrictFacts : + isZero ? TypeFacts.ZeroBigIntFacts : TypeFacts.NonZeroBigIntFacts; } if (flags & TypeFlags.Boolean) { return strictNullChecks ? TypeFacts.BooleanStrictFacts : TypeFacts.BooleanFacts; } if (flags & TypeFlags.BooleanLike) { return strictNullChecks ? - type === falseType ? TypeFacts.FalseStrictFacts : TypeFacts.TrueStrictFacts : - type === falseType ? TypeFacts.FalseFacts : TypeFacts.TrueFacts; + (type === falseType || type === regularFalseType) ? TypeFacts.FalseStrictFacts : TypeFacts.TrueStrictFacts : + (type === falseType || type === regularFalseType) ? TypeFacts.FalseFacts : TypeFacts.TrueFacts; } if (flags & TypeFlags.Object) { - return isFunctionObjectType(type) ? - strictNullChecks ? TypeFacts.FunctionStrictFacts : TypeFacts.FunctionFacts : - strictNullChecks ? TypeFacts.ObjectStrictFacts : TypeFacts.ObjectFacts; + return getObjectFlags(type) & ObjectFlags.Anonymous && isEmptyObjectType(type) ? + strictNullChecks ? TypeFacts.EmptyObjectStrictFacts : TypeFacts.EmptyObjectFacts : + isFunctionObjectType(type) ? + strictNullChecks ? TypeFacts.FunctionStrictFacts : TypeFacts.FunctionFacts : + strictNullChecks ? TypeFacts.ObjectStrictFacts : TypeFacts.ObjectFacts; } if (flags & (TypeFlags.Void | TypeFlags.Undefined)) { return TypeFacts.UndefinedFacts; @@ -14128,7 +15180,7 @@ namespace ts { } function getTypeOfDestructuredArrayElement(type: Type, index: number) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -14326,11 +15378,15 @@ namespace ts { return type.flags & TypeFlags.Union ? forEach((type).types, f) : f(type); } + function everyType(type: Type, f: (t: Type) => boolean): boolean { + return type.flags & TypeFlags.Union ? every((type).types, f) : f(type); + } + function filterType(type: Type, f: (t: Type) => boolean): Type { if (type.flags & TypeFlags.Union) { const types = (type).types; const filtered = filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & TypeFlags.UnionOfPrimitiveTypes); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, (type).primitiveTypesOnly); } return f(type) ? type : neverType; } @@ -14376,10 +15432,12 @@ namespace ts { // literals in typeWithLiterals, respectively. function replacePrimitivesWithLiterals(typeWithPrimitives: Type, typeWithLiterals: Type) { if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.StringLiteral) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.NumberLiteral)) { + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.NumberLiteral) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.BigIntLiteral)) { return mapType(typeWithPrimitives, t => t.flags & TypeFlags.String ? extractTypesOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.StringLiteral) : t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : + t.flags & TypeFlags.BigInt ? extractTypesOfKind(typeWithLiterals, TypeFlags.BigInt | TypeFlags.BigIntLiteral) : t); } return typeWithPrimitives; @@ -14522,7 +15580,7 @@ namespace ts { // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. - const resultType = getObjectFlags(evolvedType) & ObjectFlags.EvolvingArray && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + const resultType = getObjectFlags(evolvedType) & ObjectFlags.EvolvingArray && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); if (reference.parent && reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(resultType, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { return declaredType; } @@ -14647,8 +15705,20 @@ namespace ts { // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConst(node))) { + const init = getDeclaredExpandoInitializer(node); + if (init && (init.kind === SyntaxKind.FunctionExpression || init.kind === SyntaxKind.ArrowFunction)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } + // for (const _ in ref) acts as a nonnull on ref + if (isVariableDeclaration(node) && node.parent.parent.kind === SyntaxKind.ForInStatement && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } // Assignment doesn't affect reference return undefined; } @@ -14709,16 +15779,19 @@ namespace ts { } function getTypeAtSwitchClause(flow: FlowSwitchClause): FlowType { + const expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } const flowType = getTypeAtFlowNode(flow.antecedent); let type = getTypeFromFlowType(flowType); - const expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant( type, - expr as PropertyAccessExpression | ElementAccessExpression, + expr as AccessExpression, t => narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd)); } else if (expr.kind === SyntaxKind.TypeOfExpression && isMatchingReference(reference, (expr as TypeOfExpression).expression)) { @@ -14838,26 +15911,24 @@ namespace ts { } function isMatchingReferenceDiscriminant(expr: Expression, computedType: Type) { - if (!(computedType.flags & TypeFlags.Union) || - expr.kind !== SyntaxKind.PropertyAccessExpression && expr.kind !== SyntaxKind.ElementAccessExpression) { + if (!(computedType.flags & TypeFlags.Union) || !isAccessExpression(expr)) { return false; } - const access = expr as PropertyAccessExpression | ElementAccessExpression; - const name = getAccessedPropertyName(access); - if (!name) { + const name = getAccessedPropertyName(expr); + if (name === undefined) { return false; } - return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); } - function narrowTypeByDiscriminant(type: Type, access: PropertyAccessExpression | ElementAccessExpression, narrowType: (t: Type) => Type): Type { + function narrowTypeByDiscriminant(type: Type, access: AccessExpression, narrowType: (t: Type) => Type): Type { const propName = getAccessedPropertyName(access); - if (!propName) { + if (propName === undefined) { return type; } const propType = getTypeOfPropertyOfType(type, propName); const narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, t => isTypeComparableTo(getTypeOfPropertyOfType(t, propName)!, narrowedPropType!)); + return propType === narrowedPropType ? type : filterType(type, t => isTypeComparableTo(getTypeOfPropertyOrIndexSignature(t, propName), narrowedPropType!)); } function narrowTypeByTruthiness(type: Type, expr: Expression, assumeTrue: boolean): Type { @@ -14865,7 +15936,7 @@ namespace ts { return getTypeWithFacts(type, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy); } if (isMatchingReferenceDiscriminant(expr, declaredType)) { - return narrowTypeByDiscriminant(type, expr, t => getTypeWithFacts(t, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy)); + return narrowTypeByDiscriminant(type, expr, t => getTypeWithFacts(t, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy)); } if (containsMatchingReferenceDiscriminant(reference, expr)) { return declaredType; @@ -14916,10 +15987,10 @@ namespace ts { return narrowTypeByEquality(type, operator, left, assumeTrue); } if (isMatchingReferenceDiscriminant(left, declaredType)) { - return narrowTypeByDiscriminant(type, left, t => narrowTypeByEquality(t, operator, right, assumeTrue)); + return narrowTypeByDiscriminant(type, left, t => narrowTypeByEquality(t, operator, right, assumeTrue)); } if (isMatchingReferenceDiscriminant(right, declaredType)) { - return narrowTypeByDiscriminant(type, right, t => narrowTypeByEquality(t, operator, left, assumeTrue)); + return narrowTypeByDiscriminant(type, right, t => narrowTypeByEquality(t, operator, left, assumeTrue)); } if (containsMatchingReferenceDiscriminant(reference, left) || containsMatchingReferenceDiscriminant(reference, right)) { return declaredType; @@ -14977,9 +16048,9 @@ namespace ts { // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands const target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { return declaredType; } return type; @@ -14996,23 +16067,24 @@ namespace ts { return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); function narrowTypeForTypeof(type: Type) { - if (assumeTrue && !(type.flags & TypeFlags.Union)) { - if (type.flags & TypeFlags.Unknown && literal.text === "object") { - return getUnionType([nonPrimitiveType, nullType]); + if (type.flags & TypeFlags.Unknown && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. + const targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; } - // We narrow a non-union type to an exact primitive type if the non-union type - // is a supertype of that primitive type. For example, type 'any' can be narrowed - // to one of the primitive types. - const targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); - if (targetType) { - if (isTypeSubtypeOf(targetType, type)) { - return isTypeAny(type) ? targetType : getIntersectionType([type, targetType]); // Intersection to handle `string` being a subtype of `keyof T` - } - if (type.flags & TypeFlags.Instantiable) { - const constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(targetType, constraint)) { - return getIntersectionType([type, targetType]); - } + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & TypeFlags.Instantiable) { + const constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); } } } @@ -15039,6 +16111,32 @@ namespace ts { return caseType.flags & TypeFlags.Never ? defaultType : getUnionType([caseType, defaultType]); } + function getImpliedTypeFromTypeofCase(type: Type, text: string) { + switch (text) { + case "function": + return type.flags & TypeFlags.Any ? type : globalFunctionType; + case "object": + return type.flags & TypeFlags.Unknown ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + + function narrowTypeForTypeofSwitch(candidate: Type) { + return (type: Type) => { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & TypeFlags.Instantiable) { + const constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): Type { const switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!switchWitnesses.length) { @@ -15056,7 +16154,7 @@ namespace ts { // that we don't have to worry about undefined // in the witness array. const witnesses = switchWitnesses.filter(witness => witness !== undefined); - // The adjust clause start and end after removing the `default` statement. + // The adjusted clause start and end after removing the `default` statement. const fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; const fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); @@ -15066,6 +16164,9 @@ namespace ts { clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); } + if (hasDefaultClause) { + return filterType(type, t => (getTypeFacts(t) & switchFacts) === switchFacts); + } /* The implied type is the raw type suggested by a value being caught in this clause. @@ -15094,34 +16195,19 @@ namespace ts { boolean. We know that number cannot be selected because it is caught in the first clause. */ - if (!(hasDefaultClause || (type.flags & TypeFlags.Union))) { - let impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(text => typeofTypesByName.get(text) || neverType)), switchFacts); - if (impliedType.flags & TypeFlags.Union) { - impliedType = getAssignmentReducedType(impliedType as UnionType, getBaseConstraintOfType(type) || type); - } - if (!(impliedType.flags & TypeFlags.Never)) { - if (isTypeSubtypeOf(impliedType, type)) { - return impliedType; - } - if (type.flags & TypeFlags.Instantiable) { - const constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(impliedType, constraint)) { - return getIntersectionType([type, impliedType]); - } - } - } + let impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(text => getImpliedTypeFromTypeofCase(type, text))), switchFacts); + if (impliedType.flags & TypeFlags.Union) { + impliedType = getAssignmentReducedType(impliedType as UnionType, getBaseConstraintOrType(type)); } - return hasDefaultClause ? - filterType(type, t => (getTypeFacts(t) & switchFacts) === switchFacts) : - getTypeWithFacts(type, switchFacts); + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } function narrowTypeByInstanceof(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { const left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { return declaredType; } return type; @@ -15129,7 +16215,7 @@ namespace ts { // Check that right operand is a function type with a prototype property const rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } @@ -15149,24 +16235,13 @@ namespace ts { } if (!targetType) { - // Target type is type of construct signature - let constructSignatures: ReadonlyArray | undefined; - if (getObjectFlags(rightType) & ObjectFlags.Interface) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (getObjectFlags(rightType) & ObjectFlags.Anonymous) { - constructSignatures = getSignaturesOfType(rightType, SignatureKind.Construct); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(map(constructSignatures, signature => getReturnTypeOfSignature(getErasedSignature(signature)))); - } + const constructSignatures = getSignaturesOfType(rightType, SignatureKind.Construct); + targetType = constructSignatures.length ? + getUnionType(map(constructSignatures, signature => getReturnTypeOfSignature(getErasedSignature(signature)))) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type: Type, candidate: Type, assumeTrue: boolean, isRelated: (source: Type, target: Type) => boolean) { @@ -15220,9 +16295,8 @@ namespace ts { } else { const invokedExpression = skipParentheses(callExpression.expression); - if (invokedExpression.kind === SyntaxKind.ElementAccessExpression || invokedExpression.kind === SyntaxKind.PropertyAccessExpression) { - const accessExpression = invokedExpression as ElementAccessExpression | PropertyAccessExpression; - const possibleReference = skipParentheses(accessExpression.expression); + if (isAccessExpression(invokedExpression)) { + const possibleReference = skipParentheses(invokedExpression.expression); if (isMatchingReference(reference, possibleReference)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } @@ -15449,12 +16523,17 @@ namespace ts { if (assignmentKind) { if (!(localOrExportSymbol.flags & SymbolFlags.Variable) && - !(isInJavaScriptFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule)) { + !(isInJSFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule)) { error(node, Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { - error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + if (localOrExportSymbol.flags & SymbolFlags.Variable) { + error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } + else { + error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } return errorType; } } @@ -15512,7 +16591,7 @@ namespace ts { // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (type === autoType || type === autoArrayType) { + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { error(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); @@ -15533,6 +16612,10 @@ namespace ts { return !!findAncestor(node, n => n === threshold ? "quit" : isFunctionLike(n)); } + function getPartOfForStatementContainingNode(node: Node, container: ForStatement) { + return findAncestor(node, n => n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement); + } + function checkNestedBlockScopedBinding(node: Identifier, symbol: Symbol): void { if (languageVersion >= ScriptTarget.ES2015 || (symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.Class)) === 0 || @@ -15561,7 +16644,25 @@ namespace ts { if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding; + let capturesBlockScopeBindingInLoopBody = true; + if (isForStatement(container) && + getAncestor(symbol.valueDeclaration, SyntaxKind.VariableDeclarationList)!.parent === container) { + const part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + const links = getNodeLinks(part); + links.flags |= NodeCheckFlags.ContainsCapturedBlockScopeBinding; + + const capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + pushIfUnique(capturedBindings, symbol); + + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. @@ -15581,6 +16682,11 @@ namespace ts { } } + function isBindingCapturedByNode(node: Node, decl: VariableDeclaration | BindingElement) { + const links = getNodeLinks(node); + return !!links && contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } + function isAssignedInBodyOfForStatement(node: Identifier, container: ForStatement): boolean { // skip parenthesized nodes let current: Node = node; @@ -15660,7 +16766,7 @@ namespace ts { function checkThisBeforeSuper(node: Node, container: Node, diagnosticMessage: DiagnosticMessage) { const containingClassDecl = container.parent; - const baseTypeNode = getEffectiveBaseTypeNode(containingClassDecl); + const baseTypeNode = getClassExtendsHeritageElement(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. @@ -15732,42 +16838,45 @@ namespace ts { const type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error( + const diag = error( node, capturedByArrowFunction && container.kind === SyntaxKind.SourceFile ? Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!isSourceFile(container)) { + const outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, createDiagnosticForNode(container, Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } } return type || anyType; } function tryGetThisTypeAt(node: Node, container = getThisContainer(node, /*includeArrowFunctions*/ false)): Type | undefined { + const isInJS = isInJSFile(node); if (isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. - // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === SyntaxKind.FunctionExpression && - container.parent.kind === SyntaxKind.BinaryExpression && - getSpecialPropertyAssignmentKind(container.parent as BinaryExpression) === 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 className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { const classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & SymbolFlags.Function)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + const classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) && + else if (isInJS && + (container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) && getJSDocClassTag(container)) { - const classType = getJavascriptClassType(container.symbol); + const classType = getJSClassType(getMergedSymbol(container.symbol)); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -15785,7 +16894,7 @@ namespace ts { return getFlowTypeOfReference(node, type); } - if (isInJavaScriptFile(node)) { + if (isInJS) { const type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); @@ -15793,6 +16902,59 @@ namespace ts { } } + function getClassNameFromPrototypeMethod(container: Node) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === SyntaxKind.FunctionExpression && + isBinaryExpression(container.parent) && + getAssignmentDeclarationKind(container.parent) === AssignmentDeclarationKind.PrototypeProperty) { + // Get the 'x' of 'x.prototype.y = container' + return ((container.parent // x.prototype.y = container + .left as PropertyAccessExpression) // x.prototype.y + .expression as PropertyAccessExpression) // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === SyntaxKind.MethodDeclaration && + container.parent.kind === SyntaxKind.ObjectLiteralExpression && + isBinaryExpression(container.parent.parent) && + getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.Prototype) { + return (container.parent.parent.left as PropertyAccessExpression).expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === SyntaxKind.FunctionExpression && + container.parent.kind === SyntaxKind.PropertyAssignment && + container.parent.parent.kind === SyntaxKind.ObjectLiteralExpression && + isBinaryExpression(container.parent.parent.parent) && + getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.Prototype) { + return (container.parent.parent.parent.left as PropertyAccessExpression).expression; + } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === SyntaxKind.FunctionExpression && + isPropertyAssignment(container.parent) && + isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + isObjectLiteralExpression(container.parent.parent) && + isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.ObjectDefinePrototypeProperty) { + return (container.parent.parent.parent.arguments[0] as PropertyAccessExpression).expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (isMethodDeclaration(container) && + isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + isObjectLiteralExpression(container.parent) && + isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.ObjectDefinePrototypeProperty) { + return (container.parent.parent.arguments[0] as PropertyAccessExpression).expression; + } + } + function getTypeForThisExpressionFromJSDoc(node: Node) { const jsdocType = getJSDocType(node); if (jsdocType && jsdocType.kind === SyntaxKind.JSDocFunctionType) { @@ -15887,16 +17049,18 @@ namespace ts { // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // 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: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -15908,19 +17072,20 @@ namespace ts { // // 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); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = 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. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === SyntaxKind.MethodDeclaration && hasModifier(container, ModifierFlags.Async)) { if (isSuperProperty(node.parent) && isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= NodeCheckFlags.AsyncMethodWithSuperBinding; @@ -15950,7 +17115,7 @@ namespace ts { // at this point the only legal case for parent is ClassLikeDeclaration const classLikeDeclaration = container.parent; - if (!getEffectiveBaseTypeNode(classLikeDeclaration)) { + if (!getClassExtendsHeritageElement(classLikeDeclaration)) { error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } @@ -16042,7 +17207,7 @@ namespace ts { } } } - const inJs = isInJavaScriptFile(func); + const inJs = isInJSFile(func); if (noImplicitThis || inJs) { const containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -16074,7 +17239,7 @@ namespace ts { if (parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.EqualsToken) { const target = (parent).left; if (target.kind === SyntaxKind.PropertyAccessExpression || target.kind === SyntaxKind.ElementAccessExpression) { - const { expression } = target as PropertyAccessExpression | ElementAccessExpression; + const { expression } = target as AccessExpression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && isIdentifier(expression)) { const sourceFile = getSourceFileOfNode(parent); @@ -16121,6 +17286,32 @@ namespace ts { } } + function getContextualTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration): Type | undefined { + const typeNode = getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + switch (declaration.kind) { + case SyntaxKind.Parameter: + return getContextuallyTypedParameterType(declaration); + case SyntaxKind.BindingElement: + return getContextualTypeForBindingElement(declaration); + // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent + } + } + + function getContextualTypeForBindingElement(declaration: BindingElement): Type | undefined { + const parentDeclaration = declaration.parent.parent; + const name = declaration.propertyName || declaration.name; + const parentType = getContextualTypeForVariableLikeDeclaration(parentDeclaration); + if (parentType && !isBindingPattern(name)) { + const text = getTextOfPropertyName(name); + if (text !== undefined) { + return getTypeOfPropertyOfType(parentType, text); + } + } + } + // 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, @@ -16132,32 +17323,13 @@ namespace ts { function getContextualTypeForInitializerExpression(node: Expression): Type | undefined { const declaration = node.parent; if (hasInitializer(declaration) && node === declaration.initializer) { - const typeNode = getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); + const result = getContextualTypeForVariableLikeDeclaration(declaration); + if (result) { + return result; } - if (declaration.kind === SyntaxKind.Parameter) { - const type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (isBindingPattern(declaration.name)) { + if (isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } - if (isBindingPattern(declaration.parent)) { - const parentDeclaration = declaration.parent.parent; - const name = (declaration as BindingElement).propertyName || declaration.name; - if (parentDeclaration.kind !== SyntaxKind.BindingElement) { - const parentTypeNode = getEffectiveTypeAnnotationNode(parentDeclaration); - if (parentTypeNode && !isBindingPattern(name)) { - const text = getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); - } - } - } - } } return undefined; } @@ -16171,9 +17343,22 @@ namespace ts { } const contextualReturnType = getContextualReturnType(func); - return functionFlags & FunctionFlags.Async - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & FunctionFlags.Async) { // Async function + const contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + + function getContextualTypeForAwaitOperand(node: AwaitExpression): Type | undefined { + const contextualType = getContextualType(node); + if (contextualType) { + const contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -16236,6 +17421,9 @@ namespace ts { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. const signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } return getTypeAtPosition(signature, argIndex); } @@ -16265,7 +17453,7 @@ namespace ts { // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` const type = getContextualType(binaryExpression); - return !type && node === right && !isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.CommaToken: @@ -16276,16 +17464,16 @@ namespace ts { } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getIsContextSensitiveAssignmentOrContextType(binaryExpression: BinaryExpression): boolean | Type { - const kind = getSpecialPropertyAssignmentKind(binaryExpression); + const kind = getAssignmentDeclarationKind(binaryExpression); switch (kind) { - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.None: return true; - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.Prototype: - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.Prototype: + case AssignmentDeclarationKind.PrototypeProperty: // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. if (!binaryExpression.left.symbol) { @@ -16313,10 +17501,10 @@ namespace ts { return false; } } - return !isInJavaScriptFile(decl); + return !isInJSFile(decl); } - case SpecialPropertyAssignmentKind.ModuleExports: - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ModuleExports: + case AssignmentDeclarationKind.ThisProperty: if (!binaryExpression.symbol) return true; if (binaryExpression.symbol.valueDeclaration) { const annotated = getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); @@ -16327,13 +17515,17 @@ namespace ts { } } } - if (kind === SpecialPropertyAssignmentKind.ModuleExports) return false; + if (kind === AssignmentDeclarationKind.ModuleExports) return false; const thisAccess = binaryExpression.left as PropertyAccessExpression; if (!isObjectLiteralMethod(getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return false; } const thisType = checkThisExpression(thisAccess.expression); return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: + return Debug.fail("Does not apply"); default: return Debug.assertNever(kind); } @@ -16352,6 +17544,8 @@ namespace ts { return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, IndexKind.Number) || + getIndexTypeOfContextualType(t, IndexKind.String); } return undefined; }, /*noReductions*/ true); @@ -16361,11 +17555,6 @@ namespace ts { return mapType(type, t => getIndexTypeOfStructuredType(t, kind), /*noReductions*/ true); } - // 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)); - } - // 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. @@ -16408,7 +17597,6 @@ namespace ts { function getContextualTypeForElementExpression(arrayContextualType: Type | undefined, index: number): Type | undefined { return arrayContextualType && ( getTypeOfPropertyOfContextualType(arrayContextualType, "" + index as __String) - || getIndexTypeOfContextualType(arrayContextualType, IndexKind.Number) || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); } @@ -16418,11 +17606,23 @@ namespace ts { return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForChildJsxExpression(node: JsxElement) { + function getContextualTypeForChildJsxExpression(node: JsxElement, child: JsxChild) { const attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { + return undefined; + } + const childIndex = node.children.indexOf(child); + const childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName); + return childFieldType && mapType(childFieldType, t => { + if (isArrayLikeType(t)) { + return getIndexedAccessType(t, getLiteralType(childIndex)); + } + else { + return t; + } + }, /*noReductions*/ true); } function getContextualTypeForJsxExpression(node: JsxExpression): Type | undefined { @@ -16430,7 +17630,7 @@ namespace ts { return isJsxAttributeLike(exprParent) ? getContextualType(node) : isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent, node) : undefined; } @@ -16457,48 +17657,59 @@ namespace ts { switch (node.kind) { case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NullKeyword: case SyntaxKind.Identifier: + case SyntaxKind.UndefinedKeyword: return true; case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ParenthesizedExpression: return isPossiblyDiscriminantValue((node).expression); + case SyntaxKind.JsxExpression: + return !(node as JsxExpression).expression || isPossiblyDiscriminantValue((node as JsxExpression).expression!); } return false; } + function discriminateContextualTypeByObjectMembers(node: ObjectLiteralExpression, contextualType: UnionType) { + return discriminateTypeByDiscriminableItems(contextualType, + map( + filter(node.properties, p => !!p.symbol && p.kind === SyntaxKind.PropertyAssignment && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName)), + prop => ([() => checkExpression((prop as PropertyAssignment).initializer), prop.symbol.escapedName] as [() => Type, __String]) + ), + isTypeAssignableTo, + contextualType + ); + } + + function discriminateContextualTypeByJSXAttributes(node: JsxAttributes, contextualType: UnionType) { + return discriminateTypeByDiscriminableItems(contextualType, + map( + filter(node.properties, p => !!p.symbol && p.kind === SyntaxKind.JsxAttribute && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), + prop => ([!(prop as JsxAttribute).initializer ? (() => trueType) : (() => checkExpression((prop as JsxAttribute).initializer!)), prop.symbol.escapedName] as [() => Type, __String]) + ), + isTypeAssignableTo, + contextualType + ); + } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node: Expression): Type | undefined { let contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & TypeFlags.Union && isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - let match: Type | undefined; - propLoop: for (const prop of node.properties) { - if (!prop.symbol) continue; - if (prop.kind !== SyntaxKind.PropertyAssignment) continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - const discriminatingType = checkExpression(prop.initializer); - for (const type of (contextualType as UnionType).types) { - const targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & TypeFlags.Union) { + if (isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType as UnionType); + } + else if (isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType as UnionType); } } - return match || contextualType; + return contextualType; } /** @@ -16539,7 +17750,9 @@ namespace ts { return getContextualTypeForReturnExpression(node); case SyntaxKind.YieldExpression: return getContextualTypeForYieldOperand(parent); - case SyntaxKind.CallExpression: + case SyntaxKind.AwaitExpression: + return getContextualTypeForAwaitOperand(parent); + case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: return getContextualTypeForArgument(parent, node); case SyntaxKind.TypeAssertionExpression: @@ -16564,7 +17777,7 @@ namespace ts { return getContextualTypeForSubstitutionExpression(parent.parent, node); case SyntaxKind.ParenthesizedExpression: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - const tag = isInJavaScriptFile(parent) ? getJSDocTypeTag(parent) : undefined; + const tag = isInJSFile(parent) ? getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression!.type) : getContextualType(parent); } case SyntaxKind.JsxExpression: @@ -16585,72 +17798,17 @@ namespace ts { } function getContextualJsxElementAttributesType(node: JsxOpeningLikeElement) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + if (isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; } - const valueType = checkExpression(node.tagName); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - - const isJs = isInJavaScriptFile(node); - return mapType(valueType, t => getJsxSignaturesParameterTypes(t, isJs, node)); + return getContextualTypeForArgumentAtIndex(node, 0); } - function getJsxSignaturesParameterTypes(valueType: Type, isJs: boolean, context: JsxOpeningLikeElement) { - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (valueType.flags & TypeFlags.String) { - return anyType; - } - else if (valueType.flags & TypeFlags.StringLiteral) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== errorType) { - const stringLiteralTypeName = (valueType).value; - const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); - if (indexSignatureType) { - return indexSignatureType; - } - } - return anyType; - } - - // Resolve the signatures, preferring constructor - let signatures = getSignaturesOfType(valueType, SignatureKind.Construct); - let ctor = true; - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, SignatureKind.Call); - ctor = false; - if (signatures.length === 0) { - // We found no signatures at all, which is an error - return errorType; - } - } - - const links = getNodeLinks(context); - if (!links.resolvedSignatures) { - links.resolvedSignatures = createMap(); - } - const cacheKey = "" + getTypeId(valueType); - const cachedResolved = links.resolvedSignatures.get(cacheKey); - if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { - signatures = cachedResolved; - } - else if (!cachedResolved) { - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); - } - - return getUnionType(map(signatures, ctor ? t => getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false) : t => getJsxPropsTypeFromCallSignature(t, context)), UnionReduction.None); + function getEffectiveFirstArgumentForJsxSignature(signature: Signature, node: JsxOpeningLikeElement) { + return getJsxReferenceKind(node) !== JsxReferenceKind.Component ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig: Signature, context: JsxOpeningLikeElement) { @@ -16664,27 +17822,66 @@ namespace ts { } function getJsxPropsTypeForSignatureFromMember(sig: Signature, forcedLookupLocation: __String) { + if (sig.unionSignatures) { + // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input + // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, + // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur + // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. + // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. + const results: Type[] = []; + for (const signature of sig.unionSignatures) { + const instance = getReturnTypeOfSignature(signature); + if (isTypeAny(instance)) { + return instance; + } + const propType = getTypeOfPropertyOfType(instance, forcedLookupLocation); + if (!propType) { + return; + } + results.push(propType); + } + return getIntersectionType(results); + } const instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } + function getStaticTypeOfReferencedJsxConstructor(context: JsxOpeningLikeElement) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + const fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + const tagType = checkExpressionCached(context.tagName); + if (tagType.flags & TypeFlags.StringLiteral) { + const result = getIntrinsicAttributesTypeFromStringLiteralType(tagType as StringLiteralType, context); + if (!result) { + return errorType; + } + const fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } + function getJsxManagedAttributesFromLocatedAttributes(context: JsxOpeningLikeElement, ns: Symbol, attributesType: Type) { const managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + const ctorType = getStaticTypeOfReferencedJsxConstructor(context); if (length((declaredManagedType as GenericType).typeParameters) >= 2) { - const args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], (declaredManagedType as GenericType).typeParameters, 2, isInJavaScriptFile(context)); + const args = fillMissingTypeArguments([ctorType, attributesType], (declaredManagedType as GenericType).typeParameters, 2, isInJSFile(context)); return createTypeReference((declaredManagedType as GenericType), args); } else if (length(declaredManagedType.aliasTypeArguments) >= 2) { - const args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments!, 2, isInJavaScriptFile(context)); + const args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments!, 2, isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol!, args); } } return attributesType; } - function getJsxPropsTypeFromClassType(sig: Signature, isJs: boolean, context: JsxOpeningLikeElement, reportErrors: boolean) { + function getJsxPropsTypeFromClassType(sig: Signature, context: JsxOpeningLikeElement) { const ns = getJsxNamespaceAt(context); const forcedLookupLocation = getJsxElementPropertiesName(ns); let attributesType = forcedLookupLocation === undefined @@ -16698,7 +17895,7 @@ namespace ts { if (!attributesType) { // There is no property named 'props' on this instance type - if (reportErrors && !!forcedLookupLocation && !!length(context.attributes.properties)) { + if (!!forcedLookupLocation && !!length(context.attributes.properties)) { error(context, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, unescapeLeadingUnderscores(forcedLookupLocation)); } return emptyObjectType; @@ -16719,7 +17916,7 @@ namespace ts { const hostClassType = getReturnTypeOfSignature(sig); apparentAttributesType = intersectTypes( typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isInJSFile(context))) : intrinsicClassAttribs, apparentAttributesType ); @@ -16839,7 +18036,7 @@ namespace ts { (node.kind === SyntaxKind.BinaryExpression && (node).operatorToken.kind === SyntaxKind.EqualsToken); } - function checkArrayLiteral(node: ArrayLiteralExpression, checkMode: CheckMode | undefined): Type { + function checkArrayLiteral(node: ArrayLiteralExpression, checkMode: CheckMode | undefined, forceTuple: boolean | undefined): Type { const elements = node.elements; const elementCount = elements.length; let hasNonEndingSpreadElement = false; @@ -16861,7 +18058,7 @@ namespace ts { // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - const restArrayType = checkExpression((e).expression, checkMode); + const restArrayType = checkExpression((e).expression, checkMode, forceTuple); const restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -16870,7 +18067,7 @@ namespace ts { } else { const elementContextualType = getContextualTypeForElementExpression(contextualType, index); - const type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + const type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === SyntaxKind.SpreadElement) { @@ -16882,36 +18079,48 @@ namespace ts { const minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + let tupleResult: Type | undefined; if (inDestructuringPattern && minLength > 0) { const type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - 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 - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === SyntaxKind.ArrayBindingPattern || pattern.kind === SyntaxKind.ArrayLiteralExpression)) { - const patternElements = (pattern).elements; - for (let i = elementCount; i < patternElements.length; i++) { - const e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push((contextualType).typeArguments![i]); - } - else if (i < patternElements.length - 1 || !(e.kind === SyntaxKind.BindingElement && (e).dotDotDotToken || e.kind === SyntaxKind.SpreadElement)) { - if (e.kind !== SyntaxKind.OmittedExpression) { - error(e, Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, UnionReduction.Subtype); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes: Type[], contextualType: Type | undefined, hasRestElement: boolean, elementCount = elementTypes.length) { + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + const minLength = elementCount - (hasRestElement ? 1 : 0); + const 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 (!hasRestElement && pattern && (pattern.kind === SyntaxKind.ArrayBindingPattern || pattern.kind === SyntaxKind.ArrayLiteralExpression)) { + const patternElements = (pattern).elements; + for (let i = elementCount; i < patternElements.length; i++) { + const e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push((contextualType).typeArguments![i]); + } + else if (i < patternElements.length - 1 || !(e.kind === SyntaxKind.BindingElement && (e).dotDotDotToken || e.kind === SyntaxKind.SpreadElement)) { + if (e.kind !== SyntaxKind.OmittedExpression) { + error(e, Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + function getArrayLiteralType(elementTypes: Type[], unionReduction = UnionReduction.Literal) { return createArrayType(elementTypes.length ? getUnionType(elementTypes, unionReduction) : @@ -16997,6 +18206,18 @@ namespace ts { return createIndexInfo(unionType, /*isReadonly*/ false); } + function getImmediateAliasedSymbol(symbol: Symbol): Symbol | undefined { + Debug.assert((symbol.flags & SymbolFlags.Alias) !== 0, "Should only get Alias here."); + const links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + const node = getDeclarationOfAliasSymbol(symbol); + if (!node) return Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + + return links.immediateTarget; + } + function checkObjectLiteral(node: ObjectLiteralExpression, checkMode?: CheckMode): Type { const inDestructuringPattern = isAssignmentTarget(node); // Grammar checking @@ -17005,14 +18226,14 @@ namespace ts { let propertiesTable: SymbolTable; let propertiesArray: Symbol[] = []; let spread: Type = emptyObjectType; - let propagatedFlags: TypeFlags = TypeFlags.FreshLiteral; + let propagatedFlags: TypeFlags = 0; const contextualType = getApparentTypeOfContextualType(node); const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression); - const isInJSFile = isInJavaScriptFile(node) && !isInJsonFile(node); + const isInJavascript = isInJSFile(node) && !isInJsonFile(node); const enumTag = getJSDocEnumTag(node); - const isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + const isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; let typeFlags: TypeFlags = 0; let patternWithComputedProperties = false; let hasComputedStringProperty = false; @@ -17031,7 +18252,7 @@ namespace ts { let type = memberDecl.kind === SyntaxKind.PropertyAssignment ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { const jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -17090,7 +18311,7 @@ namespace ts { checkExternalEmitHelpers(memberDecl, ExternalEmitHelpers.Assign); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, ObjectFlags.FreshLiteral); propertiesArray = []; propertiesTable = createSymbolTable(); hasComputedStringProperty = false; @@ -17102,7 +18323,7 @@ namespace ts { error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, ObjectFlags.FreshLiteral); offset = i + 1; continue; } @@ -17152,7 +18373,7 @@ namespace ts { if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, ObjectFlags.FreshLiteral); } return spread; } @@ -17163,9 +18384,8 @@ namespace ts { const stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, IndexKind.String) : undefined; const numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, IndexKind.Number) : undefined; const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; - result.flags |= TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags); - result.objectFlags |= ObjectFlags.ObjectLiteral; + result.flags |= TypeFlags.ContainsObjectLiteral | typeFlags & TypeFlags.PropagatingFlags; + result.objectFlags |= ObjectFlags.ObjectLiteral | freshObjectLiteralFlag; if (isJSObjectLiteral) { result.objectFlags |= ObjectFlags.JSLiteral; } @@ -17175,22 +18395,19 @@ namespace ts { if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & TypeFlags.Nullable)) { - propagatedFlags |= (result.flags & TypeFlags.PropagatingFlags); - } + propagatedFlags |= result.flags & TypeFlags.PropagatingFlags; return result; } } function isValidSpreadType(type: Type): boolean { - return !!(type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.NonPrimitive) || + return !!(type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.NonPrimitive | TypeFlags.Object | TypeFlags.InstantiableNonPrimitive) || getFalsyFlags(type) & TypeFlags.DefinitelyFalsy && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & TypeFlags.Object && !isGenericMappedType(type) || type.flags & TypeFlags.UnionOrIntersection && every((type).types, isValidSpreadType)); } function checkJsxSelfClosingElementDeferred(node: JsxSelfClosingElement) { - checkJsxOpeningLikeElementOrOpeningFragment(node, CheckMode.Normal); + checkJsxOpeningLikeElementOrOpeningFragment(node); } function checkJsxSelfClosingElement(node: JsxSelfClosingElement, _checkMode: CheckMode | undefined): Type { @@ -17200,7 +18417,7 @@ namespace ts { function checkJsxElementDeferred(node: JsxElement) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, CheckMode.Normal); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { @@ -17209,6 +18426,8 @@ namespace ts { else { checkExpression(node.closingElement.tagName); } + + checkJsxChildren(node); } function checkJsxElement(node: JsxElement, _checkMode: CheckMode | undefined): Type { @@ -17217,8 +18436,8 @@ namespace ts { return getJsxElementTypeAt(node) || anyType; } - function checkJsxFragment(node: JsxFragment, checkMode: CheckMode | undefined): Type { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); + function checkJsxFragment(node: JsxFragment): Type { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); if (compilerOptions.jsx === JsxEmit.React && (compilerOptions.jsxFactory || getSourceFileOfNode(node).pragmas.has("jsx"))) { error(node, compilerOptions.jsxFactory @@ -17226,6 +18445,7 @@ namespace ts { : Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } + checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } @@ -17262,16 +18482,19 @@ namespace ts { function createJsxAttributesTypeFromAttributesProperty(openingLikeElement: JsxOpeningLikeElement, checkMode: CheckMode | undefined) { const attributes = openingLikeElement.attributes; let attributesTable = createSymbolTable(); - let spread: Type = emptyObjectType; + let spread: Type = emptyJsxObjectType; let hasSpreadAnyType = false; let typeToIntersect: Type | undefined; let explicitlySpecifyChildrenAttribute = false; + let typeFlags: TypeFlags = 0; + let objectFlags: ObjectFlags = ObjectFlags.JsxAttributes; const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (const attributeDecl of attributes.properties) { const member = attributeDecl.symbol; if (isJsxAttribute(attributeDecl)) { const exprType = checkJsxAttribute(attributeDecl, checkMode); + typeFlags |= exprType.flags & TypeFlags.PropagatingFlags; const attributeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; @@ -17289,7 +18512,7 @@ namespace ts { else { Debug.assert(attributeDecl.kind === SyntaxKind.JsxSpreadAttribute); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); attributesTable = createSymbolTable(); } const exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -17297,7 +18520,7 @@ namespace ts { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -17307,7 +18530,7 @@ namespace ts { if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); } } @@ -17325,15 +18548,21 @@ namespace ts { error(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + const contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + const childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process const childrenPropSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); + // Fake up a property declaration for the children + childrenPropSymbol.valueDeclaration = createPropertySignature(/*modifiers*/ undefined, unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); + childrenPropSymbol.valueDeclaration.parent = attributes; + childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol; const childPropMap = createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), - attributes.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + attributes.symbol, typeFlags, objectFlags); } } @@ -17341,10 +18570,10 @@ namespace ts { if (hasSpreadAnyType) { return anyType; } - if (typeToIntersect && spread !== emptyObjectType) { + if (typeToIntersect && spread !== emptyJsxObjectType) { return getIntersectionType([typeToIntersect, spread]); } - return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. @@ -17352,9 +18581,10 @@ namespace ts { * @param attributesTable a symbol table of attributes property */ function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; const result = createAnonymousType(attributes.symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= TypeFlags.ContainsObjectLiteral; - result.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.JsxAttributes; + result.flags |= TypeFlags.ContainsObjectLiteral | typeFlags; + result.objectFlags |= ObjectFlags.ObjectLiteral | objectFlags; return result; } } @@ -17432,57 +18662,6 @@ namespace ts { return links.resolvedSymbol; } - function instantiateJsxSignatures(node: JsxOpeningLikeElement, signatures: ReadonlyArray) { - const instantiatedSignatures = []; - let candidateForTypeArgumentError: Signature | undefined; - let hasTypeArgumentError: boolean = !!node.typeArguments; - for (const signature of signatures) { - if (signature.typeParameters) { - const isJavascript = isInJavaScriptFile(node); - const typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); - if (typeArgumentInstantiated) { - hasTypeArgumentError = false; - instantiatedSignatures.push(typeArgumentInstantiated); - } - else { - if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - candidateForTypeArgumentError = signature; - } - const inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? InferenceFlags.AnyDefault : InferenceFlags.None); - const typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - } - else { - instantiatedSignatures.push(signature); - } - } - if (node.typeArguments && hasTypeArgumentError) { - if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); - } - // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine - else if (node.typeArguments.length !== 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); - } - } - return instantiatedSignatures; - } - - function getJsxSignatureTypeArgumentInstantiation(signature: Signature, node: JsxOpeningLikeElement, isJavascript: boolean, reportErrors = false) { - if (!node.typeArguments) { - return; - } - if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - return; - } - const args = checkTypeArguments(signature, node.typeArguments, reportErrors); - if (!args) { - return; - } - return getSignatureInstantiation(signature, args, isJavascript); - } - function getJsxNamespaceAt(location: Node | undefined): Symbol { const links = location && getNodeLinks(location); if (links && links.jsxNamespace) { @@ -17558,193 +18737,43 @@ namespace ts { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType: Type | undefined): Type | undefined { - if (!propsType) { - return undefined; - } - if (propsType.flags & TypeFlags.Intersection) { - const propsApparentType: Type[] = []; - for (const t of (propsType).types) { - propsApparentType.push(getApparentType(t)); - } - return getIntersectionType(propsApparentType); - } - return getApparentType(propsType); - } - - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return only attributes type of successfully resolved call signature. - * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) - * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement: JsxOpeningLikeElement, elementType: Type, elemInstanceType: Type, elementClassType?: Type): Type | undefined { - Debug.assert(!(elementType.flags & TypeFlags.Union)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - const jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - const callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); - if (callSignature !== unknownSignature) { - const callReturnType = callSignature && getReturnTypeOfSignature(callSignature); - let paramType = callReturnType && (callSignature!.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature!.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - // Intersect in JSX.IntrinsicAttributes if it exists - const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } - } - } - return undefined; - } - - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return all attributes type of resolved call signature including candidate signatures. - * This function assumes that the caller handled other possible element type of the JSX element. - * This function is a behavior used by language service when looking up completion in JSX element. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement: JsxOpeningLikeElement, elementType: Type, elemInstanceType: Type, elementClassType?: Type): Type | undefined { - Debug.assert(!(elementType.flags & TypeFlags.Union)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type - const jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. - const candidatesOutArray: Signature[] = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); - let result: Type | undefined; - let allMatchingAttributesType: Type | undefined; - for (const candidate of candidatesOutArray) { - const callReturnType = getReturnTypeOfSignature(candidate); - // TODO: GH#18217: callReturnType should always be defined... - let paramType: Type | undefined = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - let shouldBeCandidate = true; - for (const attribute of openingLikeElement.attributes.properties) { - if (isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType!, attribute.name.escapedText)) { // TODO: GH#18217 - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - - // If we can't find any matching, just return everything. - if (!result) { - result = allMatchingAttributesType; - } - // Intersect in JSX.IntrinsicAttributes if it exists - const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - - function getInstantiatedJsxSignatures(openingLikeElement: JsxOpeningLikeElement, elementType: Type, reportErrors?: boolean) { - const links = getNodeLinks(openingLikeElement); - if (!links.resolvedSignatures) { - links.resolvedSignatures = createMap(); - } - const cacheKey = "" + getTypeId(elementType); - if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { - return; - } - else if (links.resolvedSignatures.get(cacheKey)) { - return links.resolvedSignatures.get(cacheKey); - } - - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - // Resolve the signatures, preferring constructor - let signatures = getSignaturesOfType(elementType, SignatureKind.Construct); - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(elementType, SignatureKind.Call); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - if (reportErrors) { - error(openingLikeElement.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(openingLikeElement.tagName)); - } - return; - } - } - - // Instantiate in context of source type - const results = instantiateJsxSignatures(openingLikeElement, signatures); - links.resolvedSignatures.set(cacheKey, results); - return results; - } - - /** - * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. - * For instance: - * declare function Foo(attr: { p1: string}): JSX.Element; - * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" - * - * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. - * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component - * - * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement - * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature - * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present - * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) - * @return attributes type if able to resolve the type of node - * anyType if there is no type ElementAttributesProperty or there is an error - * emptyObjectType if there is no "prop" in the element instance type - */ - function resolveCustomJsxElementAttributesType(openingLikeElement: JsxOpeningLikeElement, - shouldIncludeAllStatelessAttributesType: boolean, - elementType: Type, - elementClassType?: Type): Type { - - if (elementType.flags & TypeFlags.Union) { - const types = (elementType as UnionType).types; - return getUnionType(types.map(type => { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), UnionReduction.Subtype); - } - - // Shortcircuit any - if (isTypeAny(elementType)) { - return elementType; - } - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - else if (elementType.flags & TypeFlags.String) { - return anyType; + function getUninstantiatedJsxSignaturesOfType(elementType: Type, caller: JsxOpeningLikeElement): ReadonlyArray { + if (elementType.flags & TypeFlags.String) { + return [anySignature]; } else if (elementType.flags & TypeFlags.StringLiteral) { + const intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType as StringLiteralType, caller); + if (!intrinsicType) { + error(caller, Diagnostics.Property_0_does_not_exist_on_type_1, (elementType as StringLiteralType).value, "JSX." + JsxNames.IntrinsicElements); + return emptyArray; + } + else { + const fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; + } + } + const apparentElemType = getApparentType(elementType); + // Resolve the signatures, preferring constructor + let signatures = getSignaturesOfType(apparentElemType, SignatureKind.Construct); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(apparentElemType, SignatureKind.Call); + } + if (signatures.length === 0 && apparentElemType.flags & TypeFlags.Union) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(map((apparentElemType as UnionType).types, t => getUninstantiatedJsxSignaturesOfType(t, caller))); + } + return signatures; + } + + function getIntrinsicAttributesTypeFromStringLiteralType(type: StringLiteralType, location: Node): Type | undefined { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type // For example: // var CustomTag: "h1" = "h1"; // Hello World - const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); + const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); if (intrinsicElementsType !== errorType) { - const stringLiteralTypeName = (elementType).value; + const stringLiteralTypeName = type.value; const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -17753,37 +18782,35 @@ namespace ts { if (indexSignatureType) { return indexSignatureType; } - error(openingLikeElement, Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); + return undefined; } // If we need to report an error, we already done so here. So just return any to prevent any more error downstream return anyType; + } + + function checkJsxReturnAssignableToAppropriateBound(refKind: JsxReferenceKind, elemInstanceType: Type, openingLikeElement: Node) { + if (refKind === JsxReferenceKind.Function) { + const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } } - - // Get the element instance type (the result of newing or invoking this tag) - - const instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); - if (!length(instantiatedSignatures)) { - return errorType; + else if (refKind === JsxReferenceKind.Component) { + const classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } } - const elemInstanceType = getUnionType(instantiatedSignatures!.map(getReturnTypeOfSignature), UnionReduction.Subtype); - - // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. - // Otherwise get only attributes type from the signature picked by choose-overload logic. - const statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - - if (statelessAttributesType) { - return statelessAttributesType; + else { // Mixed + const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + const classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { + return; + } + const combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - - // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - - const isJs = isInJavaScriptFile(openingLikeElement); - return getUnionType(instantiatedSignatures!.map(sig => getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true))); } /** @@ -17809,57 +18836,6 @@ namespace ts { return links.resolvedJsxElementAttributesType; } - /** - * Get attributes type of the given custom opening-like JSX element. - * This function is intended to be called from a caller that handles intrinsic JSX element already. - * @param node a custom JSX opening-like element - * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component - */ - function getCustomJsxElementAttributesType(node: JsxOpeningLikeElement, shouldIncludeAllStatelessAttributesType: boolean): Type { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); - } - - /** - * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. - * This function is called by language service (see: completions-tryGetGlobalSymbols). - * @param node a JSX opening-like element to get attributes type for - */ - function getAllAttributesTypeFromJsxOpeningLikeElement(node: JsxOpeningLikeElement): Type { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - // Because in language service, the given JSX opening-like element may be incomplete and therefore, - // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); - } - } - - /** - * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. - * @param node a JSXOpeningLikeElement node - * @return an attributes type of the given node - */ - function getAttributesTypeFromJsxOpeningLikeElement(node: JsxOpeningLikeElement): Type { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); - } - } - - /** - * Given a JSX attribute, returns the symbol for the corresponds property - * of the element attributes type. Will return unknownSymbol for attributes - * that have no matching element attributes type property. - */ - function getJsxAttributePropertySymbol(attrib: JsxAttribute): Symbol { - const attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent as JsxOpeningElement); - const prop = getPropertyOfType(attributesType, attrib.name.escapedText); - return prop || unknownSymbol; - } - function getJsxElementClassTypeAt(location: Node): Type | undefined { const type = getJsxType(JsxNames.ElementClass, location); if (type === errorType) return undefined; @@ -17898,7 +18874,7 @@ namespace ts { } } - function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment, checkMode: CheckMode | undefined) { + function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment) { const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { @@ -17923,10 +18899,8 @@ namespace ts { } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren((node as JsxOpeningFragment).parent); + const sig = getResolvedSignature(node as JsxOpeningLikeElement); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node as JsxOpeningLikeElement), getReturnTypeOfSignature(sig), node); } } @@ -17954,65 +18928,21 @@ namespace ts { return true; } } - else if (targetType.flags & TypeFlags.UnionOrIntersection) { + else if (targetType.flags & TypeFlags.UnionOrIntersection && isExcessPropertyCheckTarget(targetType)) { for (const t of (targetType as UnionOrIntersectionType).types) { if (isKnownProperty(t, name, isComparingJsxAttributes)) { return true; } } } - else if (targetType.flags & TypeFlags.Conditional) { - return isKnownProperty((targetType as ConditionalType).root.trueType, name, isComparingJsxAttributes) || - isKnownProperty((targetType as ConditionalType).root.falseType, name, isComparingJsxAttributes); - } return false; } - /** - * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. - * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" - * Check assignablity between given attributes property, "source attributes", and the "target attributes" - * @param openingLikeElement an opening-like JSX element to check its JSXAttributes - */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement: JsxOpeningLikeElement, checkMode: CheckMode | undefined) { - // The function involves following steps: - // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. - // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) - // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. - // 3. Check if the two are assignable to each other - - - // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. - const targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); - - // sourceAttributesType is a type of an attributes properties. - // i.e
- // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - const sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); - - // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties - const isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); - // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (const attribute of openingLikeElement.attributes.properties) { - if (!isJsxAttribute(attribute)) { - continue; - } - const attrName = attribute.name; - const isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, idText(attrName), typeToString(targetAttributesType)); - // We break here so that errors won't be cascading - break; - } - } - } - else if (!isSourceAttributeTypeAssignableToTarget) { - checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); - } + function isExcessPropertyCheckTarget(type: Type): boolean { + return !!(type.flags & TypeFlags.Object && !(getObjectFlags(type) & ObjectFlags.ObjectLiteralPatternWithComputedProperties) || + type.flags & TypeFlags.NonPrimitive || + type.flags & TypeFlags.Union && some((type).types, isExcessPropertyCheckTarget) || + type.flags & TypeFlags.Intersection && every((type).types, isExcessPropertyCheckTarget)); } function checkJsxExpression(node: JsxExpression, checkMode?: CheckMode) { @@ -18040,10 +18970,10 @@ namespace ts { if (symbol.flags & SymbolFlags.Method || getCheckFlags(symbol) & CheckFlags.SyntheticMethod) { return true; } - if (isInJavaScriptFile(symbol.valueDeclaration)) { + if (isInJSFile(symbol.valueDeclaration)) { const parent = symbol.valueDeclaration.parent; return parent && isBinaryExpression(parent) && - getSpecialPropertyAssignmentKind(parent) === SpecialPropertyAssignmentKind.PrototypeProperty; + getAssignmentDeclarationKind(parent) === AssignmentDeclarationKind.PrototypeProperty; } } @@ -18094,7 +19024,7 @@ namespace ts { // Referencing abstract properties within their own constructors is not allowed if ((flags & ModifierFlags.Abstract) && isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)!); - if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name!)); // TODO: GH#18217 return false; } @@ -18182,6 +19112,14 @@ namespace ts { ); } + function getNonNullableTypeIfNeeded(type: Type) { + const kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & TypeFlags.Nullable; + if (kind) { + return getNonNullableType(type); + } + return type; + } + function checkNonNullType( type: Type, node: Node, @@ -18253,7 +19191,7 @@ namespace ts { checkPropertyAccessibility(node, left.kind === SyntaxKind.SuperKeyword, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, idText(right)); + error(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, idText(right)); return errorType; } } @@ -18281,6 +19219,12 @@ namespace ts { } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + isPropertyAccessExpression(prop.valueDeclaration) && + getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } const flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & TypeFlags.Undefined) && getFalsyFlags(flowType) & TypeFlags.Undefined) { error(right, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop!)); // TODO: GH#18217 @@ -18492,8 +19436,8 @@ namespace ts { } } - function isValidPropertyAccessForCompletions(node: PropertyAccessExpression | ImportTypeNode, type: Type, property: Symbol): boolean { - return isValidPropertyAccessWithType(node, node.kind !== SyntaxKind.ImportType && node.expression.kind === SyntaxKind.SuperKeyword, property.escapedName, type) + function isValidPropertyAccessForCompletions(node: PropertyAccessExpression | ImportTypeNode | QualifiedName, type: Type, property: Symbol): boolean { + return isValidPropertyAccessWithType(node, node.kind === SyntaxKind.PropertyAccessExpression && node.expression.kind === SyntaxKind.SuperKeyword, property.escapedName, type) && (!(property.flags & SymbolFlags.Method) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method: Symbol, actualThisType: Type): boolean { @@ -18526,7 +19470,7 @@ namespace ts { const prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : isInJavaScriptFile(node) && (type.flags & TypeFlags.Union) !== 0 && (type).types.some(elementType => isValidPropertyAccessWithType(node, isSuper, propertyName, elementType)); + : isInJSFile(node) && (type.flags & TypeFlags.Union) !== 0 && (type).types.some(elementType => isValidPropertyAccessWithType(node, isSuper, propertyName, elementType)); } /** @@ -18608,13 +19552,6 @@ namespace ts { error(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - if (isTupleType(objectType) && !objectType.target.hasRestElement && isNumericLiteral(indexExpression)) { - const index = +indexExpression.text; - const maximumIndex = length(objectType.target.typeParameters); - if (index >= maximumIndex) { - error(indexExpression, Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex); - } - } return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } @@ -18661,9 +19598,8 @@ namespace ts { return true; } - function callLikeExpressionMayHaveTypeArguments(node: CallLikeExpression): node is CallExpression | NewExpression { - // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) - return isCallOrNewExpression(node); + function callLikeExpressionMayHaveTypeArguments(node: CallLikeExpression): node is CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement { + return isCallOrNewExpression(node) || isTaggedTemplateExpression(node) || isJsxOpeningLikeElement(node); } function resolveUntypedCall(node: CallLikeExpression): Signature { @@ -18676,6 +19612,9 @@ namespace ts { if (node.kind === SyntaxKind.TaggedTemplateExpression) { checkExpression(node.template); } + else if (isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } else if (node.kind !== SyntaxKind.Decorator) { forEach((node).arguments, argument => { checkExpression(argument); @@ -18751,14 +19690,15 @@ namespace ts { return findIndex(args, isSpreadArgument); } - function hasCorrectArity(node: CallLikeExpression, args: ReadonlyArray, signature: Signature, signatureHelpTrailingComma = false) { - if (isJsxOpeningLikeElement(node)) { - // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". - return true; - } + function acceptsVoid(t: Type): boolean { + return !!(t.flags & TypeFlags.Void); + } + function hasCorrectArity(node: CallLikeExpression, args: ReadonlyArray, signature: Signature, signatureHelpTrailingComma = false) { let argCount: number; let callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments + let effectiveParameterCount = getParameterCount(signature); + let effectiveMinimumArguments = getMinArgumentCount(signature); if (node.kind === SyntaxKind.TaggedTemplateExpression) { argCount = args.length; @@ -18780,6 +19720,15 @@ namespace ts { else if (node.kind === SyntaxKind.Decorator) { argCount = getDecoratorArgumentCount(node, signature); } + else if (isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked + } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' @@ -18800,13 +19749,22 @@ namespace ts { } // Too many arguments implies incorrect arity. - if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { return false; } // If the call is incomplete, we should skip the lower bound check. - const hasEnoughArguments = argCount >= getMinArgumentCount(signature); - return callIsIncomplete || hasEnoughArguments; + // JSX signatures can have extra parameters provided by the library which we don't check + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (let i = argCount; i < effectiveMinimumArguments; i++) { + const type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & TypeFlags.Never) { + return false; + } + } + return true; } function hasCorrectTypeArgumentArity(signature: Signature, typeArguments: NodeArray | undefined) { @@ -18841,18 +19799,13 @@ namespace ts { if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), InferencePriority.ReturnType); } - return getSignatureInstantiation(signature, getInferredTypes(context), isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), isInJSFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature: Signature, node: JsxOpeningLikeElement, context: InferenceContext): Type[] { - // Skip context sensitive pass - const skipContextParamType = getTypeAtPosition(signature, 0); - const checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); - inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); + function inferJsxTypeArguments(node: JsxOpeningLikeElement, signature: Signature, excludeArgument: ReadonlyArray | undefined, context: InferenceContext): Type[] { + const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); - // Standard pass - const paramType = getTypeAtPosition(signature, 0); - const checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + const checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); @@ -18870,6 +19823,10 @@ namespace ts { } } + if (isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } + // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the @@ -18962,7 +19919,7 @@ namespace ts { } function checkTypeArguments(signature: Signature, typeArgumentNodes: ReadonlyArray, reportErrors: boolean, headMessage?: DiagnosticMessage): Type[] | undefined { - const isJavascript = isInJavaScriptFile(signature.declaration); + const isJavascript = isInJSFile(signature.declaration); const typeParameters = signature.typeParameters!; const typeArgumentTypes = fillMissingTypeArguments(map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); let mapper: TypeMapper | undefined; @@ -18989,6 +19946,20 @@ namespace ts { return typeArgumentTypes; } + function getJsxReferenceKind(node: JsxOpeningLikeElement): JsxReferenceKind { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return JsxReferenceKind.Mixed; + } + const tagType = getApparentType(checkExpression(node.tagName)); + if (length(getSignaturesOfType(tagType, SignatureKind.Construct))) { + return JsxReferenceKind.Component; + } + if (length(getSignaturesOfType(tagType, SignatureKind.Call))) { + return JsxReferenceKind.Function; + } + return JsxReferenceKind.Mixed; + } + /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. * @param node a JSX opening-like element we are trying to figure its call signature @@ -18996,31 +19967,13 @@ namespace ts { * @param relation a relationship to check parameter and argument type * @param excludeArgument */ - function checkApplicableSignatureForJsxOpeningLikeElement(node: JsxOpeningLikeElement, signature: Signature, relation: Map) { - // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: - // 1. callIsIncomplete - // 2. attributes property has same number of properties as the parameter object type. - // We can figure that out by resolving attributes property and check number of properties in the resolved type - // If the call has correct arity, we will then check if the argument type and parameter type is assignable - - const callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete - if (callIsIncomplete) { - return true; - } - - const headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + function checkApplicableSignatureForJsxOpeningLikeElement(node: JsxOpeningLikeElement, signature: Signature, relation: Map, excludeArgument: boolean[] | undefined, reportErrors: boolean) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, // can be specified by users through attributes property. - const paramType = getTypeAtPosition(signature, 0); - const attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); - const argProperties = getPropertiesOfType(attributesType); - for (const arg of argProperties) { - if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); + const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + const attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } function checkApplicableSignature( @@ -19031,7 +19984,7 @@ namespace ts { excludeArgument: boolean[] | undefined, reportErrors: boolean) { if (isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); } const thisType = getThisTypeOfSignature(signature); if (thisType && thisType !== voidType && node.kind !== SyntaxKind.NewExpression) { @@ -19078,7 +20031,7 @@ namespace ts { if (node.kind === SyntaxKind.CallExpression) { const callee = skipOuterExpressions(node.expression); if (callee.kind === SyntaxKind.PropertyAccessExpression || callee.kind === SyntaxKind.ElementAccessExpression) { - return (callee as PropertyAccessExpression | ElementAccessExpression).expression; + return (callee as AccessExpression).expression; } } } @@ -19109,7 +20062,7 @@ namespace ts { return getEffectiveDecoratorArguments(node); } if (isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : emptyArray; + return node.attributes.properties.length > 0 || (isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : emptyArray; } const args = node.arguments || emptyArray; const length = args.length; @@ -19198,12 +20151,16 @@ namespace ts { let aboveArgCount = Number.POSITIVE_INFINITY; let argCount = args.length; + let closestSignature: Signature | undefined; for (const sig of signatures) { const minCount = getMinArgumentCount(sig); const maxCount = getParameterCount(sig); if (minCount < argCount && minCount > belowArgCount) belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } @@ -19216,33 +20173,64 @@ namespace ts { argCount--; } + let related: DiagnosticWithLocation | undefined; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + const paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = createDiagnosticForNode( + paramDecl, + isBindingPattern(paramDecl.name) ? Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : Diagnostics.An_argument_for_0_was_not_provided, + !paramDecl.name ? argCount : !isBindingPattern(paramDecl.name) ? idText(getFirstIdentifier(paramDecl.name)) : undefined + ); + } + } if (hasRestParameter || hasSpreadArgument) { const error = hasRestParameter && hasSpreadArgument ? Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : Diagnostics.Expected_0_arguments_but_got_1_or_more; - return createDiagnosticForNode(node, error, paramRange, argCount); + const diagnostic = createDiagnosticForNode(node, error, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } if (min < argCount && argCount < max) { return createDiagnosticForNode(node, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return createDiagnosticForNode(node, Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + const diagnostic = createDiagnosticForNode(node, Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node: Node, signatures: ReadonlyArray, typeArguments: NodeArray) { - let min = Infinity; - let max = -Infinity; - for (const sig of signatures) { - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, length(sig.typeParameters)); + const argCount = typeArguments.length; + // No overloads exist + if (signatures.length === 1) { + const sig = signatures[0]; + const min = getMinTypeArgumentCount(sig.typeParameters); + const max = length(sig.typeParameters); + return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, min < max ? min + "-" + max : min , argCount); } - const paramCount = min === max ? min : min + "-" + max; - return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + // Overloads exist + let belowArgCount = -Infinity; + let aboveArgCount = Infinity; + for (const sig of signatures) { + const min = getMinTypeArgumentCount(sig.typeParameters); + const max = length(sig.typeParameters); + if (min > argCount) { + aboveArgCount = Math.min(aboveArgCount, min); + } + else if (max < argCount) { + belowArgCount = Math.max(belowArgCount, max); + } + } + if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) { + return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount); + } + return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node: CallLikeExpression, signatures: ReadonlyArray, candidatesOutArray: Signature[] | undefined, isForSignatureHelp: boolean, fallbackError?: DiagnosticMessage): Signature { const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; const isDecorator = node.kind === SyntaxKind.Decorator; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); + const reportErrors = !candidatesOutArray; let typeArguments: NodeArray | undefined; @@ -19259,7 +20247,9 @@ namespace ts { // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - diagnostics.add(createDiagnosticForNode(node, Diagnostics.Call_target_does_not_contain_any_signatures)); + if (reportErrors) { + diagnostics.add(createDiagnosticForNode(node, Diagnostics.Call_target_does_not_contain_any_signatures)); + } return resolveErrorCall(node); } @@ -19335,34 +20325,32 @@ namespace ts { // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, // skip the checkApplicableSignature check. - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". - return candidateForArgumentError; + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); - } - else if (candidateForArgumentArityError) { - diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); - } - else if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, (node as CallExpression | TaggedTemplateExpression).typeArguments!, /*reportErrors*/ true, fallbackError); - } - else { - const signaturesWithCorrectTypeArgumentArity = filter(signatures, s => hasCorrectTypeArgumentArity(s, typeArguments)); - if (signaturesWithCorrectTypeArgumentArity.length === 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments!)); + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); } - else if (!isDecorator) { - diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, (node as CallExpression | TaggedTemplateExpression | JsxOpeningLikeElement).typeArguments!, /*reportErrors*/ true, fallbackError); } - else if (fallbackError) { - diagnostics.add(createDiagnosticForNode(node, fallbackError)); + else { + const signaturesWithCorrectTypeArgumentArity = filter(signatures, s => hasCorrectTypeArgumentArity(s, typeArguments)); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments!)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(createDiagnosticForNode(node, fallbackError)); + } } } @@ -19404,10 +20392,10 @@ namespace ts { } } else { - inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ isInJavaScriptFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ isInJSFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJavaScriptFile(candidate.declaration)); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration)); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -19419,7 +20407,10 @@ namespace ts { checkCandidate = candidate; } if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = checkCandidate; + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } continue; } if (excludeArgument) { @@ -19429,10 +20420,19 @@ namespace ts { excludeArgument = undefined; if (inferenceContext) { const typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJavaScriptFile(candidate.declaration)); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; + } } if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = checkCandidate; + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } continue; } } @@ -19539,7 +20539,7 @@ namespace ts { const typeArgumentNodes: ReadonlyArray | undefined = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; const instantiated = typeArgumentNodes - ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJavaScriptFile(node))) + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJSFile(node))) : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); candidates[bestIndex] = instantiated; return instantiated; @@ -19557,7 +20557,7 @@ namespace ts { } function inferSignatureInstantiationForOverloadFailure(node: CallLikeExpression, typeParameters: ReadonlyArray, candidate: Signature, args: ReadonlyArray): Signature { - const inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ isInJavaScriptFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); + const inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ isInJSFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); const typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); return createSignatureInstantiation(candidate, typeArgumentTypes); } @@ -19624,12 +20624,12 @@ namespace ts { // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -19641,16 +20641,23 @@ namespace ts { // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, SignatureKind.Call); + let relatedInformation: DiagnosticRelatedInformation | undefined; + if (node.arguments.length === 1) { + const text = getSourceFileOfNode(node).text; + if (isLineBreak(text.charCodeAt(skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = createDiagnosticForNode(node.expression, Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, SignatureKind.Call, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(sig => isInJavaScriptFile(sig.declaration) && !!getJSDocClassTag(sig.declaration!))) { + if (callSignatures.some(sig => isInJSFile(sig.declaration) && !!getJSDocClassTag(sig.declaration!))) { error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -19662,9 +20669,9 @@ namespace ts { * If FuncExpr is of type Any, or of an object type that has no call or construct signatures * but is a subtype of the Function interface, the call is an untyped function call. */ - function isUntypedFunctionCall(funcType: Type, apparentFuncType: Type, numCallSignatures: number, numConstructSignatures: number) { + function isUntypedFunctionCall(funcType: Type, apparentFuncType: Type, numCallSignatures: number, numConstructSignatures: number): boolean { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & TypeFlags.TypeParameter || + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & TypeFlags.TypeParameter) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (TypeFlags.Union | TypeFlags.Never)) && isTypeAssignableTo(funcType, globalFunctionType); } @@ -19732,7 +20739,7 @@ namespace ts { if (callSignatures.length) { const signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); if (!noImplicitAny) { - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } if (getThisTypeOfSignature(signature) === voidType) { @@ -19815,11 +20822,12 @@ namespace ts { return true; } - function invocationError(node: Node, apparentType: Type, kind: SignatureKind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === SignatureKind.Call - ? Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature - , typeToString(apparentType))); + function invocationError(node: Node, apparentType: Type, kind: SignatureKind, relatedInformation?: DiagnosticRelatedInformation) { + const diagnostic = error(node, (kind === SignatureKind.Call ? + Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature + ), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType: Type, kind: SignatureKind, diagnostic: Diagnostic) { @@ -19849,9 +20857,9 @@ namespace ts { } const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length; - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } @@ -19899,8 +20907,8 @@ namespace ts { } const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } @@ -19923,6 +20931,59 @@ namespace ts { return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } + function createSignatureForJSXIntrinsic(node: JsxOpeningLikeElement, result: Type): Signature { + const namespace = getJsxNamespaceAt(node); + const exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + const typeSymbol = exports && getSymbol(exports, JsxNames.Element, SymbolFlags.Type); + const returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, SymbolFlags.Type, node); + const declaration = createFunctionTypeNode(/*typeParameters*/ undefined, + [createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], + returnNode ? createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : createKeywordTypeNode(SyntaxKind.AnyKeyword) + ); + const parameterSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, "props" as __String); + parameterSymbol.type = result; + return createSignature( + declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, + [parameterSymbol], + typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, + 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false + ); + } + + function resolveJsxOpeningLikeElement(node: JsxOpeningLikeElement, candidatesOutArray: Signature[] | undefined, isForSignatureHelp: boolean): Signature { + if (isJsxIntrinsicIdentifier(node.tagName)) { + const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + const fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + const exprTypes = checkExpression(node.tagName); + const apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + + const signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { + return resolveUntypedCall(node); + } + + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } + /** * Sometimes, we have a decorator that could accept zero arguments, * but is receiving too many arguments as part of the decorator invocation. @@ -19935,26 +20996,6 @@ namespace ts { signature.parameters.length < getDecoratorArgumentCount(decorator, signature)); } - /** - * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. - * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName - * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) - * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. - * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function - * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement: JsxOpeningLikeElement, elementType: Type, candidatesOutArray: Signature[] | undefined, isForSignatureHelp: boolean): Signature | undefined { - Debug.assert(!(elementType.flags & TypeFlags.Union)); - const callSignatures = elementType && getSignaturesOfType(elementType, SignatureKind.Call); - if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); - } - - return undefined; - } - function resolveSignature(node: CallLikeExpression, candidatesOutArray: Signature[] | undefined, isForSignatureHelp: boolean): Signature { switch (node.kind) { case SyntaxKind.CallExpression: @@ -19967,19 +21008,7 @@ namespace ts { return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: - // This code-path is called by language service - const exprTypes = checkExpression(node.tagName); - return forEachType(exprTypes, exprType => { - const sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); - if (sfcResult && sfcResult !== unknownSignature) { - return sfcResult; - } - const sigs = getInstantiatedJsxSignatures(node, exprType); - if (candidatesOutArray && length(sigs)) { - candidatesOutArray.push(...sigs!); - } - return length(sigs) ? sigs![0] : unknownSignature; - }) || unknownSignature; + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); } throw Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -20014,60 +21043,55 @@ namespace ts { * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node: Declaration | undefined): boolean { - if (node && isInJavaScriptFile(node)) { + function isJSConstructor(node: Declaration | undefined): boolean { + if (!node || !isInJSFile(node)) { + return false; + } + const func = isFunctionDeclaration(node) || isFunctionExpression(node) ? node : + isVariableDeclaration(node) && node.initializer && isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - const symbol = isFunctionDeclaration(node) || isFunctionExpression(node) ? getSymbolOfNode(node) : - isVariableDeclaration(node) && node.initializer && isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; - - return !!symbol && symbol.members !== undefined; + const symbol = getSymbolOfNode(func); + return !!symbol && (symbol.members !== undefined || symbol.exports !== undefined && symbol.exports.get("prototype" as __String) !== undefined); } - return false; } - function isJavascriptConstructorType(type: Type) { + function isJSConstructorType(type: Type) { if (type.flags & TypeFlags.Object) { const resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol: Symbol): Type | undefined { + function getJSClassType(symbol: Symbol): Type | undefined { let inferred: Type | undefined; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } const assigned = getAssignedClassType(symbol); - const valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { - inferred = getInferredClassType(valueType.symbol); - } return assigned && inferred ? getIntersectionType([inferred, assigned]) : assigned || inferred; } - function getAssignedClassType(symbol: Symbol) { + function getAssignedClassType(symbol: Symbol): Type | undefined { const decl = symbol.valueDeclaration; const assignmentSymbol = decl && decl.parent && (isFunctionDeclaration(decl) && getSymbolOfNode(decl) || isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - const prototype = forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + const prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype" as __String); + const init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node: Node) { + function getAssignedJSPrototype(node: Node) { if (!node.parent) { return false; } @@ -20090,12 +21114,6 @@ namespace ts { return links.inferredClassType; } - function isInferredClassType(type: Type) { - return type.symbol - && getObjectFlags(type) & ObjectFlags.Anonymous - && getSymbolLinks(type.symbol).inferredClassType === type; - } - /** * Syntactically and semantically checks a call or new expression. * @param node The call/new expression to be checked. @@ -20117,21 +21135,10 @@ namespace ts { declaration.kind !== SyntaxKind.Constructor && declaration.kind !== SyntaxKind.ConstructSignature && declaration.kind !== SyntaxKind.ConstructorType && - !isJSDocConstructSignature(declaration)) { + !isJSDocConstructSignature(declaration) && + !isJSConstructor(declaration)) { - // When resolved signature is a call signature (and not a construct signature) the result type is any, unless - // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations - // in a JS file - // Note:JS inferred classes might come from a variable declaration instead of a function declaration. - // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. - let funcSymbol = checkExpression(node.expression).symbol; - if (!funcSymbol && node.expression.kind === SyntaxKind.Identifier) { - funcSymbol = getResolvedSymbol(node.expression as Identifier); - } - const type = funcSymbol && getJavascriptClassType(funcSymbol); - if (type) { - return signature.target ? instantiateType(type, signature.mapper) : type; - } + // When resolved signature is a call signature (and not a construct signature) the result type is any if (noImplicitAny) { error(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } @@ -20140,7 +21147,7 @@ namespace ts { } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments![0] as StringLiteral); } @@ -20151,8 +21158,8 @@ namespace ts { return getESSymbolLikeTypeForNode(walkUpParenthesizedExpressions(node.parent)); } let jsAssignmentType: Type | undefined; - if (isInJavaScriptFile(node)) { - const decl = getDeclarationOfJSInitializer(node); + if (isInJSFile(node)) { + const decl = getDeclarationOfExpando(node); if (decl) { const jsSymbol = getSymbolOfNode(decl); if (jsSymbol && hasEntries(jsSymbol.exports)) { @@ -20221,6 +21228,7 @@ namespace ts { if (hasSyntheticDefault) { const memberTable = createSymbolTable(); const newSymbol = createSymbol(SymbolFlags.Alias, InternalSymbolName.Default); + newSymbol.nameType = getLiteralType("default"); newSymbol.target = resolveSymbol(symbol); memberTable.set(InternalSymbolName.Default, newSymbol); const anonymousSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type); @@ -20541,6 +21549,18 @@ namespace ts { return emptyObjectType; } + function createPromiseLikeType(promisedType: Type): Type { + // creates a `PromiseLike` type where `T` is the promisedType argument + const globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + + return emptyObjectType; + } + function createPromiseReturnType(func: FunctionLikeDeclaration | ImportCall, promisedType: Type) { const promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -20777,7 +21797,7 @@ namespace ts { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(t => t.symbol === func.symbol))) { + !(isJSConstructor(func) && aggregatedTypes.some(t => t.symbol === func.symbol))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined pushIfUnique(aggregatedTypes, undefinedType); } @@ -20853,6 +21873,7 @@ namespace ts { function checkFunctionExpressionOrObjectLiteralMethod(node: FunctionExpression | MethodDeclaration, checkMode?: CheckMode): Type { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === CheckMode.SkipContextSensitive && isContextSensitive(node)) { @@ -20910,7 +21931,6 @@ namespace ts { } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } @@ -20968,25 +21988,59 @@ namespace ts { } function checkArithmeticOperandType(operand: Node, type: Type, diagnostic: DiagnosticMessage): boolean { - if (!isTypeAssignableToKind(type, TypeFlags.NumberLike)) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { error(operand, diagnostic); return false; } return true; } + function isReadonlyAssignmentDeclaration(d: Declaration) { + if (!isCallExpression(d)) { + return false; + } + if (!isBindableObjectDefinePropertyCall(d)) { + return false; + } + const objectLitType = checkExpressionCached(d.arguments[2]); + const valueType = getTypeOfPropertyOfType(objectLitType, "value" as __String); + if (valueType) { + const writableProp = getPropertyOfType(objectLitType, "writable" as __String); + const writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && isPropertyAssignment(writableProp.valueDeclaration)) { + const initializer = writableProp.valueDeclaration.initializer; + const rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + const setProp = getPropertyOfType(objectLitType, "set" as __String); + return !setProp; + } + 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 + // Object.defineProperty assignments with writable false or no setter // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) return !!(getCheckFlags(symbol) & CheckFlags.Readonly || symbol.flags & SymbolFlags.Property && getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.Readonly || symbol.flags & SymbolFlags.Variable && getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const || symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) || - symbol.flags & SymbolFlags.EnumMember); + symbol.flags & SymbolFlags.EnumMember || + some(symbol.declarations, isReadonlyAssignmentDeclaration) + ); } function isReferenceToReadonlyEntity(expr: Expression, symbol: Symbol): boolean { @@ -20994,7 +22048,7 @@ namespace ts { // 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) { + (expr as AccessExpression).expression.kind === SyntaxKind.ThisKeyword) { // Look for if this is the constructor for the class that `symbol` is a property of. const func = getContainingFunction(expr); if (!(func && func.kind === SyntaxKind.Constructor)) { @@ -21012,7 +22066,7 @@ namespace ts { function isReferenceThroughNamespaceImport(expr: Expression): boolean { if (expr.kind === SyntaxKind.PropertyAccessExpression || expr.kind === SyntaxKind.ElementAccessExpression) { - const node = skipParentheses((expr as PropertyAccessExpression | ElementAccessExpression).expression); + const node = skipParentheses((expr as AccessExpression).expression); if (node.kind === SyntaxKind.Identifier) { const symbol = getNodeLinks(node).resolvedSymbol!; if (symbol.flags & SymbolFlags.Alias) { @@ -21080,13 +22134,22 @@ namespace ts { if (operandType === silentNeverType) { return silentNeverType; } - if (node.operand.kind === SyntaxKind.NumericLiteral) { - if (node.operator === SyntaxKind.MinusToken) { - return getFreshTypeOfLiteralType(getLiteralType(-(node.operand).text)); - } - else if (node.operator === SyntaxKind.PlusToken) { - return getFreshTypeOfLiteralType(getLiteralType(+(node.operand).text)); - } + switch (node.operand.kind) { + case SyntaxKind.NumericLiteral: + switch (node.operator) { + case SyntaxKind.MinusToken: + return getFreshTypeOfLiteralType(getLiteralType(-(node.operand as NumericLiteral).text)); + case SyntaxKind.PlusToken: + return getFreshTypeOfLiteralType(getLiteralType(+(node.operand as NumericLiteral).text)); + } + break; + case SyntaxKind.BigIntLiteral: + if (node.operator === SyntaxKind.MinusToken) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: parsePseudoBigInt((node.operand as BigIntLiteral).text) + })); + } } switch (node.operator) { case SyntaxKind.PlusToken: @@ -21096,7 +22159,13 @@ namespace ts { if (maybeTypeOfKind(operandType, TypeFlags.ESSymbolLike)) { error(node.operand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(node.operator)); } - return numberType; + if (node.operator === SyntaxKind.PlusToken) { + if (maybeTypeOfKind(operandType, TypeFlags.BigIntLike)) { + error(node.operand, Diagnostics.Operator_0_cannot_be_applied_to_type_1, tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); case SyntaxKind.ExclamationToken: checkTruthinessExpression(node.operand); const facts = getTypeFacts(operandType) & (TypeFacts.Truthy | TypeFacts.Falsy); @@ -21106,12 +22175,12 @@ namespace ts { case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), - Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_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_or_a_property_access); } - return numberType; + return getUnaryResultType(operandType); } return errorType; } @@ -21124,11 +22193,21 @@ namespace ts { const ok = checkArithmeticOperandType( node.operand, checkNonNullType(operandType, node.operand), - Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_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_or_a_property_access); } + return getUnaryResultType(operandType); + } + + function getUnaryResultType(operandType: Type): Type { + if (maybeTypeOfKind(operandType, TypeFlags.BigIntLike)) { + return isTypeAssignableToKind(operandType, TypeFlags.AnyOrUnknown) || maybeTypeOfKind(operandType, TypeFlags.NumberLike) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number return numberType; } @@ -21157,6 +22236,7 @@ namespace ts { return false; } return !!(kind & TypeFlags.NumberLike) && isTypeAssignableTo(source, numberType) || + !!(kind & TypeFlags.BigIntLike) && isTypeAssignableTo(source, bigintType) || !!(kind & TypeFlags.StringLike) && isTypeAssignableTo(source, stringType) || !!(kind & TypeFlags.BooleanLike) && isTypeAssignableTo(source, booleanType) || !!(kind & TypeFlags.Void) && isTypeAssignableTo(source, voidType) || @@ -21235,21 +22315,18 @@ namespace ts { function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType: Type, property: ObjectLiteralElementLike, allProperties?: NodeArray, rightIsThis = false) { if (property.kind === SyntaxKind.PropertyAssignment || property.kind === SyntaxKind.ShorthandPropertyAssignment) { const name = property.name; - if (name.kind === SyntaxKind.ComputedPropertyName) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - - const type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); - if (type) { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === SyntaxKind.ShorthandPropertyAssignment ? property : property.initializer, type); - } - else { - error(name, Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), declarationNameToString(name)); + const text = getTextOfPropertyName(name); + if (text) { + const prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + } } + const exprType = getLiteralTypeFromPropertyName(name); + const elementType = getIndexedAccessType(objectLiteralType, exprType, name); + const type = getFlowTypeOfDestructuring(property, elementType); + return checkDestructuringAssignment(property.kind === SyntaxKind.ShorthandPropertyAssignment ? property : property.initializer, type); } else if (property.kind === SyntaxKind.SpreadAssignment) { if (languageVersion < ScriptTarget.ESNext) { @@ -21270,31 +22347,11 @@ namespace ts { } } - function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType: Type, name: PropertyName, property: PropertyAssignment | ShorthandPropertyAssignment, rightIsThis: boolean) { - if (isTypeAny(objectLiteralType)) { - return objectLiteralType; - } - - let type: Type | undefined; - const text = getTextOfPropertyName(name); - if (text) { // TODO: GH#26379 - const prop = getPropertyOfType(objectLiteralType, text); - if (prop) { - markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); - type = getTypeOfSymbol(prop); - } - type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, IndexKind.Number) : undefined); - } - return type || getIndexTypeOfType(objectLiteralType, IndexKind.String); - } - function checkArrayLiteralAssignment(node: ArrayLiteralExpression, sourceType: Type, checkMode?: CheckMode): Type { const elements = node.elements; if (languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, ExternalEmitHelpers.Read); } - // This elementType will be used if the specific property corresponding to this index is not // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). @@ -21311,39 +22368,30 @@ namespace ts { const element = elements[elementIndex]; if (element.kind !== SyntaxKind.OmittedExpression) { if (element.kind !== SyntaxKind.SpreadElement) { - const propName = "" + elementIndex as __String; - const type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : - elementType; - if (type) { + const indexType = getLiteralType(elementIndex); + if (isArrayLikeType(sourceType)) { + // We create a synthetic expression so that getIndexedAccessType doesn't get confused + // when the element is a SyntaxKind.ElementAccessExpression. + const elementType = getIndexedAccessType(sourceType, indexType, createSyntheticExpression(element, indexType)); + const type = getFlowTypeOfDestructuring(element, elementType); return checkDestructuringAssignment(element, type, checkMode); } - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName as string); - } + return checkDestructuringAssignment(element, elementType, checkMode); + } + if (elementIndex < elements.length - 1) { + error(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - if (elementIndex < elements.length - 1) { - error(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + const restExpression = (element).expression; + if (restExpression.kind === SyntaxKind.BinaryExpression && (restExpression).operatorToken.kind === SyntaxKind.EqualsToken) { + error((restExpression).operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); } else { - const restExpression = (element).expression; - if (restExpression.kind === SyntaxKind.BinaryExpression && (restExpression).operatorToken.kind === SyntaxKind.EqualsToken) { - error((restExpression).operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - const type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : - createArrayType(elementType); - return checkDestructuringAssignment(restExpression, type, checkMode); - } + checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + const type = everyType(sourceType, isTupleType) ? + mapType(sourceType, t => sliceTupleType(t, elementIndex)) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); } } } @@ -21411,6 +22459,7 @@ namespace ts { case SyntaxKind.TemplateExpression: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NullKeyword: @@ -21464,7 +22513,7 @@ namespace ts { } function checkBinaryExpression(node: BinaryExpression, checkMode?: CheckMode) { - if (isInJavaScriptFile(node) && getAssignedJavascriptInitializer(node)) { + if (isInJSFile(node) && getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -21521,17 +22570,38 @@ namespace ts { (rightType.flags & TypeFlags.BooleanLike) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, tokenToString(operatorToken.kind), tokenToString(suggestedOperator)); + return numberType; } else { // otherwise just check each operand separately and report errors as normal - const leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - const rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); + const leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + const rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + let resultType: Type; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, TypeFlags.AnyOrUnknown) && isTypeAssignableToKind(rightType, TypeFlags.AnyOrUnknown)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, TypeFlags.BigIntLike) || maybeTypeOfKind(rightType, TypeFlags.BigIntLike)) + ) { + resultType = numberType; } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, TypeFlags.BigIntLike) && isTypeAssignableToKind(rightType, TypeFlags.BigIntLike)) { + switch (operator) { + case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: + reportOperatorError(); + } + resultType = bigintType; + } + else { + reportOperatorError(); + resultType = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType); + } + return resultType; } - - return numberType; case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: if (leftType === silentNeverType || rightType === silentNeverType) { @@ -21549,6 +22619,10 @@ namespace ts { // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } + else if (isTypeAssignableToKind(leftType, TypeFlags.BigIntLike, /*strict*/ true) && isTypeAssignableToKind(rightType, TypeFlags.BigIntLike, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } else if (isTypeAssignableToKind(leftType, TypeFlags.StringLike, /*strict*/ true) || isTypeAssignableToKind(rightType, TypeFlags.StringLike, /*strict*/ true)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; @@ -21580,7 +22654,9 @@ namespace ts { if (checkForDisallowedESSymbolOperand(operator)) { leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)) + )) { reportOperatorError(); } } @@ -21612,9 +22688,18 @@ namespace ts { getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], UnionReduction.Subtype) : leftType; case SyntaxKind.EqualsToken: - const special = isBinaryExpression(left.parent) ? getSpecialPropertyAssignmentKind(left.parent) : SpecialPropertyAssignmentKind.None; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : AssignmentDeclarationKind.None; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration(declKind)) { + if (!(rightType.flags & TypeFlags.Object) || + declKind !== AssignmentDeclarationKind.ModuleExports && + declKind !== AssignmentDeclarationKind.Prototype && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType as ObjectType) && + !(getObjectFlags(rightType) & ObjectFlags.Class)) { + // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete + checkAssignmentOperator(rightType); + } return leftType; } else { @@ -21631,9 +22716,8 @@ namespace ts { return Debug.fail(); } - function checkSpecialAssignment(special: SpecialPropertyAssignmentKind, right: Expression) { - if (special === SpecialPropertyAssignmentKind.ModuleExports) { - const rightType = checkExpression(right, checkMode); + function checkAssignmentDeclaration(kind: AssignmentDeclarationKind, rightType: Type) { + if (kind === AssignmentDeclarationKind.ModuleExports) { for (const prop of getPropertiesOfObjectType(rightType)) { const propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & SymbolFlags.Class) { @@ -21699,17 +22783,17 @@ namespace ts { } } - function isJSSpecialPropertyAssignment(special: SpecialPropertyAssignmentKind) { - switch (special) { - case SpecialPropertyAssignmentKind.ModuleExports: + function isAssignmentDeclaration(kind: AssignmentDeclarationKind) { + switch (kind) { + case AssignmentDeclarationKind.ModuleExports: return true; - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.Prototype: - case SpecialPropertyAssignmentKind.PrototypeProperty: - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.Prototype: + case AssignmentDeclarationKind.PrototypeProperty: + case AssignmentDeclarationKind.ThisProperty: const symbol = getSymbolOfNode(left); - const init = getAssignedJavascriptInitializer(right); + const init = getAssignedExpandoInitializer(right); return init && isObjectLiteralExpression(init) && symbol && hasEntries(symbol.exports); default: @@ -21837,7 +22921,7 @@ namespace ts { } function getContextNode(node: Expression): Node { - if (node.kind === SyntaxKind.JsxAttributes) { + if (node.kind === SyntaxKind.JsxAttributes && !isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -21884,18 +22968,15 @@ namespace ts { const type = getTypeOfExpression(initializer, /*cache*/ true); const widened = getCombinedNodeFlags(declaration) & NodeFlags.Const || isDeclarationReadonly(declaration) || - isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (isInJavaScriptFile(declaration)) { + isTypeAssertion(initializer) || + isLiteralOfContextualType(type, getContextualType(initializer)) ? type : getWidenedLiteralType(type); + if (isInJSFile(declaration)) { if (widened.flags & TypeFlags.Nullable) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -21915,6 +22996,7 @@ namespace ts { const constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; return maybeTypeOfKind(constraint, TypeFlags.String) && maybeTypeOfKind(candidateType, TypeFlags.StringLiteral) || maybeTypeOfKind(constraint, TypeFlags.Number) && maybeTypeOfKind(candidateType, TypeFlags.NumberLiteral) || + maybeTypeOfKind(constraint, TypeFlags.BigInt) && maybeTypeOfKind(candidateType, TypeFlags.BigIntLiteral) || maybeTypeOfKind(constraint, TypeFlags.ESSymbol) && maybeTypeOfKind(candidateType, TypeFlags.UniqueESSymbol) || isLiteralOfContextualType(candidateType, constraint); } @@ -21922,17 +23004,18 @@ namespace ts { // literal context for all literals of that primitive type. return !!(contextualType.flags & (TypeFlags.StringLiteral | TypeFlags.Index) && maybeTypeOfKind(candidateType, TypeFlags.StringLiteral) || contextualType.flags & TypeFlags.NumberLiteral && maybeTypeOfKind(candidateType, TypeFlags.NumberLiteral) || + contextualType.flags & TypeFlags.BigIntLiteral && maybeTypeOfKind(candidateType, TypeFlags.BigIntLiteral) || contextualType.flags & TypeFlags.BooleanLiteral && maybeTypeOfKind(candidateType, TypeFlags.BooleanLiteral) || contextualType.flags & TypeFlags.UniqueESSymbol && maybeTypeOfKind(candidateType, TypeFlags.UniqueESSymbol)); } return false; } - function checkExpressionForMutableLocation(node: Expression, checkMode: CheckMode | undefined, contextualType?: Type): Type { + function checkExpressionForMutableLocation(node: Expression, checkMode: CheckMode | undefined, contextualType?: Type, forceTuple?: boolean): Type { if (arguments.length === 2) { contextualType = getContextualType(node); } - const type = checkExpression(node, checkMode); + const type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -22032,13 +23115,13 @@ namespace ts { // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node: Expression | QualifiedName, checkMode?: CheckMode): Type { + function checkExpression(node: Expression | QualifiedName, checkMode?: CheckMode, forceTuple?: boolean): Type { let type: Type; if (node.kind === SyntaxKind.QualifiedName) { type = checkQualifiedName(node); } else { - const uninstantiatedType = checkExpressionWorker(node, checkMode); + const uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } @@ -22061,14 +23144,14 @@ namespace ts { } function checkParenthesizedExpression(node: ParenthesizedExpression, checkMode?: CheckMode): Type { - const tag = isInJavaScriptFile(node) ? getJSDocTypeTag(node) : undefined; + const tag = isInJSFile(node) ? getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression!.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node: Expression, checkMode: CheckMode | undefined): Type { + function checkExpressionWorker(node: Expression, checkMode: CheckMode | undefined, forceTuple?: boolean): Type { switch (node.kind) { case SyntaxKind.Identifier: return checkIdentifier(node); @@ -22084,6 +23167,9 @@ namespace ts { case SyntaxKind.NumericLiteral: checkGrammarNumericLiteral(node as NumericLiteral); return getFreshTypeOfLiteralType(getLiteralType(+(node as NumericLiteral).text)); + case SyntaxKind.BigIntLiteral: + checkGrammarBigIntLiteral(node as BigIntLiteral); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node as BigIntLiteral)); case SyntaxKind.TrueKeyword: return trueType; case SyntaxKind.FalseKeyword: @@ -22093,7 +23179,7 @@ namespace ts { case SyntaxKind.RegularExpressionLiteral: return globalRegExpType; case SyntaxKind.ArrayLiteralExpression: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case SyntaxKind.ObjectLiteralExpression: return checkObjectLiteral(node, checkMode); case SyntaxKind.PropertyAccessExpression: @@ -22154,7 +23240,7 @@ namespace ts { case SyntaxKind.JsxSelfClosingElement: return checkJsxSelfClosingElement(node, checkMode); case SyntaxKind.JsxFragment: - return checkJsxFragment(node, checkMode); + return checkJsxFragment(node); case SyntaxKind.JsxAttributes: return checkJsxAttributes(node, checkMode); case SyntaxKind.JsxOpeningElement: @@ -22631,7 +23717,7 @@ namespace ts { // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. const containingClassDecl = node.parent; - if (getEffectiveBaseTypeNode(containingClassDecl)) { + if (getClassExtendsHeritageElement(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); const classExtendsNull = classDeclarationExtendsNull(containingClassDecl); const superCall = getSuperCallInConstructor(node); @@ -22738,7 +23824,7 @@ namespace ts { function getEffectiveTypeArguments(node: TypeReferenceNode | ExpressionWithTypeArguments, typeParameters: ReadonlyArray): Type[] { return fillMissingTypeArguments(map(node.typeArguments!, getTypeFromTypeNode), typeParameters, - getMinTypeArgumentCount(typeParameters), isInJavaScriptFile(node)); + getMinTypeArgumentCount(typeParameters), isInJSFile(node)); } function checkTypeArgumentConstraints(node: TypeReferenceNode | ExpressionWithTypeArguments, typeParameters: ReadonlyArray): boolean { @@ -22776,7 +23862,7 @@ namespace ts { function checkTypeReferenceNode(node: TypeReferenceNode | ExpressionWithTypeArguments) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === SyntaxKind.TypeReference && node.typeName.jsdocDotPos !== undefined && !isInJavaScriptFile(node) && !isInJSDoc(node)) { + if (node.kind === SyntaxKind.TypeReference && node.typeName.jsdocDotPos !== undefined && !isInJSFile(node) && !isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } const type = getTypeFromTypeReference(node); @@ -22845,7 +23931,6 @@ namespace ts { break; } } - checkGrammarForDisallowedTrailingComma(node.elementTypes); forEach(node.elementTypes, checkSourceElement); } @@ -22853,7 +23938,7 @@ namespace ts { forEach(node.types, checkSourceElement); } - function checkIndexedAccessIndexType(type: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode) { + function checkIndexedAccessIndexType(type: Type, accessNode: Node) { if (!(type.flags & TypeFlags.IndexedAccess)) { return type; } @@ -22886,8 +23971,8 @@ namespace ts { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } const type = getTypeFromMappedTypeNode(node); @@ -23645,41 +24730,10 @@ namespace ts { switch (node.kind) { case SyntaxKind.IntersectionType: case SyntaxKind.UnionType: - let commonEntityName: EntityName | undefined; - for (let typeNode of (node).types) { - while (typeNode.kind === SyntaxKind.ParenthesizedType) { - typeNode = (typeNode as ParenthesizedTypeNode).type; // Skip parens if need be - } - if (typeNode.kind === SyntaxKind.NeverKeyword) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === SyntaxKind.NullKeyword || typeNode.kind === SyntaxKind.UndefinedKeyword)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - const individualEntityName = getEntityNameForDecoratorMetadata(typeNode); - if (!individualEntityName) { - // Individual is something like string number - // So it would be serialized to either that type or object - // Safe to return here - return undefined; - } + return getEntityNameForDecoratorMetadataFromTypeList((node).types); - if (commonEntityName) { - // Note this is in sync with the transformation that happens for type node. - // Keep this in sync with serializeUnionOrIntersectionType - // Verify if they refer to same entity and is identifier - // return undefined if they dont match because we would emit object - if (!isIdentifier(commonEntityName) || - !isIdentifier(individualEntityName) || - commonEntityName.escapedText !== individualEntityName.escapedText) { - return undefined; - } - } - else { - commonEntityName = individualEntityName; - } - } - return commonEntityName; + case SyntaxKind.ConditionalType: + return getEntityNameForDecoratorMetadataFromTypeList([(node).trueType, (node).falseType]); case SyntaxKind.ParenthesizedType: return getEntityNameForDecoratorMetadata((node).type); @@ -23690,6 +24744,44 @@ namespace ts { } } + function getEntityNameForDecoratorMetadataFromTypeList(types: ReadonlyArray): EntityName | undefined { + let commonEntityName: EntityName | undefined; + for (let typeNode of types) { + while (typeNode.kind === SyntaxKind.ParenthesizedType) { + typeNode = (typeNode as ParenthesizedTypeNode).type; // Skip parens if need be + } + if (typeNode.kind === SyntaxKind.NeverKeyword) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === SyntaxKind.NullKeyword || typeNode.kind === SyntaxKind.UndefinedKeyword)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + const individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!isIdentifier(commonEntityName) || + !isIdentifier(individualEntityName) || + commonEntityName.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } + function getParameterTypeNodeForDecoratorCheck(node: ParameterDeclaration): TypeNode | undefined { const typeNode = getEffectiveTypeAnnotationNode(node); return isRestParameter(node) ? getRestParameterElementType(typeNode) : typeNode; @@ -23807,9 +24899,17 @@ namespace ts { return; } if (!containsArgumentsReference(decl)) { - error(node.name, - Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, - idText(node.name.kind === SyntaxKind.QualifiedName ? node.name.right : node.name)); + if (isQualifiedName(node.name)) { + error(node.name, + Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, + entityNameToString(node.name), + entityNameToString(node.name.left)); + } + else { + error(node.name, + Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, + idText(node.name)); + } } else if (findLast(getJSDocTags(decl), isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && @@ -23822,6 +24922,13 @@ namespace ts { } } + function checkJSDocFunctionType(node: JSDocFunctionType): void { + if (produceDiagnostics && !node.type && !isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + checkSignatureDeclaration(node); + } + function checkJSDocAugmentsTag(node: JSDocAugmentsTag): void { const classLike = getJSDocHost(node); if (!isClassDeclaration(classLike) && !isClassExpression(classLike)) { @@ -23911,8 +25018,8 @@ namespace ts { if (produceDiagnostics && !getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & FunctionFlags.Generator && nodeIsPresent(body)) { @@ -23924,7 +25031,7 @@ namespace ts { } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { const typeTag = getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -23934,7 +25041,7 @@ namespace ts { function registerForUnusedIdentifiersCheck(node: PotentiallyUnusedIdentifier): void { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. - if (produceDiagnostics) { + if (produceDiagnostics && !(node.flags & NodeFlags.Ambient)) { const sourceFile = getSourceFileOfNode(node); let potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); if (!potentiallyUnusedIdentifiers) { @@ -23961,9 +25068,6 @@ namespace ts { checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case SyntaxKind.InterfaceDeclaration: - checkUnusedTypeParameters(node, addDiagnostic); - break; case SyntaxKind.SourceFile: case SyntaxKind.ModuleDeclaration: case SyntaxKind.Block: @@ -23980,7 +25084,7 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - if (node.body) { + if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); @@ -23991,9 +25095,12 @@ namespace ts { case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.TypeAliasDeclaration: - case SyntaxKind.InferType: + case SyntaxKind.InterfaceDeclaration: checkUnusedTypeParameters(node, addDiagnostic); break; + case SyntaxKind.InferType: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; default: Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); } @@ -24011,76 +25118,73 @@ namespace ts { } function checkUnusedClassMembers(node: ClassDeclaration | ClassExpression, addDiagnostic: AddUnusedDiagnostic): void { - if (!(node.flags & NodeFlags.Ambient)) { - for (const member of node.members) { - switch (member.kind) { - case SyntaxKind.MethodDeclaration: - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - if (member.kind === SyntaxKind.SetAccessor && member.symbol.flags & SymbolFlags.GetAccessor) { - // Already would have reported an error on the getter. - break; - } - const symbol = getSymbolOfNode(member); - if (!symbol.isReferenced && hasModifier(member, ModifierFlags.Private)) { - addDiagnostic(member, UnusedKind.Local, createDiagnosticForNode(member.name!, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); - } + for (const member of node.members) { + switch (member.kind) { + case SyntaxKind.MethodDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + if (member.kind === SyntaxKind.SetAccessor && member.symbol.flags & SymbolFlags.GetAccessor) { + // Already would have reported an error on the getter. break; - case SyntaxKind.Constructor: - for (const parameter of (member).parameters) { - if (!parameter.symbol.isReferenced && hasModifier(parameter, ModifierFlags.Private)) { - addDiagnostic(parameter, UnusedKind.Local, createDiagnosticForNode(parameter.name, Diagnostics.Property_0_is_declared_but_its_value_is_never_read, symbolName(parameter.symbol))); - } + } + const symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && hasModifier(member, ModifierFlags.Private)) { + addDiagnostic(member, UnusedKind.Local, createDiagnosticForNode(member.name!, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case SyntaxKind.Constructor: + for (const parameter of (member).parameters) { + if (!parameter.symbol.isReferenced && hasModifier(parameter, ModifierFlags.Private)) { + addDiagnostic(parameter, UnusedKind.Local, createDiagnosticForNode(parameter.name, Diagnostics.Property_0_is_declared_but_its_value_is_never_read, symbolName(parameter.symbol))); } - break; - case SyntaxKind.IndexSignature: - case SyntaxKind.SemicolonClassElement: - // Can't be private - break; - default: - Debug.fail(); - } + } + break; + case SyntaxKind.IndexSignature: + case SyntaxKind.SemicolonClassElement: + // Can't be private + break; + default: + Debug.fail(); } } } - function checkUnusedTypeParameters(node: ClassLikeDeclaration | SignatureDeclaration | InterfaceDeclaration | TypeAliasDeclaration | InferTypeNode, addDiagnostic: AddUnusedDiagnostic): void { + function checkUnusedInferTypeParameter(node: InferTypeNode, addDiagnostic: AddUnusedDiagnostic): void { + const { typeParameter } = node; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, UnusedKind.Parameter, createDiagnosticForNode(node, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(typeParameter.name))); + } + } + + function checkUnusedTypeParameters(node: ClassLikeDeclaration | SignatureDeclaration | InterfaceDeclaration | TypeAliasDeclaration, addDiagnostic: AddUnusedDiagnostic): void { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (node.flags & NodeFlags.Ambient || node.kind !== SyntaxKind.InferType && last(getSymbolOfNode(node).declarations) !== node) return; + if (last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === SyntaxKind.InferType) { - const { typeParameter } = node; - if (isTypeParameterUnused(typeParameter)) { - addDiagnostic(node, UnusedKind.Parameter, createDiagnosticForNode(node, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(typeParameter.name))); + const typeParameters = getEffectiveTypeParameterDeclarations(node); + const seenParentsWithEveryUnused = new NodeSet(); + + for (const typeParameter of typeParameters) { + if (!isTypeParameterUnused(typeParameter)) continue; + + const name = idText(typeParameter.name); + const { parent } = typeParameter; + if (parent.kind !== SyntaxKind.InferType && parent.typeParameters!.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + const range = isJSDocTemplateTag(parent) + // Whole @template tag + ? rangeOfNode(parent) + // Include the `<>` in the error message + : rangeOfTypeParameters(parent.typeParameters!); + const only = typeParameters.length === 1; + const message = only ? Diagnostics._0_is_declared_but_its_value_is_never_read : Diagnostics.All_type_parameters_are_unused; + const arg0 = only ? name : undefined; + addDiagnostic(typeParameter, UnusedKind.Parameter, createFileDiagnostic(getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } } - } - else { - const typeParameters = getEffectiveTypeParameterDeclarations(node); - const seenParentsWithEveryUnused = new NodeSet(); - - for (const typeParameter of typeParameters) { - if (!isTypeParameterUnused(typeParameter)) continue; - - const name = idText(typeParameter.name); - const { parent } = typeParameter; - if (parent.kind !== SyntaxKind.InferType && parent.typeParameters!.every(isTypeParameterUnused)) { - if (seenParentsWithEveryUnused.tryAdd(parent)) { - const range = isJSDocTemplateTag(parent) - // Whole @template tag - ? rangeOfNode(parent) - // Include the `<>` in the error message - : rangeOfTypeParameters(parent.typeParameters!); - const only = typeParameters.length === 1; - const message = only ? Diagnostics._0_is_declared_but_its_value_is_never_read : Diagnostics.All_type_parameters_are_unused; - const arg0 = only ? name : undefined; - addDiagnostic(typeParameter, UnusedKind.Parameter, createFileDiagnostic(getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); - } - } - else { - addDiagnostic(typeParameter, UnusedKind.Parameter, createDiagnosticForNode(typeParameter, Diagnostics._0_is_declared_but_its_value_is_never_read, name)); - } + else { + addDiagnostic(typeParameter, UnusedKind.Parameter, createDiagnosticForNode(typeParameter, Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } @@ -24537,10 +25641,10 @@ namespace ts { if (!isBindingPattern(name)) { const nameText = getTextOfPropertyName(name); if (nameText) { - const property = getPropertyOfType(parentType!, nameText)!; // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer.kind === SyntaxKind.SuperKeyword, parentType!, property); + const property = getPropertyOfType(parentType!, nameText); // TODO: GH#18217 + if (property) { + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === SyntaxKind.SuperKeyword, parentType!, property); } } } @@ -24581,7 +25685,7 @@ namespace ts { // Don't validate for-in initializer as it is already an error const initializer = getEffectiveInitializer(node); if (initializer) { - const isJSObjectLiteralInitializer = isInJavaScriptFile(node) && + const isJSObjectLiteralInitializer = isInJSFile(node) && isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && hasEntries(symbol.exports); @@ -24590,6 +25694,11 @@ namespace ts { checkParameterInitializer(node); } } + if (symbol.declarations.length > 1) { + if (some(symbol.declarations, d => d !== node && isVariableLike(d) && !areDeclarationFlagsIdentical(d, node))) { + error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); + } + } } else { // Node is a secondary declaration, check that type is identical to primary declaration and check that @@ -24598,14 +25707,13 @@ namespace ts { if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & SymbolFlags.JSContainer)) { + !(symbol.flags & SymbolFlags.Assignment)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(getNameOfDeclaration(symbol.valueDeclaration), Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); } } @@ -24798,7 +25906,7 @@ namespace ts { // Grammar checking checkGrammarForInOrForOfStatement(node); - const rightType = checkNonNullExpression(node.expression); + const rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement @@ -24939,7 +26047,7 @@ namespace ts { ? downlevelIteration ? Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator : isIterable - ? Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + ? Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators : Diagnostics.Type_0_is_not_an_array_type : downlevelIteration ? Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator @@ -25026,14 +26134,18 @@ namespace ts { if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = (type).typeArguments![0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType((type).typeArguments![0]) + : typeAsIterable.iteratedTypeOfIterable = (type).typeArguments![0]; } } @@ -25064,9 +26176,11 @@ namespace ts { : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } @@ -25485,6 +26599,7 @@ namespace ts { case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -25517,6 +26632,7 @@ namespace ts { if (produceDiagnostics) { if (node.default) { seenDefault = true; + checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i); } else if (seenDefault) { error(node, Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); @@ -25531,6 +26647,24 @@ namespace ts { } } + /** Check that type parameter defaults only reference previously declared type parameters */ + function checkTypeParametersNotReferenced(root: TypeNode, typeParameters: ReadonlyArray, index: number) { + visit(root); + function visit(node: Node) { + if (node.kind === SyntaxKind.TypeReference) { + const type = getTypeFromTypeReference(node); + if (type.flags & TypeFlags.TypeParameter) { + for (let i = index; i < typeParameters.length; i++) { + if (type.symbol === getSymbolOfNode(typeParameters[i])) { + error(node, Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters); + } + } + } + } + forEachChild(node, visit); + } + } + /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol: Symbol) { if (symbol.declarations.length === 1) { @@ -25678,8 +26812,11 @@ namespace ts { if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, - Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, + Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & TypeFlags.TypeVariable && !isMixinConstructorType(staticType)) { error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -25691,7 +26828,7 @@ namespace ts { // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (forEach(constructors, sig => !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType)) { + if (forEach(constructors, sig => !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType)) { error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -25719,7 +26856,7 @@ namespace ts { } } else { - error(typeRefNode, Diagnostics.A_class_may_only_implement_another_class_or_interface); + error(typeRefNode, Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } @@ -25942,6 +27079,8 @@ namespace ts { function isPropertyInitializedInConstructor(propName: Identifier, propType: Type, constructor: ConstructorDeclaration) { const reference = createPropertyAccess(createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; const flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & TypeFlags.Undefined); @@ -26058,7 +27197,7 @@ namespace ts { return 0; } else if (isConstEnum) { - error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + error(initializer, Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values); } else if (member.parent.flags & NodeFlags.Ambient) { error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); @@ -26119,7 +27258,7 @@ namespace ts { return nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); case SyntaxKind.ElementAccessExpression: case SyntaxKind.PropertyAccessExpression: - const ex = expr; + const ex = expr; if (isConstantMemberAccess(ex)) { const type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & SymbolFlags.Enum) { @@ -26396,7 +27535,7 @@ namespace ts { let reportError = !(symbol.flags & SymbolFlags.Transient); if (!reportError) { // symbol should not originate in augmentation - reportError = isExternalModuleAugmentation(symbol.parent!.declarations[0]); + reportError = !!symbol.parent && isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -26679,7 +27818,7 @@ namespace ts { const exportEqualsSymbol = moduleSymbol.exports!.get("export=" as __String); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) { error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -26729,7 +27868,7 @@ namespace ts { return; } - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { forEach((node as JSDocContainer).jsDoc, ({ tags }) => forEach(tags, checkSourceElement)); } @@ -26809,7 +27948,7 @@ namespace ts { case SyntaxKind.JSDocParameterTag: return checkJSDocParameterTag(node as JSDocParameterTag); case SyntaxKind.JSDocFunctionType: - checkSignatureDeclaration(node as JSDocFunctionType); + checkJSDocFunctionType(node as JSDocFunctionType); // falls through case SyntaxKind.JSDocNonNullableType: case SyntaxKind.JSDocNullableType: @@ -26896,7 +28035,7 @@ namespace ts { } function checkJSDocTypeIsInJsFile(node: Node): void { - if (!isInJavaScriptFile(node)) { + if (!isInJSFile(node)) { grammarErrorOnNode(node, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -26975,14 +28114,21 @@ namespace ts { // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node: Node) { - if (deferredNodes) { + const enclosingFile = getSourceFileOfNode(node); + const links = getNodeLinks(enclosingFile); + if (!(links.flags & NodeCheckFlags.TypeChecked)) { + links.deferredNodes = links.deferredNodes || createMap(); const id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes!.forEach(node => { + function checkDeferredNodes(context: SourceFile) { + const links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(node => { switch (node.kind) { case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: @@ -27043,10 +28189,10 @@ namespace ts { clear(potentialThisCollisions); clear(potentialNewTargetCollisions); - deferredNodes = createMap(); forEach(node.statements, checkSourceElement); + checkSourceElement(node.endOfFileToken); - checkDeferredNodes(); + checkDeferredNodes(node); if (isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); @@ -27060,8 +28206,6 @@ namespace ts { }); } - deferredNodes = undefined; - if (isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -27161,8 +28305,11 @@ namespace ts { } switch (location.kind) { + case SyntaxKind.SourceFile: + if (!isExternalOrCommonJsModule(location)) break; + // falls through case SyntaxKind.ModuleDeclaration: - copySymbols(getSymbolOfNode(location as ModuleDeclaration).exports!, meaning & SymbolFlags.ModuleMember); + copySymbols(getSymbolOfNode(location as ModuleDeclaration | SourceFile).exports!, meaning & SymbolFlags.ModuleMember); break; case SyntaxKind.EnumDeclaration: copySymbols(getSymbolOfNode(location as EnumDeclaration).exports!, meaning & SymbolFlags.EnumMember); @@ -27280,12 +28427,12 @@ namespace ts { return result; } - function isNodeUsedDuringClassInitialization(node: Node, classDeclaration: ClassLikeDeclaration) { + function isNodeUsedDuringClassInitialization(node: Node) { return !!findAncestor(node, element => { - if ((isConstructorDeclaration(element) && nodeIsPresent(element.body) || isPropertyDeclaration(element)) && element.parent === classDeclaration) { + if (isConstructorDeclaration(element) && nodeIsPresent(element.body) || isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || isFunctionLikeDeclaration(element)) { + else if (isClassLike(element) || isFunctionLikeDeclaration(element)) { return "quit"; } @@ -27318,14 +28465,14 @@ namespace ts { } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName: EntityName | PropertyAccessExpression) { - const specialPropertyAssignmentKind = getSpecialPropertyAssignmentKind(entityName.parent.parent as BinaryExpression); + const specialPropertyAssignmentKind = getAssignmentDeclarationKind(entityName.parent.parent as BinaryExpression); switch (specialPropertyAssignmentKind) { - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.PrototypeProperty: return getSymbolOfNode(entityName.parent); - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.ModuleExports: - case SpecialPropertyAssignmentKind.Property: + case AssignmentDeclarationKind.ThisProperty: + case AssignmentDeclarationKind.ModuleExports: + case AssignmentDeclarationKind.Property: return getSymbolOfNode(entityName.parent.parent); } } @@ -27347,7 +28494,7 @@ namespace ts { return getSymbolOfNode(entityName.parent); } - if (isInJavaScriptFile(entityName) && + if (isInJSFile(entityName) && entityName.parent.kind === SyntaxKind.PropertyAccessExpression && entityName.parent === (entityName.parent.parent as BinaryExpression).left) { // Check if this is a special property assignment @@ -27412,7 +28559,7 @@ namespace ts { } if (entityName.parent.kind === SyntaxKind.TypeParameter && entityName.parent.parent.kind === SyntaxKind.JSDocTemplateTag) { - Debug.assert(!isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + Debug.assert(!isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. const typeParameter = getTypeParameterFromJsDoc(entityName.parent as TypeParameterDeclaration & { parent: JSDocTemplateTag }); return typeParameter && typeParameter.symbol; } @@ -27450,9 +28597,6 @@ namespace ts { const meaning = entityName.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === SyntaxKind.JsxAttribute) { - return getJsxAttributePropertySymbol(entityName.parent); - } if (entityName.parent.kind === SyntaxKind.TypePredicate) { return resolveEntityName(entityName, /*meaning*/ SymbolFlags.FunctionScopedVariable); @@ -27476,7 +28620,10 @@ namespace ts { if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(parent); + const parentSymbol = getSymbolOfNode(parent)!; + return isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node + ? getImmediateAliasedSymbol(parentSymbol) + : parentSymbol; } else if (isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(parent.parent); @@ -27539,11 +28686,14 @@ namespace ts { // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration) && (node.parent).moduleSpecifier === node) || - ((isInJavaScriptFile(node) && isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || isImportCall(node.parent)) || + ((isInJSFile(node) && isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || isImportCall(node.parent)) || (isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) ) { return resolveExternalModuleName(node, node); } + if (isCallExpression(parent) && isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } // falls through case SyntaxKind.NumericLiteral: @@ -27563,6 +28713,9 @@ namespace ts { case SyntaxKind.ImportType: return isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case SyntaxKind.ExportKeyword: + return isExportAssignment(node.parent) ? Debug.assertDefined(node.parent.symbol) : undefined; + default: return undefined; } @@ -27588,24 +28741,20 @@ namespace ts { return errorType; } + const classDecl = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + const classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (isPartOfTypeNode(node)) { const typeFromTypeNode = getTypeFromTypeNode(node); - - if (isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - return getTypeWithThisArgument(typeFromTypeNode, getTypeOfClassContainingHeritageClause(node).thisType); - } - - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl!.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - const classType = getTypeOfClassContainingHeritageClause(node); const baseType = firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -27647,10 +28796,6 @@ namespace ts { return errorType; } - function getTypeOfClassContainingHeritageClause(node: ExpressionWithTypeArguments): InterfaceType { - return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node.parent.parent)); - } - // Gets the type of object literal or array literal of destructuring assignment. // { a } from // for ( { a } of elems) { @@ -27739,8 +28884,11 @@ namespace ts { function getAugmentedPropertiesOfType(type: Type): Symbol[] { type = getApparentType(type); const propsByName = createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - forEach(getPropertiesOfType(globalFunctionType), p => { + const functionType = getSignaturesOfType(type, SignatureKind.Call).length ? globalCallableFunctionType : + getSignaturesOfType(type, SignatureKind.Construct).length ? globalNewableFunctionType : + undefined; + if (functionType) { + forEach(getPropertiesOfType(functionType), p => { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -27753,7 +28901,7 @@ namespace ts { return ts.typeHasCallOrConstructSignatures(type, checker); } - function getRootSymbols(symbol: Symbol): Symbol[] { + function getRootSymbols(symbol: Symbol): ReadonlyArray { const roots = getImmediateRootSymbols(symbol); return roots ? flatMap(roots, getRootSymbols) : [symbol]; } @@ -28004,7 +29152,8 @@ namespace ts { return true; } const target = getSymbolLinks(symbol!).target; // TODO: GH#18217 - if (target && getModifierFlags(node) & ModifierFlags.Export && target.flags & SymbolFlags.Value) { + if (target && getModifierFlags(node) & ModifierFlags.Export && + target.flags & SymbolFlags.Value && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -28053,7 +29202,7 @@ namespace ts { hasModifier(parameter, ModifierFlags.ParameterPropertyModifier); } - function isJSContainerFunctionDeclaration(node: Declaration): boolean { + function isExpandoFunctionDeclaration(node: Declaration): boolean { const declaration = getParseTreeNode(node, isFunctionDeclaration); if (!declaration) { return false; @@ -28062,7 +29211,7 @@ namespace ts { if (!symbol || !(symbol.flags & SymbolFlags.Function)) { return false; } - return !!forEachEntry(getExportsOfSymbol(symbol), p => isPropertyAccessExpression(p.valueDeclaration)); + return !!forEachEntry(getExportsOfSymbol(symbol), p => p.flags & SymbolFlags.Value && isPropertyAccessExpression(p.valueDeclaration)); } function getPropertiesOfContainerFunction(node: Declaration): Symbol[] { @@ -28083,7 +29232,7 @@ namespace ts { return getNodeLinks(node).enumMemberValue; } - function canHaveConstantValue(node: Node): node is EnumMember | PropertyAccessExpression | ElementAccessExpression { + function canHaveConstantValue(node: Node): node is EnumMember | AccessExpression { switch (node.kind) { case SyntaxKind.EnumMember: case SyntaxKind.PropertyAccessExpression: @@ -28093,7 +29242,7 @@ namespace ts { return false; } - function getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined { + function getConstantValue(node: EnumMember | AccessExpression): string | number | undefined { if (node.kind === SyntaxKind.EnumMember) { return getEnumMemberValue(node); } @@ -28161,6 +29310,9 @@ namespace ts { else if (isTypeAssignableToKind(type, TypeFlags.NumberLike)) { return TypeReferenceSerializationKind.NumberLikeType; } + else if (isTypeAssignableToKind(type, TypeFlags.BigIntLike)) { + return TypeReferenceSerializationKind.BigIntLikeType; + } else if (isTypeAssignableToKind(type, TypeFlags.StringLike)) { return TypeReferenceSerializationKind.StringLikeType; } @@ -28258,19 +29410,20 @@ namespace ts { function isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean { if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node)) { - const type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & TypeFlags.StringOrNumberLiteral && type.flags & TypeFlags.FreshLiteral); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } - function literalTypeToNode(type: LiteralType): Expression { - return createLiteral(type.value); + function literalTypeToNode(type: FreshableType, enclosing: Node, tracker: SymbolTracker): Expression { + const enumResult = type.flags & TypeFlags.EnumLiteral ? nodeBuilder.symbolToExpression(type.symbol, SymbolFlags.Value, enclosing, /*flags*/ undefined, tracker) + : type === trueType ? createTrue() : type === falseType && createFalse(); + return enumResult || createLiteral((type as LiteralType).value); } - function createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration) { + function createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, tracker: SymbolTracker) { const type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node, tracker); } function createResolver(): EmitResolver { @@ -28314,7 +29467,7 @@ namespace ts { isImplementationOfOverload, isRequiredInitializedParameter, isOptionalUninitializedParameterProperty, - isJSContainerFunctionDeclaration, + isExpandoFunctionDeclaration, getPropertiesOfContainerFunction, createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration, @@ -28357,7 +29510,12 @@ namespace ts { getAccessor }; }, - getSymbolOfExternalModuleSpecifier: moduleName => resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined) + getSymbolOfExternalModuleSpecifier: moduleName => resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined), + isBindingCapturedByNode: (node, decl) => { + const parseNode = getParseTreeNode(node); + const parseDecl = getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (isVariableDeclaration(parseDecl) || isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node: PropertyAccessEntityNameExpression) { @@ -28470,6 +29628,9 @@ namespace ts { if (!isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals!); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -28515,6 +29676,8 @@ namespace ts { globalArrayType = getGlobalType("Array" as __String, /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object" as __String, /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function" as __String, /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction" as __String, /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction" as __String, /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String" as __String, /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number" as __String, /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean" as __String, /*arity*/ 0, /*reportErrors*/ true); @@ -28542,38 +29705,33 @@ namespace ts { } } - amalgamatedDuplicates.forEach(({ firstFile, secondFile, firstFileInstances, secondFileInstances }) => { - const conflictingKeys = arrayFrom(firstFileInstances.keys()); + amalgamatedDuplicates.forEach(({ firstFile, secondFile, conflictingSymbols }) => { // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(({ isBlockScoped, firstFileLocations, secondFileLocations }, symbolName) => { + const message = isBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; + for (const node of firstFileLocations) { + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (const node of secondFileLocations) { + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + const list = arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo( + createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), + createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file) + )); + diagnostics.add(addRelatedInfo( + createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), + createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file) + )); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - const list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo( - createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), - createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file) - )); - diagnostics.add(addRelatedInfo( - createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), - createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file) - )); }); amalgamatedDuplicates = undefined; - - function addErrorsForDuplicates(secondFileInstances: Map<{ instances: Node[]; blockScoped: boolean; }>, firstFileInstances: Map<{ instances: Node[]; blockScoped: boolean; }>) { - secondFileInstances.forEach((locations, symbolName) => { - const firstFileEquivalent = firstFileInstances.get(symbolName)!; - const message = locations.blockScoped - ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(node => { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location: Node, helpers: ExternalEmitHelpers) { @@ -28960,10 +30118,6 @@ namespace ts { checkGrammarForDisallowedTrailingComma(parameters, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); } - if (isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (parameter.questionToken) { return grammarErrorOnNode(parameter.questionToken, Diagnostics.A_rest_parameter_cannot_be_optional); } @@ -29633,20 +30787,39 @@ namespace ts { (expr).operand.kind === SyntaxKind.NumericLiteral; } + function isBigIntLiteralExpression(expr: Expression) { + return expr.kind === SyntaxKind.BigIntLiteral || + expr.kind === SyntaxKind.PrefixUnaryExpression && (expr).operator === SyntaxKind.MinusToken && + (expr).operand.kind === SyntaxKind.BigIntLiteral; + } + + function isSimpleLiteralEnumReference(expr: Expression) { + if ( + (isPropertyAccessExpression(expr) || (isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + isEntityNameExpression(expr.expression) + ) return !!(checkExpressionCached(expr).flags & TypeFlags.EnumLiteral); + } + function checkAmbientInitializer(node: VariableDeclaration | PropertyDeclaration | PropertySignature) { - if (node.initializer) { - const isInvalidInitializer = !isStringOrNumberLiteralExpression(node.initializer); + const {initializer} = node; + if (initializer) { + const isInvalidInitializer = !( + isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === SyntaxKind.TrueKeyword || initializer.kind === SyntaxKind.FalseKeyword || + isBigIntLiteralExpression(initializer) + ); const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node); if (isConstOrReadonly && !node.type) { if (isInvalidInitializer) { - return grammarErrorOnNode(node.initializer!, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + return grammarErrorOnNode(initializer, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); } } else { - return grammarErrorOnNode(node.initializer!, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorOnNode(initializer, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } if (!isConstOrReadonly || isInvalidInitializer) { - return grammarErrorOnNode(node.initializer!, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorOnNode(initializer, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } } @@ -29810,10 +30983,11 @@ namespace ts { } function checkGrammarConstructorTypeParameters(node: ConstructorDeclaration) { - const jsdocTypeParameters = isInJavaScriptFile(node) && getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - const { pos, end } = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node; - return grammarErrorAtPos(node, pos, end - pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + const jsdocTypeParameters = isInJSFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined; + const range = node.typeParameters || jsdocTypeParameters && firstOrUndefined(jsdocTypeParameters); + if (range) { + const pos = range.pos === range.end ? range.pos : skipTrivia(getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } @@ -29955,6 +31129,19 @@ namespace ts { return false; } + function checkGrammarBigIntLiteral(node: BigIntLiteral): boolean { + const literalType = isLiteralTypeNode(node.parent) || + isPrefixUnaryExpression(node.parent) && isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < ScriptTarget.ESNext) { + if (grammarErrorOnNode(node, Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { + return true; + } + } + } + return false; + } + function grammarErrorAfterFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { @@ -30040,8 +31227,4 @@ namespace ts { export const LibraryManagedAttributes = "LibraryManagedAttributes" as __String; // tslint:enable variable-name } - - function typeIsLiteralType(type: Type): type is LiteralType { - return !!(type.flags & TypeFlags.Literal); - } } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index e4c4edcb4db..43275605e23 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -44,7 +44,8 @@ namespace ts { ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.symbol", "lib.esnext.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], - ["esnext.intl", "lib.esnext.intl.d.ts"] + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] ]; /** @@ -62,7 +63,8 @@ namespace ts { /* @internal */ export const libMap = createMapFromEntries(libEntries); - const commonOptionsWithBuild: CommandLineOption[] = [ + /* @internal */ + export const commonOptionsWithBuild: CommandLineOption[] = [ { name: "help", shortName: "h", @@ -76,6 +78,14 @@ namespace ts { shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Watch_input_files, + }, { name: "preserveWatchOutput", type: "boolean", @@ -84,12 +94,42 @@ namespace ts { description: Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, }, { - name: "watch", - shortName: "w", + name: "listFiles", + type: "boolean", + category: Diagnostics.Advanced_Options, + description: Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: Diagnostics.Advanced_Options, + description: Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "pretty", type: "boolean", showInSimplifiedHelpView: true, category: Diagnostics.Command_line_Options, - description: Diagnostics.Watch_input_files, + description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + + { + name: "traceResolution", + type: "boolean", + category: Diagnostics.Advanced_Options, + description: Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "diagnostics", + type: "boolean", + category: Diagnostics.Advanced_Options, + description: Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: Diagnostics.Advanced_Options, + description: Diagnostics.Show_verbose_diagnostic_information }, ]; @@ -138,11 +178,11 @@ namespace ts { description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date }, { - name: "pretty", + name: "showConfig", type: "boolean", - showInSimplifiedHelpView: true, category: Diagnostics.Command_line_Options, - description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + isCommandLineOnly: true, + description: Diagnostics.Print_the_final_configuration_instead_of_building }, // Basic @@ -159,6 +199,8 @@ namespace ts { es2018: ScriptTarget.ES2018, esnext: ScriptTarget.ESNext, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: Diagnostics.VERSION, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, @@ -177,6 +219,7 @@ namespace ts { es2015: ModuleKind.ES2015, esnext: ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: Diagnostics.KIND, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, @@ -189,6 +232,7 @@ namespace ts { name: "lib", type: libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -196,6 +240,7 @@ namespace ts { { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, description: Diagnostics.Allow_javascript_files_to_be_compiled @@ -213,6 +258,7 @@ namespace ts { "react-native": JsxEmit.ReactNative, "react": JsxEmit.React }), + affectsSourceFile: true, paramType: Diagnostics.KIND, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, @@ -323,6 +369,7 @@ namespace ts { { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -331,6 +378,7 @@ namespace ts { { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -339,14 +387,24 @@ namespace ts { { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, description: Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Strict_Type_Checking_Options, + description: Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -355,6 +413,7 @@ namespace ts { { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -363,6 +422,7 @@ namespace ts { { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -397,6 +457,7 @@ namespace ts { { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: Diagnostics.Additional_Checks, @@ -410,6 +471,7 @@ namespace ts { node: ModuleResolutionKind.NodeJs, classic: ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: Diagnostics.STRATEGY, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -417,6 +479,7 @@ namespace ts { { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -426,6 +489,7 @@ namespace ts { // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -441,6 +505,7 @@ namespace ts { type: "string", isFilePath: true }, + affectsModuleResolution: true, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -452,6 +517,7 @@ namespace ts { type: "string", isFilePath: true }, + affectsModuleResolution: true, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -462,6 +528,7 @@ namespace ts { name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -537,42 +604,12 @@ namespace ts { category: Diagnostics.Advanced_Options, description: Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h }, - { - name: "diagnostics", - type: "boolean", - category: Diagnostics.Advanced_Options, - description: Diagnostics.Show_diagnostic_information - }, - { - name: "extendedDiagnostics", - type: "boolean", - category: Diagnostics.Advanced_Options, - description: Diagnostics.Show_verbose_diagnostic_information - }, - { - name: "traceResolution", - type: "boolean", - category: Diagnostics.Advanced_Options, - description: Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: Diagnostics.Advanced_Options, description: Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: Diagnostics.Advanced_Options, - description: Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: Diagnostics.Advanced_Options, - description: Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", @@ -632,12 +669,14 @@ namespace ts { { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: Diagnostics.Advanced_Options, description: Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: Diagnostics.Advanced_Options, description: Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -650,6 +689,7 @@ namespace ts { { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: Diagnostics.Advanced_Options, description: Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -695,6 +735,7 @@ namespace ts { { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: Diagnostics.Advanced_Options, description: Diagnostics.Do_not_report_errors_on_unused_labels @@ -702,6 +743,7 @@ namespace ts { { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: Diagnostics.Advanced_Options, description: Diagnostics.Do_not_report_errors_on_unreachable_code @@ -729,6 +771,7 @@ namespace ts { { name: "maxNodeModuleJsDepth", type: "number", + affectsModuleResolution: true, category: Diagnostics.Advanced_Options, description: Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -758,6 +801,18 @@ namespace ts { } ]; + /* @internal */ + export const semanticDiagnosticsOptionDeclarations: ReadonlyArray = + optionDeclarations.filter(option => !!option.affectsSemanticDiagnostics); + + /* @internal */ + export const moduleResolutionOptionDeclarations: ReadonlyArray = + optionDeclarations.filter(option => !!option.affectsModuleResolution); + + /* @internal */ + export const sourceFileAffectingCompilerOptions: ReadonlyArray = optionDeclarations.filter(option => + !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics); + /* @internal */ export const buildOpts: CommandLineOption[] = [ ...commonOptionsWithBuild, @@ -903,17 +958,27 @@ namespace ts { } } - export function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine { - const options: CompilerOptions = {}; + /* @internal */ + export interface OptionsBase { + [option: string]: CompilerOptionsValue | undefined; + } + + /** Tuple with error messages for 'unknown compiler option', 'option requires type' */ + type ParseCommandLineWorkerDiagnostics = [DiagnosticMessage, DiagnosticMessage]; + + function parseCommandLineWorker( + getOptionNameMap: () => OptionNameMap, + [unknownOptionDiagnostic, optionTypeMismatchDiagnostic]: ParseCommandLineWorkerDiagnostics, + commandLine: ReadonlyArray, + readFile?: (path: string) => string | undefined) { + const options = {} as OptionsBase; const fileNames: string[] = []; - const projectReferences: ProjectReference[] | undefined = undefined; const errors: Diagnostic[] = []; parseStrings(commandLine); return { options, fileNames, - projectReferences, errors }; @@ -926,7 +991,7 @@ namespace ts { parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === CharacterCodes.minus) { - const opt = getOptionFromName(s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1), /*allowShort*/ true); + const opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -934,7 +999,7 @@ namespace ts { 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)); + errors.push(createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { @@ -956,7 +1021,7 @@ namespace ts { i++; break; case "list": - const result = parseListTypeOption(opt, args[i], errors); + const result = parseListTypeOption(opt, args[i], errors); options[opt.name] = result || []; if (result) { i++; @@ -971,7 +1036,7 @@ namespace ts { } } else { - errors.push(createCompilerDiagnostic(Diagnostics.Unknown_compiler_option_0, s)); + errors.push(createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -1014,13 +1079,19 @@ namespace ts { } } + export function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine { + return parseCommandLineWorker(getOptionNameMap, [ + Diagnostics.Unknown_compiler_option_0, + Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } + /** @internal */ export function getOptionFromName(optionName: string, allowShort?: boolean): CommandLineOption | undefined { return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); } - /*@internal*/ - export function getOptionDeclarationFromName(getOptionNameMap: () => OptionNameMap, optionName: string, allowShort = false): CommandLineOption | undefined { + function getOptionDeclarationFromName(getOptionNameMap: () => OptionNameMap, optionName: string, allowShort = false): CommandLineOption | undefined { optionName = optionName.toLowerCase(); const { optionNameMap, shortOptionNames } = getOptionNameMap(); // Try to translate short option names to their full equivalents. @@ -1044,25 +1115,11 @@ namespace ts { export function parseBuildCommand(args: string[]): ParsedBuildCommand { let buildOptionNameMap: OptionNameMap | undefined; const returnBuildOptionNameMap = () => (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(buildOpts))); - - const buildOptions: BuildOptions = {}; - const projects: string[] = []; - let errors: Diagnostic[] | undefined; - for (const arg of args) { - if (arg.charCodeAt(0) === CharacterCodes.minus) { - const opt = getOptionDeclarationFromName(returnBuildOptionNameMap, arg.slice(arg.charCodeAt(1) === CharacterCodes.minus ? 2 : 1), /*allowShort*/ true); - if (opt) { - buildOptions[opt.name as keyof BuildOptions] = true; - } - else { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Unknown_build_option_0, arg)); - } - } - else { - // Not a flag, parse as filename - projects.push(arg); - } - } + const { options, fileNames: projects, errors } = parseCommandLineWorker(returnBuildOptionNameMap, [ + Diagnostics.Unknown_build_option_0, + Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args); + const buildOptions = options as BuildOptions; if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." @@ -1071,19 +1128,19 @@ namespace ts { // Nonsensical combinations if (buildOptions.clean && buildOptions.force) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); } if (buildOptions.clean && buildOptions.verbose) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); } if (buildOptions.clean && buildOptions.watch) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); } if (buildOptions.watch && buildOptions.dry) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); } - return { buildOptions, projects, errors: errors || emptyArray }; + return { buildOptions, projects, errors }; } function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string { @@ -1097,7 +1154,7 @@ namespace ts { } /* @internal */ - export function printHelp(optionsList: CommandLineOption[], syntaxPrefix = "") { + export function printHelp(optionsList: ReadonlyArray, syntaxPrefix = "") { const output: string[] = []; // We want to align our "syntax" and "examples" commands to a certain margin. @@ -1244,6 +1301,9 @@ namespace ts { const result = parseJsonText(configFileName, configFileText); const cwd = host.getCurrentDirectory(); + result.path = toPath(configFileName, cwd, createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), optionsToExtend, getNormalizedAbsolutePath(configFileName, cwd)); } @@ -1480,7 +1540,12 @@ namespace ts { elements: NodeArray, elementOption: CommandLineOption | undefined ): any[] | void { - return (returnValue ? elements.map : elements.forEach).call(elements, (element: Expression) => convertPropertyValueToJson(element, elementOption)); + if (!returnValue) { + return elements.forEach(element => convertPropertyValueToJson(element, elementOption)); + } + + // Filter out invalid values + return filter(elements.map(element => convertPropertyValueToJson(element, elementOption)), v => v !== undefined); } function convertPropertyValueToJson(valueExpression: Expression, option: CommandLineOption | undefined): any { @@ -1596,6 +1661,139 @@ namespace ts { return false; } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + export function convertToTSConfig(configParseResult: ParsedCommandLine, configFileName: string, host: { getCurrentDirectory(): string, useCaseSensitiveFileNames: boolean }): object { + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + const files = map( + filter( + configParseResult.fileNames, + (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? _ => true : matchesSpecs( + configFileName, + configParseResult.configFileSpecs.validatedIncludeSpecs, + configParseResult.configFileSpecs.validatedExcludeSpecs + ) + ), + f => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName) + ); + const optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + const config = { + compilerOptions: { + ...arrayFrom(optionMap.entries()).reduce((prev, cur) => ({ ...prev, [cur[0]]: cur[1] }), {}), + showConfig: undefined, + configFile: undefined, + configFilePath: undefined, + help: undefined, + init: undefined, + listFiles: undefined, + listEmittedFiles: undefined, + project: undefined, + build: undefined, + version: undefined, + }, + references: map(configParseResult.projectReferences, r => ({ ...r, path: r.originalPath, originalPath: undefined })), + files: length(files) ? files : undefined, + ...(configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), + compilerOnSave: !!configParseResult.compileOnSave ? true : undefined + }; + return config; + } + + function filterSameAsDefaultInclude(specs: ReadonlyArray | undefined) { + if (!length(specs)) return undefined; + if (length(specs) !== 1) return specs; + if (specs![0] === "**/*") return undefined; + return specs; + } + + function matchesSpecs(path: string, includeSpecs: ReadonlyArray | undefined, excludeSpecs: ReadonlyArray | undefined): (path: string) => boolean { + if (!includeSpecs) return _ => true; + const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, sys.useCaseSensitiveFileNames, sys.getCurrentDirectory()); + const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, sys.useCaseSensitiveFileNames); + const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return path => !(includeRe.test(path) && !excludeRe.test(path)); + } + return path => !includeRe.test(path); + } + if (excludeRe) { + return path => excludeRe.test(path); + } + return _ => true; + } + + function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map | undefined { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return (optionDefinition).type; + } + } + + function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: Map): string | undefined { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return forEachEntry(customTypeMap, (mapValue, key) => { + if (mapValue === value) { + return key; + } + }); + } + + function serializeCompilerOptions(options: CompilerOptions, pathOptions?: { configFilePath: string, useCaseSensitiveFileNames: boolean }): Map { + const result = createMap(); + const optionsNameMap = getOptionNameMap().optionNameMap; + const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + + for (const name in options) { + if (hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name)!.category === Diagnostics.Command_line_Options) { + continue; + } + const value = options[name]; + const optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, getRelativePathFromFile(pathOptions.configFilePath, getNormalizedAbsolutePath(value as string, getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName!)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, (value as ReadonlyArray).map(element => getNameOfCompilerOptionValue(element, customTypeMap)!)); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap)); + } + } + } + } + } + return result; + } + /** * Generate tsconfig configuration when running command line "--init" * @param options commandlineOptions to be generated into tsconfig.json @@ -1607,63 +1805,6 @@ namespace ts { const compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); - function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map | undefined { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption((optionDefinition).element); - } - else { - return (optionDefinition).type; - } - } - - function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: Map): string | undefined { - // There is a typeMap associated with this command-line option so use it to map value back to its name - return forEachEntry(customTypeMap, (mapValue, key) => { - if (mapValue === value) { - return key; - } - }); - } - - function serializeCompilerOptions(options: CompilerOptions): Map { - const result = createMap(); - const optionsNameMap = getOptionNameMap().optionNameMap; - - for (const name in options) { - if (hasProperty(options, name)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - if (optionsNameMap.has(name) && optionsNameMap.get(name)!.category === Diagnostics.Command_line_Options) { - continue; - } - const value = options[name]; - const optionDefinition = optionsNameMap.get(name.toLowerCase()); - if (optionDefinition) { - const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result.set(name, value); - } - else { - if (optionDefinition.type === "list") { - result.set(name, (value as ReadonlyArray).map(element => getNameOfCompilerOptionValue(element, customTypeMap)!)); // TODO: GH#18217 - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap)); - } - } - } - } - } - return result; - } - function getDefaultValueForOption(option: CommandLineOption) { switch (option.type) { case "number": @@ -1677,7 +1818,7 @@ namespace ts { case "object": return {}; default: - return (option as CommandLineOptionOfCustomType).type.keys().next().value; + return option.type.keys().next().value; } } @@ -1754,7 +1895,7 @@ namespace ts { } result.push(`}`); - return result.join(newLine); + return result.join(newLine) + newLine; } } @@ -1825,7 +1966,8 @@ namespace ts { const options = extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - const { fileNames, wildcardDirectories, spec, projectReferences } = getFileNames(); + let projectReferences: ProjectReference[] | undefined; + const { fileNames, wildcardDirectories, spec } = getFileNames(); return { options, fileNames, @@ -1843,8 +1985,22 @@ namespace ts { if (hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (isArray(raw.files)) { filesSpecs = >raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + const hasReferences = hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + const hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + const hasExtends = hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + const fileName = configFileName || "tsconfig.json"; + const diagnosticMessage = Diagnostics.The_files_list_in_config_file_0_is_empty; + const nodeValue = firstDefined(getTsConfigPropArray(sourceFile, "files"), property => property.initializer); + const error = nodeValue + ? createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -1885,19 +2041,18 @@ namespace ts { } const result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !hasProperty(raw, "files") && resolutionStack.length === 0 && !hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (isArray(raw.references)) { - const references: ProjectReference[] = []; for (const ref of raw.references) { if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -1905,7 +2060,6 @@ namespace ts { }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -1922,13 +2076,11 @@ namespace ts { } } - /*@internal*/ - export function isErrorNoInputFiles(error: Diagnostic) { + function isErrorNoInputFiles(error: Diagnostic) { return error.code === Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - /*@internal*/ - export function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }: ConfigFileSpecs, configFileName: string | undefined) { + function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }: ConfigFileSpecs, configFileName: string | undefined) { return createCompilerDiagnostic( Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", @@ -1936,6 +2088,27 @@ namespace ts { JSON.stringify(excludeSpecs || [])); } + function shouldReportNoInputFiles(result: ExpandResult, canJsonReportNoInutFiles: boolean, resolutionStack?: Path[]) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + + /*@internal*/ + export function canJsonReportNoInutFiles(raw: any) { + return !hasProperty(raw, "files") && !hasProperty(raw, "references"); + } + + /*@internal*/ + export function updateErrorForNoInputFiles(result: ExpandResult, configFileName: string, configFileSpecs: ConfigFileSpecs, configParseDiagnostics: Diagnostic[], canJsonReportNoInutFiles: boolean) { + const existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + filterMutate(configParseDiagnostics, error => !isErrorNoInputFiles(error)); + } + return existingErrors !== configParseDiagnostics.length; + } + interface ParsedTsconfig { raw: any; options?: CompilerOptions; @@ -1978,7 +2151,7 @@ namespace ts { if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - const extendedConfig = getExtendedConfig(sourceFile!, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); + const extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { const baseRaw = extendedConfig.raw; const raw = ownConfig.raw; @@ -2067,11 +2240,6 @@ namespace ts { createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0) ); return; - case "files": - if ((>value).length === 0) { - errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueNode, Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot(key: string, keyNode: PropertyName, _value: CompilerOptionsValue, _valueNode: Expression) { @@ -2081,6 +2249,7 @@ namespace ts { } }; const json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -2106,24 +2275,28 @@ namespace ts { errors: Push, createDiagnostic: (message: DiagnosticMessage, arg1?: string) => Diagnostic) { extendedConfig = normalizeSlashes(extendedConfig); - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(isRootedDiskPath(extendedConfig) || startsWith(extendedConfig, "./") || startsWith(extendedConfig, "../"))) { - errors.push(createDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return undefined; - } - let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath); - if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, Extension.Json)) { - extendedConfigPath = `${extendedConfigPath}.json`; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig)); - return undefined; + if (isRootedDiskPath(extendedConfig) || startsWith(extendedConfig, "./") || startsWith(extendedConfig, "../")) { + let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, Extension.Json)) { + extendedConfigPath = `${extendedConfigPath}.json`; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } } + return extendedConfigPath; } - return extendedConfigPath; + // If the path isn't a rooted or relative path, resolve like a module + const resolved = nodeModuleNameResolver(extendedConfig, combinePaths(basePath, "tsconfig.json"), { moduleResolution: ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; } function getExtendedConfig( - sourceFile: TsConfigSourceFile, + sourceFile: TsConfigSourceFile | undefined, extendedConfigPath: string, host: ParseConfigHost, basePath: string, @@ -2132,7 +2305,7 @@ namespace ts { ): ParsedTsconfig | undefined { const extendedResult = readJsonConfigFile(extendedConfigPath, path => host.readFile(path)); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push(...extendedResult.parseDiagnostics); @@ -2142,8 +2315,8 @@ namespace ts { const extendedDirname = getDirectoryPath(extendedConfigPath); const extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { - sourceFile.extendedSourceFiles!.push(...extendedResult.extendedSourceFiles!); + if (sourceFile && extendedResult.extendedSourceFiles) { + sourceFile.extendedSourceFiles!.push(...extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -2256,7 +2429,7 @@ namespace ts { function normalizeOptionValue(option: CommandLineOption, basePath: string, value: any): CompilerOptionsValue { if (isNullOrUndefined(value)) return undefined; if (option.type === "list") { - const listOption = option; + const listOption = option; if (listOption.element.isFilePath || !isString(listOption.element.type)) { return filter(map(value, v => normalizeOptionValue(listOption.element, basePath, v)), v => !!v); } @@ -2398,7 +2571,7 @@ namespace ts { // new entries in these paths. const wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - const spec: ConfigFileSpecs = { filesSpecs, referencesSpecs: undefined, includeSpecs, excludeSpecs, validatedIncludeSpecs, validatedExcludeSpecs, wildcardDirectories }; + const spec: ConfigFileSpecs = { filesSpecs, includeSpecs, excludeSpecs, validatedIncludeSpecs, validatedExcludeSpecs, wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } @@ -2427,11 +2600,16 @@ namespace ts { // via wildcard, and to handle extension priority. const wildcardFileMap = createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + const wildCardJsonFileMap = createMap(); const { filesSpecs, validatedIncludeSpecs, validatedExcludeSpecs, wildcardDirectories } = spec; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. const supportedExtensions = getSupportedExtensions(options, extraFileExtensions); + const supportedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. @@ -2442,8 +2620,25 @@ namespace ts { } } + let jsonOnlyIncludeRegexes: ReadonlyArray | undefined; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (const file of host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined)) { + for (const file of host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined)) { + if (fileExtensionIs(file, Extension.Json)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + const includes = validatedIncludeSpecs.filter(s => endsWith(s, Extension.Json)); + const includeFilePatterns = map(getRegularExpressionsForWildcards(includes, basePath, "files"), pattern => `^${pattern}$`); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(pattern => getRegexFromPattern(pattern, host.useCaseSensitiveFileNames)) : emptyArray; + } + const includeIndex = findIndex(jsonOnlyIncludeRegexes, re => re.test(file)); + if (includeIndex !== -1) { + const key = keyMapper(file); + if (!literalFileMap.has(key) && !wildCardJsonFileMap.has(key)) { + wildCardJsonFileMap.set(key, file); + } + } + continue; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -2469,16 +2664,9 @@ namespace ts { const literalFiles = arrayFrom(literalFileMap.values()); const wildcardFiles = arrayFrom(wildcardFileMap.values()); - const projectReferences = spec.referencesSpecs && spec.referencesSpecs.map((r): ProjectReference => { - return { - ...r, - path: getNormalizedAbsolutePath(r.path, basePath) - }; - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences, + fileNames: literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories, spec }; @@ -2620,7 +2808,7 @@ namespace ts { } /** - * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. * Also converts enum values back to strings. */ /* @internal */ @@ -2648,7 +2836,7 @@ namespace ts { case "boolean": return typeof value === "boolean" ? value : ""; case "list": - const elementType = (option as CommandLineOptionOfListType).element; + const elementType = option.element; return isArray(value) ? value.map(v => getOptionValueWithEmptyStrings(v, elementType)) : ""; default: return forEachEntry(option.type, (optionEnumValue, optionStringValue) => { diff --git a/src/compiler/comments.ts b/src/compiler/comments.ts deleted file mode 100644 index 7dfda66c965..00000000000 --- a/src/compiler/comments.ts +++ /dev/null @@ -1,431 +0,0 @@ -/* @internal */ -namespace ts { - export interface CommentWriter { - reset(): void; - setSourceFile(sourceFile: SourceFile): void; - setWriter(writer: EmitTextWriter | undefined): void; - emitNodeWithComments(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node) => void): void; - emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void; - emitTrailingCommentsOfPosition(pos: number, prefixSpace?: boolean): void; - emitLeadingCommentsOfPosition(pos: number): void; - } - - export function createCommentWriter(printerOptions: PrinterOptions, emitPos: ((pos: number) => void) | undefined): CommentWriter { - const extendedDiagnostics = printerOptions.extendedDiagnostics; - const newLine = getNewLineCharacter(printerOptions); - let writer: EmitTextWriter; - let containerPos = -1; - let containerEnd = -1; - let declarationListContainerEnd = -1; - let currentSourceFile: SourceFile; - let currentText: string; - let currentLineMap: ReadonlyArray; - let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number}[] | undefined; - let hasWrittenComment = false; - let disabled: boolean = !!printerOptions.removeComments; - - return { - reset, - setWriter, - setSourceFile, - emitNodeWithComments, - emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition, - emitLeadingCommentsOfPosition, - }; - - function emitNodeWithComments(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) { - if (disabled) { - emitCallback(hint, node); - return; - } - - if (node) { - hasWrittenComment = false; - - const emitNode = node.emitNode; - const emitFlags = emitNode && emitNode.flags || 0; - const { pos, end } = emitNode && emitNode.commentRange || node; - if ((pos < 0 && end < 0) || (pos === end)) { - // Both pos and end are synthesized, so just emit the node without comments. - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - } - else { - if (extendedDiagnostics) { - performance.mark("preEmitNodeWithComment"); - } - - const isEmittedNode = node.kind !== SyntaxKind.NotEmittedStatement; - // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. - // It is expensive to walk entire tree just to set one kind of node to have no comments. - const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0 || node.kind === SyntaxKind.JsxText; - const skipTrailingComments = end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0 || node.kind === SyntaxKind.JsxText; - - // Emit leading comments if the position is not synthesized and the node - // has not opted out from emitting leading comments. - if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); - } - - // Save current container state on the stack. - const savedContainerPos = containerPos; - const savedContainerEnd = containerEnd; - const savedDeclarationListContainerEnd = declarationListContainerEnd; - - if (!skipLeadingComments || (pos >= 0 && (emitFlags & EmitFlags.NoLeadingComments) !== 0)) { - // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. - containerPos = pos; - } - - if (!skipTrailingComments || (end >= 0 && (emitFlags & EmitFlags.NoTrailingComments) !== 0)) { - // As above. - containerEnd = end; - - // To avoid invalid comment emit in a down-level binding pattern, we - // keep track of the last declaration list container's end - if (node.kind === SyntaxKind.VariableDeclarationList) { - declarationListContainerEnd = end; - } - } - - if (extendedDiagnostics) { - performance.measure("commentTime", "preEmitNodeWithComment"); - } - - emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); - - if (extendedDiagnostics) { - performance.mark("postEmitNodeWithComment"); - } - - // Restore previous container state. - containerPos = savedContainerPos; - containerEnd = savedContainerEnd; - declarationListContainerEnd = savedDeclarationListContainerEnd; - - // Emit trailing comments if the position is not synthesized and the node - // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { - emitTrailingComments(end); - } - - if (extendedDiagnostics) { - performance.measure("commentTime", "postEmitNodeWithComment"); - } - } - } - } - - function emitNodeWithSynthesizedComments(hint: EmitHint, node: Node, emitNode: EmitNode | undefined, emitFlags: EmitFlags, emitCallback: (hint: EmitHint, node: Node) => void) { - const leadingComments = emitNode && emitNode.leadingComments; - if (some(leadingComments)) { - if (extendedDiagnostics) { - performance.mark("preEmitNodeWithSynthesizedComments"); - } - - forEach(leadingComments, emitLeadingSynthesizedComment); - - if (extendedDiagnostics) { - performance.measure("commentTime", "preEmitNodeWithSynthesizedComments"); - } - } - - emitNodeWithNestedComments(hint, node, emitFlags, emitCallback); - - const trailingComments = emitNode && emitNode.trailingComments; - if (some(trailingComments)) { - if (extendedDiagnostics) { - performance.mark("postEmitNodeWithSynthesizedComments"); - } - - forEach(trailingComments, emitTrailingSynthesizedComment); - - if (extendedDiagnostics) { - performance.measure("commentTime", "postEmitNodeWithSynthesizedComments"); - } - } - } - - function emitLeadingSynthesizedComment(comment: SynthesizedComment) { - if (comment.kind === SyntaxKind.SingleLineCommentTrivia) { - writer.writeLine(); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine || comment.kind === SyntaxKind.SingleLineCommentTrivia) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - - function emitTrailingSynthesizedComment(comment: SynthesizedComment) { - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - } - - function writeSynthesizedComment(comment: SynthesizedComment) { - const text = formatSynthesizedComment(comment); - const lineMap = comment.kind === SyntaxKind.MultiLineCommentTrivia ? computeLineStarts(text) : undefined; - writeCommentRange(text, lineMap!, writer, 0, text.length, newLine); - } - - function formatSynthesizedComment(comment: SynthesizedComment) { - return comment.kind === SyntaxKind.MultiLineCommentTrivia - ? `/*${comment.text}*/` - : `//${comment.text}`; - } - - function emitNodeWithNestedComments(hint: EmitHint, node: Node, emitFlags: EmitFlags, emitCallback: (hint: EmitHint, node: Node) => void) { - if (emitFlags & EmitFlags.NoNestedComments) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - } - - function emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void) { - if (extendedDiagnostics) { - performance.mark("preEmitBodyWithDetachedComments"); - } - - const { pos, end } = detachedRange; - const emitFlags = getEmitFlags(node); - const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0; - const skipTrailingComments = disabled || end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0; - - if (!skipLeadingComments) { - emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); - } - - if (extendedDiagnostics) { - performance.measure("commentTime", "preEmitBodyWithDetachedComments"); - } - - if (emitFlags & EmitFlags.NoNestedComments && !disabled) { - disabled = true; - emitCallback(node); - disabled = false; - } - else { - emitCallback(node); - } - - if (extendedDiagnostics) { - performance.mark("beginEmitBodyWithDetachedCommetns"); - } - - if (!skipTrailingComments) { - emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); - if (hasWrittenComment && !writer.isAtStartOfLine()) { - writer.writeLine(); - } - } - - if (extendedDiagnostics) { - performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); - } - } - - function emitLeadingComments(pos: number, isEmittedNode: boolean) { - hasWrittenComment = false; - - if (isEmittedNode) { - forEachLeadingCommentToEmit(pos, emitLeadingComment); - } - else if (pos === 0) { - // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, - // unless it is a triple slash comment at the top of the file. - // For Example: - // /// - // declare var x; - // /// - // interface F {} - // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted - forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); - } - } - - function emitTripleSlashLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) { - if (isTripleSlashComment(commentPos, commentEnd)) { - emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); - } - } - - function shouldWriteComment(text: string, pos: number) { - if (printerOptions.onlyPrintJsDocStyle) { - return (isJSDocLikeText(text, pos) || isPinnedComment(text, pos)); - } - return true; - } - - function emitLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) { - if (!shouldWriteComment(currentText, commentPos)) return; - if (!hasWrittenComment) { - emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); - hasWrittenComment = true; - } - - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - if (emitPos) emitPos(commentPos); - writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) emitPos(commentEnd); - - if (hasTrailingNewLine) { - writer.writeLine(); - } - else if (kind === SyntaxKind.MultiLineCommentTrivia) { - writer.write(" "); - } - } - - function emitLeadingCommentsOfPosition(pos: number) { - if (disabled || pos === -1) { - return; - } - - emitLeadingComments(pos, /*isEmittedNode*/ true); - } - - function emitTrailingComments(pos: number) { - forEachTrailingCommentToEmit(pos, emitTrailingComment); - } - - function emitTrailingComment(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean) { - if (!shouldWriteComment(currentText, commentPos)) return; - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ - if (!writer.isAtStartOfLine()) { - writer.write(" "); - } - - if (emitPos) emitPos(commentPos); - writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) emitPos(commentEnd); - - if (hasTrailingNewLine) { - writer.writeLine(); - } - } - - function emitTrailingCommentsOfPosition(pos: number, prefixSpace?: boolean) { - if (disabled) { - return; - } - - if (extendedDiagnostics) { - performance.mark("beforeEmitTrailingCommentsOfPosition"); - } - - forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); - - if (extendedDiagnostics) { - performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); - } - } - - function emitTrailingCommentOfPosition(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean) { - // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space - - if (emitPos) emitPos(commentPos); - writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) emitPos(commentEnd); - - if (hasTrailingNewLine) { - writer.writeLine(); - } - else { - writer.write(" "); - } - } - - function forEachLeadingCommentToEmit(pos: number, cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) { - // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments - if (containerPos === -1 || pos !== containerPos) { - if (hasDetachedComments(pos)) { - forEachLeadingCommentWithoutDetachedComments(cb); - } - else { - forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - } - } - - function forEachTrailingCommentToEmit(end: number, cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) => void) { - // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments - if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { - forEachTrailingCommentRange(currentText, end, cb); - } - } - - function reset() { - currentSourceFile = undefined!; - currentText = undefined!; - currentLineMap = undefined!; - detachedCommentsInfo = undefined; - } - - function setWriter(output: EmitTextWriter): void { - writer = output; - } - - function setSourceFile(sourceFile: SourceFile) { - currentSourceFile = sourceFile; - currentText = currentSourceFile.text; - currentLineMap = getLineStarts(currentSourceFile); - detachedCommentsInfo = undefined; - } - - function hasDetachedComments(pos: number) { - return detachedCommentsInfo !== undefined && last(detachedCommentsInfo).nodePos === pos; - } - - function forEachLeadingCommentWithoutDetachedComments(cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) { - // get the leading comments from detachedPos - const pos = last(detachedCommentsInfo!).detachedCommentEndPos; - if (detachedCommentsInfo!.length - 1) { - detachedCommentsInfo!.pop(); - } - else { - detachedCommentsInfo = undefined; - } - - forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); - } - - function emitDetachedCommentsAndUpdateCommentsInfo(range: TextRange) { - const currentDetachedCommentInfo = emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - - function writeComment(text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) { - if (!shouldWriteComment(currentText, commentPos)) return; - if (emitPos) emitPos(commentPos); - writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); - if (emitPos) emitPos(commentEnd); - } - - /** - * Determine if the given comment is a triple-slash - * - * @return true if the comment is a triple-slash comment else false - */ - function isTripleSlashComment(commentPos: number, commentEnd: number) { - return isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); - } - } -} diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 7840c66e601..d4f5fe9664a 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1,7 +1,7 @@ namespace ts { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - export const versionMajorMinor = "3.1"; + export const versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ export const version = `${versionMajorMinor}.0-dev`; } @@ -16,6 +16,10 @@ namespace ts { [index: string]: T; } + export interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } + export interface SortedArray extends Array { " __sortedArrayBrand": any; } @@ -65,6 +69,7 @@ namespace ts { /* @internal */ namespace ts { + export const emptyArray: never[] = [] as never[]; /** Create a MapLike with good performance. */ function createDictionaryObject(): MapLike { @@ -107,13 +112,13 @@ namespace ts { } // The global Map object. This may not be available, so we must test for it. - declare const Map: { new (): Map } | undefined; + declare const Map: (new () => Map) | undefined; // Internet Explorer's Map doesn't support iteration, so don't use it. // tslint:disable-next-line no-in-operator variable-name export const MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap(): { new (): Map } { + function shimMap(): new () => Map { class MapIterator { private data: MapLike; @@ -510,12 +515,27 @@ namespace ts { * @param array The array to map. * @param mapfn The callback used to map the result into one or more values. */ - export function flatMap(array: ReadonlyArray, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[]; - export function flatMap(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[] | undefined; - export function flatMap(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[] | undefined { + export function flatMap(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): ReadonlyArray { let result: U[] | undefined; if (array) { - result = []; + for (let i = 0; i < array.length; i++) { + const v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || emptyArray; + } + + export function flatMapToMutable(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[] { + const result: U[] = []; + if (array) { for (let i = 0; i < array.length; i++) { const v = mapfn(array[i], i); if (v) { @@ -799,8 +819,8 @@ namespace ts { /** * Deduplicates an array that has already been sorted. */ - function deduplicateSorted(array: ReadonlyArray, comparer: EqualityComparer | Comparer): T[] { - if (array.length === 0) return []; + function deduplicateSorted(array: SortedReadonlyArray, comparer: EqualityComparer | Comparer): SortedReadonlyArray { + if (array.length === 0) return emptyArray as any as SortedReadonlyArray; let last = array[0]; const deduplicated: T[] = [last]; @@ -822,7 +842,7 @@ namespace ts { deduplicated.push(last = next); } - return deduplicated; + return deduplicated as any as SortedReadonlyArray; } export function insertSorted(array: SortedArray, insert: T, compare: Comparer): void { @@ -837,11 +857,13 @@ namespace ts { } } - export function sortAndDeduplicate(array: ReadonlyArray, comparer: Comparer, equalityComparer?: EqualityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + export function sortAndDeduplicate(array: ReadonlyArray): SortedReadonlyArray; + export function sortAndDeduplicate(array: ReadonlyArray, comparer: Comparer, equalityComparer?: EqualityComparer): SortedReadonlyArray; + export function sortAndDeduplicate(array: ReadonlyArray, comparer?: Comparer, equalityComparer?: EqualityComparer): SortedReadonlyArray { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive as any as Comparer); } - export function arrayIsEqualTo(array1: ReadonlyArray | undefined, array2: ReadonlyArray | undefined, equalityComparer: (a: T, b: T) => boolean = equateValues): boolean { + export function arrayIsEqualTo(array1: ReadonlyArray | undefined, array2: ReadonlyArray | undefined, equalityComparer: (a: T, b: T, index: number) => boolean = equateValues): boolean { if (!array1 || !array2) { return array1 === array2; } @@ -851,7 +873,7 @@ namespace ts { } for (let i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1019,8 +1041,8 @@ namespace ts { /** * Returns a new sorted array. */ - export function sort(array: ReadonlyArray, comparer: Comparer): T[] { - return array.slice().sort(comparer); + export function sort(array: ReadonlyArray, comparer?: Comparer): SortedReadonlyArray { + return (array.length === 0 ? array : array.slice().sort(comparer)) as SortedReadonlyArray; } export function arrayIterator(array: ReadonlyArray): Iterator { @@ -1039,10 +1061,10 @@ namespace ts { /** * Stable sort of an array. Elements equal to each other maintain their relative position in the array. */ - export function stableSort(array: ReadonlyArray, comparer: Comparer) { + export function stableSort(array: ReadonlyArray, comparer: Comparer): SortedReadonlyArray { const indices = array.map((_, i) => i); stableSortIndices(array, indices, comparer); - return indices.map(i => array[i]); + return indices.map(i => array[i]) as SortedArray as SortedReadonlyArray; } export function rangeEquals(array1: ReadonlyArray, array2: ReadonlyArray, pos: number, end: number) { @@ -1134,13 +1156,26 @@ namespace ts { * @param offset An offset into `array` at which to start the search. */ export function binarySearch(array: ReadonlyArray, value: T, keySelector: (v: T) => U, keyComparer: Comparer, offset?: number): number { - if (!array || array.length === 0) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); + } + + /** + * Performs a binary search, finding the index at which an object with `key` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `key`. + * @param array A sorted array whose first element must be no larger than number + * @param key The key to be searched for in the array. + * @param keySelector A callback used to select the search key from each element of `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + export function binarySearchKey(array: ReadonlyArray, key: U, keySelector: (v: T) => U, keyComparer: Comparer, offset?: number): number { + if (!some(array)) { return -1; } let low = offset || 0; let high = array.length - 1; - const key = keySelector(value); while (low <= high) { const middle = low + ((high - low) >> 1); const midKey = keySelector(array[middle]); @@ -1233,9 +1268,9 @@ namespace ts { } /** Shims `Array.from`. */ - export function arrayFrom(iterator: Iterator, map: (t: T) => U): U[]; - export function arrayFrom(iterator: Iterator): T[]; - export function arrayFrom(iterator: Iterator, map?: (t: any) => any): any[] { + export function arrayFrom(iterator: Iterator | IterableIterator, map: (t: T) => U): U[]; + export function arrayFrom(iterator: Iterator | IterableIterator): T[]; + export function arrayFrom(iterator: Iterator | IterableIterator, map?: (t: any) => any): any[] { const result: any[] = []; for (let { value, done } = iterator.next(); !done; { value, done } = iterator.next()) { result.push(map ? map(value) : value); @@ -1352,6 +1387,18 @@ namespace ts { return result; } + export function copyProperties(first: T1, second: T2) { + for (const id in second) { + if (hasOwnProperty.call(second, id)) { + (first as any)[id] = second[id]; + } + } + } + + export function maybeBind(obj: T, fn: ((this: T, ...args: A) => R) | undefined): ((...args: A) => R) | undefined { + return fn ? fn.bind(obj) : undefined; + } + export interface MultiMap extends Map { /** * Adds the value to an array of values associated with the key, and returns the array. @@ -1408,9 +1455,12 @@ namespace ts { /** * Tests whether a value is string */ - export function isString(text: any): text is string { + export function isString(text: unknown): text is string { return typeof text === "string"; } + export function isNumber(x: unknown): x is number { + return typeof x === "number"; + } export function tryCast(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut | undefined; export function tryCast(value: T, test: (value: T) => boolean): T | undefined; @@ -1533,6 +1583,7 @@ namespace ts { * Every function should be assignable to this, but this should not be assignable to every function. */ export type AnyFunction = (...args: never[]) => void; + export type AnyConstructor = new (...args: unknown[]) => unknown; export namespace Debug { export let currentAssertionLevel = AssertionLevel.None; @@ -1597,8 +1648,9 @@ namespace ts { return value; } - export function assertNever(member: never, message?: string, stackCrawlMark?: AnyFunction): never { - return fail(message || `Illegal value: ${member}`, stackCrawlMark || assertNever); + export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never { + const detail = "kind" in member && "pos" in member ? "SyntaxKind: " + showSyntaxKind(member as Node) : JSON.stringify(member); + return fail(`${message} ${detail}`, stackCrawlMark || assertNever); } export function getFunctionName(func: AnyFunction) { @@ -2025,7 +2077,6 @@ namespace ts { } /** Represents a "prefix*suffix" pattern. */ - /* @internal */ export interface Pattern { prefix: string; suffix: string; @@ -2124,4 +2175,12 @@ namespace ts { deleted(oldItems[oldIndex++]); } } + + export function fill(length: number, cb: (index: number) => T): T[] { + const result = Array(length); + for (let i = 0; i < length; i++) { + result[i] = cb(i); + } + return result; + } } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 4057a5528aa..dab5aeed461 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -835,7 +835,7 @@ "category": "Error", "code": 1253 }, - "A 'const' initializer in an ambient context must be a string or numeric literal.": { + "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.": { "category": "Error", "code": 1254 }, @@ -1007,6 +1007,22 @@ "category": "Error", "code": 1349 }, + "Print the final configuration instead of building.": { + "category": "Message", + "code": 1350 + }, + "An identifier or keyword cannot immediately follow a numeric literal.": { + "category": "Error", + "code": 1351 + }, + "A bigint literal cannot use exponential notation.": { + "category": "Error", + "code": 1352 + }, + "A bigint literal must be an integer.": { + "category": "Error", + "code": 1353 + }, "Duplicate identifier '{0}'.": { "category": "Error", @@ -1056,7 +1072,7 @@ "category": "Error", "code": 2311 }, - "An interface may only extend a class or another interface.": { + "An interface can only extend an object type or intersection of object types with statically known members.": { "category": "Error", "code": 2312 }, @@ -1232,7 +1248,7 @@ "category": "Error", "code": 2355 }, - "An arithmetic operand must be of type 'any', 'number' or an enum type.": { + "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.": { "category": "Error", "code": 2356 }, @@ -1256,11 +1272,11 @@ "category": "Error", "code": 2361 }, - "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.": { "category": "Error", "code": 2362 }, - "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.": { "category": "Error", "code": 2363 }, @@ -1484,7 +1500,7 @@ "category": "Error", "code": 2420 }, - "A class may only implement another class or interface.": { + "A class can only implement an object type or intersection of object types with statically known members.": { "category": "Error", "code": 2422 }, @@ -1628,14 +1644,6 @@ "category": "Error", "code": 2458 }, - "Type '{0}' has no property '{1}' and no string index signature.": { - "category": "Error", - "code": 2459 - }, - "Type '{0}' has no property '{1}'.": { - "category": "Error", - "code": 2460 - }, "Type '{0}' is not an array type.": { "category": "Error", "code": 2461 @@ -1688,7 +1696,7 @@ "category": "Error", "code": 2473 }, - "In 'const' enum declarations member initializer must be constant expression.": { + "const enum member initializers can only contain literal values and other computed enum values.": { "category": "Error", "code": 2474 }, @@ -1752,7 +1760,7 @@ "category": "Error", "code": 2492 }, - "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'.": { + "Tuple type '{0}' of length '{1}' has no element at index '{2}'.": { "category": "Error", "code": 2493 }, @@ -1768,7 +1776,7 @@ "category": "Error", "code": 2496 }, - "Module '{0}' resolves to a non-module entity and cannot be imported using this construct.": { + "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export.": { "category": "Error", "code": 2497 }, @@ -1816,7 +1824,7 @@ "category": "Error", "code": 2508 }, - "Base constructor return type '{0}' is not a class or interface type.": { + "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members.": { "category": "Error", "code": 2509 }, @@ -1940,7 +1948,7 @@ "category": "Error", "code": 2539 }, - "Cannot assign to '{0}' because it is a constant or a read-only property.": { + "Cannot assign to '{0}' because it is a read-only property.": { "category": "Error", "code": 2540 }, @@ -2048,10 +2056,6 @@ "category": "Error", "code": 2567 }, - "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators.": { - "category": "Error", - "code": 2568 - }, "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.": { "category": "Error", "code": 2569 @@ -2088,6 +2092,42 @@ "category": "Error", "code": 2577 }, + "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.": { + "category": "Error", + "code": 2580 + }, + "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig.": { + "category": "Error", + "code": 2581 + }, + "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.": { + "category": "Error", + "code": 2582 + }, + "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.": { + "category": "Error", + "code": 2583 + }, + "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.": { + "category": "Error", + "code": 2584 + }, + "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.": { + "category": "Error", + "code": 2585 + }, + "Enum type '{0}' circularly references itself.": { + "category": "Error", + "code": 2586 + }, + "JSDoc type '{0}' circularly references itself.": { + "category": "Error", + "code": 2587 + }, + "Cannot assign to '{0}' because it is a constant.": { + "category": "Error", + "code": 2588 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 @@ -2453,9 +2493,61 @@ "category": "Error", "code": 2732 }, - "Index '{0}' is out-of-bounds in tuple of length {1}.": { + "It is highly likely that you are missing a semicolon.": { "category": "Error", - "code": 2733 + "code": 2734 + }, + "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?": { + "category": "Error", + "code": 2735 + }, + "Operator '{0}' cannot be applied to type '{1}'.": { + "category": "Error", + "code": 2736 + }, + "BigInt literals are not available when targeting lower than ESNext.": { + "category": "Error", + "code": 2737 + }, + "An outer value of 'this' is shadowed by this container.": { + "category": "Message", + "code": 2738 + }, + "Type '{0}' is missing the following properties from type '{1}': {2}": { + "category": "Error", + "code": 2739 + }, + "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more.": { + "category": "Error", + "code": 2740 + }, + "Property '{0}' is missing in type '{1}' but required in type '{2}'.": { + "category": "Error", + "code": 2741 + }, + "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary.": { + "category": "Error", + "code": 2742 + }, + "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments.": { + "category": "Error", + "code": 2743 + }, + "Type parameter defaults can only reference previously declared type parameters.": { + "category": "Error", + "code": 2744 + }, + "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided.": { + "category": "Error", + "code": 2745 + }, + "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided.": { + "category": "Error", + "code": 2746 + }, + "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'.": { + "category": "Error", + "code": 2747 }, "Import declaration '{0}' is using private name '{1}'.": { @@ -2920,7 +3012,10 @@ "category": "Error", "code": 5072 }, - + "Build option '{0}' requires a value of type {1}.": { + "category": "Error", + "code": 5073 + }, "Generates a sourcemap for each corresponding '.d.ts' file.": { "category": "Message", @@ -3294,7 +3389,7 @@ "category": "Message", "code": 6104 }, - "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'.": { + "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'.": { "category": "Message", "code": 6105 }, @@ -3692,6 +3787,54 @@ "category": "Error", "code": 6205 }, + "'package.json' has a 'typesVersions' field with version-specific path mappings.": { + "category": "Message", + "code": 6206 + }, + "'package.json' does not have a 'typesVersions' entry that matches version '{0}'.": { + "category": "Message", + "code": 6207 + }, + "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'.": { + "category": "Message", + "code": 6208 + }, + "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range.": { + "category": "Message", + "code": 6209 + }, + "An argument for '{0}' was not provided.": { + "category": "Message", + "code": 6210 + }, + "An argument matching this binding pattern was not provided.": { + "category": "Message", + "code": 6211 + }, + "Did you mean to call this expression?": { + "category": "Message", + "code": 6212 + }, + "Did you mean to use 'new' with this expression?": { + "category": "Message", + "code": 6213 + }, + "Enable strict 'bind', 'call', and 'apply' methods on functions.": { + "category": "Message", + "code": 6214 + }, + "Using compiler options of project reference redirect '{0}'.": { + "category": "Message", + "code": 6215 + }, + "Found 1 error.": { + "category": "Message", + "code": 6216 + }, + "Found {0} errors.": { + "category": "Message", + "code": 6217 + }, "Projects to reference": { "category": "Message", @@ -3814,8 +3957,8 @@ "category": "Error", "code": 6370 }, - "Skipping clean because not all projects could be located": { - "category": "Error", + "Updating unchanged output timestamps of project '{0}'...": { + "category": "Message", "code": 6371 }, @@ -3827,6 +3970,10 @@ "category": "Message", "code": 6501 }, + "The expected type comes from the return type of this signature.": { + "category": "Message", + "code": 6502 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", @@ -3856,6 +4003,10 @@ "category": "Error", "code": 7013 }, + "Function type, which lacks return-type annotation, implicitly has an '{0}' return type.": { + "category": "Error", + "code": 7014 + }, "Element implicitly has an 'any' type because index expression is not of type 'number'.": { "category": "Error", "code": 7015 @@ -3966,6 +4117,43 @@ "category": "Error", "code": 7042 }, + "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7043 + }, + "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7044 + }, + "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7045 + }, + "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7046 + }, + "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7047 + }, + "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage.": { + "category": "Suggestion", + "code": 7048 + }, + "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage.": { + "category": "Suggestion", + "code": 7049 + }, + "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7050 + }, + "Parameter has a name but no type. Did you mean '{0}: {1}'?": { + "category": "Error", + "code": 7051 + }, + "You cannot rename this element.": { "category": "Error", "code": 8000 @@ -4086,6 +4274,14 @@ "category": "Error", "code": 8030 }, + "You cannot rename a module via a global import.": { + "category": "Error", + "code": 8031 + }, + "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'.": { + "category": "Error", + "code": 8032 + }, "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.": { "category": "Error", "code": 9002 @@ -4344,6 +4540,10 @@ "category": "Message", "code": 90033 }, + "Add parameter name": { + "category": "Message", + "code": 90034 + }, "Convert function to an ES2015 class": { "category": "Message", "code": 95001 @@ -4584,7 +4784,6 @@ "category": "Message", "code": 95062 }, - "Add missing enum member '{0}'": { "category": "Message", "code": 95063 @@ -4593,12 +4792,44 @@ "category": "Message", "code": 95064 }, - "Convert to async function":{ + "Convert to async function": { "category": "Message", - "code": 95065 + "code": 95065 }, "Convert all to async functions": { - "category": "Message", - "code": 95066 + "category": "Message", + "code": 95066 + }, + "Generate types for '{0}'": { + "category": "Message", + "code": 95067 + }, + "Generate types for all packages without types": { + "category": "Message", + "code": 95068 + }, + "Add 'unknown' conversion for non-overlapping types": { + "category": "Message", + "code": 95069 + }, + "Add 'unknown' to all conversions of non-overlapping types": { + "category": "Message", + "code": 95070 + }, + "Add missing 'new' operator to call": { + "category": "Message", + "code": 95071 + }, + "Add missing 'new' operator to all calls": { + "category": "Message", + "code": 95072 + }, + "Add names to all parameters without names": { + "category": "Message", + "code": 95073 + }, + "Enable the 'experimentalDecorators' option in your configuration file": { + "category": "Message", + "code": 95074 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 8cb1d4f34a9..395f6448890 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1,6 +1,7 @@ namespace ts { const infoExtension = ".tsbundleinfo"; const brackets = createBracketsMap(); + const syntheticParent: TextRange = { pos: -1, end: -1 }; /*@internal*/ /** @@ -41,20 +42,25 @@ namespace ts { export function getOutputPathsFor(sourceFile: SourceFile | Bundle, host: EmitHost, forceDtsPaths: boolean): EmitFileNames { const options = host.getCompilerOptions(); if (sourceFile.kind === SyntaxKind.Bundle) { - const jsFilePath = options.outFile || options.out!; - const sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - const declarationFilePath = (forceDtsPaths || getEmitDeclarations(options)) ? removeFileExtension(jsFilePath) + Extension.Dts : undefined; - const declarationMapPath = getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + const outPath = options.outFile || options.out!; + const jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + const sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + const declarationFilePath = (forceDtsPaths || getEmitDeclarations(options)) ? removeFileExtension(outPath) + Extension.Dts : undefined; + const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; const bundleInfoPath = options.references && jsFilePath ? (removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath }; } else { - const jsFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - const sourceMapFilePath = isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + const isJsonEmittedToSameLocation = isJsonSourceFile(sourceFile) && + comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === Comparison.EqualTo; + const jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + const sourceMapFilePath = !jsFilePath || isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - const isJs = isSourceFileJavaScript(sourceFile); + const isJs = isSourceFileJS(sourceFile); const declarationFilePath = ((forceDtsPaths || getEmitDeclarations(options)) && !isJs) ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - const declarationMapPath = getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath: undefined }; } } @@ -80,7 +86,7 @@ namespace ts { } if (options.jsx === JsxEmit.Preserve) { - if (isSourceFileJavaScript(sourceFile)) { + if (isSourceFileJS(sourceFile)) { if (fileExtensionIs(sourceFile.fileName, Extension.Jsx)) { return Extension.Jsx; } @@ -97,28 +103,20 @@ namespace ts { // 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, emitOnlyDtsFiles?: boolean, transformers?: TransformerFactory[], declarationTransformers?: TransformerFactory[]): EmitResult { const compilerOptions = host.getCompilerOptions(); - const sourceMapDataList: SourceMapData[] | undefined = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; + const sourceMapDataList: SourceMapEmitResult[] | undefined = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; const emittedFilesList: string[] | undefined = compilerOptions.listEmittedFiles ? [] : undefined; const emitterDiagnostics = createDiagnosticCollection(); - const newLine = host.getNewLine(); + const newLine = getNewLineCharacter(compilerOptions, () => host.getNewLine()); const writer = createTextWriter(newLine); - const sourceMap = createSourceMapWriter(host, writer); - const declarationSourceMap = createSourceMapWriter(host, writer, { - sourceMap: compilerOptions.declarationMap, - sourceRoot: compilerOptions.sourceRoot, - mapRoot: compilerOptions.mapRoot, - extendedDiagnostics: compilerOptions.extendedDiagnostics, - // Explicitly do not passthru either `inline` option - }); - + const { enter, exit } = performance.createTimer("printTime", "beforePrint", "afterPrint"); let bundleInfo: BundleInfo = createDefaultBundleInfo(); let emitSkipped = false; let exportedModulesFromDeclarationEmit: ExportedModulesFromDeclarationEmit | undefined; // Emit each output file - performance.mark("beforePrint"); + enter(); forEachEmittedFile(host, emitSourceFileOrBundle, getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); - performance.measure("printTime", "beforePrint"); + exit(); return { @@ -135,64 +133,74 @@ namespace ts { if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } - function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, jsFilePath: string, sourceMapFilePath: string | undefined, bundleInfoPath: string | undefined) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, jsFilePath: string | undefined, sourceMapFilePath: string | undefined, bundleInfoPath: string | undefined) { + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files const transform = transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers!, /*allowDtsFiles*/ false); + const printerOptions: PrinterOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }; + // Create a printer to print the nodes - const printer = createPrinter({ ...compilerOptions, noEmitHelpers: compilerOptions.noEmitHelpers } as PrinterOptions, { + const printer = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, // transform hooks onEmitNode: transform.emitNodeWithNotification, substituteNode: transform.substituteNode, - - // sourcemap hooks - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - - // emitter hooks - onSetSourceFile: setSourceFile, }); Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, declarationFilePath: string | undefined, declarationMapPath: string | undefined) { - if (!(declarationFilePath && !isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !isInJSFile(sourceFileOrBundle))) { return; } const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - const nonJsFiles = filter(sourceFiles, isSourceFileNotJavaScript); + const nonJsFiles = filter(sourceFiles, isSourceFileNotJS); const inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [createBundle(nonJsFiles, !isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -205,16 +213,23 @@ namespace ts { emitterDiagnostics.add(diagnostic); } } - const declarationPrinter = createPrinter({ ...compilerOptions, onlyPrintJsDocStyle: true, noEmitHelpers: true } as PrinterOptions, { + + const printerOptions: PrinterOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + target: compilerOptions.target, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + }; + + const declarationPrinter = createPrinter(printerOptions, { // resolver hooks hasGlobalName: resolver.hasGlobalName, - // sourcemap hooks - onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: declarationSourceMap.emitPos, - onSetSourceFile: setSourceFileForDeclarationSourceMaps, - // transform hooks onEmitNode: declarationTransform.emitNodeWithNotification, substituteNode: declarationTransform.substituteNode, @@ -223,7 +238,13 @@ namespace ts { emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + // Explicitly do not passthru either `inline` option + }); if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === SyntaxKind.SourceFile) { const sourceFile = declarationTransform.transformed[0] as SourceFile; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; @@ -246,29 +267,56 @@ namespace ts { forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath: string, sourceMapFilePath: string | undefined, sourceFileOrBundle: SourceFile | Bundle, bundleInfoPath: string | undefined, printer: Printer, mapRecorder: SourceMapWriter) { + function printSourceFileOrBundle(jsFilePath: string, sourceMapFilePath: string | undefined, sourceFileOrBundle: SourceFile | Bundle, bundleInfoPath: string | undefined, printer: Printer, mapOptions: SourceMapOptions) { const bundle = sourceFileOrBundle.kind === SyntaxKind.Bundle ? sourceFileOrBundle : undefined; const sourceFile = sourceFileOrBundle.kind === SyntaxKind.SourceFile ? sourceFileOrBundle : undefined; const sourceFiles = bundle ? bundle.sourceFiles : [sourceFile!]; - mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); + + let sourceMapGenerator: SourceMapGenerator | undefined; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = createSourceMapGenerator( + host, + getBaseFileName(normalizeSlashes(jsFilePath)), + getSourceRoot(mapOptions), + getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), + mapOptions); + } if (bundle) { - printer.writeBundle(bundle, writer, bundleInfo); + printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); } else { - printer.writeFile(sourceFile!, writer); + printer.writeFile(sourceFile!, writer, sourceMapGenerator); } - writer.writeLine(); + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } - const sourceMappingURL = mapRecorder.getSourceMappingURL(); - if (sourceMappingURL) { - writer.write(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); // Sometimes tools can sometimes see this line as a source mapping url comment + const sourceMappingURL = getSourceMappingURL( + mapOptions, + sourceMapGenerator, + jsFilePath, + sourceMapFilePath, + sourceFile); + + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) writer.rawWrite(newLine); + writer.writeComment(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); // Tools can sometimes see this line as a source mapping url comment + } + + // Write the source map + if (sourceMapFilePath) { + const sourceMap = sourceMapGenerator.toString(); + writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + } } - - // Write the source map - if (sourceMapFilePath) { - writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); + else { + writer.writeLine(); } // Write the output file @@ -281,23 +329,87 @@ namespace ts { } // Reset state - mapRecorder.reset(); writer.clear(); bundleInfo = createDefaultBundleInfo(); } - function setSourceFile(node: SourceFile) { - sourceMap.setSourceFile(node); + interface SourceMapOptions { + sourceMap?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + sourceRoot?: string; + mapRoot?: string; + extendedDiagnostics?: boolean; } - function setSourceFileForDeclarationSourceMaps(node: SourceFile) { - declarationSourceMap.setSourceFile(node); + function shouldEmitSourceMaps(mapOptions: SourceMapOptions, sourceFileOrBundle: SourceFile | Bundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) + && (sourceFileOrBundle.kind !== SyntaxKind.SourceFile || !fileExtensionIs(sourceFileOrBundle.fileName, Extension.Json)); + } + + function getSourceRoot(mapOptions: SourceMapOptions) { + // 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 + const sourceRoot = normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + + function getSourceMapDirectory(mapOptions: SourceMapOptions, filePath: string, sourceFile: SourceFile | undefined) { + if (mapOptions.sourceRoot) return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + let sourceMapDir = normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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 = getDirectoryPath(getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return getDirectoryPath(normalizePath(filePath)); + } + + function getSourceMappingURL(mapOptions: SourceMapOptions, sourceMapGenerator: SourceMapGenerator, filePath: string, sourceMapFilePath: string | undefined, sourceFile: SourceFile | undefined) { + if (mapOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + const sourceMapText = sourceMapGenerator.toString(); + const base64SourceMapText = base64encode(sys, sourceMapText); + return `data:application/json;base64,${base64SourceMapText}`; + } + + const sourceMapFile = getBaseFileName(normalizeSlashes(Debug.assertDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + let sourceMapDir = normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + // 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 = getDirectoryPath(getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (getRootLength(sourceMapDir) === 0) { + // The relative paths are relative to the common directory + sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return getRelativePathToDirectoryOrUrl( + getDirectoryPath(normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap + host.getCurrentDirectory(), + host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + return combinePaths(sourceMapDir, sourceMapFile); + } + } + return sourceMapFile; } } const enum PipelinePhase { Notification, + Substitution, Comments, SourceMaps, Emit @@ -306,28 +418,20 @@ namespace ts { export function createPrinter(printerOptions: PrinterOptions = {}, handlers: PrintHandlers = {}): Printer { const { hasGlobalName, - onEmitSourceMapOfNode, - onEmitSourceMapOfToken, - onEmitSourceMapOfPosition, - onEmitNode, - onSetSourceFile, - substituteNode, + onEmitNode = noEmitNotification, + substituteNode = noEmitSubstitution, onBeforeEmitNodeArray, onAfterEmitNodeArray, onBeforeEmitToken, onAfterEmitToken } = handlers; + const extendedDiagnostics = !!printerOptions.extendedDiagnostics; const newLine = getNewLineCharacter(printerOptions); - const comments = createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - const { - emitNodeWithComments, - emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition, - emitLeadingCommentsOfPosition, - } = comments; + const moduleKind = getEmitModuleKind(printerOptions); + const bundledHelpers = createMap(); - let currentSourceFile!: SourceFile; + let currentSourceFile: SourceFile | undefined; let nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes. let autoGeneratedIdToGeneratedName: string[]; // Map of generated names for temp and loop variables. let generatedNames: Map; // Set of names generated by the NameGenerator. @@ -337,20 +441,26 @@ namespace ts { let reservedNames: Map; // TempFlags to reserve in nested name generation scopes. let writer: EmitTextWriter; - let ownWriter: EmitTextWriter; + let ownWriter: EmitTextWriter; // Reusable `EmitTextWriter` for basic printing. let write = writeBase; - let commitPendingSemicolon: typeof commitPendingSemicolonInternal = noop; - let writeSemicolon: typeof writeSemicolonInternal = writeSemicolonInternal; - let pendingSemicolon = false; - if (printerOptions.omitTrailingSemicolon) { - commitPendingSemicolon = commitPendingSemicolonInternal; - writeSemicolon = deferWriteSemicolon; - } - const syntheticParent: TextRange = { pos: -1, end: -1 }; - const moduleKind = getEmitModuleKind(printerOptions); - const bundledHelpers = createMap(); let isOwnFileEmit: boolean; + // Source Maps + let sourceMapsDisabled = true; + let sourceMapGenerator: SourceMapGenerator | undefined; + let sourceMapSource: SourceMapSource; + let sourceMapSourceIndex = -1; + + // Comments + let containerPos = -1; + let containerEnd = -1; + let declarationListContainerEnd = -1; + let currentLineMap: ReadonlyArray | undefined; + let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number}[] | undefined; + let hasWrittenComment = false; + let commentsDisabled = !!printerOptions.removeComments; + const { enter: enterComment, exit: exitComment } = performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"); + reset(); return { // public API @@ -393,12 +503,12 @@ namespace ts { } function printBundle(bundle: Bundle): string { - writeBundle(bundle, beginPrint()); + writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printFile(sourceFile: SourceFile): string { - writeFile(sourceFile, beginPrint()); + writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } @@ -414,7 +524,7 @@ namespace ts { function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, output: EmitTextWriter): void; function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, output: EmitTextWriter) { const previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(hint, node, sourceFile); reset(); writer = previousWriter; @@ -422,7 +532,7 @@ namespace ts { function writeList(format: ListFormat, nodes: NodeArray, sourceFile: SourceFile | undefined, output: EmitTextWriter) { const previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); if (sourceFile) { setSourceFile(sourceFile); } @@ -431,18 +541,18 @@ namespace ts { writer = previousWriter; } - function writeBundle(bundle: Bundle, output: EmitTextWriter, bundleInfo?: BundleInfo) { + function writeBundle(bundle: Bundle, bundleInfo: BundleInfo | undefined, output: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined) { isOwnFileEmit = false; const previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (const prepend of bundle.prepends) { - print(EmitHint.Unspecified, prepend, /*sourceFile*/ undefined); writeLine(); + print(EmitHint.Unspecified, prepend, /*sourceFile*/ undefined); } if (bundleInfo) { @@ -458,16 +568,16 @@ namespace ts { function writeUnparsedSource(unparsed: UnparsedSource, output: EmitTextWriter) { const previousWriter = writer; - setWriter(output); + setWriter(output, /*_sourceMapGenerator*/ undefined); print(EmitHint.Unspecified, unparsed, /*sourceFile*/ undefined); reset(); writer = previousWriter; } - function writeFile(sourceFile: SourceFile, output: EmitTextWriter) { + function writeFile(sourceFile: SourceFile, output: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined) { isOwnFileEmit = true; const previousWriter = writer; - setWriter(output); + setWriter(output, sourceMapGenerator); emitShebangIfNeeded(sourceFile); emitPrologueDirectivesIfNeeded(sourceFile); print(EmitHint.SourceFile, sourceFile, sourceFile); @@ -490,21 +600,27 @@ namespace ts { setSourceFile(sourceFile); } - const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, hint); + const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node); pipelinePhase(hint, node); } - function setSourceFile(sourceFile: SourceFile) { + function setSourceFile(sourceFile: SourceFile | undefined) { currentSourceFile = sourceFile; - comments.setSourceFile(sourceFile); - if (onSetSourceFile) { - onSetSourceFile(sourceFile); + currentLineMap = undefined; + detachedCommentsInfo = undefined; + if (sourceFile) { + setSourceMapSource(sourceFile); } } - function setWriter(output: EmitTextWriter | undefined) { - writer = output!; // TODO: GH#18217 - comments.setWriter(output!); + function setWriter(_writer: EmitTextWriter | undefined, _sourceMapGenerator: SourceMapGenerator | undefined) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = getTrailingSemicolonOmittingWriter(_writer); + } + + writer = _writer!; // TODO: GH#18217 + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; } function reset() { @@ -514,44 +630,56 @@ namespace ts { tempFlagsStack = []; tempFlags = TempFlags.Auto; reservedNamesStack = []; - comments.reset(); - setWriter(/*output*/ undefined); + currentSourceFile = undefined!; + currentLineMap = undefined!; + detachedCommentsInfo = undefined; + setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); + } + + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = getLineStarts(currentSourceFile!)); } function emit(node: Node | undefined) { - if (!node) return; - const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, EmitHint.Unspecified); + if (node === undefined) return; + const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node); pipelinePhase(EmitHint.Unspecified, node); } function emitIdentifierName(node: Identifier | undefined) { - if (!node) return; - const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, EmitHint.IdentifierName); + if (node === undefined) return; + const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node); pipelinePhase(EmitHint.IdentifierName, node); } function emitExpression(node: Expression | undefined) { - if (!node) return; - const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, EmitHint.Expression); + if (node === undefined) return; + const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node); pipelinePhase(EmitHint.Expression, node); } - function getPipelinePhase(phase: PipelinePhase, hint: EmitHint) { + function getPipelinePhase(phase: PipelinePhase, node: Node) { switch (phase) { case PipelinePhase.Notification: - if (onEmitNode) { + if (onEmitNode !== noEmitNotification) { return pipelineEmitWithNotification; } // falls through + case PipelinePhase.Substitution: + if (substituteNode !== noEmitSubstitution) { + return pipelineEmitWithSubstitution; + } + // falls through + case PipelinePhase.Comments: - if (emitNodeWithComments && hint !== EmitHint.SourceFile) { + if (!commentsDisabled && node.kind !== SyntaxKind.SourceFile) { return pipelineEmitWithComments; } - return pipelineEmitWithoutComments; + // falls through case PipelinePhase.SourceMaps: - if (onEmitSourceMapOfNode && hint !== EmitHint.SourceFile) { + if (!sourceMapsDisabled && node.kind !== SyntaxKind.SourceFile && !isInJsonFile(node)) { return pipelineEmitWithSourceMap; } // falls through @@ -560,38 +688,27 @@ namespace ts { return pipelineEmitWithHint; default: - return Debug.assertNever(phase, `Unexpected value for PipelinePhase: ${phase}`); + return Debug.assertNever(phase); } } - function getNextPipelinePhase(currentPhase: PipelinePhase, hint: EmitHint) { - return getPipelinePhase(currentPhase + 1, hint); + function getNextPipelinePhase(currentPhase: PipelinePhase, node: Node) { + return getPipelinePhase(currentPhase + 1, node); } function pipelineEmitWithNotification(hint: EmitHint, node: Node) { - Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(PipelinePhase.Notification, hint)); - } - - function pipelineEmitWithComments(hint: EmitHint, node: Node) { - Debug.assertDefined(emitNodeWithComments); - Debug.assert(hint !== EmitHint.SourceFile); - emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(PipelinePhase.Comments, hint)); - } - - function pipelineEmitWithoutComments(hint: EmitHint, node: Node) { - const pipelinePhase = getNextPipelinePhase(PipelinePhase.Comments, hint); - pipelinePhase(hint, trySubstituteNode(hint, node)); - } - - function pipelineEmitWithSourceMap(hint: EmitHint, node: Node) { - Debug.assert(hint !== EmitHint.SourceFile); - Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); + const pipelinePhase = getNextPipelinePhase(PipelinePhase.Notification, node); + onEmitNode(hint, node, pipelinePhase); } function pipelineEmitWithHint(hint: EmitHint, node: Node): void { if (hint === EmitHint.SourceFile) return emitSourceFile(cast(node, isSourceFile)); if (hint === EmitHint.IdentifierName) return emitIdentifier(cast(node, isIdentifier)); if (hint === EmitHint.MappedTypeParameter) return emitMappedTypeParameter(cast(node, isTypeParameterDeclaration)); + if (hint === EmitHint.EmbeddedStatement) { + Debug.assertNode(node, isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } if (hint === EmitHint.Unspecified) { if (isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); @@ -692,10 +809,10 @@ namespace ts { case SyntaxKind.ImportType: return emitImportTypeNode(node); case SyntaxKind.JSDocAllType: - write("*"); + writePunctuation("*"); return; case SyntaxKind.JSDocUnknownType: - write("?"); + writePunctuation("?"); return; case SyntaxKind.JSDocNullableType: return emitJSDocNullableType(node as JSDocNullableType); @@ -727,7 +844,7 @@ namespace ts { case SyntaxKind.VariableStatement: return emitVariableStatement(node); case SyntaxKind.EmptyStatement: - return emitEmptyStatement(); + return emitEmptyStatement(/*isEmbeddedStatement*/ false); case SyntaxKind.ExpressionStatement: return emitExpressionStatement(node); case SyntaxKind.IfStatement: @@ -851,13 +968,42 @@ namespace ts { case SyntaxKind.EnumMember: return emitEnumMember(node); - // JSDoc nodes (ignored) + // JSDoc nodes (only used in codefixes currently) + case SyntaxKind.JSDocParameterTag: + case SyntaxKind.JSDocPropertyTag: + return emitJSDocPropertyLikeTag(node as JSDocPropertyLikeTag); + case SyntaxKind.JSDocReturnTag: + case SyntaxKind.JSDocTypeTag: + case SyntaxKind.JSDocThisTag: + case SyntaxKind.JSDocEnumTag: + return emitJSDocSimpleTypedTag(node as JSDocTypeTag); + case SyntaxKind.JSDocAugmentsTag: + return emitJSDocAugmentsTag(node as JSDocAugmentsTag); + case SyntaxKind.JSDocTemplateTag: + return emitJSDocTemplateTag(node as JSDocTemplateTag); + case SyntaxKind.JSDocTypedefTag: + return emitJSDocTypedefTag(node as JSDocTypedefTag); + case SyntaxKind.JSDocCallbackTag: + return emitJSDocCallbackTag(node as JSDocCallbackTag); + case SyntaxKind.JSDocSignature: + return emitJSDocSignature(node as JSDocSignature); + case SyntaxKind.JSDocTypeLiteral: + return emitJSDocTypeLiteral(node as JSDocTypeLiteral); + case SyntaxKind.JSDocClassTag: + case SyntaxKind.JSDocTag: + return emitJSDocSimpleTag(node as JSDocTag); + + case SyntaxKind.JSDocComment: + return emitJSDoc(node as JSDoc); + // Transformation nodes (ignored) } if (isExpression(node)) { hint = EmitHint.Expression; - node = trySubstituteNode(EmitHint.Expression, node); + if (substituteNode !== noEmitSubstitution) { + node = substituteNode(hint, node); + } } else if (isToken(node)) { return writeTokenNode(node, writePunctuation); @@ -867,7 +1013,8 @@ namespace ts { switch (node.kind) { // Literals case SyntaxKind.NumericLiteral: - return emitNumericLiteral(node); + case SyntaxKind.BigIntLiteral: + return emitNumericOrBigIntLiteral(node); case SyntaxKind.StringLiteral: case SyntaxKind.RegularExpressionLiteral: @@ -970,8 +1117,9 @@ namespace ts { emit(node.constraint); } - function trySubstituteNode(hint: EmitHint, node: Node) { - return node && substituteNode && substituteNode(hint, node) || node; + function pipelineEmitWithSubstitution(hint: EmitHint, node: Node) { + const pipelinePhase = getNextPipelinePhase(PipelinePhase.Substitution, node); + pipelinePhase(hint, substituteNode(hint, node)); } function emitHelpers(node: Node) { @@ -984,7 +1132,7 @@ namespace ts { const numNodes = bundle ? bundle.sourceFiles.length : 1; for (let i = 0; i < numNodes; i++) { const currentNode = bundle ? bundle.sourceFiles[i] : node; - const sourceFile = isSourceFile(currentNode) ? currentNode : currentSourceFile; + const sourceFile = isSourceFile(currentNode) ? currentNode : currentSourceFile!; const shouldSkip = printerOptions.noEmitHelpers || getExternalHelpersModuleName(sourceFile) !== undefined; const shouldBundle = isSourceFile(currentNode) && !isOwnFileEmit; const helpers = getEmitHelpers(currentNode); @@ -1015,7 +1163,7 @@ namespace ts { writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -1030,7 +1178,8 @@ namespace ts { // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node: NumericLiteral) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node: NumericLiteral | BigIntLiteral) { emitLiteral(node); } @@ -1041,7 +1190,7 @@ namespace ts { // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node: LiteralLikeNode) { - const text = getLiteralTextOfNode(node); + const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -1143,7 +1292,7 @@ namespace ts { emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node: PropertyDeclaration) { @@ -1154,7 +1303,7 @@ namespace ts { emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); - writeSemicolon(); + writeTrailingSemicolon(); } function emitMethodSignature(node: MethodSignature) { @@ -1166,7 +1315,7 @@ namespace ts { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } @@ -1201,7 +1350,7 @@ namespace ts { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } @@ -1214,7 +1363,7 @@ namespace ts { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } @@ -1223,11 +1372,11 @@ namespace ts { emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // @@ -1259,26 +1408,26 @@ namespace ts { } function emitJSDocFunctionType(node: JSDocFunctionType) { - write("function"); + writeKeyword("function"); emitParameters(node, node.parameters); - write(":"); + writePunctuation(":"); emit(node.type); } function emitJSDocNullableType(node: JSDocNullableType) { - write("?"); + writePunctuation("?"); emit(node.type); } function emitJSDocNonNullableType(node: JSDocNonNullableType) { - write("!"); + writePunctuation("!"); emit(node.type); } function emitJSDocOptionalType(node: JSDocOptionalType) { emit(node.type); - write("="); + writePunctuation("="); } function emitConstructorType(node: ConstructorTypeNode) { @@ -1314,7 +1463,7 @@ namespace ts { } function emitRestOrJSDocVariadicType(node: RestTypeNode | JSDocVariadicType) { - write("..."); + writePunctuation("..."); emit(node.type); } @@ -1326,7 +1475,7 @@ namespace ts { function emitOptionalType(node: OptionalTypeNode) { emit(node.type); - write("?"); + writePunctuation("?"); } function emitUnionType(node: UnionTypeNode) { @@ -1401,7 +1550,7 @@ namespace ts { } writePunctuation("["); - const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, EmitHint.MappedTypeParameter); + const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node.typeParameter); pipelinePhase(EmitHint.MappedTypeParameter, node.typeParameter); writePunctuation("]"); @@ -1414,7 +1563,7 @@ namespace ts { writePunctuation(":"); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); if (emitFlags & EmitFlags.SingleLine) { writeSpace(); } @@ -1491,7 +1640,7 @@ namespace ts { } const preferNewLine = node.multiLine ? ListFormat.PreferNewLine : ListFormat.None; - const allowTrailingComma = currentSourceFile.languageVersion >= ScriptTarget.ES5 && !isJsonSourceFile(currentSourceFile) ? ListFormat.AllowTrailingComma : ListFormat.None; + const allowTrailingComma = currentSourceFile!.languageVersion >= ScriptTarget.ES5 && !isJsonSourceFile(currentSourceFile!) ? ListFormat.AllowTrailingComma : ListFormat.None; emitList(node, node.properties, ListFormat.ObjectLiteralExpressionProperties | allowTrailingComma | preferNewLine); if (indentedFlag) { @@ -1502,39 +1651,48 @@ namespace ts { function emitPropertyAccessExpression(node: PropertyAccessExpression) { let indentBeforeDot = false; let indentAfterDot = false; + const dotRangeFirstCommentStart = skipTrivia( + currentSourceFile!.text, + node.expression.end, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ true + ); + const dotRangeStart = skipTrivia(currentSourceFile!.text, dotRangeFirstCommentStart); + const dotRangeEnd = dotRangeStart + 1; if (!(getEmitFlags(node) & EmitFlags.NoIndentation)) { - const dotRangeStart = node.expression.end; - const dotRangeEnd = skipTrivia(currentSourceFile.text, node.expression.end) + 1; const dotToken = createToken(SyntaxKind.DotToken); - dotToken.pos = dotRangeStart; + dotToken.pos = node.expression.end; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); - increaseIndentIf(indentBeforeDot); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); - const shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + const dotHasCommentTrivia = dotRangeFirstCommentStart !== dotRangeStart; + const shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression, dotHasCommentTrivia); if (shouldEmitDotDot) { writePunctuation("."); } emitTokenWithComment(SyntaxKind.DotToken, node.expression.end, writePunctuation, node); - increaseIndentIf(indentAfterDot); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); } // 1..toString is a valid property access, emit a dot after the literal // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal - function needsDotDotForPropertyAccess(expression: Expression) { + function needsDotDotForPropertyAccess(expression: Expression, dotHasTrivia: boolean) { expression = skipPartiallyEmittedExpressions(expression); if (isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - const text = getLiteralTextOfNode(expression); - return !expression.numericLiteralFlags - && !stringContains(text, tokenToString(SyntaxKind.DotToken)!); + const text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); + // If he number will be printed verbatim and it doesn't already contain a dot, add one + // if the expression doesn't have any comments that will be emitted. + return !expression.numericLiteralFlags && !stringContains(text, tokenToString(SyntaxKind.DotToken)!) && + (!dotHasTrivia || printerOptions.removeComments); } else if (isPropertyAccessExpression(expression) || isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -1668,11 +1826,11 @@ namespace ts { const indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); - increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + increaseIndentIf(indentBeforeOperator, isCommaOperator); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, writeOperator); + writeTokenNode(node.operatorToken, node.operatorToken.kind === SyntaxKind.InKeyword ? writeKeyword : writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - increaseIndentIf(indentAfterOperator, " "); + increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); } @@ -1684,15 +1842,15 @@ namespace ts { const indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); - increaseIndentIf(indentBeforeQuestion, " "); + increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); - increaseIndentIf(indentAfterQuestion, " "); + increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); - increaseIndentIf(indentBeforeColon, " "); + increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); - increaseIndentIf(indentAfterColon, " "); + increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); } @@ -1709,7 +1867,7 @@ namespace ts { } function emitSpreadExpression(node: SpreadElement) { - writePunctuation("..."); + emitTokenWithComment(SyntaxKind.DotDotDotToken, node.pos, writePunctuation, node); emitExpression(node.expression); } @@ -1771,19 +1929,27 @@ namespace ts { function emitVariableStatement(node: VariableStatement) { emitModifiers(node, node.modifiers); emit(node.declarationList); - writeSemicolon(); + writeTrailingSemicolon(); } - function emitEmptyStatement() { - writeSemicolon(); + function emitEmptyStatement(isEmbeddedStatement: boolean) { + // While most trailing semicolons are possibly insignificant, an embedded "empty" + // statement is significant and cannot be elided by a trailing-semicolon-omitting writer. + if (isEmbeddedStatement) { + writePunctuation(";"); + } + else { + writeTrailingSemicolon(); + } } + function emitExpressionStatement(node: ExpressionStatement) { emitExpression(node.expression); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) - if (!isJsonSourceFile(currentSourceFile) || nodeIsSynthesized(node.expression)) { - writeSemicolon(); + if (!isJsonSourceFile(currentSourceFile!) || nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); } } @@ -1839,9 +2005,9 @@ namespace ts { writeSpace(); let pos = emitTokenWithComment(SyntaxKind.OpenParenToken, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - pos = emitTokenWithComment(SyntaxKind.SemicolonToken, node.initializer ? node.initializer.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(SyntaxKind.SemicolonToken, node.initializer ? node.initializer.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.condition); - pos = emitTokenWithComment(SyntaxKind.SemicolonToken, node.condition ? node.condition.end : pos, writeSemicolon, node); + pos = emitTokenWithComment(SyntaxKind.SemicolonToken, node.condition ? node.condition.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.incrementor); emitTokenWithComment(SyntaxKind.CloseParenToken, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); @@ -1888,13 +2054,13 @@ namespace ts { function emitContinueStatement(node: ContinueStatement) { emitTokenWithComment(SyntaxKind.ContinueKeyword, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitBreakStatement(node: BreakStatement) { emitTokenWithComment(SyntaxKind.BreakKeyword, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTokenWithComment(token: SyntaxKind, pos: number, writer: (s: string) => void, contextNode: Node, indentLeading?: boolean) { @@ -1902,10 +2068,10 @@ namespace ts { const isSimilarNode = node && node.kind === contextNode.kind; const startPos = pos; if (isSimilarNode) { - pos = skipTrivia(currentSourceFile.text, pos); + pos = skipTrivia(currentSourceFile!.text, pos); } if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { - const needsIndent = indentLeading && !positionsAreOnSameLine(startPos, pos, currentSourceFile); + const needsIndent = indentLeading && !positionsAreOnSameLine(startPos, pos, currentSourceFile!); if (needsIndent) { increaseIndent(); } @@ -1924,7 +2090,7 @@ namespace ts { function emitReturnStatement(node: ReturnStatement) { emitTokenWithComment(SyntaxKind.ReturnKeyword, node.pos, writeKeyword, /*contextNode*/ node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitWithStatement(node: WithStatement) { @@ -1956,7 +2122,7 @@ namespace ts { function emitThrowStatement(node: ThrowStatement) { emitTokenWithComment(SyntaxKind.ThrowKeyword, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitTryStatement(node: TryStatement) { @@ -1977,7 +2143,7 @@ namespace ts { function emitDebuggerStatement(node: DebuggerStatement) { writeToken(SyntaxKind.DebuggerKeyword, node.pos, writeKeyword); - writeSemicolon(); + writeTrailingSemicolon(); } // @@ -2048,7 +2214,7 @@ namespace ts { } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } @@ -2076,7 +2242,7 @@ namespace ts { return false; } - if (!nodeIsSynthesized(body) && !rangeIsOnSingleLine(body, currentSourceFile)) { + if (!nodeIsSynthesized(body) && !rangeIsOnSingleLine(body, currentSourceFile!)) { return false; } @@ -2194,7 +2360,7 @@ namespace ts { writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node: EnumDeclaration) { @@ -2218,7 +2384,7 @@ namespace ts { emit(node.name); let body = node.body; - if (!body) return writeSemicolon(); + if (!body) return writeTrailingSemicolon(); while (body.kind === SyntaxKind.ModuleDeclaration) { writePunctuation("."); emit((body).name); @@ -2251,7 +2417,7 @@ namespace ts { emitTokenWithComment(SyntaxKind.EqualsToken, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); - writeSemicolon(); + writeTrailingSemicolon(); } function emitModuleReference(node: ModuleReference) { @@ -2274,7 +2440,7 @@ namespace ts { writeSpace(); } emitExpression(node.moduleSpecifier); - writeSemicolon(); + writeTrailingSemicolon(); } function emitImportClause(node: ImportClause) { @@ -2313,7 +2479,7 @@ namespace ts { } writeSpace(); emitExpression(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitExportDeclaration(node: ExportDeclaration) { @@ -2332,7 +2498,7 @@ namespace ts { writeSpace(); emitExpression(node.moduleSpecifier); } - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamespaceExportDeclaration(node: NamespaceExportDeclaration) { @@ -2343,7 +2509,7 @@ namespace ts { nextPos = emitTokenWithComment(SyntaxKind.NamespaceKeyword, nextPos, writeKeyword, node); writeSpace(); emit(node.name); - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamedExports(node: NamedExports) { @@ -2395,6 +2561,7 @@ namespace ts { function emitJsxSelfClosingElement(node: JsxSelfClosingElement) { writePunctuation("<"); emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); writeSpace(); emit(node.attributes); writePunctuation("/>"); @@ -2411,6 +2578,7 @@ namespace ts { if (isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } @@ -2421,7 +2589,6 @@ namespace ts { } function emitJsxText(node: JsxText) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } @@ -2490,7 +2657,7 @@ namespace ts { // treat synthesized nodes as located on the same line for emit purposes nodeIsSynthesized(parentNode) || nodeIsSynthesized(statements[0]) || - rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile) + rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile!) ); let format = ListFormat.CaseOrDefaultClauseStatements; @@ -2559,7 +2726,7 @@ namespace ts { function emitSpreadAssignment(node: SpreadAssignment) { if (node.expression) { - writePunctuation("..."); + emitTokenWithComment(SyntaxKind.DotDotDotToken, node.pos, writePunctuation, node); emitExpression(node.expression); } } @@ -2573,6 +2740,154 @@ namespace ts { emitInitializer(node.initializer, node.name.end, node); } + // + // JSDoc + // + function emitJSDoc(node: JSDoc) { + write("/**"); + if (node.comment) { + const lines = node.comment.split(/\r\n?|\n/g); + for (const line of lines) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === SyntaxKind.JSDocTypeTag && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, ListFormat.JSDocComment); + } + } + writeSpace(); + write("*/"); + } + + function emitJSDocSimpleTypedTag(tag: JSDocTypeTag | JSDocThisTag | JSDocEnumTag | JSDocReturnTag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + + function emitJSDocAugmentsTag(tag: JSDocAugmentsTag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + + function emitJSDocTemplateTag(tag: JSDocTemplateTag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, ListFormat.CommaListElements); + emitJSDocComment(tag.comment); + } + + function emitJSDocTypedefTag(tag: JSDocTypedefTag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === SyntaxKind.JSDocTypeExpression) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === SyntaxKind.JSDocTypeLiteral) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + + function emitJSDocCallbackTag(tag: JSDocCallbackTag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + + function emitJSDocSimpleTag(tag: JSDocTag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + + function emitJSDocTypeLiteral(lit: JSDocTypeLiteral) { + emitList(lit, createNodeArray(lit.jsDocPropertyTags), ListFormat.JSDocComment); + } + + function emitJSDocSignature(sig: JSDocSignature) { + if (sig.typeParameters) { + emitList(sig, createNodeArray(sig.typeParameters), ListFormat.JSDocComment); + } + if (sig.parameters) { + emitList(sig, createNodeArray(sig.parameters), ListFormat.JSDocComment); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + + function emitJSDocPropertyLikeTag(param: JSDocPropertyLikeTag) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + + function emitJSDocTagName(tagName: Identifier) { + writePunctuation("@"); + emit(tagName); + } + + function emitJSDocComment(comment: string | undefined) { + if (comment) { + writeSpace(); + write(comment); + } + } + + function emitJSDocTypeExpression(typeExpression: JSDocTypeExpression | undefined) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // // Top-level nodes // @@ -2604,34 +2919,34 @@ namespace ts { function emitTripleSlashDirectives(hasNoDefaultLib: boolean, files: ReadonlyArray, types: ReadonlyArray, libs: ReadonlyArray) { if (hasNoDefaultLib) { - write(`/// `); + writeComment(`/// `); writeLine(); } if (currentSourceFile && currentSourceFile.moduleName) { - write(`/// `); + writeComment(`/// `); writeLine(); } if (currentSourceFile && currentSourceFile.amdDependencies) { for (const dep of currentSourceFile.amdDependencies) { if (dep.name) { - write(`/// `); + writeComment(`/// `); } else { - write(`/// `); + writeComment(`/// `); } writeLine(); } } for (const directive of files) { - write(`/// `); + writeComment(`/// `); writeLine(); } for (const directive of types) { - write(`/// `); + writeComment(`/// `); writeLine(); } for (const directive of libs) { - write(`/// `); + writeComment(`/// `); writeLine(); } } @@ -2696,6 +3011,7 @@ namespace ts { setSourceFile(sourceFile); emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); } + setSourceFile(undefined); } } @@ -2703,7 +3019,7 @@ namespace ts { if (isSourceFile(sourceFileOrBundle)) { const shebang = getShebang(sourceFileOrBundle.text); if (shebang) { - write(shebang); + writeComment(shebang); writeLine(); return true; } @@ -2790,7 +3106,13 @@ namespace ts { else { writeLine(); increaseIndent(); - emit(node); + if (isEmptyStatement(node)) { + const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node); + pipelinePhase(EmitHint.EmbeddedStatement, node); + } + else { + emit(node); + } decreaseIndent(); } } @@ -2818,7 +3140,8 @@ namespace ts { const parameter = singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !some(parentNode.decorators) // parent may not have decorators && !some(parentNode.modifiers) // parent may not have modifiers && !some(parentNode.typeParameters) // parent may not have type parameters @@ -2863,6 +3186,11 @@ namespace ts { writeSpace(); writePunctuation("|"); break; + case ListFormat.AsteriskDelimited: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case ListFormat.AmpersandDelimited: writeSpace(); writePunctuation("&"); @@ -2932,7 +3260,12 @@ namespace ts { const child = children![start + i]; // Write the delimiter if this is not the first node. - if (previousSibling) { + if (format & ListFormat.AsteriskDelimited) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { // i.e // function commentedParameters( // /* Parameter a */ @@ -3026,89 +3359,71 @@ namespace ts { } } - function commitPendingSemicolonInternal() { - if (pendingSemicolon) { - writeSemicolonInternal(); - pendingSemicolon = false; - } - } + // Writers function writeLiteral(s: string) { - commitPendingSemicolon(); writer.writeLiteral(s); } function writeStringLiteral(s: string) { - commitPendingSemicolon(); writer.writeStringLiteral(s); } function writeBase(s: string) { - commitPendingSemicolon(); writer.write(s); } function writeSymbol(s: string, sym: Symbol) { - commitPendingSemicolon(); writer.writeSymbol(s, sym); } function writePunctuation(s: string) { - commitPendingSemicolon(); writer.writePunctuation(s); } - function deferWriteSemicolon() { - pendingSemicolon = true; - } - - function writeSemicolonInternal() { - writer.writePunctuation(";"); + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); } function writeKeyword(s: string) { - commitPendingSemicolon(); writer.writeKeyword(s); } function writeOperator(s: string) { - commitPendingSemicolon(); writer.writeOperator(s); } function writeParameter(s: string) { - commitPendingSemicolon(); writer.writeParameter(s); } + function writeComment(s: string) { + writer.writeComment(s); + } + function writeSpace() { - commitPendingSemicolon(); writer.writeSpace(" "); } function writeProperty(s: string) { - commitPendingSemicolon(); writer.writeProperty(s); } function writeLine() { - commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { - commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { - commitPendingSemicolon(); writer.decreaseIndent(); } function writeToken(token: SyntaxKind, pos: number, writer: (s: string) => void, contextNode?: Node) { - return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + return !sourceMapsDisabled + ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText) : writeTokenText(token, writer, pos); } @@ -3147,18 +3462,18 @@ namespace ts { if (line.length) { writeLine(); write(line); - writeLine(); + writer.rawWrite(newLine); } } } - function increaseIndentIf(value: boolean, valueToWriteWhenNotIndenting?: string) { + function increaseIndentIf(value: boolean, writeSpaceIfNotIndenting: boolean) { if (value) { increaseIndent(); writeLine(); } - else if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); + else if (writeSpaceIfNotIndenting) { + writeSpace(); } } @@ -3166,7 +3481,7 @@ namespace ts { // previous indent values to be considered at a time. This also allows caller to just // call this once, passing in all their appropriate indent values, instead of needing // to call this helper function multiple times. - function decreaseIndentIf(value1: boolean, value2?: boolean) { + function decreaseIndentIf(value1: boolean, value2: boolean) { if (value1) { decreaseIndent(); } @@ -3187,13 +3502,13 @@ namespace ts { const firstChild = children[0]; if (firstChild === undefined) { - return !rangeIsOnSingleLine(parentNode, currentSourceFile); + return !rangeIsOnSingleLine(parentNode, currentSourceFile!); } else if (positionIsSynthesized(parentNode.pos) || nodeIsSynthesized(firstChild)) { return synthesizedNodeStartsOnNewLine(firstChild, format); } else { - return !rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + return !rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile!); } } else { @@ -3213,7 +3528,7 @@ namespace ts { return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); } else { - return !rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + return !rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile!); } } else { @@ -3232,13 +3547,13 @@ namespace ts { const lastChild = lastOrUndefined(children); if (lastChild === undefined) { - return !rangeIsOnSingleLine(parentNode, currentSourceFile); + return !rangeIsOnSingleLine(parentNode, currentSourceFile!); } else if (positionIsSynthesized(parentNode.pos) || nodeIsSynthesized(lastChild)) { return synthesizedNodeStartsOnNewLine(lastChild, format); } else { - return !rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + return !rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile!); } } else { @@ -3272,12 +3587,12 @@ namespace ts { return !nodeIsSynthesized(parent) && !nodeIsSynthesized(node1) && !nodeIsSynthesized(node2) - && !rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + && !rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile!); } function isEmptyBlock(block: BlockLike) { return block.statements.length === 0 - && rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + && rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile!); } function skipSynthesizedParentheses(node: Node) { @@ -3302,23 +3617,23 @@ namespace ts { return node.text; } - return getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + return getSourceTextOfNodeFromSourceFile(currentSourceFile!, node, includeTrivia); } - function getLiteralTextOfNode(node: LiteralLikeNode): string { + function getLiteralTextOfNode(node: LiteralLikeNode, neverAsciiEscape: boolean | undefined): string { if (node.kind === SyntaxKind.StringLiteral && (node).textSourceNode) { const textSourceNode = (node).textSourceNode!; if (isIdentifier(textSourceNode)) { - return getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? + return neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? `"${escapeString(getTextOfNode(textSourceNode))}"` : `"${escapeNonAsciiString(getTextOfNode(textSourceNode))}"`; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return getLiteralText(node, currentSourceFile); + return getLiteralText(node, currentSourceFile!, neverAsciiEscape); } /** @@ -3587,7 +3902,7 @@ namespace ts { } } - function makeFileLevelOptmiisticUniqueName(name: string) { + function makeFileLevelOptimisticUniqueName(name: string) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } @@ -3709,6 +4024,448 @@ namespace ts { // otherwise, return the original node for the source; return node; } + + // Comments + + function pipelineEmitWithComments(hint: EmitHint, node: Node) { + enterComment(); + hasWrittenComment = false; + const emitFlags = getEmitFlags(node); + const { pos, end } = getCommentRange(node); + const isEmittedNode = node.kind !== SyntaxKind.NotEmittedStatement; + + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0 || node.kind === SyntaxKind.JsxText; + const skipTrailingComments = end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0 || node.kind === SyntaxKind.JsxText; + + // Save current container state on the stack. + const savedContainerPos = containerPos; + const savedContainerEnd = containerEnd; + const savedDeclarationListContainerEnd = declarationListContainerEnd; + if ((pos > 0 || end > 0) && pos !== end) { + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + + if (!skipLeadingComments || (pos >= 0 && (emitFlags & EmitFlags.NoLeadingComments) !== 0)) { + // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. + containerPos = pos; + } + + if (!skipTrailingComments || (end >= 0 && (emitFlags & EmitFlags.NoTrailingComments) !== 0)) { + // As above. + containerEnd = end; + + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === SyntaxKind.VariableDeclarationList) { + declarationListContainerEnd = end; + } + } + } + forEach(getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + + const pipelinePhase = getNextPipelinePhase(PipelinePhase.Comments, node); + if (emitFlags & EmitFlags.NoNestedComments) { + commentsDisabled = true; + pipelinePhase(hint, node); + commentsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + + enterComment(); + forEach(getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + } + exitComment(); + } + + function emitLeadingSynthesizedComment(comment: SynthesizedComment) { + if (comment.kind === SyntaxKind.SingleLineCommentTrivia) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === SyntaxKind.SingleLineCommentTrivia) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + + function emitTrailingSynthesizedComment(comment: SynthesizedComment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + + function writeSynthesizedComment(comment: SynthesizedComment) { + const text = formatSynthesizedComment(comment); + const lineMap = comment.kind === SyntaxKind.MultiLineCommentTrivia ? computeLineStarts(text) : undefined; + writeCommentRange(text, lineMap!, writer, 0, text.length, newLine); + } + + function formatSynthesizedComment(comment: SynthesizedComment) { + return comment.kind === SyntaxKind.MultiLineCommentTrivia + ? `/*${comment.text}*/` + : `//${comment.text}`; + } + + function emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void) { + enterComment(); + const { pos, end } = detachedRange; + const emitFlags = getEmitFlags(node); + const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0; + const skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + + exitComment(); + if (emitFlags & EmitFlags.NoNestedComments && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } + else { + emitCallback(node); + } + + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + + } + + function emitLeadingComments(pos: number, isEmittedNode: boolean) { + hasWrittenComment = false; + + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + + function emitTripleSlashLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + + function shouldWriteComment(text: string, pos: number) { + if (printerOptions.onlyPrintJsDocStyle) { + return (isJSDocLikeText(text, pos) || isPinnedComment(text, pos)); + } + return true; + } + + function emitLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) { + if (!shouldWriteComment(currentSourceFile!.text, commentPos)) return; + if (!hasWrittenComment) { + emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + writeCommentRange(currentSourceFile!.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + + if (hasTrailingNewLine) { + writer.writeLine(); + } + else if (kind === SyntaxKind.MultiLineCommentTrivia) { + writer.writeSpace(" "); + } + } + + function emitLeadingCommentsOfPosition(pos: number) { + if (commentsDisabled || pos === -1) { + return; + } + + emitLeadingComments(pos, /*isEmittedNode*/ true); + } + + function emitTrailingComments(pos: number) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + + function emitTrailingComment(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean) { + if (!shouldWriteComment(currentSourceFile!.text, commentPos)) return; + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + + emitPos(commentPos); + writeCommentRange(currentSourceFile!.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + + function emitTrailingCommentsOfPosition(pos: number, prefixSpace?: boolean) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); + exitComment(); + } + + function emitTrailingCommentOfPosition(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + + emitPos(commentPos); + writeCommentRange(currentSourceFile!.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.writeSpace(" "); + } + } + + function forEachLeadingCommentToEmit(pos: number, cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos); + } + } + } + + function forEachTrailingCommentToEmit(end: number, cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) => void) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) { + forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + + function hasDetachedComments(pos: number) { + return detachedCommentsInfo !== undefined && last(detachedCommentsInfo).nodePos === pos; + } + + function forEachLeadingCommentWithoutDetachedComments(cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) { + // get the leading comments from detachedPos + const pos = last(detachedCommentsInfo!).detachedCommentEndPos; + if (detachedCommentsInfo!.length - 1) { + detachedCommentsInfo!.pop(); + } + else { + detachedCommentsInfo = undefined; + } + + forEachLeadingCommentRange(currentSourceFile!.text, pos, cb, /*state*/ pos); + } + + function emitDetachedCommentsAndUpdateCommentsInfo(range: TextRange) { + const currentDetachedCommentInfo = emitDetachedComments(currentSourceFile!.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + + function emitComment(text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) { + if (!shouldWriteComment(currentSourceFile!.text, commentPos)) return; + emitPos(commentPos); + writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isTripleSlashComment(commentPos: number, commentEnd: number) { + return isRecognizedTripleSlashComment(currentSourceFile!.text, commentPos, commentEnd); + } + + // Source Maps + + function pipelineEmitWithSourceMap(hint: EmitHint, node: Node) { + const pipelinePhase = getNextPipelinePhase(PipelinePhase.SourceMaps, node); + if (isUnparsedSource(node) && node.sourceMapText !== undefined) { + const parsed = tryParseRawSourceMap(node.sourceMapText); + if (parsed) { + sourceMapGenerator!.appendSourceMap( + writer.getLine(), + writer.getColumn(), + parsed, + node.sourceMapPath!); + } + pipelinePhase(hint, node); + } + else { + const { pos, end, source = sourceMapSource } = getSourceMapRange(node); + const emitFlags = getEmitFlags(node); + if (node.kind !== SyntaxKind.NotEmittedStatement + && (emitFlags & EmitFlags.NoLeadingSourceMap) === 0 + && pos >= 0) { + emitSourcePos(source, skipSourceTrivia(source, pos)); + } + + if (emitFlags & EmitFlags.NoNestedSourceMaps) { + sourceMapsDisabled = true; + pipelinePhase(hint, node); + sourceMapsDisabled = false; + } + else { + pipelinePhase(hint, node); + } + + if (node.kind !== SyntaxKind.NotEmittedStatement + && (emitFlags & EmitFlags.NoTrailingSourceMap) === 0 + && end >= 0) { + emitSourcePos(source, end); + } + } + } + + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(source: SourceMapSource, pos: number): number { + return source.skipTrivia ? source.skipTrivia(pos) : skipTrivia(sourceMapSource.text, pos); + } + + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ + function emitPos(pos: number) { + if (sourceMapsDisabled || positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + + const { line: sourceLine, character: sourceCharacter } = getLineAndCharacterOfPosition(sourceMapSource, pos); + sourceMapGenerator!.addMapping( + writer.getLine(), + writer.getColumn(), + sourceMapSourceIndex, + sourceLine, + sourceCharacter, + /*nameIndex*/ undefined); + } + + function emitSourcePos(source: SourceMapSource, pos: number) { + if (source !== sourceMapSource) { + const savedSourceMapSource = sourceMapSource; + setSourceMapSource(source); + emitPos(pos); + setSourceMapSource(savedSourceMapSource); + } + else { + emitPos(pos); + } + } + + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node: Node | undefined, token: SyntaxKind, writer: (s: string) => void, tokenPos: number, emitCallback: (token: SyntaxKind, writer: (s: string) => void, tokenStartPos: number) => number) { + if (sourceMapsDisabled || node && isInJsonFile(node)) { + return emitCallback(token, writer, tokenPos); + } + + const emitNode = node && node.emitNode; + const emitFlags = emitNode && emitNode.flags || EmitFlags.None; + const range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + const source = range && range.source || sourceMapSource; + + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & EmitFlags.NoTokenLeadingSourceMaps) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + + tokenPos = emitCallback(token, writer, tokenPos); + + if (range) tokenPos = range.end; + if ((emitFlags & EmitFlags.NoTokenTrailingSourceMaps) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + + return tokenPos; + } + + function setSourceMapSource(source: SourceMapSource) { + if (sourceMapsDisabled) { + return; + } + + sourceMapSource = source; + + if (isJsonSourceMapSource(source)) { + return; + } + + sourceMapSourceIndex = sourceMapGenerator!.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator!.setSourceContent(sourceMapSourceIndex, source.text); + } + } + + function isJsonSourceMapSource(sourceFile: SourceMapSource) { + return fileExtensionIs(sourceFile.fileName, Extension.Json); + } } function createBracketsMap() { diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 984e6d59b2e..ec19d2c906c 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -68,13 +68,16 @@ namespace ts { /* @internal */ export function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier, isSingleQuote: boolean): StringLiteral; // tslint:disable-line unified-signatures /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ export function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; - export function createLiteral(value: number): NumericLiteral; + export function createLiteral(value: number | PseudoBigInt): NumericLiteral; export function createLiteral(value: boolean): BooleanLiteral; - export function createLiteral(value: string | number | boolean): PrimaryExpression; - export function createLiteral(value: string | number | boolean | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier, isSingleQuote?: boolean): PrimaryExpression { + export function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; + export function createLiteral(value: string | number | PseudoBigInt | boolean | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier, isSingleQuote?: boolean): PrimaryExpression { if (typeof value === "number") { return createNumericLiteral(value + ""); } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + return createBigIntLiteral(pseudoBigIntToString(value) + "n"); + } if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } @@ -93,6 +96,12 @@ namespace ts { return node; } + export function createBigIntLiteral(value: string): BigIntLiteral { + const node = createSynthesizedNode(SyntaxKind.BigIntLiteral); + node.text = value; + return node; + } + export function createStringLiteral(text: string): StringLiteral { const node = createSynthesizedNode(SyntaxKind.StringLiteral); node.text = text; @@ -235,7 +244,7 @@ namespace ts { // Modifiers - export function createModifier(kind: T) { + export function createModifier(kind: T): Token { return createToken(kind); } @@ -2170,6 +2179,56 @@ namespace ts { : node; } + // JSDoc + + /* @internal */ + export function createJSDocTypeExpression(type: TypeNode): JSDocTypeExpression { + const node = createSynthesizedNode(SyntaxKind.JSDocTypeExpression) as JSDocTypeExpression; + node.type = type; + return node; + } + + /* @internal */ + export function createJSDocTypeTag(typeExpression?: JSDocTypeExpression, comment?: string): JSDocTypeTag { + const tag = createJSDocTag(SyntaxKind.JSDocTypeTag, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + + /* @internal */ + export function createJSDocReturnTag(typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag { + const tag = createJSDocTag(SyntaxKind.JSDocReturnTag, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + + /* @internal */ + export function createJSDocParamTag(name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, comment?: string): JSDocParameterTag { + const tag = createJSDocTag(SyntaxKind.JSDocParameterTag, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + + /* @internal */ + export function createJSDocComment(comment?: string | undefined, tags?: NodeArray | undefined) { + const node = createSynthesizedNode(SyntaxKind.JSDocComment) as JSDoc; + node.comment = comment; + node.tags = tags; + return node; + } + + /* @internal */ + function createJSDocTag(kind: T["kind"], tagName: string): T { + const node = createSynthesizedNode(kind) as T; + node.tagName = createIdentifier(tagName); + return node; + } + // JSX export function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement) { @@ -3416,6 +3475,7 @@ namespace ts { return cacheIdentifiers; case SyntaxKind.ThisKeyword: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: return false; case SyntaxKind.ArrayLiteralExpression: diff --git a/src/compiler/inspectValue.ts b/src/compiler/inspectValue.ts new file mode 100644 index 00000000000..fab4a57ef1b --- /dev/null +++ b/src/compiler/inspectValue.ts @@ -0,0 +1,162 @@ +/* @internal */ +namespace ts { + export interface InspectValueOptions { + readonly fileNameToRequire: string; + } + + export const enum ValueKind { Const, Array, FunctionOrClass, Object } + export interface ValueInfoBase { + readonly name: string; + } + export type ValueInfo = ValueInfoSimple | ValueInfoArray | ValueInfoFunctionOrClass | ValueInfoObject; + export interface ValueInfoSimple extends ValueInfoBase { + readonly kind: ValueKind.Const; + readonly typeName: string; + readonly comment?: string | undefined; + } + export interface ValueInfoFunctionOrClass extends ValueInfoBase { + readonly kind: ValueKind.FunctionOrClass; + readonly source: string | number; // For a native function, this is the length. + readonly prototypeMembers: ReadonlyArray; + readonly namespaceMembers: ReadonlyArray; + } + export interface ValueInfoArray extends ValueInfoBase { + readonly kind: ValueKind.Array; + readonly inner: ValueInfo; + } + export interface ValueInfoObject extends ValueInfoBase { + readonly kind: ValueKind.Object; + readonly hasNontrivialPrototype: boolean; + readonly members: ReadonlyArray; + } + + export function inspectModule(fileNameToRequire: string): ValueInfo { + return inspectValue(removeFileExtension(getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + + export function inspectValue(name: string, value: unknown): ValueInfo { + return getValueInfo(name, value, getRecurser()); + } + + type Recurser = (obj: unknown, name: string, cbOk: () => T, cbFail: (isCircularReference: boolean, keyStack: ReadonlyArray) => T) => T; + function getRecurser(): Recurser { + const seen: unknown[] = []; + const nameStack: string[] = []; + return (obj, name, cbOk, cbFail) => { + if (seen.indexOf(obj) !== -1 || nameStack.length > 4) { + return cbFail(seen.indexOf(obj) !== -1, nameStack); + } + + seen.push(obj); + nameStack.push(name); + const res = cbOk(); + nameStack.pop(); + seen.pop(); + return res; + }; + } + + function getValueInfo(name: string, value: unknown, recurser: Recurser): ValueInfo { + return recurser(value, name, + (): ValueInfo => { + if (typeof value === "function") return getFunctionOrClassInfo(value as AnyFunction, name, recurser); + if (typeof value === "object") { + const builtin = getBuiltinType(name, value as object, recurser); + if (builtin !== undefined) return builtin; + const entries = getEntriesOfObject(value as object); + const hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; + const members = flatMap(entries, ({ key, value }) => getValueInfo(key, value, recurser)); + return { kind: ValueKind.Object, name, hasNontrivialPrototype, members }; + } + return { kind: ValueKind.Const, name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, + (isCircularReference, keyStack) => anyValue(name, ` ${isCircularReference ? "Circular reference" : "Too-deep object hierarchy"} from ${keyStack.join(".")}`)); + } + + function getFunctionOrClassInfo(fn: AnyFunction, name: string, recurser: Recurser): ValueInfoFunctionOrClass { + const prototypeMembers = getPrototypeMembers(fn, recurser); + const namespaceMembers = flatMap(getEntriesOfObject(fn), ({ key, value }) => getValueInfo(key, value, recurser)); + const toString = cast(Function.prototype.toString.call(fn), isString); + const source = stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: ValueKind.FunctionOrClass, name, source, namespaceMembers, prototypeMembers }; + } + + const builtins: () => ReadonlyMap = memoize(() => { + const map = createMap(); + for (const { key, value } of getEntriesOfObject(global)) { + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value as AnyConstructor); + } + } + return map; + }); + function getBuiltinType(name: string, value: object, recurser: Recurser): ValueInfo | undefined { + return isArray(value) + ? { name, kind: ValueKind.Array, inner: value.length && getValueInfo("element", first(value), recurser) || anyValue(name) } + : forEachEntry(builtins(), (builtin, builtinName): ValueInfo | undefined => + value instanceof builtin ? { kind: ValueKind.Const, name, typeName: builtinName } : undefined); + } + + function getPrototypeMembers(fn: AnyFunction, recurser: Recurser): ReadonlyArray { + const prototype = fn.prototype as unknown; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? emptyArray : mapDefined(getEntriesOfObject(prototype as object), ({ key, value }) => + key === "constructor" ? undefined : getValueInfo(key, value, recurser)); + } + + const ignoredProperties: ReadonlyArray = ["arguments", "caller", "constructor", "eval", "super_"]; + const reservedFunctionProperties: ReadonlyArray = Object.getOwnPropertyNames(noop); + interface ObjectEntry { readonly key: string; readonly value: unknown; } + function getEntriesOfObject(obj: object): ReadonlyArray { + const seen = createMap(); + const entries: ObjectEntry[] = []; + let chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (const key of Object.getOwnPropertyNames(chain)) { + if (!isJsPrivate(key) && + ignoredProperties.indexOf(key) === -1 && + (typeof obj !== "function" || reservedFunctionProperties.indexOf(key) === -1) && + // Don't add property from a higher prototype if it already exists in a lower one + addToSeen(seen, key)) { + const value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key, value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort((e1, e2) => compareStringsCaseSensitive(e1.key, e2.key)); + } + + function getFunctionLength(fn: AnyFunction): number { + return tryCast(safeGetPropertyOfObject(fn, "length"), isNumber) || 0; + } + + function safeGetPropertyOfObject(obj: object, key: string): unknown { + const desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + + function isNullOrUndefined(value: unknown): value is null | undefined { + return value == null; // tslint:disable-line + } + + function anyValue(name: string, comment?: string): ValueInfo { + return { kind: ValueKind.Const, name, typeName: "any", comment }; + } + + export function isJsPrivate(name: string): boolean { + return startsWith(name, "_"); + } + + function tryRequire(fileNameToRequire: string): unknown { + try { + return require(fileNameToRequire); + } + catch { + return undefined; + } + } +} diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 7fb308912c3..b8aa9fa2df4 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -24,6 +24,13 @@ namespace ts { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r: Resolved | undefined): PathAndExtension | undefined { + if (r) { + Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } + /** Result of trying to resolve a module. */ interface Resolved { path: string; @@ -55,6 +62,7 @@ namespace ts { TypeScript, /** '.ts', '.tsx', or '.d.ts' */ JavaScript, /** '.js' or '.jsx' */ Json, /** '.json' */ + TSConfig, /** '.json' with `tsconfig` used instead of `index` */ DtsOnly /** Only '.d.ts' */ } @@ -67,7 +75,7 @@ namespace ts { if (!resolved) { return undefined; } - Debug.assert(extensionIsTypeScript(resolved.extension)); + Debug.assert(extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } @@ -82,13 +90,16 @@ namespace ts { host: ModuleResolutionHost; compilerOptions: CompilerOptions; traceEnabled: boolean; + failedLookupLocations: Push; } /** Just the fields that we use for module resolution. */ interface PackageJsonPathFields { typings?: string; types?: string; + typesVersions?: MapLike>; main?: string; + tsconfig?: string; } interface PackageJson extends PackageJsonPathFields { @@ -96,48 +107,115 @@ namespace ts { version?: string; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes: boolean, jsonContent: PackageJsonPathFields, baseDirectory: string, state: ModuleResolutionState): string | undefined { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); + type MatchingKeys = K extends (TRecord[K] extends TMatch ? K : never) ? K : never; - function tryReadFromField(fieldName: "typings" | "types" | "main"): string | undefined { - if (!hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - - const fileName = jsonContent[fieldName]; - if (!isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - - const path = normalizePath(combinePaths(baseDirectory, fileName)); + function readPackageJsonField>(jsonContent: PackageJson, fieldName: K, typeOfTag: "string", state: ModuleResolutionState): PackageJson[K] | undefined; + function readPackageJsonField>(jsonContent: PackageJson, fieldName: K, typeOfTag: "object", state: ModuleResolutionState): PackageJson[K] | undefined; + function readPackageJsonField(jsonContent: PackageJson, fieldName: K, typeOfTag: "string" | "object", state: ModuleResolutionState): PackageJson[K] | undefined { + if (!hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + const value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } - /* @internal */ - export function readJson(path: string, host: { readFile(fileName: string): string | undefined }): object { - try { - const jsonText = host.readFile(path); - if (!jsonText) return {}; - const result = parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; - } - return result.config; + function readPackageJsonPathField(jsonContent: PackageJson, fieldName: K, baseDirectory: string, state: ModuleResolutionState): PackageJson[K] | undefined { + const fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) return; + const path = normalizePath(combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; + return path; + } + + function readPackageJsonTypesFields(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + + function readPackageJsonTSConfigField(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + + function readPackageJsonMainField(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + + function readPackageJsonTypesVersionsField(jsonContent: PackageJson, state: ModuleResolutionState) { + const typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) return; + + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + + return typesVersions; + } + + interface VersionPaths { + version: string; + paths: MapLike; + } + + function readPackageJsonTypesVersionPaths(jsonContent: PackageJson, state: ModuleResolutionState): VersionPaths | undefined { + const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) return; + + if (state.traceEnabled) { + for (const key in typesVersions) { + if (hasProperty(typesVersions, key) && !VersionRange.tryParse(key)) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + + const result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor); + } + return; + } + + const { version: bestVersionKey, paths: bestVersionPaths } = result; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "object", typeof bestVersionPaths); + } + return; + } + + return result; + } + + let typeScriptVersion: Version | undefined; + + /* @internal */ + export function getPackageJsonTypesVersionsPaths(typesVersions: MapLike>) { + if (!typeScriptVersion) typeScriptVersion = new Version(version); + + for (const key in typesVersions) { + if (!hasProperty(typesVersions, key)) continue; + + const keyRange = VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; + } } } @@ -186,9 +264,13 @@ namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations { + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations { const traceEnabled = isTraceEnabled(options, host); - const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled }; + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + const failedLookupLocations: string[] = []; + const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled, failedLookupLocations }; const typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { @@ -208,10 +290,11 @@ namespace ts { trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } + if (redirectedReference) { + trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } - const failedLookupLocations: string[] = []; - let resolved = primaryLookup(); let primary = true; if (!resolved) { @@ -221,14 +304,12 @@ namespace ts { let resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; if (resolved) { - if (!options.preserveSymlinks) { - resolved = { ...resolved, fileName: realPath(resolved.fileName, host, traceEnabled) }; - } - + const { fileName, packageId } = resolved; + const resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); if (traceEnabled) { - trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); + trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); } - resolvedTypeReferenceDirective = { primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; + resolvedTypeReferenceDirective = { primary, resolvedFileName, packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } return { resolvedTypeReferenceDirective, failedLookupLocations }; @@ -239,7 +320,7 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } - return forEach(typeRoots, typeRoot => { + return firstDefined(typeRoots, typeRoot => { const candidate = combinePaths(typeRoot, typeReferenceDirectiveName); const candidateDirectory = getDirectoryPath(candidate); const directoryExists = directoryProbablyExists(candidateDirectory, host); @@ -247,7 +328,7 @@ namespace ts { trace(host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } return resolvedTypeScriptOnly( - loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, + loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } @@ -266,8 +347,16 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - const result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - const resolvedFile = resolvedTypeScriptOnly(result && result.value); + let result: Resolved | undefined; + if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { + const searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; + } + else { + const { path: candidate } = normalizePathAndParts(combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)); + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + const resolvedFile = resolvedTypeScriptOnly(result); if (!resolvedFile && traceEnabled) { trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -304,14 +393,19 @@ namespace ts { if (host.directoryExists(root)) { for (const typeDirectivePath of host.getDirectories(root)) { const normalized = normalizePath(typeDirectivePath); - const packageJsonPath = pathToPackageJson(combinePaths(root, normalized)); + const packageJsonPath = combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword const isNotNeededPackage = host.fileExists(packageJsonPath) && (readJson(packageJsonPath, host) as PackageJson).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(getBaseFileName(normalized)); + const baseFileName = getBaseFileName(normalized); + + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== CharacterCodes.dot) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -326,7 +420,7 @@ namespace ts { * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ export interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string): Map; + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; } /** @@ -334,7 +428,7 @@ namespace ts { * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ export interface NonRelativeModuleNameResolutionCache { - getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; + getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } export interface PerModuleNameCache { @@ -344,40 +438,78 @@ namespace ts { export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache { return createModuleResolutionCacheWithMaps( - createMap>(), - createMap(), + createCacheWithRedirects(), + createCacheWithRedirects(), currentDirectory, getCanonicalFileName ); } + /*@internal*/ + export interface CacheWithRedirects { + ownMap: Map; + redirectsMap: Map>; + getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): Map; + clear(): void; + } + + /*@internal*/ + export function createCacheWithRedirects(): CacheWithRedirects { + const ownMap: Map = createMap(); + const redirectsMap: Map> = createMap(); + return { + ownMap, + redirectsMap, + getOrCreateMapOfCacheRedirects, + clear + }; + + function getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined) { + if (!redirectedReference) { + return ownMap; + } + const path = redirectedReference.sourceFile.path; + let redirects = redirectsMap.get(path); + if (!redirects) { + redirects = createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + /*@internal*/ export function createModuleResolutionCacheWithMaps( - directoryToModuleNameMap: Map>, - moduleNameToDirectoryMap: Map, + directoryToModuleNameMap: CacheWithRedirects>, + moduleNameToDirectoryMap: CacheWithRedirects, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName): ModuleResolutionCache { return { getOrCreateCacheForDirectory, getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName: string) { + function getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference) { const path = toPath(directoryName, currentDirectory, getCanonicalFileName); - let perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; + return getOrCreateCache>(directoryToModuleNameMap, redirectedReference, path, createMap); } - function getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache { + function getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache { Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName)); - let perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + + function getOrCreateCache(cacheWithRedirects: CacheWithRedirects, redirectedReference: ResolvedProjectReference | undefined, key: string, create: () => T): T { + const cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + let result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); } - return perModuleNameCache; + return result; } function createPerModuleNameCache(): PerModuleNameCache { @@ -459,13 +591,19 @@ namespace ts { return perFolderCache && perFolderCache.get(moduleName); } - export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } if (traceEnabled) { trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } const containingDirectory = getDirectoryPath(containingFile); - const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); let result = perFolderCache && perFolderCache.get(moduleName); if (result) { @@ -489,10 +627,10 @@ namespace ts { switch (moduleResolution) { case ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; case ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; default: return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`); @@ -502,7 +640,7 @@ namespace ts { perFolderCache.set(moduleName, result); if (!isExternalModuleNameRelative(moduleName)) { // put result in per-module name cache - cache!.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); + cache!.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); } } } @@ -527,7 +665,7 @@ namespace ts { * 'typings' entry or file 'index' with some supported extension * - Classic loader will only try to interpret '/a/b/c' as file. */ - type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined; + type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined; /** * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to @@ -590,18 +728,32 @@ namespace ts { * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ function tryLoadModuleUsingOptionalResolutionSettings(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, - failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { + state: ModuleResolutionState): Resolved | undefined { + + const resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) return resolved.value; if (!isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); + } + } + + function tryLoadModuleUsingPathsIfEligible(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState) { + const { baseUrl, paths } = state.compilerOptions; + if (baseUrl && paths && !pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); } } function tryLoadModuleUsingRootDirs(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, - failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { + state: ModuleResolutionState): Resolved | undefined { if (!state.compilerOptions.rootDirs) { return undefined; @@ -646,7 +798,7 @@ namespace ts { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - const resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -665,7 +817,7 @@ namespace ts { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate); } const baseDirectory = getDirectoryPath(candidate); - const resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -677,60 +829,19 @@ namespace ts { return undefined; } - function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined { + const { baseUrl } = state.compilerOptions; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - - // string is for exact match - let matchedPattern: Pattern | string | undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(getOwnKeys(state.compilerOptions.paths), moduleName); + const candidate = normalizePath(combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } - - if (matchedPattern) { - const matchedStar = isString(matchedPattern) ? undefined : matchedText(matchedPattern, moduleName); - const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - return forEach(state.compilerOptions.paths![matchedPatternText], subst => { - const path = matchedStar ? subst.replace("*", matchedStar) : subst; - const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl!, path)); - if (state.traceEnabled) { - trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - const extension = tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - const path = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path !== undefined) { - return noPackageId({ path, ext: extension }); - } - } - - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); - }); - } - else { - const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName)); - - if (state.traceEnabled) { - trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); - } - } - - export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { - return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + return loader(extensions, candidate, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); } /** @@ -739,26 +850,41 @@ namespace ts { * Throws an error if the module can't be resolved. */ /* @internal */ - export function resolveJavaScriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { - const { resolvedModule, failedLookupLocations } = - nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + export function resolveJSModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { + const { resolvedModule, failedLookupLocations } = tryResolveJSModuleWorker(moduleName, initialDir, host); if (!resolvedModule) { throw new Error(`Could not resolve JS module '${moduleName}' starting at '${initialDir}'. Looked in: ${failedLookupLocations.join(", ")}`); } return resolvedModule.resolvedFileName; } - function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, jsOnly: boolean): ResolvedModuleWithFailedLookupLocations { + /* @internal */ + export function tryResolveJSModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string | undefined { + const { resolvedModule } = tryResolveJSModuleWorker(moduleName, initialDir, host); + return resolvedModule && resolvedModule.resolvedFileName; + } + + const jsOnlyExtensions = [Extensions.JavaScript]; + const tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + const tsPlusJsonExtensions = [...tsExtensions, Extensions.Json]; + const tsconfigExtensions = [Extensions.TSConfig]; + function tryResolveJSModuleWorker(moduleName: string, initialDir: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); + } + + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + /* @internal */ export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, lookupConfig?: boolean): ResolvedModuleWithFailedLookupLocations; // tslint:disable-line unified-signatures + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, lookupConfig?: boolean): ResolvedModuleWithFailedLookupLocations { + return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); + } + + function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, extensions: Extensions[], redirectedReference: ResolvedProjectReference | undefined): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; - const result = jsOnly ? - tryResolve(Extensions.JavaScript) : - (tryResolve(Extensions.TypeScript) || - tryResolve(Extensions.JavaScript) || - (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); + const result = forEach(extensions, ext => tryResolve(ext)); if (result && result.value) { const { resolved, isExternalLibraryImport } = result.value; return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); @@ -766,17 +892,17 @@ namespace ts { return { resolvedModule: undefined, failedLookupLocations }; function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> { - const loader: ResolutionKindSpecificLoader = (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); - const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); + const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { - return toSearchResult({ resolved, isExternalLibraryImport: stringContains(resolved.path, nodeModulesPathPart) }); + return toSearchResult({ resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); } if (!isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - const resolved = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + const resolved = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); if (!resolved) return undefined; let resolvedValue = resolved.value; @@ -790,7 +916,7 @@ namespace ts { } else { const { path: candidate, parts } = normalizePathAndParts(combinePaths(containingDirectory, moduleName)); - const resolved = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + const resolved = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved && toSearchResult({ resolved, isExternalLibraryImport: contains(parts, "node_modules") }); } @@ -810,7 +936,7 @@ namespace ts { return real; } - function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson: boolean): Resolved | undefined { + function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson: boolean): Resolved | undefined { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } @@ -824,10 +950,11 @@ namespace ts { onlyRecordFailures = true; } } - const resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + const resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { const nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - const packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + const packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + const packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } @@ -840,11 +967,15 @@ namespace ts { onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ export const nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + export function pathContainsNodeModules(path: string): boolean { + return stringContains(path, nodeModulesPathPart); + } /** * This will be called on the successfully resolved path from `loadModuleFromFile`. @@ -886,52 +1017,46 @@ namespace ts { if (endsWith(path, ".d.ts")) { return path; } - if (endsWith(path, "/index")) { + if (path === "index" || endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean }): boolean { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - - function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { - if (extensions === Extensions.Json) { + function loadModuleFromFile(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { const extensionLess = tryRemoveExtension(candidate, Extension.Json); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (hasJavaScriptFileExtension(candidate)) { + if (hasJSFileExtension(candidate)) { const extensionless = removeFileExtension(candidate); if (state.traceEnabled) { const extension = candidate.substring(extensionless.length); trace(state.host, Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate: string, extensions: Extensions, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { + function tryAddingExtensions(candidate: string, extensions: Extensions, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing const directory = getDirectoryPath(candidate); @@ -947,18 +1072,19 @@ namespace ts { return tryExtension(Extension.Ts) || tryExtension(Extension.Tsx) || tryExtension(Extension.Dts); case Extensions.JavaScript: return tryExtension(Extension.Js) || tryExtension(Extension.Jsx); + case Extensions.TSConfig: case Extensions.Json: return tryExtension(Extension.Json); } function tryExtension(ext: Extension): PathAndExtension | undefined { - const path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + const path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path, ext }; } } /** Return the file if it exists. */ - function tryFile(fileName: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined { + function tryFile(fileName: string, onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -972,48 +1098,40 @@ namespace ts { } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true) { - const { packageJsonContent, packageId } = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true) { + const packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + const packageId = packageInfo && packageInfo.packageId; + const packageJsonContent = packageInfo && packageInfo.packageJsonContent; + const versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, packageJsonContent: PackageJsonPathFields | undefined): PathAndExtension | undefined { - const fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + interface PackageJsonInfo { + packageJsonContent: PackageJsonPathFields | undefined; + packageId: PackageId | undefined; + versionPaths: VersionPaths | undefined; } - function getPackageJsonInfo( - nodeModuleDirectory: string, - subModuleName: string, - failedLookupLocations: Push, - onlyRecordFailures: boolean, - state: ModuleResolutionState, - ): { found: boolean, packageJsonContent: PackageJsonPathFields | undefined, packageId: PackageId | undefined } { + function getPackageJsonInfo(packageDirectory: string, subModuleName: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PackageJsonInfo | undefined { const { host, traceEnabled } = state; - const directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - const packageJsonPath = pathToPackageJson(nodeModuleDirectory); + const directoryExists = !onlyRecordFailures && directoryProbablyExists(packageDirectory, host); + const packageJsonPath = combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { const packageJsonContent = readJson(packageJsonPath, host) as PackageJson; if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - const path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + const path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - const jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - const potentialSubModule = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (forEach(supportedJavascriptExtensions, extension => + const jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + const potentialSubModule = jsPath.substring(packageDirectory.length + 1); + subModuleName = (forEach(supportedJSExtensions, extension => tryRemoveExtension(potentialSubModule, extension)) || potentialSubModule) + Extension.Dts; } else { @@ -1021,9 +1139,12 @@ namespace ts { } } } + if (!endsWith(subModuleName, Extension.Dts)) { subModuleName = addExtensionAndIndex(subModuleName); } + + const versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); const packageId: PackageId | undefined = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName, version: packageJsonContent.version } : undefined; @@ -1035,54 +1156,80 @@ namespace ts { trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent, packageId }; + + return { packageJsonContent, packageId, versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath); } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent: PackageJsonPathFields, extensions: Extensions, candidate: string, failedLookupLocations: Push, state: ModuleResolutionState): PathAndExtension | undefined { - let file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { - // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + function loadNodeModuleFromDirectoryWorker(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, jsonContent: PackageJsonPathFields | undefined, versionPaths: VersionPaths | undefined): PathAndExtension | undefined { + let packageFile: string | undefined; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return Debug.assertNever(extensions); + } + } + + const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => { + const fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + const resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(file), state.host); - const fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - const resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + const nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + + const onlyRecordFailuresForPackageFile = packageFile ? !directoryProbablyExists(getDirectoryPath(packageFile), state.host) : undefined; + const onlyRecordFailuresForIndex = onlyRecordFailures || !directoryProbablyExists(candidate, state.host); + const indexPath = combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); + + if (versionPaths && (!packageFile || containsPath(candidate, packageFile))) { + const moduleName = getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, moduleName); + } + const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - const nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - const result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + const packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile!, state)); + if (packageFileResult) return packageFileResult; + + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ @@ -1096,6 +1243,7 @@ namespace ts { switch (extensions) { case Extensions.JavaScript: return extension === Extension.Js || extension === Extension.Jsx; + case Extensions.TSConfig: case Extensions.Json: return extension === Extension.Json; case Extensions.TypeScript: @@ -1105,34 +1253,8 @@ namespace ts { } } - function pathToPackageJson(directory: string): string { - return combinePaths(directory, "package.json"); - } - - function loadModuleFromNodeModulesFolder(extensions: Extensions, moduleName: string, nodeModulesFolder: string, nodeModulesFolderExists: boolean, failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { - const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - let packageJsonContent: PackageJsonPathFields | undefined; - let packageId: PackageId | undefined; - const packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - ({ packageJsonContent, packageId } = packageInfo); - } - else { - const { packageName, rest } = getPackageName(moduleName); - if (rest !== "") { // If "rest" is empty, we just did this search above. - const packageRootPath = combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - const pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } - /* @internal */ - export function getPackageName(moduleName: string): { packageName: string, rest: string } { + export function parsePackageName(moduleName: string): { packageName: string, rest: string } { let idx = moduleName.indexOf(directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(directorySeparator, idx + 1); @@ -1140,40 +1262,40 @@ namespace ts { return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - function loadModuleFromNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); - } - function loadModuleFromNodeModulesAtTypes(moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState): SearchResult { - // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + function loadModuleFromNearestNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined): SearchResult { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); } - function loadModuleFromNodeModulesWorker(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { - const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName: string, directory: string, state: ModuleResolutionState): SearchResult { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); + } + + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, typesScopeOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined): SearchResult { + const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); return forEachAncestorDirectory(normalizeSlashes(directory), ancestorDirectory => { if (getBaseFileName(ancestorDirectory) !== "node_modules") { - const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly = false): Resolved | undefined { + function loadModuleFromImmediateNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, typesScopeOnly: boolean): Resolved | undefined { const nodeModulesFolder = combinePaths(directory, "node_modules"); const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - const packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + const packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { const nodeModulesAtTypes = combinePaths(nodeModulesFolder, "@types"); let nodeModulesAtTypesExists = nodeModulesFolderExists; if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes, state.host)) { @@ -1182,7 +1304,84 @@ namespace ts { } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes, nodeModulesAtTypesExists, state); + } + } + + function loadModuleFromSpecificNodeModulesDirectory(extensions: Extensions, moduleName: string, nodeModulesDirectory: string, nodeModulesDirectoryExists: boolean, state: ModuleResolutionState): Resolved | undefined { + const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName)); + + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + let packageJsonContent: PackageJsonPathFields | undefined; + let packageId: PackageId | undefined; + let versionPaths: VersionPaths | undefined; + + const packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + ({ packageJsonContent, packageId, versionPaths } = packageInfo); + const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + + const fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + + const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => { + const pathAndExtension = + loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + + const { packageName, rest } = parsePackageName(moduleName); + if (rest !== "") { // If "rest" is empty, we just did this search above. + const packageDirectory = combinePaths(nodeModulesDirectory, packageName); + + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + const packageInfo = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo) ({ packageId, versionPaths } = packageInfo); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, rest); + } + const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host); + const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + + function tryLoadModuleUsingPaths(extensions: Extensions, moduleName: string, baseDirectory: string, paths: MapLike, loader: ResolutionKindSpecificLoader, onlyRecordFailures: boolean, state: ModuleResolutionState): SearchResult { + const matchedPattern = matchPatternOrExact(getOwnKeys(paths), moduleName); + if (matchedPattern) { + const matchedStar = isString(matchedPattern) ? undefined : matchedText(matchedPattern, moduleName); + const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + const resolved = forEach(paths[matchedPatternText], subst => { + const path = matchedStar ? subst.replace("*", matchedStar) : subst; + const candidate = normalizePath(combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + const extension = tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + const path = tryFile(candidate, onlyRecordFailures, state); + if (path !== undefined) { + return noPackageId({ path, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } @@ -1190,8 +1389,8 @@ namespace ts { const mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName: string, state: ModuleResolutionState): string { - const mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName: string, state: ModuleResolutionState): string { + const mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -1200,11 +1399,11 @@ namespace ts { /* @internal */ export function getTypesPackageName(packageName: string): string { - return `@types/${getMangledNameForScopedPackage(packageName)}`; + return `@types/${mangleScopedPackageName(packageName)}`; } /* @internal */ - export function getMangledNameForScopedPackage(packageName: string): string { + export function mangleScopedPackageName(packageName: string): string { if (startsWith(packageName, "@")) { const replaceSlash = packageName.replace(directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -1215,36 +1414,36 @@ namespace ts { } /* @internal */ - export function getPackageNameFromAtTypesDirectory(mangledName: string): string { + export function getPackageNameFromTypesPackageName(mangledName: string): string { const withoutAtTypePrefix = removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } /* @internal */ - export function getUnmangledNameForScopedPackage(typesPackageName: string): string { + export function unmangleScopedPackageName(typesPackageName: string): string { return stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) : typesPackageName; } - function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, traceEnabled: boolean, host: ModuleResolutionHost, failedLookupLocations: Push): SearchResult { + function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, state: ModuleResolutionState): SearchResult { const result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push(...result.failedLookupLocations); + state.failedLookupLocations.push(...result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } - export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations { + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; const failedLookupLocations: string[] = []; + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; const containingDirectory = getDirectoryPath(containingFile); const resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); @@ -1252,33 +1451,33 @@ namespace ts { return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions: Extensions): SearchResult { - const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } if (!isExternalModuleNameRelative(moduleName)) { - const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); // Climb up parent directories looking for a module. const resolved = forEachAncestorDirectory(containingDirectory, directory => { - const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } const searchName = normalizePath(combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved) { return resolved; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -1293,9 +1492,9 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; const failedLookupLocations: string[] = []; - const resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; + const resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index eda480d032c..f5bac45f6ab 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -30,7 +30,7 @@ namespace ts.moduleSpecifiers { function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpecifier: string): Preferences { return { relativePreference: isExternalModuleNameRelative(oldImportSpecifier) ? RelativePreference.Relative : RelativePreference.NonRelative, - ending: hasJavaScriptOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension + ending: hasJSOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension : getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs || endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal, }; } @@ -139,7 +139,7 @@ namespace ts.moduleSpecifiers { return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; } - function countPathComponents(path: string): number { + export function countPathComponents(path: string): number { let count = 0; for (let i = startsWith(path, "./") ? 2 : 0; i < path.length; i++) { if (path.charCodeAt(i) === CharacterCodes.slash) count++; @@ -148,7 +148,7 @@ namespace ts.moduleSpecifiers { } function usesJsExtensionOnImports({ imports }: SourceFile): boolean { - return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJavaScriptOrJsonFileExtension(text) : undefined) || false; + return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJSOrJsonFileExtension(text) : undefined) || false; } function stringsEqual(a: string, b: string, getCanonicalFileName: GetCanonicalFileName): boolean { @@ -203,7 +203,7 @@ namespace ts.moduleSpecifiers { return; // Don't want to a package to globally import from itself } - const target = targets.find(t => compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === Comparison.EqualTo); + const target = find(targets, t => compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === Comparison.EqualTo); if (target === undefined) return; const relative = getRelativePathFromDirectory(resolved, target, getCanonicalFileName); @@ -235,7 +235,8 @@ namespace ts.moduleSpecifiers { const suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && startsWith(relativeToBaseUrl, prefix) && - endsWith(relativeToBaseUrl, suffix)) { + endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === removeTrailingDirectorySeparator(prefix)) { const matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -259,11 +260,34 @@ namespace ts.moduleSpecifiers { } function tryGetModuleNameAsNodeModule(moduleFileName: string, { getCanonicalFileName, sourceDirectory }: Info, host: ModuleSpecifierResolutionHost, options: CompilerOptions): string | undefined { + if (!host.fileExists || !host.readFile) { + return undefined; + } const parts: NodeModulePathParts = getNodeModulePathParts(moduleFileName)!; if (!parts) { return undefined; } + const packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + const packageJsonPath = combinePaths(packageRootPath, "package.json"); + const packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)!) + : undefined; + const versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + const subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + const fromPaths = tryGetModuleNameFromPaths( + removeFileExtension(subModuleName), + removeExtensionAndIndexPostFix(subModuleName, Ending.Minimal, options), + versionPaths.paths + ); + if (fromPaths !== undefined) { + moduleFileName = combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } + // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name @@ -274,23 +298,18 @@ namespace ts.moduleSpecifiers { // If the module was found in @types, get the actual Node package name const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); - const packageName = getPackageNameFromAtTypesDirectory(nodeModulesDirectoryName); + const packageName = getPackageNameFromTypesPackageName(nodeModulesDirectoryName); // For classic resolution, only allow importing from node_modules/@types, not other node_modules return getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path: string): string { // If the file is the main module, it can be imported by the package name - const packageRootPath = path.substring(0, parts.packageRootIndex); - const packageJsonPath = combinePaths(packageRootPath, "package.json"); - if (host.fileExists!(packageJsonPath)) { // TODO: GH#18217 - const packageJsonContent = JSON.parse(host.readFile!(packageJsonPath)!); - if (packageJsonContent) { - const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -309,11 +328,12 @@ namespace ts.moduleSpecifiers { } function tryGetAnyFileFromPath(host: ModuleSpecifierResolutionHost, path: string) { + if (!host.fileExists) return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory const extensions = getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: ScriptKind.JSON }]); for (const e of extensions) { const fullPath = path + e; - if (host.fileExists!(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -399,13 +419,13 @@ namespace ts.moduleSpecifiers { case Ending.Index: return noExtension; case Ending.JsExtension: - return noExtension + getJavaScriptExtensionForFile(fileName, options); + return noExtension + getJSExtensionForFile(fileName, options); default: return Debug.assertNever(ending); } } - function getJavaScriptExtensionForFile(fileName: string, options: CompilerOptions): Extension { + function getJSExtensionForFile(fileName: string, options: CompilerOptions): Extension { const ext = extensionFromPath(fileName); switch (ext) { case Extension.Ts: diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 1405428458f..92792c7a1a2 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -462,52 +462,46 @@ namespace ts { return visitNodes(cbNode, cbNodes, (node).tags); case SyntaxKind.JSDocParameterTag: case SyntaxKind.JSDocPropertyTag: - if ((node as JSDocPropertyLikeTag).isNameFirst) { - return visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).typeExpression); - } - else { - return visitNode(cbNode, (node).typeExpression) || - visitNode(cbNode, (node).name); - } - case SyntaxKind.JSDocReturnTag: - return visitNode(cbNode, (node).typeExpression); - case SyntaxKind.JSDocTypeTag: - return visitNode(cbNode, (node).typeExpression); + return visitNode(cbNode, (node as JSDocTag).tagName) || + ((node as JSDocPropertyLikeTag).isNameFirst + ? visitNode(cbNode, (node).name) || + visitNode(cbNode, (node).typeExpression) + : visitNode(cbNode, (node).typeExpression) || + visitNode(cbNode, (node).name)); case SyntaxKind.JSDocAugmentsTag: - return visitNode(cbNode, (node).class); + return visitNode(cbNode, (node as JSDocTag).tagName) || + visitNode(cbNode, (node).class); case SyntaxKind.JSDocTemplateTag: - return visitNode(cbNode, (node).constraint) || visitNodes(cbNode, cbNodes, (node).typeParameters); + return visitNode(cbNode, (node as JSDocTag).tagName) || + visitNode(cbNode, (node).constraint) || + visitNodes(cbNode, cbNodes, (node).typeParameters); case SyntaxKind.JSDocTypedefTag: - if ((node as JSDocTypedefTag).typeExpression && - (node as JSDocTypedefTag).typeExpression!.kind === SyntaxKind.JSDocTypeExpression) { - return visitNode(cbNode, (node).typeExpression) || - visitNode(cbNode, (node).fullName); - } - else { - return visitNode(cbNode, (node).fullName) || - visitNode(cbNode, (node).typeExpression); - } + return visitNode(cbNode, (node as JSDocTag).tagName) || + ((node as JSDocTypedefTag).typeExpression && + (node as JSDocTypedefTag).typeExpression!.kind === SyntaxKind.JSDocTypeExpression + ? visitNode(cbNode, (node).typeExpression) || + visitNode(cbNode, (node).fullName) + : visitNode(cbNode, (node).fullName) || + visitNode(cbNode, (node).typeExpression)); case SyntaxKind.JSDocCallbackTag: - return visitNode(cbNode, (node as JSDocCallbackTag).fullName) || + return visitNode(cbNode, (node as JSDocTag).tagName) || + visitNode(cbNode, (node as JSDocCallbackTag).fullName) || visitNode(cbNode, (node as JSDocCallbackTag).typeExpression); + case SyntaxKind.JSDocReturnTag: + case SyntaxKind.JSDocTypeTag: case SyntaxKind.JSDocThisTag: - return visitNode(cbNode, (node as JSDocThisTag).typeExpression); case SyntaxKind.JSDocEnumTag: - return visitNode(cbNode, (node as JSDocEnumTag).typeExpression); + return visitNode(cbNode, (node as JSDocTag).tagName) || + visitNode(cbNode, (node as JSDocReturnTag | JSDocTypeTag | JSDocThisTag | JSDocEnumTag).typeExpression); case SyntaxKind.JSDocSignature: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - forEach((node).typeParameters, cbNode) || + return forEach((node).typeParameters, cbNode) || forEach((node).parameters, cbNode) || visitNode(cbNode, (node).type); case SyntaxKind.JSDocTypeLiteral: - if ((node as JSDocTypeLiteral).jsDocPropertyTags) { - for (const tag of (node as JSDocTypeLiteral).jsDocPropertyTags!) { - visitNode(cbNode, tag); - } - } - return; + return forEach((node as JSDocTypeLiteral).jsDocPropertyTags, cbNode); + case SyntaxKind.JSDocTag: + case SyntaxKind.JSDocClassTag: + return visitNode(cbNode, (node as JSDocTag).tagName); case SyntaxKind.PartiallyEmittedExpression: return visitNode(cbNode, (node).expression); } @@ -1486,7 +1480,15 @@ namespace ts { // which would be a candidate for improved error reporting. return token() === SyntaxKind.OpenBracketToken || isLiteralPropertyName(); case ParsingContext.ObjectLiteralMembers: - return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.AsteriskToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName(); + switch (token()) { + case SyntaxKind.OpenBracketToken: + case SyntaxKind.AsteriskToken: + case SyntaxKind.DotDotDotToken: + case SyntaxKind.DotToken: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case ParsingContext.RestProperties: return isLiteralPropertyName(); case ParsingContext.ObjectBindingElements: @@ -1514,8 +1516,10 @@ namespace ts { case ParsingContext.TypeParameters: return isIdentifier(); case ParsingContext.ArrayLiteralMembers: - if (token() === SyntaxKind.CommaToken) { - return true; + switch (token()) { + case SyntaxKind.CommaToken: + case SyntaxKind.DotToken: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; } // falls through case ParsingContext.ArgumentExpressions: @@ -1717,6 +1721,8 @@ namespace ts { } function currentNode(parsingContext: ParsingContext): Node | undefined { + // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. + // // If there is an outstanding parse error that we've encountered, but not attached to // some node, then we cannot get a node from the old source tree. This is because we // want to mark the next node we encounter as being unusable. @@ -1724,30 +1730,17 @@ namespace ts { // Note: This may be too conservative. Perhaps we could reuse the node and set the bit // on it (or its leftmost child) as having the error. For now though, being conservative // is nice and likely won't ever affect perf. - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - - if (!syntaxCursor) { - // if we don't have a cursor, we could never return a node from the old tree. + if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } const node = syntaxCursor.currentNode(scanner.getStartPos()); // Can't reuse a missing node. - if (nodeIsMissing(node)) { - return undefined; - } - // Can't reuse a node that intersected the change range. - if (node.intersectsChange) { - return undefined; - } - // Can't reuse a node that contains a parse error. This is necessary so that we // produce the same set of errors again. - if (containsParseError(node)) { + if (nodeIsMissing(node) || node.intersectsChange || containsParseError(node)) { return undefined; } @@ -1788,6 +1781,23 @@ namespace ts { return node; } + function isReusableParsingContext(parsingContext: ParsingContext): boolean { + switch (parsingContext) { + case ParsingContext.ClassMembers: + case ParsingContext.SwitchClauses: + case ParsingContext.SourceElements: + case ParsingContext.BlockStatements: + case ParsingContext.SwitchClauseStatements: + case ParsingContext.EnumMembers: + case ParsingContext.TypeMembers: + case ParsingContext.VariableDeclarations: + case ParsingContext.JSDocParameters: + case ParsingContext.Parameters: + return true; + } + return false; + } + function canReuseNode(node: Node, parsingContext: ParsingContext): boolean { switch (parsingContext) { case ParsingContext.ClassMembers: @@ -1814,25 +1824,23 @@ namespace ts { case ParsingContext.Parameters: return isReusableParameter(node); - case ParsingContext.RestProperties: - return false; - // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case ParsingContext.HeritageClauses: + + // case ParsingContext.HeritageClauses: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case ParsingContext.TypeParameters: + // case ParsingContext.TypeParameters: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case ParsingContext.TupleElementTypes: + // case ParsingContext.TupleElementTypes: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. @@ -1841,28 +1849,28 @@ namespace ts { // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case ParsingContext.TypeArguments: + // case ParsingContext.TypeArguments: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. - case ParsingContext.ArgumentExpressions: + // case ParsingContext.ArgumentExpressions: // This is not safe to reuse for the same reason as the 'AssignmentExpression' // cases. i.e. a property assignment may end with an expression, and thus might // have lookahead far beyond it's old node. - case ParsingContext.ObjectLiteralMembers: + // case ParsingContext.ObjectLiteralMembers: // This is probably not safe to reuse. There can be speculative parsing with // type names in a heritage clause. There can be generic names in the type // name list, and there can be left hand side expressions (which can have type // arguments.) - case ParsingContext.HeritageClauseElement: + // case ParsingContext.HeritageClauseElement: // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes // on any given element. Same for children. - case ParsingContext.JsxAttributes: - case ParsingContext.JsxChildren: + // case ParsingContext.JsxAttributes: + // case ParsingContext.JsxChildren: } @@ -2241,8 +2249,7 @@ namespace ts { function parseLiteralLikeNode(kind: SyntaxKind): LiteralExpression | LiteralLikeNode { const node = createNode(kind); - const text = scanner.getTokenValue(); - node.text = text; + node.text = scanner.getTokenValue(); if (scanner.hasExtendedUnicodeEscape()) { node.hasExtendedUnicodeEscape = true; @@ -2886,8 +2893,9 @@ namespace ts { return finishNode(node); } - function nextTokenIsNumericLiteral() { - return nextToken() === SyntaxKind.NumericLiteral; + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === SyntaxKind.NumericLiteral || token() === SyntaxKind.BigIntLiteral; } function parseNonArrayType(): TypeNode { @@ -2896,6 +2904,7 @@ namespace ts { case SyntaxKind.UnknownKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.UndefinedKeyword: @@ -2916,11 +2925,12 @@ namespace ts { case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: return parseLiteralTypeNode(); case SyntaxKind.MinusToken: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); case SyntaxKind.VoidKeyword: case SyntaxKind.NullKeyword: return parseTokenNode(); @@ -2954,6 +2964,7 @@ namespace ts { case SyntaxKind.UnknownKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.UniqueKeyword: @@ -2971,6 +2982,7 @@ namespace ts { case SyntaxKind.NewKeyword: case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.ObjectKeyword: @@ -2984,7 +2996,7 @@ namespace ts { case SyntaxKind.FunctionKeyword: return !inStartOfParameter; case SyntaxKind.MinusToken: - return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); case SyntaxKind.OpenParenToken: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. @@ -3209,6 +3221,7 @@ namespace ts { case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TemplateHead: @@ -4620,6 +4633,7 @@ namespace ts { function parsePrimaryExpression(): PrimaryExpression { switch (token()) { case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: return parseLiteralNode(); @@ -4734,8 +4748,7 @@ namespace ts { // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - const isShorthandPropertyAssignment = - tokenIsIdentifier && (token() === SyntaxKind.CommaToken || token() === SyntaxKind.CloseBraceToken || token() === SyntaxKind.EqualsToken); + const isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== SyntaxKind.ColonToken); if (isShorthandPropertyAssignment) { node.kind = SyntaxKind.ShorthandPropertyAssignment; const equalsToken = parseOptionalToken(SyntaxKind.EqualsToken); @@ -5136,7 +5149,7 @@ namespace ts { function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.NumericLiteral || token() === SyntaxKind.StringLiteral) && !scanner.hasPrecedingLineBreak(); + return (tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.NumericLiteral || token() === SyntaxKind.BigIntLiteral || token() === SyntaxKind.StringLiteral) && !scanner.hasPrecedingLineBreak(); } function isDeclaration(): boolean { @@ -6314,7 +6327,7 @@ namespace ts { // Parses out a JSDoc type expression. export function parseJSDocTypeExpression(mayOmitBraces?: boolean): JSDocTypeExpression { - const result = createNode(SyntaxKind.JSDocTypeExpression, scanner.getTokenPos()); + const result = createNode(SyntaxKind.JSDocTypeExpression); const hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(SyntaxKind.OpenBraceToken); result.type = doInsideOfContext(NodeFlags.JSDoc, parseJSDocType); @@ -6447,13 +6460,6 @@ namespace ts { indent += asterisk.length; } break; - case SyntaxKind.Identifier: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = JSDocState.SavingComments; - break; case SyntaxKind.WhitespaceTrivia: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin const whitespace = scanner.getTokenText(); @@ -6468,7 +6474,9 @@ namespace ts { case SyntaxKind.EndOfFileToken: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = JSDocState.SavingComments; pushComment(scanner.getTokenText()); break; @@ -6544,51 +6552,50 @@ namespace ts { function parseTag(indent: number) { Debug.assert(token() === SyntaxKind.AtToken); - const atToken = createNode(SyntaxKind.AtToken, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); + const start = scanner.getTokenPos(); nextJSDocToken(); - const tagName = parseJSDocIdentifierName(); + const tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); let tag: JSDocTag | undefined; switch (tagName.escapedText) { case "augments": case "extends": - tag = parseAugmentsTag(atToken, tagName); + tag = parseAugmentsTag(start, tagName); break; case "class": case "constructor": - tag = parseClassTag(atToken, tagName); + tag = parseClassTag(start, tagName); break; case "this": - tag = parseThisTag(atToken, tagName); + tag = parseThisTag(start, tagName); break; case "enum": - tag = parseEnumTag(atToken, tagName); + tag = parseEnumTag(start, tagName); break; case "arg": case "argument": case "param": - return parseParameterOrPropertyTag(atToken, tagName, PropertyLikeParse.Parameter, indent); + return parseParameterOrPropertyTag(start, tagName, PropertyLikeParse.Parameter, indent); case "return": case "returns": - tag = parseReturnTag(atToken, tagName); + tag = parseReturnTag(start, tagName); break; case "template": - tag = parseTemplateTag(atToken, tagName); + tag = parseTemplateTag(start, tagName); break; case "type": - tag = parseTypeTag(atToken, tagName); + tag = parseTypeTag(start, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName, indent); + tag = parseTypedefTag(start, tagName, indent); break; case "callback": - tag = parseCallbackTag(atToken, tagName, indent); + tag = parseCallbackTag(start, tagName, indent); break; default: - tag = parseUnknownTag(atToken, tagName); + tag = parseUnknownTag(start, tagName); break; } @@ -6671,9 +6678,8 @@ namespace ts { return comments.length === 0 ? undefined : comments.join(""); } - function parseUnknownTag(atToken: AtToken, tagName: Identifier) { - const result = createNode(SyntaxKind.JSDocTag, atToken.pos); - result.atToken = atToken; + function parseUnknownTag(start: number, tagName: Identifier) { + const result = createNode(SyntaxKind.JSDocTag, start); result.tagName = tagName; return finishNode(result); } @@ -6730,7 +6736,7 @@ namespace ts { } } - function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number | undefined): JSDocParameterTag | JSDocPropertyTag { + function parseParameterOrPropertyTag(start: number, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag { let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -6743,16 +6749,14 @@ namespace ts { } const result = target === PropertyLikeParse.Property ? - createNode(SyntaxKind.JSDocPropertyTag, atToken.pos) : - createNode(SyntaxKind.JSDocParameterTag, atToken.pos); - let comment: string | undefined; - if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - const nestedTypeLiteral = target !== PropertyLikeParse.CallbackParameter && parseNestedTypeLiteral(typeExpression, name, target); + createNode(SyntaxKind.JSDocPropertyTag, start) : + createNode(SyntaxKind.JSDocParameterTag, start); + const comment = parseTagComments(indent + scanner.getStartPos() - start); + const nestedTypeLiteral = target !== PropertyLikeParse.CallbackParameter && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; } - result.atToken = atToken; result.tagName = tagName; result.typeExpression = typeExpression; result.name = name; @@ -6762,14 +6766,14 @@ namespace ts { return finishNode(result); } - function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression | undefined, name: EntityName, target: PropertyLikeParse) { + function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression | undefined, name: EntityName, target: PropertyLikeParse, indent: number) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { const typeLiteralExpression = createNode(SyntaxKind.JSDocTypeExpression, scanner.getTokenPos()); let child: JSDocPropertyLikeTag | JSDocTypeTag | false; let jsdocTypeLiteral: JSDocTypeLiteral; const start = scanner.getStartPos(); let children: JSDocPropertyLikeTag[] | undefined; - while (child = tryParse(() => parseChildParameterOrPropertyTag(target, name))) { + while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent, name))) { if (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) { children = append(children, child); } @@ -6786,33 +6790,30 @@ namespace ts { } } - function parseReturnTag(atToken: AtToken, tagName: Identifier): JSDocReturnTag { + function parseReturnTag(start: number, tagName: Identifier): JSDocReturnTag { if (forEach(tags, t => t.kind === SyntaxKind.JSDocReturnTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), Diagnostics._0_tag_already_specified, tagName.escapedText); } - const result = createNode(SyntaxKind.JSDocReturnTag, atToken.pos); - result.atToken = atToken; + const result = createNode(SyntaxKind.JSDocReturnTag, start); result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function parseTypeTag(atToken: AtToken, tagName: Identifier): JSDocTypeTag { + function parseTypeTag(start: number, tagName: Identifier): JSDocTypeTag { if (forEach(tags, t => t.kind === SyntaxKind.JSDocTypeTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), Diagnostics._0_tag_already_specified, tagName.escapedText); } - const result = createNode(SyntaxKind.JSDocTypeTag, atToken.pos); - result.atToken = atToken; + const result = createNode(SyntaxKind.JSDocTypeTag, start); result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } - function parseAugmentsTag(atToken: AtToken, tagName: Identifier): JSDocAugmentsTag { - const result = createNode(SyntaxKind.JSDocAugmentsTag, atToken.pos); - result.atToken = atToken; + function parseAugmentsTag(start: number, tagName: Identifier): JSDocAugmentsTag { + const result = createNode(SyntaxKind.JSDocAugmentsTag, start); result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); @@ -6841,37 +6842,33 @@ namespace ts { return node; } - function parseClassTag(atToken: AtToken, tagName: Identifier): JSDocClassTag { - const tag = createNode(SyntaxKind.JSDocClassTag, atToken.pos); - tag.atToken = atToken; + function parseClassTag(start: number, tagName: Identifier): JSDocClassTag { + const tag = createNode(SyntaxKind.JSDocClassTag, start); tag.tagName = tagName; return finishNode(tag); } - function parseThisTag(atToken: AtToken, tagName: Identifier): JSDocThisTag { - const tag = createNode(SyntaxKind.JSDocThisTag, atToken.pos); - tag.atToken = atToken; + function parseThisTag(start: number, tagName: Identifier): JSDocThisTag { + const tag = createNode(SyntaxKind.JSDocThisTag, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseEnumTag(atToken: AtToken, tagName: Identifier): JSDocEnumTag { - const tag = createNode(SyntaxKind.JSDocEnumTag, atToken.pos); - tag.atToken = atToken; + function parseEnumTag(start: number, tagName: Identifier): JSDocEnumTag { + const tag = createNode(SyntaxKind.JSDocEnumTag, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseTypedefTag(atToken: AtToken, tagName: Identifier, indent: number): JSDocTypedefTag { + function parseTypedefTag(start: number, tagName: Identifier, indent: number): JSDocTypedefTag { const typeExpression = tryParseTypeExpression(); skipWhitespaceOrAsterisk(); - const typedefTag = createNode(SyntaxKind.JSDocTypedefTag, atToken.pos); - typedefTag.atToken = atToken; + const typedefTag = createNode(SyntaxKind.JSDocTypedefTag, start); typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); @@ -6884,8 +6881,7 @@ namespace ts { let child: JSDocTypeTag | JSDocPropertyTag | false; let jsdocTypeLiteral: JSDocTypeLiteral | undefined; let childTypeTag: JSDocTypeTag | undefined; - const start = atToken.pos; - while (child = tryParse(() => parseChildPropertyTag())) { + while (child = tryParse(() => parseChildPropertyTag(indent))) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(SyntaxKind.JSDocTypeLiteral, start); } @@ -6938,9 +6934,8 @@ namespace ts { return typeNameOrNamespaceName; } - function parseCallbackTag(atToken: AtToken, tagName: Identifier, indent: number): JSDocCallbackTag { - const callbackTag = createNode(SyntaxKind.JSDocCallbackTag, atToken.pos) as JSDocCallbackTag; - callbackTag.atToken = atToken; + function parseCallbackTag(start: number, tagName: Identifier, indent: number): JSDocCallbackTag { + const callbackTag = createNode(SyntaxKind.JSDocCallbackTag, start) as JSDocCallbackTag; callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); @@ -6948,10 +6943,9 @@ namespace ts { callbackTag.comment = parseTagComments(indent); let child: JSDocParameterTag | false; - const start = scanner.getStartPos(); const jsdocSignature = createNode(SyntaxKind.JSDocSignature, start) as JSDocSignature; jsdocSignature.parameters = []; - while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter) as JSDocParameterTag)) { + while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter, indent) as JSDocParameterTag)) { jsdocSignature.parameters = append(jsdocSignature.parameters as MutableNodeArray, child); } const returnTag = tryParse(() => { @@ -6994,18 +6988,18 @@ namespace ts { return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(PropertyLikeParse.Property) as JSDocTypeTag | JSDocPropertyTag | false; + function parseChildPropertyTag(indent: number) { + return parseChildParameterOrPropertyTag(PropertyLikeParse.Property, indent) as JSDocTypeTag | JSDocPropertyTag | false; } - function parseChildParameterOrPropertyTag(target: PropertyLikeParse, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { + function parseChildParameterOrPropertyTag(target: PropertyLikeParse, indent: number, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { let canParseTag = true; let seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case SyntaxKind.AtToken: if (canParseTag) { - const child = tryParseChildTag(target); + const child = tryParseChildTag(target, indent); if (child && (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) && target !== PropertyLikeParse.CallbackParameter && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -7034,10 +7028,9 @@ namespace ts { } } - function tryParseChildTag(target: PropertyLikeParse): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { + function tryParseChildTag(target: PropertyLikeParse, indent: number): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { Debug.assert(token() === SyntaxKind.AtToken); - const atToken = createNode(SyntaxKind.AtToken); - atToken.end = scanner.getTextPos(); + const start = scanner.getStartPos(); nextJSDocToken(); const tagName = parseJSDocIdentifierName(); @@ -7045,7 +7038,7 @@ namespace ts { let t: PropertyLikeParse; switch (tagName.escapedText) { case "type": - return target === PropertyLikeParse.Property && parseTypeTag(atToken, tagName); + return target === PropertyLikeParse.Property && parseTypeTag(start, tagName); case "prop": case "property": t = PropertyLikeParse.Property; @@ -7061,12 +7054,10 @@ namespace ts { if (!(target & t)) { return false; } - const tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(start, tagName, target, indent); } - function parseTemplateTag(atToken: AtToken, tagName: Identifier): JSDocTemplateTag { + function parseTemplateTag(start: number, tagName: Identifier): JSDocTemplateTag { // the template tag looks like '@template {Constraint} T,U,V' let constraint: JSDocTypeExpression | undefined; if (token() === SyntaxKind.OpenBraceToken) { @@ -7084,8 +7075,7 @@ namespace ts { typeParameters.push(typeParameter); } while (parseOptionalJsdoc(SyntaxKind.CommaToken)); - const result = createNode(SyntaxKind.JSDocTemplateTag, atToken.pos); - result.atToken = atToken; + const result = createNode(SyntaxKind.JSDocTemplateTag, start); result.tagName = tagName; result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -7733,7 +7723,7 @@ namespace ts { /*@internal*/ export function processCommentPragmas(context: PragmaContext, sourceText: string): void { const triviaScanner = createScanner(context.languageVersion, /*skipTrivia*/ false, LanguageVariant.Standard, sourceText); - const pragmas: PragmaPsuedoMapEntry[] = []; + const pragmas: PragmaPseudoMapEntry[] = []; // Keep scanning all the leading trivia in the file until we get to something that // isn't trivia. Any single line comment will be analyzed to see if it is a @@ -7788,19 +7778,20 @@ namespace ts { const referencedFiles = context.referencedFiles; const typeReferenceDirectives = context.typeReferenceDirectives; const libReferenceDirectives = context.libReferenceDirectives; - forEach(toArray(entryOrList), (arg: PragmaPsuedoMap["reference"]) => { + forEach(toArray(entryOrList), (arg: PragmaPseudoMap["reference"]) => { // TODO: GH#18217 + const { types, lib, path } = arg!.arguments; if (arg!.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } - else if (arg!.arguments.types) { - typeReferenceDirectives.push({ pos: arg!.arguments.types!.pos, end: arg!.arguments.types!.end, fileName: arg!.arguments.types!.value }); + else if (types) { + typeReferenceDirectives.push({ pos: types.pos, end: types.end, fileName: types.value }); } - else if (arg!.arguments.lib) { - libReferenceDirectives.push({ pos: arg!.arguments.lib!.pos, end: arg!.arguments.lib!.end, fileName: arg!.arguments.lib!.value }); + else if (lib) { + libReferenceDirectives.push({ pos: lib.pos, end: lib.end, fileName: lib.value }); } - else if (arg!.arguments.path) { - referencedFiles.push({ pos: arg!.arguments.path!.pos, end: arg!.arguments.path!.end, fileName: arg!.arguments.path!.value }); + else if (path) { + referencedFiles.push({ pos: path.pos, end: path.end, fileName: path.value }); } else { reportDiagnostic(arg!.range.pos, arg!.range.end - arg!.range.pos, Diagnostics.Invalid_reference_directive_syntax); @@ -7811,7 +7802,7 @@ namespace ts { case "amd-dependency": { context.amdDependencies = map( toArray(entryOrList), - (x: PragmaPsuedoMap["amd-dependency"]) => ({ name: x!.arguments.name!, path: x!.arguments.path })); // TODO: GH#18217 + (x: PragmaPseudoMap["amd-dependency"]) => ({ name: x!.arguments.name!, path: x!.arguments.path })); // TODO: GH#18217 break; } case "amd-module": { @@ -7821,11 +7812,11 @@ namespace ts { // TODO: It's probably fine to issue this diagnostic on all instances of the pragma reportDiagnostic(entry!.range.pos, entry!.range.end - entry!.range.pos, Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); } - context.moduleName = (entry as PragmaPsuedoMap["amd-module"])!.arguments.name; + context.moduleName = (entry as PragmaPseudoMap["amd-module"])!.arguments.name; } } else { - context.moduleName = (entryOrList as PragmaPsuedoMap["amd-module"])!.arguments.name; + context.moduleName = (entryOrList as PragmaPseudoMap["amd-module"])!.arguments.name; } break; } @@ -7861,10 +7852,10 @@ namespace ts { const tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; const singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; - function extractPragmas(pragmas: PragmaPsuedoMapEntry[], range: CommentRange, text: string) { + function extractPragmas(pragmas: PragmaPseudoMapEntry[], range: CommentRange, text: string) { const tripleSlash = range.kind === SyntaxKind.SingleLineCommentTrivia && tripleSlashXMLCommentStartRegEx.exec(text); if (tripleSlash) { - const name = tripleSlash[1].toLowerCase() as keyof PragmaPsuedoMap; // Technically unsafe cast, but we do it so the below check to make it safe typechecks + const name = tripleSlash[1].toLowerCase() as keyof PragmaPseudoMap; // Technically unsafe cast, but we do it so the below check to make it safe typechecks const pragma = commentPragmas[name] as PragmaDefinition; if (!pragma || !(pragma.kind! & PragmaKindFlags.TripleSlashXML)) { return; @@ -7891,10 +7882,10 @@ namespace ts { } } } - pragmas.push({ name, args: { arguments: argument, range } } as PragmaPsuedoMapEntry); + pragmas.push({ name, args: { arguments: argument, range } } as PragmaPseudoMapEntry); } else { - pragmas.push({ name, args: { arguments: {}, range } } as PragmaPsuedoMapEntry); + pragmas.push({ name, args: { arguments: {}, range } } as PragmaPseudoMapEntry); } return; } @@ -7913,9 +7904,9 @@ namespace ts { } } - function addPragmaForMatch(pragmas: PragmaPsuedoMapEntry[], range: CommentRange, kind: PragmaKindFlags, match: RegExpExecArray) { + function addPragmaForMatch(pragmas: PragmaPseudoMapEntry[], range: CommentRange, kind: PragmaKindFlags, match: RegExpExecArray) { if (!match) return; - const name = match[1].toLowerCase() as keyof PragmaPsuedoMap; // Technically unsafe cast, but we do it so they below check to make it safe typechecks + const name = match[1].toLowerCase() as keyof PragmaPseudoMap; // Technically unsafe cast, but we do it so they below check to make it safe typechecks const pragma = commentPragmas[name] as PragmaDefinition; if (!pragma || !(pragma.kind! & kind)) { return; @@ -7923,7 +7914,7 @@ namespace ts { const args = match[2]; // Split on spaces and match up positionally with definition const argument = getNamedPragmaArguments(pragma, args); if (argument === "fail") return; // Missing required argument, fail to parse it - pragmas.push({ name, args: { arguments: argument, range } } as PragmaPsuedoMapEntry); + pragmas.push({ name, args: { arguments: argument, range } } as PragmaPseudoMapEntry); return; } diff --git a/src/compiler/performance.ts b/src/compiler/performance.ts index 64709a12ba9..3471ecd0591 100644 --- a/src/compiler/performance.ts +++ b/src/compiler/performance.ts @@ -19,6 +19,41 @@ namespace ts.performance { let marks: Map; let measures: Map; + export interface Timer { + enter(): void; + exit(): void; + } + + export function createTimerIf(condition: boolean, measureName: string, startMarkName: string, endMarkName: string) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : nullTimer; + } + + export function createTimer(measureName: string, startMarkName: string, endMarkName: string): Timer { + let enterCount = 0; + return { + enter, + exit + }; + + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } + else if (enterCount < 0) { + Debug.fail("enter/exit count does not match."); + } + } + } + + export const nullTimer: Timer = { enter: noop, exit: noop }; + /** * Marks a performance event. * diff --git a/src/compiler/program.ts b/src/compiler/program.ts index c97f1a61d27..14042a89e94 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -69,11 +69,11 @@ namespace ts { export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost { return createCompilerHostWorker(options, setParentNodes); } + /*@internal*/ // TODO(shkamat): update this after reworking ts build API export function createCompilerHostWorker(options: CompilerOptions, setParentNodes?: boolean, system = sys): CompilerHost { const existingDirectories = createMap(); - function getCanonicalFileName(fileName: string): string { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. @@ -84,7 +84,7 @@ namespace ts { let text: string | undefined; try { performance.mark("beforeIORead"); - text = system.readFile(fileName, options.charset); + text = compilerHost.readFile(fileName); performance.mark("afterIORead"); performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -94,7 +94,6 @@ namespace ts { } text = ""; } - return text !== undefined ? createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } @@ -113,7 +112,12 @@ namespace ts { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { const parentDirectory = getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - system.createDirectory(directoryPath); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } } } @@ -177,8 +181,7 @@ namespace ts { const newLine = getNewLineCharacter(options, () => system.newLine); const realpath = system.realpath && ((path: string) => system.realpath!(path)); - - return { + const compilerHost: CompilerHost = { getSourceFile, getDefaultLibLocation, getDefaultLibFileName: options => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options)), @@ -194,11 +197,128 @@ namespace ts { getEnvironmentVariable: name => system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : "", getDirectories: (path: string) => system.getDirectories(path), realpath, - readDirectory: (path, extensions, include, exclude, depth) => system.readDirectory(path, extensions, include, exclude, depth) + readDirectory: (path, extensions, include, exclude, depth) => system.readDirectory(path, extensions, include, exclude, depth), + createDirectory: d => system.createDirectory(d) + }; + return compilerHost; + } + + interface CompilerHostLikeForCache { + fileExists(fileName: string): boolean; + readFile(fileName: string, encoding?: string): string | undefined; + directoryExists?(directory: string): boolean; + createDirectory?(directory: string): void; + writeFile?: WriteFileCallback; + } + + /*@internal*/ + export function changeCompilerHostLikeToUseCache( + host: CompilerHostLikeForCache, + toPath: (fileName: string) => Path, + getSourceFile?: CompilerHost["getSourceFile"] + ) { + const originalReadFile = host.readFile; + const originalFileExists = host.fileExists; + const originalDirectoryExists = host.directoryExists; + const originalCreateDirectory = host.createDirectory; + const originalWriteFile = host.writeFile; + const readFileCache = createMap(); + const fileExistsCache = createMap(); + const directoryExistsCache = createMap(); + const sourceFileCache = createMap(); + + const readFileWithCache = (fileName: string): string | undefined => { + const key = toPath(fileName); + const value = readFileCache.get(key); + if (value !== undefined) return value || undefined; + return setReadFileCache(key, fileName); + }; + const setReadFileCache = (key: Path, fileName: string) => { + const newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = fileName => { + const key = toPath(fileName); + const value = readFileCache.get(key); + if (value !== undefined) return value; // could be .d.ts from output + if (!fileExtensionIs(fileName, Extension.Json)) { + return originalReadFile.call(host, fileName); + } + + return setReadFileCache(key, fileName); + }; + + const getSourceFileWithCache: CompilerHost["getSourceFile"] | undefined = getSourceFile ? (fileName, languageVersion, onError, shouldCreateNewSourceFile) => { + const key = toPath(fileName); + const value = sourceFileCache.get(key); + if (value) return value; + + const sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (isDeclarationFileName(fileName) || fileExtensionIs(fileName, Extension.Json))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + } : undefined; + + // fileExists for any kind of extension + host.fileExists = fileName => { + const key = toPath(fileName); + const value = fileExistsCache.get(key); + if (value !== undefined) return value; + const newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + if (originalWriteFile) { + host.writeFile = (fileName, data, writeByteOrderMark, onError, sourceFiles) => { + const key = toPath(fileName); + fileExistsCache.delete(key); + + const value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (getSourceFileWithCache) { + const sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + } + + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = directory => { + const key = toPath(directory); + const value = directoryExistsCache.get(key); + if (value !== undefined) return value; + const newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = directory => { + const key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + + return { + originalReadFile, + originalFileExists, + originalDirectoryExists, + originalCreateDirectory, + originalWriteFile, + getSourceFileWithCache, + readFileWithCache }; } - export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] { + export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray { const diagnostics = [ ...program.getConfigFileParsingDiagnostics(), ...program.getOptionsDiagnostics(cancellationToken), @@ -207,7 +327,7 @@ namespace ts { ...program.getSemanticDiagnostics(sourceFile, cancellationToken) ]; - if (program.getCompilerOptions().declaration) { + if (getEmitDeclarations(program.getCompilerOptions())) { addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } @@ -250,7 +370,7 @@ namespace ts { Blue = "\u001b[94m", Cyan = "\u001b[96m" } - const gutterStyleSequence = "\u001b[30;47m"; + const gutterStyleSequence = "\u001b[7m"; const gutterSeparator = " "; const resetEscapeSequence = "\u001b[0m"; const ellipsis = "..."; @@ -406,7 +526,7 @@ namespace ts { } } - function loadWithLocalCache(names: string[], containingFile: string, loader: (name: string, containingFile: string) => T): T[] { + function loadWithLocalCache(names: string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, loader: (name: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => T): T[] { if (names.length === 0) { return []; } @@ -418,7 +538,7 @@ namespace ts { result = cache.get(name)!; } else { - cache.set(name, result = loader(name, containingFile)); + cache.set(name, result = loader(name, containingFile, redirectedReference)); } resolutions.push(result); } @@ -442,6 +562,7 @@ namespace ts { fileExists: (fileName: string) => boolean, hasInvalidatedResolution: HasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: boolean, + projectReferences: ReadonlyArray | undefined ): boolean { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { @@ -453,6 +574,13 @@ namespace ts { return false; } + let seenResolvedRefs: ResolvedProjectReference[] | undefined; + + // If project references dont match + if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -477,10 +605,46 @@ namespace ts { return true; - function sourceFileNotUptoDate(sourceFile: SourceFile): boolean { - return sourceFile.version !== getSourceVersion(sourceFile.path) || + function sourceFileNotUptoDate(sourceFile: SourceFile) { + return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolution(sourceFile.path); } + + function sourceFileVersionUptoDate(sourceFile: SourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + + function projectReferenceUptoDate(oldRef: ProjectReference, newRef: ProjectReference, index: number) { + if (!projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + return resolvedProjectReferenceUptoDate(program!.getResolvedProjectReferences()![index], oldRef); + } + + function resolvedProjectReferenceUptoDate(oldResolvedRef: ResolvedProjectReference | undefined, oldRef: ProjectReference): boolean { + if (oldResolvedRef) { + if (contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + + // If child project references are upto date, this project reference is uptodate + return !forEach(oldResolvedRef.references, (childResolvedRef, index) => + !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences![index])); + } + + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); + } } export function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray { @@ -490,23 +654,15 @@ namespace ts { } /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ - function shouldProgramCreateNewSourceFiles(program: Program | undefined, newOptions: CompilerOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - const oldOptions = program && program.getCompilerOptions(); - return oldOptions && ( - oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !equalOwnProperties(oldOptions.paths, newOptions.paths) - ); + function shouldProgramCreateNewSourceFiles(program: Program | undefined, newOptions: CompilerOptions): boolean { + if (!program) return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + const oldOptions = program.getCompilerOptions(); + return !!sourceFileAffectingCompilerOptions.some(option => + !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option))); } function createCreateProgramOptions(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): CreateProgramOptions { @@ -558,12 +714,12 @@ namespace ts { let diagnosticsProducingTypeChecker: TypeChecker; let noDiagnosticsTypeChecker: TypeChecker; let classifiableNames: UnderscoreEscapedMap; - let modifiedFilePaths: Path[] | undefined; + const ambientModuleNameToUnmodifiedFileName = createMap(); const cachedSemanticDiagnosticsForFile: DiagnosticCache = {}; const cachedDeclarationDiagnosticsForFile: DiagnosticCache = {}; - let resolvedTypeReferenceDirectives = createMap(); + let resolvedTypeReferenceDirectives = createMap(); let fileProcessingDiagnostics = createDiagnosticCollection(); // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. @@ -586,7 +742,7 @@ namespace ts { performance.mark("beforeProgram"); const host = createProgramOptions.host || createCompilerHost(options); - const configParsingHost = parseConfigHostFromCompilerHost(host); + const configParsingHost = parseConfigHostFromCompilerHostLike(host); let skipDefaultLib = options.noLib; const getDefaultLibraryFileName = memoize(() => host.getDefaultLibFileName(options)); @@ -594,18 +750,17 @@ namespace ts { const programDiagnostics = createDiagnosticCollection(); const currentDirectory = host.getCurrentDirectory(); const supportedExtensions = getSupportedExtensions(options); - const supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? [...supportedExtensions, Extension.Json] : undefined; + const supportedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input const hasEmitBlockingDiagnostics = createMap(); let _compilerOptionsObjectLiteralSyntax: ObjectLiteralExpression | null | undefined; - let _referencesArrayLiteralSyntax: ArrayLiteralExpression | null | undefined; let moduleResolutionCache: ModuleResolutionCache | undefined; - let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[]) => ResolvedModuleFull[]; + let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference) => ResolvedModuleFull[]; const hasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames) => host.resolveModuleNames!(Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(resolved => { + resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(resolved => { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || (resolved as ResolvedModuleFull).extension !== undefined) { return resolved as ResolvedModuleFull; @@ -617,17 +772,17 @@ namespace ts { } else { moduleResolutionCache = createModuleResolutionCache(currentDirectory, x => host.getCanonicalFileName(x)); - const loader = (moduleName: string, containingFile: string) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule!; // TODO: GH#18217 - resolveModuleNamesWorker = (moduleNames, containingFile) => loadWithLocalCache(Debug.assertEachDefined(moduleNames), containingFile, loader); + const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule!; // TODO: GH#18217 + resolveModuleNamesWorker = (moduleNames, containingFile, _reusedNames, redirectedReference) => loadWithLocalCache(Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader); } - let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[]; + let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference) => (ResolvedTypeReferenceDirective | undefined)[]; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives!(Debug.assertEachDefined(typeDirectiveNames), containingFile); + resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); } else { - const loader = (typesRef: string, containingFile: string) => resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective!; // TODO: GH#18217 - resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile) => loadWithLocalCache(Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader); + const loader = (typesRef: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective!; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile, redirectedReference) => loadWithLocalCache(Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader); } // Map from a stringified PackageId to the source file with that id. @@ -639,15 +794,22 @@ namespace ts { // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. let redirectTargetsMap = createMultiMap(); - const filesByName = createMap(); + /** + * map with + * - SourceFile if present + * - false if sourceFile missing for source of project reference redirect + * - undefined otherwise + */ + const filesByName = createMap(); let missingFilePaths: ReadonlyArray | undefined; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files - let resolvedProjectReferences: (ResolvedProjectReference | undefined)[] | undefined = projectReferences ? [] : undefined; - const projectReferenceRedirects: Map = createMap(); + let resolvedProjectReferences: ReadonlyArray | undefined; + let projectReferenceRedirects: Map | undefined; + let mapFromFileToProjectReferenceRedirects: Map | undefined; const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); const structuralIsReused = tryReuseStructureFromOldProgram(); @@ -656,15 +818,18 @@ namespace ts { processingOtherFiles = []; if (projectReferences) { - for (const ref of projectReferences) { - const parsedRef = parseProjectReferenceConfigFile(ref); - resolvedProjectReferences!.push(parsedRef); - if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - const dtsOutfile = changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); - processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + for (const parsedRef of resolvedProjectReferences) { + if (parsedRef) { + const out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + const dtsOutfile = changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); } } } @@ -672,7 +837,7 @@ namespace ts { forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false)); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - const typeReferences: string[] = getAutomaticTypeDirectiveNames(options, host); + const typeReferences: string[] = rootNames.length ? getAutomaticTypeDirectiveNames(options, host) : emptyArray; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side @@ -688,7 +853,7 @@ namespace ts { // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. - if (!skipDefaultLib) { + if (rootNames.length && !skipDefaultLib) { // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file const defaultLibraryFileName = getDefaultLibraryFileName(); @@ -702,7 +867,7 @@ namespace ts { } } - missingFilePaths = arrayFrom(filesByName.keys(), p => p).filter(p => !filesByName.get(p)); + missingFilePaths = arrayFrom(mapDefinedIterator(filesByName.entries(), ([path, file]) => file === undefined ? path as Path : undefined)); files = stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = undefined; processingOtherFiles = undefined; @@ -715,10 +880,18 @@ namespace ts { if (oldProgram && host.onReleaseOldSourceFile) { const oldSourceFiles = oldProgram.getSourceFiles(); for (const oldSourceFile of oldSourceFiles) { - if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { - host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + const newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } + oldProgram.forEachResolvedProjectReference((resolvedProjectReference, resolvedProjectReferencePath) => { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile!(resolvedProjectReference.sourceFile, oldProgram!.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); } // unconditionally set oldProgram to undefined to prevent it from being captured in closure @@ -759,7 +932,12 @@ namespace ts { isEmittedFile, getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences + getProjectReferences, + getResolvedProjectReferences, + getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath, + forEachResolvedProjectReference }; verifyCompilerOptions(); @@ -798,9 +976,9 @@ namespace ts { // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = getDirectoryPath(normalizeSlashes(options.configFilePath!)); // TODO: GH#18217 + commonSourceDirectory = getDirectoryPath(normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -831,21 +1009,14 @@ namespace ts { return classifiableNames; } - interface OldProgramState { - program: Program | undefined; - oldSourceFile: SourceFile | undefined; - /** The collection of paths modified *since* the old program. */ - modifiedFilePaths: Path[] | undefined; - } - - function resolveModuleNamesReusingOldState(moduleNames: string[], containingFile: string, file: SourceFile, oldProgramState: OldProgramState) { + function resolveModuleNamesReusingOldState(moduleNames: string[], containingFile: string, file: SourceFile) { if (structuralIsReused === StructureIsReused.Not && !file.ambientModuleNames.length) { // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, // the best we can do is fallback to the default logic. - return resolveModuleNamesWorker(moduleNames, containingFile); + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); } - const oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + const oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { // `file` was created for the new program. // @@ -909,7 +1080,7 @@ namespace ts { } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { @@ -922,7 +1093,7 @@ namespace ts { } const resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) : emptyArray; // Combine results of resolutions and predicted results @@ -952,12 +1123,9 @@ namespace ts { // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName: string, oldProgramState: OldProgramState): boolean { - if (!oldProgramState.program) { - return false; - } - const resolutionToFile = getResolvedModule(oldProgramState.oldSourceFile!, moduleName); // TODO: GH#18217 - const resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName: string): boolean { + const resolutionToFile = getResolvedModule(oldSourceFile!, moduleName); + const resolvedFile = resolutionToFile && oldProgram!.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -967,21 +1135,43 @@ namespace ts { } // at least one of declarations should come from non-modified source file - const firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find( - f => !contains(oldProgramState.modifiedFilePaths, f.path) && contains(f.ambientModuleNames, moduleName) - ); + const unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); - if (!firstUnmodifiedFile) { + if (!unmodifiedFile) { return false; } if (isTraceEnabled(options, host)) { - trace(host, Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + trace(host, Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); } return true; } } + function canReuseProjectReferences(): boolean { + return !forEachProjectReference( + oldProgram!.getProjectReferences(), + oldProgram!.getResolvedProjectReferences(), + (oldResolvedRef, index, parent) => { + const newRef = (parent ? parent.commandLine.projectReferences : projectReferences)![index]; + const newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + } + else { + // A previously-unresolved reference may be resolved now + return newResolvedRef !== undefined; + } + }, + (oldProjectReferences, parent) => { + // If array of references is changed, we cant resue old program + const newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path)!.commandLine.projectReferences : projectReferences; + return !arrayIsEqualTo(oldProjectReferences, newReferences, projectReferenceIsEqualTo); + } + ); + } + function tryReuseStructureFromOldProgram(): StructureIsReused { if (!oldProgram) { return StructureIsReused.Not; @@ -1007,37 +1197,15 @@ namespace ts { } // Check if any referenced project tsconfig files are different - const oldRefs = oldProgram.getProjectReferences(); - if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = StructureIsReused.Not; - } - for (let i = 0; i < projectReferences.length; i++) { - const oldRef = oldRefs[i]; - if (oldRef) { - const newRef = parseProjectReferenceConfigFile(projectReferences[i]); - if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { - // Resolved project reference has gone missing or changed - return oldProgram.structureIsReused = StructureIsReused.Not; - } - } - else { - // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { - return oldProgram.structureIsReused = StructureIsReused.Not; - } - } - } + if (!canReuseProjectReferences()) { + return oldProgram.structureIsReused = StructureIsReused.Not; } - else { - if (oldRefs) { - return oldProgram.structureIsReused = StructureIsReused.Not; - } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); } // check if program source files has changed in the way that can affect structure of the program const newSourceFiles: SourceFile[] = []; - const filePaths: Path[] = []; const modifiedSourceFiles: { oldFile: SourceFile, newFile: SourceFile }[] = []; oldProgram.structureIsReused = StructureIsReused.Completely; @@ -1054,7 +1222,7 @@ namespace ts { for (const oldSourceFile of oldSourceFiles) { let newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target!, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target!, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target!, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { @@ -1085,8 +1253,11 @@ namespace ts { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; - filePaths.push(newSourceFile.path); + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; const packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -1159,14 +1330,20 @@ namespace ts { return oldProgram.structureIsReused; } - modifiedFilePaths = modifiedSourceFiles.map(f => f.newFile.path); + const modifiedFiles = modifiedSourceFiles.map(f => f.oldFile); + for (const oldFile of oldSourceFiles) { + if (!contains(modifiedFiles, oldFile)) { + for (const moduleName of oldFile.ambientModuleNames) { + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } // try to verify results of module resolution for (const { oldFile: oldSourceFile, newFile: newSourceFile } of modifiedSourceFiles) { - const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { const moduleNames = getModuleNames(newSourceFile); - const oldProgramState: OldProgramState = { program: oldProgram, oldSourceFile, modifiedFilePaths }; - const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); // ensure that module resolution results are still correct const resolutionsChanged = hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, moduleResolutionIsEqualTo); if (resolutionsChanged) { @@ -1180,7 +1357,7 @@ namespace ts { if (resolveTypeReferenceDirectiveNamesWorker) { // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, ref => ref.fileName.toLocaleLowerCase()); - const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); // ensure that types resolutions are still correct const resolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -1204,11 +1381,12 @@ namespace ts { missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping - for (let i = 0; i < newSourceFiles.length; i++) { - filesByName.set(filePaths[i], newSourceFiles[i]); + for (const newSourceFile of newSourceFiles) { + const filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); // Set the file as found during node modules search if it was found that way in old progra, - if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i])!)) { - sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath)!)) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); } } @@ -1219,7 +1397,6 @@ namespace ts { fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; @@ -1257,10 +1434,14 @@ namespace ts { }; } - function getProjectReferences() { + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } + function getPrependNodes(): InputFiles[] { if (!projectReferences) { return emptyArray; @@ -1271,12 +1452,13 @@ namespace ts { const ref = projectReferences[i]; const resolvedRefOpts = resolvedProjectReferences![i]!.commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + const out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) continue; + if (!out) continue; - const dtsFilename = changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - const js = host.readFile(resolvedRefOpts.options.outFile) || `/* Input file ${resolvedRefOpts.options.outFile} was missing */\r\n`; - const jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + const dtsFilename = changeExtension(out, ".d.ts"); + const js = host.readFile(out) || `/* Input file ${out} was missing */\r\n`; + const jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file const jsMap = host.readFile(jsMapPath); const dts = host.readFile(dtsFilename) || `/* Input file ${dtsFilename} was missing */\r\n`; const dtsMapPath = dtsFilename + ".map"; @@ -1351,7 +1533,7 @@ namespace ts { ...program.getSemanticDiagnostics(sourceFile, cancellationToken) ]; - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } @@ -1398,7 +1580,7 @@ namespace ts { } function getSourceFileByPath(path: Path): SourceFile | undefined { - return filesByName.get(path); + return filesByName.get(path) || undefined; } function getDiagnosticsHelper( @@ -1438,9 +1620,9 @@ namespace ts { function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): ReadonlyArray { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (isSourceFileJavaScript(sourceFile)) { + if (isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -1538,7 +1720,7 @@ namespace ts { return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] { + function getJSSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] { return runWithCancellationToken(() => { const diagnostics: DiagnosticWithLocation[] = []; let parent: Node = sourceFile; @@ -1764,18 +1946,29 @@ namespace ts { return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } - function getOptionsDiagnostics(): Diagnostic[] { + function getOptionsDiagnostics(): SortedReadonlyArray { return sortAndDeduplicateDiagnostics(concatenate( fileProcessingDiagnostics.getGlobalDiagnostics(), concatenate( programDiagnostics.getGlobalDiagnostics(), - options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : [] + getOptionsDiagnosticsOfConfigFile() ) )); } - function getGlobalDiagnostics(): Diagnostic[] { - return sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { return emptyArray; } + let diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(resolvedRef => { + if (resolvedRef) { + diagnostics = concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; + } + + function getGlobalDiagnostics(): SortedReadonlyArray { + return rootNames.length ? sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : emptyArray as any as SortedReadonlyArray; } function getConfigFileParsingDiagnostics(): ReadonlyArray { @@ -1801,7 +1994,7 @@ namespace ts { return; } - const isJavaScriptFile = isSourceFileJavaScript(file); + const isJavaScriptFile = isSourceFileJS(file); const isExternalModuleFile = isExternalModule(file); // file.imports may not be undefined if there exists dynamic import @@ -1825,12 +2018,9 @@ namespace ts { for (const node of file.statements) { collectModuleReferences(node, /*inAmbientModule*/ false); - if ((file.flags & NodeFlags.PossiblyContainsDynamicImport) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(node); - } } if ((file.flags & NodeFlags.PossiblyContainsDynamicImport) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(file.endOfFileToken); + collectDynamicImportOrRequireCalls(file); } file.imports = imports || emptyArray; @@ -1882,25 +2072,38 @@ namespace ts { } } - function collectDynamicImportOrRequireCalls(node: Node): void { - if (isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { - imports = append(imports, node.arguments[0]); - } - // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. - else if (isImportCall(node) && node.arguments.length === 1 && isStringLiteralLike(node.arguments[0])) { - imports = append(imports, node.arguments[0] as StringLiteralLike); - } - else if (isLiteralImportTypeNode(node)) { - imports = append(imports, node.argument.literal); - } - collectDynamicImportOrRequireCallsForEachChild(node); - if (hasJSDocNodes(node)) { - forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); + function collectDynamicImportOrRequireCalls(file: SourceFile) { + const r = /import|require/g; + while (r.exec(file.text) !== null) { + const node = getNodeAtPosition(file, r.lastIndex); + if (isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (isImportCall(node) && node.arguments.length === 1 && isStringLiteralLike(node.arguments[0])) { + imports = append(imports, node.arguments[0] as StringLiteralLike); + } + else if (isLiteralImportTypeNode(node)) { + imports = append(imports, node.argument.literal); + } } } - function collectDynamicImportOrRequireCallsForEachChild(node: Node) { - forEachChild(node, collectDynamicImportOrRequireCalls); + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile: SourceFile, position: number): Node { + let current: Node = sourceFile; + const getContainingChild = (child: Node) => { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === SyntaxKind.EndOfFileToken)))) { + return child; + } + }; + while (true) { + const child = isJavaScriptFile && hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } } } @@ -1914,7 +2117,7 @@ namespace ts { /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ function getSourceFileFromReference(referencingFile: SourceFile, ref: FileReference): SourceFile | undefined { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), fileName => filesByName.get(toPath(fileName))); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), fileName => filesByName.get(toPath(fileName)) || undefined); } function getSourceFileFromReferenceWorker( @@ -1924,7 +2127,7 @@ namespace ts { refFile?: SourceFile): SourceFile | undefined { if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { + if (!options.allowNonTsExtensions && !forEach(supportedExtensionsWithJsonIfResolveJsonModule, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { if (fail) fail(Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; } @@ -1983,11 +2186,14 @@ namespace ts { } } - function createRedirectSourceFile(redirectTarget: SourceFile, unredirected: SourceFile, fileName: string, path: Path): SourceFile { + function createRedirectSourceFile(redirectTarget: SourceFile, unredirected: SourceFile, fileName: string, path: Path, resolvedPath: Path, originalFileName: string): SourceFile { const redirect: SourceFile = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget, unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get(this: SourceFile) { return this.redirectInfo!.redirectTarget.id; }, @@ -2003,6 +2209,7 @@ namespace ts { // Get source file from normalized fileName function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, ignoreNoDefaultLib: boolean, refFile: SourceFile, refPos: number, refEnd: number, packageId: PackageId | undefined): SourceFile | undefined { + const originalFileName = fileName; if (filesByName.has(path)) { const file = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -2027,8 +2234,9 @@ namespace ts { processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } - - processLibReferenceDirectives(file); + if (!options.noLib) { + processLibReferenceDirectives(file); + } modulesWithElidedImports.set(file.path, false); processImportedModules(file); @@ -2041,10 +2249,10 @@ namespace ts { } } - return file; + return file || undefined; } - let redirectedPath: string | undefined; + let redirectedPath: Path | undefined; if (refFile) { const redirect = getProjectReferenceRedirect(fileName); if (redirect) { @@ -2076,9 +2284,9 @@ namespace ts { if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - const dupFile = createRedirectSourceFile(fileFromPackageId, file!, fileName, path); // TODO: GH#18217 + const dupFile = createRedirectSourceFile(fileFromPackageId, file!, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); - filesByName.set(path, dupFile); + addFileToFilesByName(dupFile, path, redirectedPath); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles!.push(dupFile); return dupFile; @@ -2089,16 +2297,13 @@ namespace ts { sourceFileToPackageName.set(path, packageId.name); } } - - filesByName.set(path, file); - if (redirectedPath) { - filesByName.set(redirectedPath, file); - } + addFileToFilesByName(file, path, redirectedPath); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { const pathLowerCase = path.toLowerCase(); @@ -2118,8 +2323,10 @@ namespace ts { processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } + if (!options.noLib) { + processLibReferenceDirectives(file); + } - processLibReferenceDirectives(file); // always process imported modules to record module name resolutions processImportedModules(file); @@ -2135,26 +2342,118 @@ namespace ts { return file; } + function addFileToFilesByName(file: SourceFile | undefined, path: Path, redirectedPath: Path | undefined) { + if (redirectedPath) { + filesByName.set(redirectedPath, file); + filesByName.set(path, file || false); + } + else { + filesByName.set(path, file); + } + } + function getProjectReferenceRedirect(fileName: string): string | undefined { - const path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!resolvedProjectReferences || !resolvedProjectReferences.length || fileExtensionIs(fileName, Extension.Dts) || !fileExtensionIsOneOf(fileName, supportedTSExtensions)) { + return undefined; + } + // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - const normalized = getNormalizedAbsolutePath(fileName, path); - let result: string | undefined; - projectReferenceRedirects.forEach((v, k) => { - if (result !== undefined) { - return undefined; - } - if (normalized.indexOf(k) === 0) { - result = changeExtension(fileName.replace(k, v), ".d.ts"); - } + const referencedProject = getResolvedProjectReferenceToRedirect(fileName); + if (!referencedProject) { + return undefined; + } + const out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + changeExtension(out, Extension.Dts) : + getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + + /** + * Get the referenced project if the file is input file from that reference project + */ + function getResolvedProjectReferenceToRedirect(fileName: string) { + if (mapFromFileToProjectReferenceRedirects === undefined) { + mapFromFileToProjectReferenceRedirects = createMap(); + forEachResolvedProjectReference((referencedProject, referenceProjectPath) => { + // not input file from the referenced project, ignore + if (referencedProject && + toPath(options.configFilePath!) !== referenceProjectPath) { + referencedProject.commandLine.fileNames.forEach(f => + mapFromFileToProjectReferenceRedirects!.set(toPath(f), referenceProjectPath)); + } + }); + } + + const referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + + function forEachResolvedProjectReference( + cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined + ): T | undefined { + return forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, index, parent) => { + const ref = (parent ? parent.commandLine.projectReferences : projectReferences)![index]; + const resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); }); - return result; + } + + function forEachProjectReference( + projectReferences: ReadonlyArray | undefined, + resolvedProjectReferences: ReadonlyArray | undefined, + cbResolvedRef: (resolvedRef: ResolvedProjectReference | undefined, index: number, parent: ResolvedProjectReference | undefined) => T | undefined, + cbRef?: (projectReferences: ReadonlyArray | undefined, parent: ResolvedProjectReference | undefined) => T | undefined + ): T | undefined { + let seenResolvedRefs: ResolvedProjectReference[] | undefined; + + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + + function worker( + projectReferences: ReadonlyArray | undefined, + resolvedProjectReferences: ReadonlyArray | undefined, + parent: ResolvedProjectReference | undefined, + cbResolvedRef: (resolvedRef: ResolvedProjectReference | undefined, index: number, parent: ResolvedProjectReference | undefined) => T | undefined, + cbRef?: (projectReferences: ReadonlyArray | undefined, parent: ResolvedProjectReference | undefined) => T | undefined, + ): T | undefined { + + // Visit project references first + if (cbRef) { + const result = cbRef(projectReferences, parent); + if (result) { return result; } + } + + return forEach(resolvedProjectReferences, (resolvedRef, index) => { + if (contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + + const result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + + if (!resolvedRef) return undefined; + + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + + function getResolvedProjectReferenceByPath(projectReferencePath: Path): ResolvedProjectReference | undefined { + if (!projectReferenceRedirects) { + return undefined; + } + + return projectReferenceRedirects.get(projectReferencePath) || undefined; } function processReferencedFiles(file: SourceFile, isDefaultLib: boolean) { forEach(file.referencedFiles, ref => { - const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + const referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -2166,7 +2465,7 @@ namespace ts { return; } - const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); for (let i = 0; i < typeDirectives.length; i++) { const ref = file.typeReferenceDirectives[i]; @@ -2178,7 +2477,7 @@ namespace ts { } } - function processTypeReferenceDirective(typeReferenceDirective: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective, + function processTypeReferenceDirective(typeReferenceDirective: string, resolvedTypeReferenceDirective?: ResolvedTypeReferenceDirective, refFile?: SourceFile, refPos?: number, refEnd?: number): void { // If we already found this library as a primary reference - nothing to do @@ -2188,6 +2487,8 @@ namespace ts { } let saveResolution = true; if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth++; + if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path processSourceFile(resolvedTypeReferenceDirective.resolvedFileName!, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 @@ -2216,6 +2517,8 @@ namespace ts { processSourceFile(resolvedTypeReferenceDirective.resolvedFileName!, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } + + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth--; } else { fileProcessingDiagnostics.add(createDiagnostic(refFile!, refPos!, refEnd!, Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 @@ -2261,8 +2564,7 @@ namespace ts { if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. const moduleNames = getModuleNames(file); - const oldProgramState: OldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths }; - const resolutions = resolveModuleNamesReusingOldState(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + const resolutions = resolveModuleNamesReusingOldState(moduleNames, getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); Debug.assert(resolutions.length === moduleNames.length); for (let i = 0; i < moduleNames.length; i++) { const resolution = resolutions[i]; @@ -2273,7 +2575,7 @@ namespace ts { } const isFromNodeModulesSearch = resolution.isExternalLibraryImport; - const isJsFile = !resolutionExtensionIsTypeScriptOrJson(resolution.extension); + const isJsFile = !resolutionExtensionIsTSOrJson(resolution.extension); const isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; const resolvedFileName = resolution.resolvedFileName; @@ -2295,7 +2597,7 @@ namespace ts { && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & NodeFlags.JSDoc)); + && (isInJSFile(file.imports[i]) || !(file.imports[i].flags & NodeFlags.JSDoc)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -2339,29 +2641,37 @@ namespace ts { return allFilesBelongToPath; } - function parseProjectReferenceConfigFile(ref: ProjectReference): { commandLine: ParsedCommandLine, sourceFile: SourceFile } | undefined { + function parseProjectReferenceConfigFile(ref: ProjectReference): ResolvedProjectReference | undefined { + if (!projectReferenceRedirects) { + projectReferenceRedirects = createMap(); + } + // The actual filename (i.e. add "/tsconfig.json" if necessary) - const refPath = resolveProjectReferencePath(host, ref); + const refPath = resolveProjectReferencePath(ref); + const sourceFilePath = toPath(refPath); + const fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } + // An absolute path pointing to the containing directory of the config file const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory()); const sourceFile = host.getSourceFile(refPath, ScriptTarget.JSON) as JsonSourceFile | undefined; + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); return undefined; } - sourceFile.path = toPath(refPath); + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; const commandLine = parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); - return { commandLine, sourceFile }; - } - - function addProjectReferenceRedirects(referencedProject: ParsedCommandLine, target: Map) { - const rootDir = normalizePath(referencedProject.options.rootDir || getDirectoryPath(referencedProject.options.configFilePath!)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - - function getDeclarationOutputDirectory(proj: ParsedCommandLine) { - return proj.options.declarationDir || - proj.options.outDir || - getDirectoryPath(proj.options.configFilePath!); // TODO: GH#18217 + const resolvedRef: ResolvedProjectReference = { commandLine, sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; } function verifyCompilerOptions() { @@ -2370,8 +2680,8 @@ namespace ts { } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { @@ -2406,29 +2716,7 @@ namespace ts { } } - if (projectReferences) { - for (let i = 0; i < projectReferences.length; i++) { - const ref = projectReferences[i]; - const resolvedRefOpts = resolvedProjectReferences![i] && resolvedProjectReferences![i]!.commandLine.options; - if (resolvedRefOpts === undefined) { - createDiagnosticForReference(i, Diagnostics.File_0_does_not_exist, ref.path); - continue; - } - if (!resolvedRefOpts.composite) { - createDiagnosticForReference(i, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - } - if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); - } - } - else { - createDiagnosticForReference(i, Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); - } - } - } - } + verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -2494,8 +2782,8 @@ namespace ts { } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); @@ -2503,7 +2791,7 @@ namespace ts { } if (options.declarationMap && !getEmitDeclarations(options)) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { @@ -2517,13 +2805,13 @@ namespace ts { const languageVersion = options.target || ScriptTarget.ES3; const outFile = options.outFile || options.out; - const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !f.isDeclarationFile ? f : undefined); + const firstNonAmbientExternalModuleSourceFile = find(files, f => isExternalModule(f) && !f.isDeclarationFile); if (options.isolatedModules) { if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES2015) { createDiagnosticForOptionName(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } - const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !f.isDeclarationFile ? f : undefined); + const firstNonExternalModuleSourceFile = find(files, f => !isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== ScriptKind.JSON); if (firstNonExternalModuleSourceFile) { const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -2536,7 +2824,7 @@ namespace ts { } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) { createDiagnosticForOptionName(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -2566,13 +2854,13 @@ namespace ts { const 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 === "" && forEach(files, file => getRootLength(file.fileName) > 1)) { + if (options.outDir && dir === "" && files.some(file => getRootLength(file.fileName) > 1)) { createDiagnosticForOptionName(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { @@ -2580,8 +2868,8 @@ namespace ts { } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { @@ -2646,6 +2934,36 @@ namespace ts { } } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, index, parent) => { + const ref = (parent ? parent.commandLine.projectReferences : projectReferences)![index]; + const parentFile = parent && parent.sourceFile as JsonSourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, Diagnostics.File_0_not_found, ref.path); + return; + } + const options = resolvedRef.commandLine.options; + if (!options.composite) { + // ok to not have composite if the current program is container only + const inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + } + if (ref.prepend) { + const out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } + function createDiagnosticForOptionPathKeyValue(key: string, valueIndex: number, message: DiagnosticMessage, arg0: string | number, arg1: string | number, arg2?: string | number) { let needCompilerDiagnostic = true; const pathsSyntax = getOptionPathsSyntax(); @@ -2702,10 +3020,11 @@ namespace ts { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } - function createDiagnosticForReference(index: number, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number) { - const referencesSyntax = getProjectReferencesSyntax(); + function createDiagnosticForReference(sourceFile: JsonSourceFile | undefined, index: number, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number) { + const referencesSyntax = firstDefined(getTsConfigPropArray(sourceFile || options.configFile, "references"), + property => isArrayLiteralExpression(property.initializer) ? property.initializer : undefined); if (referencesSyntax && referencesSyntax.elements.length > index) { - programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile!, referencesSyntax.elements[index], message, arg0, arg1)); + programDiagnostics.add(createDiagnosticForNodeInSourceFile(sourceFile || options.configFile!, referencesSyntax.elements[index], message, arg0, arg1)); } else { programDiagnostics.add(createCompilerDiagnostic(message, arg0, arg1)); @@ -2722,22 +3041,6 @@ namespace ts { } } - function getProjectReferencesSyntax(): ArrayLiteralExpression | null { - if (_referencesArrayLiteralSyntax === undefined) { - _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile) { - const jsonObjectLiteral = getTsConfigObjectLiteralExpression(options.configFile)!; // TODO: GH#18217 - for (const prop of getPropertyAssignment(jsonObjectLiteral, "references")) { - if (isArrayLiteralExpression(prop.initializer)) { - _referencesArrayLiteralSyntax = prop.initializer; - break; - } - } - } - } - return _referencesArrayLiteralSyntax; - } - function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword @@ -2794,7 +3097,7 @@ namespace ts { return containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (fileExtensionIsOneOf(filePath, supportedJavascriptExtensions) || fileExtensionIs(filePath, Extension.Dts)) { + if (fileExtensionIsOneOf(filePath, supportedJSExtensions) || fileExtensionIs(filePath, Extension.Dts)) { // Otherwise just check if sourceFile with the name exists const filePathWithoutExtension = removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + Extension.Ts) as Path) || @@ -2808,32 +3111,51 @@ namespace ts { } } + interface CompilerHostLike { + useCaseSensitiveFileNames(): boolean; + getCurrentDirectory(): string; + fileExists(fileName: string): boolean; + readFile(fileName: string): string | undefined; + readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + trace?(s: string): void; + onUnRecoverableConfigFileDiagnostic?: DiagnosticReporter; + } + /* @internal */ - export function parseConfigHostFromCompilerHost(host: CompilerHost): ParseConfigFileHost { + export function parseConfigHostFromCompilerHostLike(host: CompilerHostLike, directoryStructureHost: DirectoryStructureHost = host): ParseConfigFileHost { return { - fileExists: f => host.fileExists(f), - readDirectory: (root, extensions, includes, depth?) => host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : [], - readFile: f => host.readFile(f), + fileExists: f => directoryStructureHost.fileExists(f), + readDirectory(root, extensions, excludes, includes, depth) { + Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return directoryStructureHost.readDirectory!(root, extensions, excludes, includes, depth); + }, + readFile: f => directoryStructureHost.readFile(f), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: () => host.getCurrentDirectory(), - onUnRecoverableConfigFileDiagnostic: () => undefined + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (() => undefined), + trace: host.trace ? (s) => host.trace!(s) : undefined }; } - export interface ResolveProjectReferencePathHost { + // For backward compatibility + /** @deprecated */ export interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } + /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - export function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName { - if (!host.fileExists(ref.path)) { - return combinePaths(ref.path, "tsconfig.json") as ResolvedConfigFileName; - } - return ref.path as ResolvedConfigFileName; + export function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ export function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + export function resolveProjectReferencePath(hostOrRef: ResolveProjectReferencePathHost | ProjectReference, ref?: ProjectReference): ResolvedConfigFileName { + const passedInRef = ref ? ref : hostOrRef as ProjectReference; + return resolveConfigFileProjectName(passedInRef.path); } + function getEmitDeclarationOptionName(options: CompilerOptions) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 2d7bcb34c2d..237c1637d31 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -5,12 +5,13 @@ namespace ts { startRecordingFilesWithChangedResolutions(): void; finishRecordingFilesWithChangedResolutions(): Path[] | undefined; - resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined): ResolvedModuleFull[]; + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): CachedResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; invalidateResolutionOfFile(filePath: Path): void; removeResolutionsOfFile(filePath: Path): void; + removeResolutionsFromProjectReferenceRedirects(filePath: Path): void; setFilesWithInvalidatedNonRelativeUnresolvedImports(filesWithUnresolvedImports: Map>): void; createHasInvalidatedResolution(forceAllFilesAsInvalidated?: boolean): HasInvalidatedResolution; @@ -68,7 +69,10 @@ namespace ts { dir: string; dirPath: Path; nonRecursive?: boolean; - ignore?: true; + } + + export function isPathInNodeModulesStartingWithDot(path: Path) { + return stringContains(path, "/node_modules/."); } export const maxNumberOfFilesToIterateForInvalidation = 256; @@ -79,7 +83,7 @@ namespace ts { export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string | undefined, logChangesWhenResolvingModule: boolean): ResolutionCache { let filesWithChangedSetOfUnresolvedImports: Path[] | undefined; let filesWithInvalidatedResolutions: Map | undefined; - let filesWithInvalidatedNonRelativeUnresolvedImports: Map> | undefined; + let filesWithInvalidatedNonRelativeUnresolvedImports: ReadonlyMap> | undefined; let allFilesHaveInvalidatedResolution = false; const nonRelativeExternalModuleResolutions = createMultiMap(); @@ -90,17 +94,17 @@ namespace ts { // The key in the map is source file's path. // The values are Map of resolutions with key being name lookedup. const resolvedModuleNames = createMap>(); - const perDirectoryResolvedModuleNames = createMap>(); - const nonRelaticeModuleNameCache = createMap(); + const perDirectoryResolvedModuleNames: CacheWithRedirects> = createCacheWithRedirects(); + const nonRelativeModuleNameCache: CacheWithRedirects = createCacheWithRedirects(); const moduleResolutionCache = createModuleResolutionCacheWithMaps( perDirectoryResolvedModuleNames, - nonRelaticeModuleNameCache, + nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName ); const resolvedTypeReferenceDirectives = createMap>(); - const perDirectoryResolvedTypeReferenceDirectives = createMap>(); + const perDirectoryResolvedTypeReferenceDirectives: CacheWithRedirects> = createCacheWithRedirects(); /** * These are the extensions that failed lookup files will have by default, @@ -128,6 +132,7 @@ namespace ts { resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile, invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -199,7 +204,7 @@ namespace ts { function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -217,8 +222,8 @@ namespace ts { }); } - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): CachedResolvedModuleWithFailedLookupLocations { - const primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): CachedResolvedModuleWithFailedLookupLocations { + const primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { return primaryResult; @@ -226,7 +231,7 @@ namespace ts { // otherwise try to load typings from @types const globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results const { resolvedModule, failedLookupLocations } = loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache); @@ -240,41 +245,52 @@ namespace ts { } function resolveNamesWithLocalCache( - names: string[], + names: ReadonlyArray, containingFile: string, + redirectedReference: ResolvedProjectReference | undefined, cache: Map>, - perDirectoryCache: Map>, - loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => T, + perDirectoryCacheWithRedirects: CacheWithRedirects>, + loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference) => T, getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName, - reusedNames: string[] | undefined, - logChanges: boolean): R[] { + shouldRetryResolution: (t: T) => boolean, + reusedNames: ReadonlyArray | undefined, + logChanges: boolean): (R | undefined)[] { const path = resolutionHost.toPath(containingFile); const resolutionsInFile = cache.get(path) || cache.set(path, createMap()).get(path)!; const dirPath = getDirectoryPath(path); + const perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); let perDirectoryResolution = perDirectoryCache.get(dirPath); if (!perDirectoryResolution) { perDirectoryResolution = createMap(); perDirectoryCache.set(dirPath, perDirectoryResolution); } - const resolvedModules: R[] = []; + const resolvedModules: (R | undefined)[] = []; const compilerOptions = resolutionHost.getCompilationSettings(); const hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + const program = resolutionHost.getCurrentProgram(); + const oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + const unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; + const seenNamesInFile = createMap(); for (const name of names) { let resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - (hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { + (hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { const existingResolution = resolution; const resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { resolution = resolutionInDirectory; } else { - resolution = loader(name, containingFile, compilerOptions, resolutionHost); + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); @@ -291,7 +307,7 @@ namespace ts { } Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)!); // TODO: GH#18217 + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); } // Stop watching and remove the unused name @@ -323,20 +339,22 @@ namespace ts { } } - function resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] { + function resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[] { return resolveNamesWithLocalCache( - typeDirectiveNames, containingFile, + typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ resolution => resolution.resolvedTypeReferenceDirective === undefined, /*reusedNames*/ undefined, /*logChanges*/ false ); } - function resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined): ResolvedModuleFull[] { + function resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[] { return resolveNamesWithLocalCache( - moduleNames, containingFile, + moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ resolution => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), reusedNames, logChangesWhenResolvingModule ); } @@ -389,16 +407,10 @@ namespace ts { return true; } - function filterFSRootDirectoriesToWatch(watchPath: DirectoryOfFailedLookupWatch, dirPath: Path): DirectoryOfFailedLookupWatch { - if (!canWatchDirectory(dirPath)) { - watchPath.ignore = true; - } - return watchPath; - } - - function getDirectoryToWatchFailedLookupLocation(failedLookupLocation: string, failedLookupLocationPath: Path): DirectoryOfFailedLookupWatch { + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation: string, failedLookupLocationPath: Path): DirectoryOfFailedLookupWatch | undefined { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, `FailedLookup: ${failedLookupLocation} failedLookupLocationPath: ${failedLookupLocationPath}`); // tslint:disable-line const subDirectoryInRoot = failedLookupLocationPath.indexOf(directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -417,16 +429,16 @@ namespace ts { ); } - function getDirectoryToWatchFromFailedLookupLocationDirectory(dir: string, dirPath: Path) { + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir: string, dirPath: Path): DirectoryOfFailedLookupWatch | undefined { // If directory path contains node module, get the most parent node_modules directory for watching - while (stringContains(dirPath, nodeModulesPathPart)) { + while (pathContainsNodeModules(dirPath)) { dir = getDirectoryPath(dir); dirPath = getDirectoryPath(dirPath); } // If the directory is node_modules use it to watch, always watch it recursively if (isNodeModulesDirectory(dirPath)) { - return filterFSRootDirectoriesToWatch({ dir, dirPath }, getDirectoryPath(dirPath)); + return canWatchDirectory(getDirectoryPath(dirPath)) ? { dir, dirPath } : undefined; } let nonRecursive = true; @@ -446,7 +458,7 @@ namespace ts { } } - return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive }, dirPath); + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path: Path) { @@ -478,8 +490,9 @@ namespace ts { let setAtRoot = false; for (const failedLookupLocation of failedLookupLocations) { const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const { dir, dirPath, nonRecursive, ignore } = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (!ignore) { + const toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + const { dir, dirPath, nonRecursive } = toWatch; // If the failed lookup location path is not one of the supported extensions, // store it in the custom path if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { @@ -538,8 +551,9 @@ namespace ts { let removeAtRoot = false; for (const failedLookupLocation of failedLookupLocations) { const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const { dirPath, ignore } = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (!ignore) { + const toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + const { dirPath } = toWatch; const refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { if (refCount === 1) { @@ -593,6 +607,20 @@ namespace ts { } } + function removeResolutionsFromProjectReferenceRedirects(filePath: Path) { + if (!fileExtensionIs(filePath, Extension.Json)) { return; } + + const program = resolutionHost.getCurrentProgram(); + if (!program) { return; } + + // If this file is input file for the referenced project, get it + const resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { return; } + + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(f => removeResolutionsOfFile(resolutionHost.toPath(f))); + } + function removeResolutionsOfFile(filePath: Path) { removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); @@ -654,7 +682,7 @@ namespace ts { ); } - function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap: Map>) { + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap: ReadonlyMap>) { Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; } @@ -667,6 +695,9 @@ namespace ts { isChangedFailedLookupLocation = location => isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); } else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return false; + // Some file or directory in the watching directory is created // Return early if it does not have any of the watching extension or not the custom failed lookup path const dirOfFileOrDirectory = getDirectoryPath(fileOrDirectoryPath); @@ -711,8 +742,8 @@ namespace ts { if (isInDirectoryPath(rootPath, typeRootPath)) { return rootPath; } - const { dirPath, ignore } = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; + const toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; } function createTypeRootsWatch(typeRootPath: Path, typeRoot: string): FileWatcher { diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 90e0c9f7681..4f3eba37296 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -61,81 +61,88 @@ namespace ts { tryScan(callback: () => T): T; } - const textToToken = createMapFromTemplate({ - "abstract": SyntaxKind.AbstractKeyword, - "any": SyntaxKind.AnyKeyword, - "as": SyntaxKind.AsKeyword, - "boolean": SyntaxKind.BooleanKeyword, - "break": SyntaxKind.BreakKeyword, - "case": SyntaxKind.CaseKeyword, - "catch": SyntaxKind.CatchKeyword, - "class": SyntaxKind.ClassKeyword, - "continue": SyntaxKind.ContinueKeyword, - "const": SyntaxKind.ConstKeyword, - "constructor": SyntaxKind.ConstructorKeyword, - "debugger": SyntaxKind.DebuggerKeyword, - "declare": SyntaxKind.DeclareKeyword, - "default": SyntaxKind.DefaultKeyword, - "delete": SyntaxKind.DeleteKeyword, - "do": SyntaxKind.DoKeyword, - "else": SyntaxKind.ElseKeyword, - "enum": SyntaxKind.EnumKeyword, - "export": SyntaxKind.ExportKeyword, - "extends": SyntaxKind.ExtendsKeyword, - "false": SyntaxKind.FalseKeyword, - "finally": SyntaxKind.FinallyKeyword, - "for": SyntaxKind.ForKeyword, - "from": SyntaxKind.FromKeyword, - "function": SyntaxKind.FunctionKeyword, - "get": SyntaxKind.GetKeyword, - "if": SyntaxKind.IfKeyword, - "implements": SyntaxKind.ImplementsKeyword, - "import": SyntaxKind.ImportKeyword, - "in": SyntaxKind.InKeyword, - "infer": SyntaxKind.InferKeyword, - "instanceof": SyntaxKind.InstanceOfKeyword, - "interface": SyntaxKind.InterfaceKeyword, - "is": SyntaxKind.IsKeyword, - "keyof": SyntaxKind.KeyOfKeyword, - "let": SyntaxKind.LetKeyword, - "module": SyntaxKind.ModuleKeyword, - "namespace": SyntaxKind.NamespaceKeyword, - "never": SyntaxKind.NeverKeyword, - "new": SyntaxKind.NewKeyword, - "null": SyntaxKind.NullKeyword, - "number": SyntaxKind.NumberKeyword, - "object": SyntaxKind.ObjectKeyword, - "package": SyntaxKind.PackageKeyword, - "private": SyntaxKind.PrivateKeyword, - "protected": SyntaxKind.ProtectedKeyword, - "public": SyntaxKind.PublicKeyword, - "readonly": SyntaxKind.ReadonlyKeyword, - "require": SyntaxKind.RequireKeyword, - "global": SyntaxKind.GlobalKeyword, - "return": SyntaxKind.ReturnKeyword, - "set": SyntaxKind.SetKeyword, - "static": SyntaxKind.StaticKeyword, - "string": SyntaxKind.StringKeyword, - "super": SyntaxKind.SuperKeyword, - "switch": SyntaxKind.SwitchKeyword, - "symbol": SyntaxKind.SymbolKeyword, - "this": SyntaxKind.ThisKeyword, - "throw": SyntaxKind.ThrowKeyword, - "true": SyntaxKind.TrueKeyword, - "try": SyntaxKind.TryKeyword, - "type": SyntaxKind.TypeKeyword, - "typeof": SyntaxKind.TypeOfKeyword, - "undefined": SyntaxKind.UndefinedKeyword, - "unique": SyntaxKind.UniqueKeyword, - "unknown": SyntaxKind.UnknownKeyword, - "var": SyntaxKind.VarKeyword, - "void": SyntaxKind.VoidKeyword, - "while": SyntaxKind.WhileKeyword, - "with": SyntaxKind.WithKeyword, - "yield": SyntaxKind.YieldKeyword, - "async": SyntaxKind.AsyncKeyword, - "await": SyntaxKind.AwaitKeyword, - "of": SyntaxKind.OfKeyword, + const textToKeywordObj: MapLike = { + abstract: SyntaxKind.AbstractKeyword, + any: SyntaxKind.AnyKeyword, + as: SyntaxKind.AsKeyword, + bigint: SyntaxKind.BigIntKeyword, + boolean: SyntaxKind.BooleanKeyword, + break: SyntaxKind.BreakKeyword, + case: SyntaxKind.CaseKeyword, + catch: SyntaxKind.CatchKeyword, + class: SyntaxKind.ClassKeyword, + continue: SyntaxKind.ContinueKeyword, + const: SyntaxKind.ConstKeyword, + ["" + "constructor"]: SyntaxKind.ConstructorKeyword, + debugger: SyntaxKind.DebuggerKeyword, + declare: SyntaxKind.DeclareKeyword, + default: SyntaxKind.DefaultKeyword, + delete: SyntaxKind.DeleteKeyword, + do: SyntaxKind.DoKeyword, + else: SyntaxKind.ElseKeyword, + enum: SyntaxKind.EnumKeyword, + export: SyntaxKind.ExportKeyword, + extends: SyntaxKind.ExtendsKeyword, + false: SyntaxKind.FalseKeyword, + finally: SyntaxKind.FinallyKeyword, + for: SyntaxKind.ForKeyword, + from: SyntaxKind.FromKeyword, + function: SyntaxKind.FunctionKeyword, + get: SyntaxKind.GetKeyword, + if: SyntaxKind.IfKeyword, + implements: SyntaxKind.ImplementsKeyword, + import: SyntaxKind.ImportKeyword, + in: SyntaxKind.InKeyword, + infer: SyntaxKind.InferKeyword, + instanceof: SyntaxKind.InstanceOfKeyword, + interface: SyntaxKind.InterfaceKeyword, + is: SyntaxKind.IsKeyword, + keyof: SyntaxKind.KeyOfKeyword, + let: SyntaxKind.LetKeyword, + module: SyntaxKind.ModuleKeyword, + namespace: SyntaxKind.NamespaceKeyword, + never: SyntaxKind.NeverKeyword, + new: SyntaxKind.NewKeyword, + null: SyntaxKind.NullKeyword, + number: SyntaxKind.NumberKeyword, + object: SyntaxKind.ObjectKeyword, + package: SyntaxKind.PackageKeyword, + private: SyntaxKind.PrivateKeyword, + protected: SyntaxKind.ProtectedKeyword, + public: SyntaxKind.PublicKeyword, + readonly: SyntaxKind.ReadonlyKeyword, + require: SyntaxKind.RequireKeyword, + global: SyntaxKind.GlobalKeyword, + return: SyntaxKind.ReturnKeyword, + set: SyntaxKind.SetKeyword, + static: SyntaxKind.StaticKeyword, + string: SyntaxKind.StringKeyword, + super: SyntaxKind.SuperKeyword, + switch: SyntaxKind.SwitchKeyword, + symbol: SyntaxKind.SymbolKeyword, + this: SyntaxKind.ThisKeyword, + throw: SyntaxKind.ThrowKeyword, + true: SyntaxKind.TrueKeyword, + try: SyntaxKind.TryKeyword, + type: SyntaxKind.TypeKeyword, + typeof: SyntaxKind.TypeOfKeyword, + undefined: SyntaxKind.UndefinedKeyword, + unique: SyntaxKind.UniqueKeyword, + unknown: SyntaxKind.UnknownKeyword, + var: SyntaxKind.VarKeyword, + void: SyntaxKind.VoidKeyword, + while: SyntaxKind.WhileKeyword, + with: SyntaxKind.WithKeyword, + yield: SyntaxKind.YieldKeyword, + async: SyntaxKind.AsyncKeyword, + await: SyntaxKind.AwaitKeyword, + of: SyntaxKind.OfKeyword, + }; + + const textToKeyword = createMapFromTemplate(textToKeywordObj); + + const textToToken = createMapFromTemplate({ + ...textToKeywordObj, "{": SyntaxKind.OpenBraceToken, "}": SyntaxKind.CloseBraceToken, "(": SyntaxKind.OpenParenToken, @@ -331,17 +338,35 @@ namespace ts { return result; } - export function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number): number { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + export function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number): number; + /* @internal */ + // tslint:disable-next-line:unified-signatures + export function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number, allowEdits?: true): number; + export function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number, allowEdits?: true): number { + return sourceFile.getPositionOfLineAndCharacter ? + sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) : + computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits); } /* @internal */ - export function computePositionOfLineAndCharacter(lineStarts: ReadonlyArray, line: number, character: number, debugText?: string): number { + export function computePositionOfLineAndCharacter(lineStarts: ReadonlyArray, line: number, character: number, debugText?: string, allowEdits?: true): number { if (line < 0 || line >= lineStarts.length) { - Debug.fail(`Bad line number. Line: ${line}, lineStarts.length: ${lineStarts.length} , line map is correct? ${debugText !== undefined ? arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"}`); + if (allowEdits) { + // Clamp line to nearest allowable value + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } + else { + Debug.fail(`Bad line number. Line: ${line}, lineStarts.length: ${lineStarts.length} , line map is correct? ${debugText !== undefined ? arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"}`); + } } const res = lineStarts[line] + character; + if (allowEdits) { + // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead) + // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and + // apply them to the computed position to improve accuracy + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } if (line < lineStarts.length - 1) { Debug.assert(res < lineStarts[line + 1]); } @@ -915,7 +940,7 @@ namespace ts { return result + text.substring(start, pos); } - function scanNumber(): string { + function scanNumber(): {type: SyntaxKind, value: string} { const start = pos; const mainFragment = scanNumberFragment(); let decimalFragment: string | undefined; @@ -939,18 +964,54 @@ namespace ts { end = pos; } } + let result: string; if (tokenFlags & TokenFlags.ContainsSeparator) { - let result = mainFragment; + result = mainFragment; if (decimalFragment) { result += "." + decimalFragment; } if (scientificFragment) { result += scientificFragment; } - return "" + +result; } else { - return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + + if (decimalFragment !== undefined || tokenFlags & TokenFlags.Scientific) { + checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & TokenFlags.Scientific)); + return { + type: SyntaxKind.NumericLiteral, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; + } + else { + tokenValue = result; + const type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + checkForIdentifierStartAfterNumericLiteral(start); + return { type, value: tokenValue }; + } + } + + function checkForIdentifierStartAfterNumericLiteral(numericStart: number, isScientific?: boolean) { + if (!isIdentifierStart(text.charCodeAt(pos), languageVersion)) { + return; + } + + const identifierStart = pos; + const { length } = scanIdentifierParts(); + + if (length === 1 && text[identifierStart] === "n") { + if (isScientific) { + error(Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); + } + else { + error(Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1); + } + } + else { + error(Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length); + pos = identifierStart; } } @@ -967,24 +1028,24 @@ namespace ts { * returning -1 if the given number is unavailable. */ function scanExactNumberOfHexDigits(count: number, canHaveSeparators: boolean): number { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + const valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; } /** * Scans as many hexadecimal digits as are available in the text, - * returning -1 if the given number of digits was unavailable. + * returning "" if the given number of digits was unavailable. */ - function scanMinimumNumberOfHexDigits(count: number, canHaveSeparators: boolean): number { + function scanMinimumNumberOfHexDigits(count: number, canHaveSeparators: boolean): string { return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } - function scanHexDigits(minCount: number, scanAsManyAsPossible: boolean, canHaveSeparators: boolean): number { - let digits = 0; - let value = 0; + function scanHexDigits(minCount: number, scanAsManyAsPossible: boolean, canHaveSeparators: boolean): string { + let valueChars: number[] = []; let allowSeparator = false; let isPreviousTokenSeparator = false; - while (digits < minCount || scanAsManyAsPossible) { - const ch = text.charCodeAt(pos); + while (valueChars.length < minCount || scanAsManyAsPossible) { + let ch = text.charCodeAt(pos); if (canHaveSeparators && ch === CharacterCodes._) { tokenFlags |= TokenFlags.ContainsSeparator; if (allowSeparator) { @@ -1001,29 +1062,25 @@ namespace ts { continue; } allowSeparator = canHaveSeparators; - if (ch >= CharacterCodes._0 && ch <= CharacterCodes._9) { - value = value * 16 + ch - CharacterCodes._0; + if (ch >= CharacterCodes.A && ch <= CharacterCodes.F) { + ch += CharacterCodes.a - CharacterCodes.A; // standardize hex literals to lowercase } - else if (ch >= CharacterCodes.A && ch <= CharacterCodes.F) { - value = value * 16 + ch - CharacterCodes.A + 10; - } - else if (ch >= CharacterCodes.a && ch <= CharacterCodes.f) { - value = value * 16 + ch - CharacterCodes.a + 10; - } - else { + else if (!((ch >= CharacterCodes._0 && ch <= CharacterCodes._9) || + (ch >= CharacterCodes.a && ch <= CharacterCodes.f) + )) { break; } + valueChars.push(ch); pos++; - digits++; isPreviousTokenSeparator = false; } - if (digits < minCount) { - value = -1; + if (valueChars.length < minCount) { + valueChars = []; } if (text.charCodeAt(pos - 1) === CharacterCodes._) { error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } - return value; + return String.fromCharCode(...valueChars); } function scanString(jsxAttributeString = false): string { @@ -1203,7 +1260,8 @@ namespace ts { } function scanExtendedUnicodeEscape(): string { - const escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + const escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; let isInvalidExtendedEscape = false; // Validate the value of the digit @@ -1290,28 +1348,25 @@ namespace ts { return result; } - function getIdentifierToken(): SyntaxKind { + function getIdentifierToken(): SyntaxKind.Identifier | KeywordSyntaxKind { // Reserved words are between 2 and 11 characters long and start with a lowercase letter const len = tokenValue.length; if (len >= 2 && len <= 11) { const ch = tokenValue.charCodeAt(0); if (ch >= CharacterCodes.a && ch <= CharacterCodes.z) { - token = textToToken.get(tokenValue)!; - if (token !== undefined) { - return token; + const keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } return token = SyntaxKind.Identifier; } - function scanBinaryOrOctalDigits(base: number): number { - Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); - - let value = 0; + function scanBinaryOrOctalDigits(base: 2 | 8): string { + let value = ""; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. - let numberOfDigits = 0; let separatorAllowed = false; let isPreviousTokenSeparator = false; while (true) { @@ -1333,27 +1388,42 @@ namespace ts { continue; } separatorAllowed = true; - const valueOfCh = ch - CharacterCodes._0; - if (!isDigit(ch) || valueOfCh >= base) { + if (!isDigit(ch) || ch - CharacterCodes._0 >= base) { break; } - value = value * base + valueOfCh; + value += text[pos]; pos++; - numberOfDigits++; isPreviousTokenSeparator = false; } - // Invalid binaryIntegerLiteral or octalIntegerLiteral - if (numberOfDigits === 0) { - return -1; - } if (text.charCodeAt(pos - 1) === CharacterCodes._) { // Literal ends with underscore - not allowed error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); - return value; } return value; } + function checkBigIntSuffix(): SyntaxKind { + if (text.charCodeAt(pos) === CharacterCodes.n) { + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & TokenFlags.BinaryOrOctalSpecifier) { + tokenValue = parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return SyntaxKind.BigIntLiteral; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + const numericValue = tokenFlags & TokenFlags.BinarySpecifier + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & TokenFlags.OctalSpecifier + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + return SyntaxKind.NumericLiteral; + } + } + function scan(): SyntaxKind { startPos = pos; tokenFlags = 0; @@ -1502,7 +1572,7 @@ namespace ts { return token = SyntaxKind.MinusToken; case CharacterCodes.dot: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber(); + tokenValue = scanNumber().value; return token = SyntaxKind.NumericLiteral; } if (text.charCodeAt(pos + 1) === CharacterCodes.dot && text.charCodeAt(pos + 2) === CharacterCodes.dot) { @@ -1578,36 +1648,36 @@ namespace ts { case CharacterCodes._0: if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.X || text.charCodeAt(pos + 1) === CharacterCodes.x)) { pos += 2; - let value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); - if (value < 0) { + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { error(Diagnostics.Hexadecimal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0x" + tokenValue; tokenFlags |= TokenFlags.HexSpecifier; - return token = SyntaxKind.NumericLiteral; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.B || text.charCodeAt(pos + 1) === CharacterCodes.b)) { pos += 2; - let value = scanBinaryOrOctalDigits(/* base */ 2); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { error(Diagnostics.Binary_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0b" + tokenValue; tokenFlags |= TokenFlags.BinarySpecifier; - return token = SyntaxKind.NumericLiteral; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.O || text.charCodeAt(pos + 1) === CharacterCodes.o)) { pos += 2; - let value = scanBinaryOrOctalDigits(/* base */ 8); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { error(Diagnostics.Octal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0o" + tokenValue; tokenFlags |= TokenFlags.OctalSpecifier; - return token = SyntaxKind.NumericLiteral; + return token = checkBigIntSuffix(); } // Try to parse as an octal if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { @@ -1628,8 +1698,8 @@ namespace ts { case CharacterCodes._7: case CharacterCodes._8: case CharacterCodes._9: - tokenValue = scanNumber(); - return token = SyntaxKind.NumericLiteral; + ({ type: token, value: tokenValue } = scanNumber()); + return token; case CharacterCodes.colon: pos++; return token = SyntaxKind.ColonToken; @@ -2026,7 +2096,7 @@ namespace ts { pos++; } tokenValue = text.substring(tokenPos, pos); - return token = SyntaxKind.Identifier; + return token = getIdentifierToken(); } else { return token = SyntaxKind.Unknown; diff --git a/src/compiler/semver.ts b/src/compiler/semver.ts new file mode 100644 index 00000000000..33623f45542 --- /dev/null +++ b/src/compiler/semver.ts @@ -0,0 +1,391 @@ +/* @internal */ +namespace ts { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + const versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + const prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + const buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + const numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + + /** + * Describes a precise semantic version number, https://semver.org + */ + export class Version { + static readonly zero = new Version(0, 0, 0); + + readonly major: number; + readonly minor: number; + readonly patch: number; + readonly prerelease: ReadonlyArray; + readonly build: ReadonlyArray; + + constructor(text: string); + constructor(major: number, minor?: number, patch?: number, prerelease?: string, build?: string); + constructor(major: number | string, minor = 0, patch = 0, prerelease = "", build = "") { + if (typeof major === "string") { + const result = Debug.assertDefined(tryParseComponents(major), "Invalid version"); + ({ major, minor, patch, prerelease, build } = result); + } + + Debug.assert(major >= 0, "Invalid argument: major"); + Debug.assert(minor >= 0, "Invalid argument: minor"); + Debug.assert(patch >= 0, "Invalid argument: patch"); + Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : emptyArray; + this.build = build ? build.split(".") : emptyArray; + } + + static tryParse(text: string) { + const result = tryParseComponents(text); + if (!result) return undefined; + + const { major, minor, patch, prerelease, build } = result; + return new Version(major, minor, patch, prerelease, build); + } + + compareTo(other: Version | undefined) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) return Comparison.EqualTo; + if (other === undefined) return Comparison.GreaterThan; + return compareValues(this.major, other.major) + || compareValues(this.minor, other.minor) + || compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + } + + increment(field: "major" | "minor" | "patch") { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return Debug.assertNever(field); + } + } + + toString() { + let result = `${this.major}.${this.minor}.${this.patch}`; + if (some(this.prerelease)) result += `-${this.prerelease.join(".")}`; + if (some(this.build)) result += `+${this.build.join(".")}`; + return result; + } + } + + function tryParseComponents(text: string) { + const match = versionRegExp.exec(text); + if (!match) return undefined; + + const [, major, minor = "0", patch = "0", prerelease = "", build = ""] = match; + if (prerelease && !prereleaseRegExp.test(prerelease)) return undefined; + if (build && !buildRegExp.test(build)) return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease, + build + }; + } + + function comparePrerelaseIdentifiers(left: ReadonlyArray, right: ReadonlyArray) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) return Comparison.EqualTo; + if (left.length === 0) return right.length === 0 ? Comparison.EqualTo : Comparison.GreaterThan; + if (right.length === 0) return Comparison.LessThan; + + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftIdentifier = left[i]; + const rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) continue; + + const leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + const rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) return leftIsNumeric ? Comparison.LessThan : Comparison.GreaterThan; + + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + const result = compareValues(+leftIdentifier, +rightIdentifier); + if (result) return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + const result = compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) return result; + } + } + + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return compareValues(left.length, right.length); + } + + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + export class VersionRange { + private _alternatives: ReadonlyArray>; + + constructor(spec: string) { + this._alternatives = spec ? Debug.assertDefined(parseRange(spec), "Invalid range spec.") : emptyArray; + } + + static tryParse(text: string) { + const sets = parseRange(text); + if (sets) { + const range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + } + + test(version: Version | string) { + if (typeof version === "string") version = new Version(version); + return testDisjunction(version, this._alternatives); + } + + toString() { + return formatDisjunction(this._alternatives); + } + } + + interface Comparator { + readonly operator: "<" | "<=" | ">" | ">=" | "="; + readonly operand: Version; + } + + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + const logicalOrRegExp = /\s*\|\|\s*/g; + const whitespaceRegExp = /\s+/g; + + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + const partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + const hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + const rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + + function parseRange(text: string) { + const alternatives: Comparator[][] = []; + for (const range of text.trim().split(logicalOrRegExp)) { + if (!range) continue; + const comparators: Comparator[] = []; + const match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) return undefined; + } + else { + for (const simple of range.split(whitespaceRegExp)) { + const match = rangeRegExp.exec(simple); + if (!match || !parseComparator(match[1], match[2], comparators)) return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + + function parsePartial(text: string) { + const match = partialRegExp.exec(text); + if (!match) return undefined; + + const [, major, minor = "*", patch = "*", prerelease, build] = match; + const version = new Version( + isWildcard(major) ? 0 : parseInt(major, 10), + isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), + isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), + prerelease, + build); + + return { version, major, minor, patch }; + } + + function parseHyphen(left: string, right: string, comparators: Comparator[]) { + const leftResult = parsePartial(left); + if (!leftResult) return false; + + const rightResult = parsePartial(right); + if (!rightResult) return false; + + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + + if (!isWildcard(rightResult.major)) { + comparators.push( + isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + + return true; + } + + function parseComparator(operator: string, text: string, comparators: Comparator[]) { + const result = parsePartial(text); + if (!result) return false; + + const { version, major, minor, patch } = result; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment( + isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment( + version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push( + isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + + return true; + } + + function isWildcard(part: string) { + return part === "*" || part === "x" || part === "X"; + } + + function createComparator(operator: Comparator["operator"], operand: Version) { + return { operator, operand }; + } + + function testDisjunction(version: Version, alternatives: ReadonlyArray>) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) return true; + for (const alternative of alternatives) { + if (testAlternative(version, alternative)) return true; + } + return false; + } + + function testAlternative(version: Version, comparators: ReadonlyArray) { + for (const comparator of comparators) { + if (!testComparator(version, comparator.operator, comparator.operand)) return false; + } + return true; + } + + function testComparator(version: Version, operator: Comparator["operator"], operand: Version) { + const cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return Debug.assertNever(operator); + } + } + + function formatDisjunction(alternatives: ReadonlyArray>) { + return map(alternatives, formatAlternative).join(" || ") || "*"; + } + + function formatAlternative(comparators: ReadonlyArray) { + return map(comparators, formatComparator).join(" "); + } + + function formatComparator(comparator: Comparator) { + return `${comparator.operator}${comparator.operand}`; + } +} \ No newline at end of file diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index eff543849cd..c2597d688d8 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -1,595 +1,532 @@ /* @internal */ namespace ts { - export interface SourceMapWriter { - /** - * Initialize the SourceMapWriter for a new output file. - * - * @param filePath The path to the generated output file. - * @param sourceMapFilePath The path to the output source map file. - * @param sourceFileOrBundle The input source file or bundle for the program. - */ - initialize(filePath: string, sourceMapFilePath: string | undefined, sourceFileOrBundle: SourceFile | Bundle, sourceMapOutput?: SourceMapData[]): void; - - /** - * Reset the SourceMapWriter to an empty state. - */ - reset(): void; - - /** - * Set the current source file. - * - * @param sourceFile The source file. - */ - setSourceFile(sourceFile: SourceMapSource): void; - - /** - * Emits a mapping. - * - * If the position is synthetic (undefined or a negative value), no mapping will be - * created. - * - * @param pos The position. - */ - emitPos(pos: number): void; - - /** - * Emits a node with possible leading and trailing source maps. - * - * @param hint The current emit context - * @param node The node to emit. - * @param emitCallback The callback used to emit the node. - */ - emitNodeWithSourceMap(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; - - /** - * Emits a token of a node node with possible leading and trailing source maps. - * - * @param node The node containing the token. - * @param token The token to emit. - * @param tokenStartPos The start pos of the token. - * @param emitCallback The callback used to emit the token. - */ - emitTokenWithSourceMap(node: Node, token: SyntaxKind, writer: (s: string) => void, tokenStartPos: number, emitCallback: (token: SyntaxKind, writer: (s: string) => void, tokenStartPos: number) => number): number; - - /** - * Gets the text for the source map. - */ - getText(): string; - - /** - * Gets the SourceMappingURL for the source map. - */ - getSourceMappingURL(): string; - } - - // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans - const defaultLastEncodedSourceMapSpan: SourceMapSpan = { - emittedLine: 0, - emittedColumn: 0, - sourceLine: 0, - sourceColumn: 0, - sourceIndex: 0 - }; - - export interface SourceMapOptions { - sourceMap?: boolean; - inlineSourceMap?: boolean; - inlineSources?: boolean; - sourceRoot?: string; - mapRoot?: string; + export interface SourceMapGeneratorOptions { extendedDiagnostics?: boolean; } - export function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter, compilerOptions: SourceMapOptions = host.getCompilerOptions()): SourceMapWriter { - const extendedDiagnostics = compilerOptions.extendedDiagnostics; - let currentSource: SourceMapSource; - let currentSourceText: string; - let sourceMapDir: string; // The directory in which sourcemap will be + export function createSourceMapGenerator(host: EmitHost, file: string, sourceRoot: string, sourcesDirectoryPath: string, generatorOptions: SourceMapGeneratorOptions): SourceMapGenerator { + const { enter, exit } = generatorOptions.extendedDiagnostics + ? performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") + : performance.nullTimer; // Current source map file and its index in the sources list - let sourceMapSourceIndex: number; + const rawSources: string[] = []; + const sources: string[] = []; + const sourceToSourceIndexMap = createMap(); + let sourcesContent: (string | null)[] | undefined; - // Last recorded and encoded spans - let lastRecordedSourceMapSpan: SourceMapSpan | undefined; - let lastEncodedSourceMapSpan: SourceMapSpan | undefined; - let lastEncodedNameIndex: number | undefined; + const names: string[] = []; + let nameToNameIndexMap: Map | undefined; + let mappings = ""; - // Source map data - let sourceMapData: SourceMapData; - let sourceMapDataList: SourceMapData[] | undefined; - let disabled: boolean = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); + // Last recorded and encoded mappings + let lastGeneratedLine = 0; + let lastGeneratedCharacter = 0; + let lastSourceIndex = 0; + let lastSourceLine = 0; + let lastSourceCharacter = 0; + let lastNameIndex = 0; + let hasLast = false; + + let pendingGeneratedLine = 0; + let pendingGeneratedCharacter = 0; + let pendingSourceIndex = 0; + let pendingSourceLine = 0; + let pendingSourceCharacter = 0; + let pendingNameIndex = 0; + let hasPending = false; + let hasPendingSource = false; + let hasPendingName = false; return { - initialize, - reset, - setSourceFile, - emitPos, - emitNodeWithSourceMap, - emitTokenWithSourceMap, - getText, - getSourceMappingURL, + getSources: () => rawSources, + addSource, + setSourceContent, + addName, + addMapping, + appendSourceMap, + toJSON, + toString: () => JSON.stringify(toJSON()) }; - /** - * Skips trivia such as comments and white-space that can optionally overriden by the source map source - */ - function skipSourceTrivia(pos: number): number { - return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : skipTrivia(currentSourceText, pos); + function addSource(fileName: string) { + enter(); + const source = getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, + fileName, + host.getCurrentDirectory(), + host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + + let sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === undefined) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; } - /** - * Initialize the SourceMapWriter for a new output file. - * - * @param filePath The path to the generated output file. - * @param sourceMapFilePath The path to the output source map file. - * @param sourceFileOrBundle The input source file or bundle for the program. - */ - function initialize(filePath: string, sourceMapFilePath: string, sourceFileOrBundle: SourceFile | Bundle, outputSourceMapDataList?: SourceMapData[]) { - if (disabled || fileExtensionIs(filePath, Extension.Json)) { + function setSourceContent(sourceIndex: number, content: string | null) { + enter(); + if (content !== null) { + if (!sourcesContent) sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + // tslint:disable-next-line:no-null-keyword boolean-trivia + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = content; + } + exit(); + } + + function addName(name: string) { + enter(); + if (!nameToNameIndexMap) nameToNameIndexMap = createMap(); + let nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === undefined) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + + function isNewGeneratedPosition(generatedLine: number, generatedCharacter: number) { + return !hasPending + || pendingGeneratedLine !== generatedLine + || pendingGeneratedCharacter !== generatedCharacter; + } + + function isBacktrackingSourcePosition(sourceIndex: number | undefined, sourceLine: number | undefined, sourceCharacter: number | undefined) { + return sourceIndex !== undefined + && sourceLine !== undefined + && sourceCharacter !== undefined + && pendingSourceIndex === sourceIndex + && (pendingSourceLine > sourceLine + || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + + function addMapping(generatedLine: number, generatedCharacter: number, sourceIndex?: number, sourceLine?: number, sourceCharacter?: number, nameIndex?: number) { + Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative"); + Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative"); + Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + // If this location wasn't recorded or the location in source is going backwards, record the mapping + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + + if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== undefined) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + + function appendSourceMap(generatedLine: number, generatedCharacter: number, map: RawSourceMap, sourceMapPath: string) { + Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + // First, decode the old component sourcemap + const sourceIndexToNewSourceIndexMap: number[] = []; + let nameIndexToNewNameIndexMap: number[] | undefined; + const mappingIterator = decodeMappings(map.mappings); + for (let { value: raw, done } = mappingIterator.next(); !done; { value: raw, done } = mappingIterator.next()) { + // Then reencode all the updated mappings into the overall map + let newSourceIndex: number | undefined; + let newSourceLine: number | undefined; + let newSourceCharacter: number | undefined; + let newNameIndex: number | undefined; + if (raw.sourceIndex !== undefined) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === undefined) { + // Apply offsets to each position and fixup source entries + const rawPath = map.sources[raw.sourceIndex]; + const relativePath = map.sourceRoot ? combinePaths(map.sourceRoot, rawPath) : rawPath; + const combinedPath = combinePaths(getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]); + } + } + + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map.names && raw.nameIndex !== undefined) { + if (!nameIndexToNewNameIndexMap) nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === undefined) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]); + } + } + } + + const newGeneratedLine = raw.generatedLine + generatedLine; + const newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + + function shouldCommitMapping() { + return !hasLast + || lastGeneratedLine !== pendingGeneratedLine + || lastGeneratedCharacter !== pendingGeneratedCharacter + || lastSourceIndex !== pendingSourceIndex + || lastSourceLine !== pendingSourceLine + || lastSourceCharacter !== pendingSourceCharacter + || lastNameIndex !== pendingNameIndex; + } + + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { return; } - if (sourceMapData) { - reset(); - } - sourceMapDataList = outputSourceMapDataList; + enter(); - currentSource = undefined!; - currentSourceText = 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, - jsSourceMappingURL: !compilerOptions.inlineSourceMap ? getBaseFileName(normalizeSlashes(sourceMapFilePath)) : undefined!, // TODO: GH#18217 - sourceMapFile: getBaseFileName(normalizeSlashes(filePath)), - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, - }; - - // 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 = normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== CharacterCodes.slash) { - sourceMapData.sourceMapSourceRoot += directorySeparator; - } - - if (compilerOptions.mapRoot) { - sourceMapDir = normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === SyntaxKind.SourceFile) { // emitting single module file - // 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 = getDirectoryPath(getSourceFilePathInNewDir(sourceFileOrBundle.fileName, host, sourceMapDir)); - } - - if (!isRootedDiskPath(sourceMapDir) && !isUrl(sourceMapDir)) { - // The relative paths are relative to the common directory - sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = getRelativePathToDirectoryOrUrl( - getDirectoryPath(normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath - combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap - host.getCurrentDirectory(), - host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - else { - sourceMapData.jsSourceMappingURL = combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + // Line/Comma delimiters + if (lastGeneratedLine < pendingGeneratedLine) { + // Emit line delimiters + do { + mappings += ";"; + lastGeneratedLine++; + lastGeneratedCharacter = 0; } + while (lastGeneratedLine < pendingGeneratedLine); } else { - sourceMapDir = getDirectoryPath(normalizePath(filePath)); - } - } - - /** - * Reset the SourceMapWriter to an empty state. - */ - function reset() { - if (disabled) { - return; + Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + // Emit comma to separate the entry + if (hasLast) { + mappings += ","; + } } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMapData); + // 1. Relative generated character + mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + + if (hasPendingSource) { + // 2. Relative sourceIndex + mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + + // 3. Relative source line + mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + + // 4. Relative source character + mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + + if (hasPendingName) { + // 5. Relative nameIndex + mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } } - currentSource = undefined!; - sourceMapDir = undefined!; - sourceMapSourceIndex = undefined!; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = undefined!; - lastEncodedNameIndex = undefined; - sourceMapData = undefined!; - sourceMapDataList = undefined!; + hasLast = true; + exit(); } - type SourceMapSectionDefinition = - | { offset: { line: number, column: number }, url: string } // Included for completeness - | { offset: { line: number, column: number }, map: SourceMap }; - - interface SectionalSourceMap { - version: 3; - file: string; - sections: SourceMapSectionDefinition[]; - } - - type SourceMap = SectionalSourceMap | SourceMapSection; - - function captureSection(): SourceMapSection { + function toJSON(): RawSourceMap { + commitPendingMapping(); return { version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent, + file, + sourceRoot, + sources, + names, + mappings, + sourcesContent, + }; + } + } + + // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + const sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + const whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + + export interface LineInfo { + getLineCount(): number; + getLineText(line: number): string; + } + + export function getLineInfo(text: string, lineStarts: ReadonlyArray): LineInfo { + return { + getLineCount: () => lineStarts.length, + getLineText: line => text.substring(lineStarts[line], lineStarts[line + 1]) + }; + } + + /** + * Tries to find the sourceMappingURL comment at the end of a file. + */ + export function tryGetSourceMappingURL(lineInfo: LineInfo) { + for (let index = lineInfo.getLineCount() - 1; index >= 0; index--) { + const line = lineInfo.getLineText(index); + const comment = sourceMapCommentRegExp.exec(line); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + + function isStringOrNull(x: any) { + // tslint:disable-next-line:no-null-keyword + return typeof x === "string" || x === null; + } + + export function isRawSourceMap(x: any): x is RawSourceMap { + // tslint:disable-next-line:no-null-keyword + return x !== null + && typeof x === "object" + && x.version === 3 + && typeof x.file === "string" + && typeof x.mappings === "string" + && isArray(x.sources) && every(x.sources, isString) + && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string") + && (x.sourcesContent === undefined || x.sourcesContent === null || isArray(x.sourcesContent) && every(x.sourcesContent, isStringOrNull)) + && (x.names === undefined || x.names === null || isArray(x.names) && every(x.names, isString)); + } + + export function tryParseRawSourceMap(text: string) { + try { + const parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } + catch { + // empty + } + + return undefined; + } + + export interface MappingsDecoder extends Iterator { + readonly pos: number; + readonly error: string | undefined; + readonly state: Required; + } + + export interface Mapping { + generatedLine: number; + generatedCharacter: number; + sourceIndex?: number; + sourceLine?: number; + sourceCharacter?: number; + nameIndex?: number; + } + + export interface SourceMapping extends Mapping { + sourceIndex: number; + sourceLine: number; + sourceCharacter: number; + } + + export function decodeMappings(mappings: string): MappingsDecoder { + let done = false; + let pos = 0; + let generatedLine = 0; + let generatedCharacter = 0; + let sourceIndex = 0; + let sourceLine = 0; + let sourceCharacter = 0; + let nameIndex = 0; + let error: string | undefined; + + return { + get pos() { return pos; }, + get error() { return error; }, + get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + next() { + while (!done && pos < mappings.length) { + const ch = mappings.charCodeAt(pos); + if (ch === CharacterCodes.semicolon) { + // new line + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + + if (ch === CharacterCodes.comma) { + // Next entry is on same line - no action needed + pos++; + continue; + } + + let hasSource = false; + let hasName = false; + + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) return stopIterating(); + if (generatedCharacter < 0) return setErrorAndStopIterating("Invalid generatedCharacter found"); + + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) return stopIterating(); + if (sourceIndex < 0) return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) return stopIterating(); + if (sourceLine < 0) return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) return stopIterating(); + if (sourceCharacter < 0) return setErrorAndStopIterating("Invalid sourceCharacter found"); + + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) return stopIterating(); + if (nameIndex < 0) return setErrorAndStopIterating("Invalid nameIndex found"); + + if (!isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + + return { value: captureMapping(hasSource, hasName), done }; + } + + return stopIterating(); + } + }; + + function captureMapping(hasSource: true, hasName: true): Required; + function captureMapping(hasSource: boolean, hasName: boolean): Mapping; + function captureMapping(hasSource: boolean, hasName: boolean): Mapping { + return { + generatedLine, + generatedCharacter, + sourceIndex: hasSource ? sourceIndex : undefined, + sourceLine: hasSource ? sourceLine : undefined, + sourceCharacter: hasSource ? sourceCharacter : undefined, + nameIndex: hasName ? nameIndex : undefined }; } + function stopIterating(): { value: never, done: true } { + done = true; + return { value: undefined!, done: true }; + } - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; + function setError(message: string) { + if (error === undefined) { + error = message; + } + } + + function setErrorAndStopIterating(message: string) { + setError(message); + return stopIterating(); + } + + function hasReportedError() { + return error !== undefined; + } + + function isSourceMappingSegmentEnd() { + return (pos === mappings.length || + mappings.charCodeAt(pos) === CharacterCodes.comma || + mappings.charCodeAt(pos) === CharacterCodes.semicolon); + } + + function base64VLQFormatDecode(): number { + let moreDigits = true; + let shiftCount = 0; + let value = 0; + + for (; moreDigits; pos++) { + if (pos >= mappings.length) return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + + // 6 digit number + const currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) return setError("Invalid character in VLQ"), -1; + + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; } - Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative"); - Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative"); - Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative"); - Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative"); - - let prevEncodedEmittedColumn = lastEncodedSourceMapSpan!.emittedColumn; - // Line/Comma delimiters - if (lastEncodedSourceMapSpan!.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - // Emit comma to separate the entry - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; } else { - // Emit line delimiters - for (let encodedLine = lastEncodedSourceMapSpan!.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 0; + // - number + value = value >> 1; + value = -value; } - // 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) { - 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; - } - - /** - * Emits a mapping. - * - * If the position is synthetic (undefined or a negative value), no mapping will be - * created. - * - * @param pos The position. - */ - function emitPos(pos: number) { - if (disabled || positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { - return; - } - - if (extendedDiagnostics) { - performance.mark("beforeSourcemap"); - } - - const sourceLinePos = getLineAndCharacterOfPosition(currentSource, pos); - - const emittedLine = writer.getLine(); - const 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, - emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - 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; - } - - if (extendedDiagnostics) { - performance.mark("afterSourcemap"); - performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } - } - - function isPossiblySourceMap(x: {}): x is SourceMapSection { - return typeof x === "object" && !!(x as any).mappings && typeof (x as any).mappings === "string" && !!(x as any).sources; - } - - /** - * Emits a node with possible leading and trailing source maps. - * - * @param hint A hint as to the intended usage of the node. - * @param node The node to emit. - * @param emitCallback The callback used to emit the node. - */ - function emitNodeWithSourceMap(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) { - if (disabled || isInJsonFile(node)) { - return emitCallback(hint, node); - } - - if (node) { - if (isUnparsedSource(node) && node.sourceMapText !== undefined) { - const text = node.sourceMapText; - let parsed: {} | undefined; - try { - parsed = JSON.parse(text); - } - catch { - // empty - } - if (!parsed || !isPossiblySourceMap(parsed)) { - return emitCallback(hint, node); - } - const offsetLine = writer.getLine(); - const firstLineColumnOffset = writer.getColumn(); - // First, decode the old component sourcemap - const originalMap = parsed; - - const sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - const resolvedPathCache = createMap(); - const absolutePathCache = createMap(); - const sourcemapIterator = sourcemaps.decodeMappings(originalMap); - for (let { value: raw, done } = sourcemapIterator.next(); !done; { value: raw, done } = sourcemapIterator.next()) { - const pathCacheKey = "" + raw.sourceIndex; - // Apply offsets to each position and fixup source entries - if (!resolvedPathCache.has(pathCacheKey)) { - const rawPath = originalMap.sources[raw.sourceIndex]; - const relativePath = originalMap.sourceRoot ? combinePaths(originalMap.sourceRoot, rawPath) : rawPath; - const combinedPath = combinePaths(getDirectoryPath(node.sourceMapPath!), relativePath); - const resolvedPath = getRelativePathToDirectoryOrUrl( - sourcesDirectoryPath, - combinedPath, - host.getCurrentDirectory(), - host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true - ); - resolvedPathCache.set(pathCacheKey, resolvedPath); - absolutePathCache.set(pathCacheKey, getNormalizedAbsolutePath(resolvedPath, sourcesDirectoryPath)); - } - const resolvedPath = resolvedPathCache.get(pathCacheKey)!; - const absolutePath = absolutePathCache.get(pathCacheKey)!; - // tslint:disable-next-line:no-null-keyword - setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); // TODO: Lookup content for inlining? - const newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath); - // Then reencode all the updated spans into the overall map - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = { - ...raw, - emittedLine: raw.emittedLine + offsetLine, - emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, - sourceIndex: newIndex, - }; - } - // And actually emit the text these sourcemaps are for - return emitCallback(hint, node); - } - const emitNode = node.emitNode; - const emitFlags = emitNode && emitNode.flags || EmitFlags.None; - const range = emitNode && emitNode.sourceMapRange; - const { pos, end } = range || node; - let source = range && range.source; - const oldSource = currentSource; - if (source === oldSource) source = undefined; - - if (source) setSourceFile(source); - - if (node.kind !== SyntaxKind.NotEmittedStatement - && (emitFlags & EmitFlags.NoLeadingSourceMap) === 0 - && pos >= 0) { - emitPos(skipSourceTrivia(pos)); - } - - if (source) setSourceFile(oldSource); - - if (emitFlags & EmitFlags.NoNestedSourceMaps) { - disabled = true; - emitCallback(hint, node); - disabled = false; - } - else { - emitCallback(hint, node); - } - - if (source) setSourceFile(source); - - if (node.kind !== SyntaxKind.NotEmittedStatement - && (emitFlags & EmitFlags.NoTrailingSourceMap) === 0 - && end >= 0) { - emitPos(end); - } - - if (source) setSourceFile(oldSource); - } - } - - /** - * Emits a token of a node with possible leading and trailing source maps. - * - * @param node The node containing the token. - * @param token The token to emit. - * @param tokenStartPos The start pos of the token. - * @param emitCallback The callback used to emit the token. - */ - function emitTokenWithSourceMap(node: Node, token: SyntaxKind, writer: (s: string) => void, tokenPos: number, emitCallback: (token: SyntaxKind, writer: (s: string) => void, tokenStartPos: number) => number) { - if (disabled || isInJsonFile(node)) { - return emitCallback(token, writer, tokenPos); - } - - const emitNode = node && node.emitNode; - const emitFlags = emitNode && emitNode.flags || EmitFlags.None; - const range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - - tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); - if ((emitFlags & EmitFlags.NoTokenLeadingSourceMaps) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - - tokenPos = emitCallback(token, writer, tokenPos); - - if (range) tokenPos = range.end; - if ((emitFlags & EmitFlags.NoTokenTrailingSourceMaps) === 0 && tokenPos >= 0) { - emitPos(tokenPos); - } - - return tokenPos; - } - - function isJsonSourceMapSource(sourceFile: SourceMapSource) { - return fileExtensionIs(sourceFile.fileName, Extension.Json); - } - - /** - * Set the current source file. - * - * @param sourceFile The source file. - */ - function setSourceFile(sourceFile: SourceMapSource) { - if (disabled) { - return; - } - - currentSource = sourceFile; - currentSourceText = currentSource.text; - - if (isJsonSourceMapSource(sourceFile)) { - return; - } - - setupSourceEntry(sourceFile.fileName, sourceFile.text); - } - - function setupSourceEntry(fileName: string, content: string | null, source?: string) { - if (!source) { - // 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 - const sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - - source = getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, - fileName, - host.getCurrentDirectory(), - host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - - sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(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(fileName); - - if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent!.push(content); - } - } - } - - /** - * Gets the text for the source map. - */ - function getText() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined!; // TODO: GH#18217 - } - - encodeLastRecordedSourceMapSpan(); - - return JSON.stringify(captureSection()); - } - - /** - * Gets the SourceMappingURL for the source map. - */ - function getSourceMappingURL() { - if (disabled || isJsonSourceMapSource(currentSource)) { - return undefined!; // TODO: GH#18217 - } - - if (compilerOptions.inlineSourceMap) { - // Encode the sourceMap into the sourceMap url - const base64SourceMapText = base64encode(sys, getText()); - return sourceMapData.jsSourceMappingURL = `data:application/json;base64,${base64SourceMapText}`; - } - else { - return sourceMapData.jsSourceMappingURL; - } + return value; } } - export interface SourceMapSection { - version: 3; - file: string; - sourceRoot?: string; - sources: string[]; - names?: string[]; - mappings: string; - sourcesContent?: (string | null)[]; - sections?: undefined; + export function sameMapping(left: T, right: T) { + return left === right + || left.generatedLine === right.generatedLine + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; } - const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + export function isSourceMapping(mapping: Mapping): mapping is SourceMapping { + return mapping.sourceIndex !== undefined + && mapping.sourceLine !== undefined + && mapping.sourceCharacter !== undefined; + } - function base64FormatEncode(inValue: number) { - if (inValue < 64) { - return base64Chars.charAt(inValue); - } + function base64FormatEncode(value: number) { + return value >= 0 && value < 26 ? CharacterCodes.A + value : + value >= 26 && value < 52 ? CharacterCodes.a + value - 26 : + value >= 52 && value < 62 ? CharacterCodes._0 + value - 52 : + value === 62 ? CharacterCodes.plus : + value === 63 ? CharacterCodes.slash : + Debug.fail(`${value}: not a base64 value`); + } - throw TypeError(inValue + ": not a 64 based value"); + function base64FormatDecode(ch: number) { + return ch >= CharacterCodes.A && ch <= CharacterCodes.Z ? ch - CharacterCodes.A : + ch >= CharacterCodes.a && ch <= CharacterCodes.z ? ch - CharacterCodes.a + 26 : + ch >= CharacterCodes._0 && ch <= CharacterCodes._9 ? ch - CharacterCodes._0 + 52 : + ch === CharacterCodes.plus ? 62 : + ch === CharacterCodes.slash ? 63 : + -1; } function base64VLQFormatEncode(inValue: number) { @@ -614,9 +551,178 @@ namespace ts { // There are still more digits to decode, set the msb (6th bit) currentDigit = currentDigit | 32; } - encodedStr = encodedStr + base64FormatEncode(currentDigit); + encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit)); } while (inValue > 0); return encodedStr; } + + interface MappedPosition { + generatedPosition: number; + source: string | undefined; + sourceIndex: number | undefined; + sourcePosition: number | undefined; + nameIndex: number | undefined; + } + + interface SourceMappedPosition extends MappedPosition { + source: string; + sourceIndex: number; + sourcePosition: number; + } + + function isSourceMappedPosition(value: MappedPosition): value is SourceMappedPosition { + return value.sourceIndex !== undefined + && value.sourcePosition !== undefined; + } + + function sameMappedPosition(left: MappedPosition, right: MappedPosition) { + return left.generatedPosition === right.generatedPosition + && left.sourceIndex === right.sourceIndex + && left.sourcePosition === right.sourcePosition; + } + + function compareSourcePositions(left: SourceMappedPosition, right: SourceMappedPosition) { + // Compares sourcePosition without comparing sourceIndex + // since the mappings are grouped by sourceIndex + Debug.assert(left.sourceIndex === right.sourceIndex); + return compareValues(left.sourcePosition, right.sourcePosition); + } + + function compareGeneratedPositions(left: MappedPosition, right: MappedPosition) { + return compareValues(left.generatedPosition, right.generatedPosition); + } + + function getSourcePositionOfMapping(value: SourceMappedPosition) { + return value.sourcePosition; + } + + function getGeneratedPositionOfMapping(value: MappedPosition) { + return value.generatedPosition; + } + + export function createDocumentPositionMapper(host: DocumentPositionMapperHost, map: RawSourceMap, mapPath: string): DocumentPositionMapper { + const mapDirectory = getDirectoryPath(mapPath); + const sourceRoot = map.sourceRoot ? getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; + const generatedAbsoluteFilePath = getNormalizedAbsolutePath(map.file, mapDirectory); + const generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath); + const sourceFileAbsolutePaths = map.sources.map(source => getNormalizedAbsolutePath(source, sourceRoot)); + const sourceToSourceIndexMap = createMapFromEntries(sourceFileAbsolutePaths.map((source, i) => [host.getCanonicalFileName(source), i] as [string, number])); + let decodedMappings: ReadonlyArray | undefined; + let generatedMappings: SortedReadonlyArray | undefined; + let sourceMappings: ReadonlyArray> | undefined; + + return { + getSourcePosition, + getGeneratedPosition + }; + + function processMapping(mapping: Mapping): MappedPosition { + const generatedPosition = generatedFile !== undefined + ? getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true) + : -1; + let source: string | undefined; + let sourcePosition: number | undefined; + if (isSourceMapping(mapping)) { + const sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true) + : -1; + } + return { + generatedPosition, + source, + sourceIndex: mapping.sourceIndex, + sourcePosition, + nameIndex: mapping.nameIndex + }; + } + + function getDecodedMappings() { + if (decodedMappings === undefined) { + const decoder = decodeMappings(map.mappings); + const mappings = arrayFrom(decoder, processMapping); + if (decoder.error !== undefined) { + if (host.log) { + host.log(`Encountered error while decoding sourcemap: ${decoder.error}`); + } + decodedMappings = emptyArray; + } + else { + decodedMappings = mappings; + } + } + return decodedMappings; + } + + function getSourceMappings(sourceIndex: number) { + if (sourceMappings === undefined) { + const lists: SourceMappedPosition[][] = []; + for (const mapping of getDecodedMappings()) { + if (!isSourceMappedPosition(mapping)) continue; + let list = lists[mapping.sourceIndex]; + if (!list) lists[mapping.sourceIndex] = list = []; + list.push(mapping); + } + sourceMappings = lists.map(list => sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition)); + } + return sourceMappings[sourceIndex]; + } + + function getGeneratedMappings() { + if (generatedMappings === undefined) { + const list: MappedPosition[] = []; + for (const mapping of getDecodedMappings()) { + list.push(mapping); + } + generatedMappings = sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition); + } + return generatedMappings; + } + + function getGeneratedPosition(loc: DocumentPosition): DocumentPosition { + const sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); + if (sourceIndex === undefined) return loc; + + const sourceMappings = getSourceMappings(sourceIndex); + if (!some(sourceMappings)) return loc; + + let targetIndex = binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + + const mapping = sourceMappings[targetIndex]; + if (mapping === undefined || mapping.sourceIndex !== sourceIndex) { + return loc; + } + + return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos + } + + function getSourcePosition(loc: DocumentPosition): DocumentPosition { + const generatedMappings = getGeneratedMappings(); + if (!some(generatedMappings)) return loc; + + let targetIndex = binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, compareValues); + if (targetIndex < 0) { + // if no exact match, closest is 2's complement of result + targetIndex = ~targetIndex; + } + + const mapping = generatedMappings[targetIndex]; + if (mapping === undefined || !isSourceMappedPosition(mapping)) { + return loc; + } + + return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos + } + } + + export const identitySourceMapConsumer: DocumentPositionMapper = { + getSourcePosition: identity, + getGeneratedPosition: identity + }; } diff --git a/src/compiler/sourcemapDecoder.ts b/src/compiler/sourcemapDecoder.ts deleted file mode 100644 index 28cbbe39cf5..00000000000 --- a/src/compiler/sourcemapDecoder.ts +++ /dev/null @@ -1,377 +0,0 @@ -/* @internal */ -namespace ts { - export interface SourceFileLikeCache { - get(path: Path): SourceFileLike | undefined; - } - - export function createSourceFileLikeCache(host: { readFile?: (path: string) => string | undefined, fileExists?: (path: string) => boolean }): SourceFileLikeCache { - const cached = createMap(); - return { - get(path: Path) { - if (cached.has(path)) { - return cached.get(path); - } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) return; - // And failing that, check the disk - const text = host.readFile(path)!; // TODO: GH#18217 - const file = { - text, - lineMap: undefined, - getLineAndCharacterOfPosition(pos: number) { - return computeLineAndCharacterOfPosition(getLineStarts(this), pos); - } - } as SourceFileLike; - cached.set(path, file); - return file; - } - }; - } -} - -/* @internal */ -namespace ts.sourcemaps { - export interface SourceMapData { - version?: number; - file?: string; - sourceRoot?: string; - sources: string[]; - sourcesContent?: (string | null)[]; - names?: string[]; - mappings: string; - } - - export interface SourceMappableLocation { - fileName: string; - position: number; - } - - export interface SourceMapper { - getOriginalPosition(input: SourceMappableLocation): SourceMappableLocation; - getGeneratedPosition(input: SourceMappableLocation): SourceMappableLocation; - } - - export const identitySourceMapper = { getOriginalPosition: identity, getGeneratedPosition: identity }; - - export interface SourceMapDecodeHost { - readFile(path: string): string | undefined; - fileExists(path: string): boolean; - getCanonicalFileName(path: string): string; - log(text: string): void; - } - - export function decode(host: SourceMapDecodeHost, mapPath: string, map: SourceMapData, program?: Program, fallbackCache = createSourceFileLikeCache(host)): SourceMapper { - const currentDirectory = getDirectoryPath(mapPath); - const sourceRoot = map.sourceRoot ? getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; - let decodedMappings: ProcessedSourceMapPosition[]; - let generatedOrderedMappings: ProcessedSourceMapPosition[]; - let sourceOrderedMappings: ProcessedSourceMapPosition[]; - - return { - getOriginalPosition, - getGeneratedPosition - }; - - function getGeneratedPosition(loc: SourceMappableLocation): SourceMappableLocation { - const maps = getSourceOrderedMappings(); - if (!length(maps)) return loc; - let targetIndex = binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, identity, compareProcessedPositionSourcePositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - if (!maps[targetIndex] || comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { - return loc; - } - return { fileName: toPath(map.file!, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos - } - - function getOriginalPosition(loc: SourceMappableLocation): SourceMappableLocation { - const maps = getGeneratedOrderedMappings(); - if (!length(maps)) return loc; - let targetIndex = binarySearch(maps, { emittedPosition: loc.position }, identity, compareProcessedPositionEmittedPositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - return { fileName: toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos - } - - function getSourceFileLike(fileName: string, location: string): SourceFileLike | undefined { - // Lookup file in program, if provided - const path = toPath(fileName, location, host.getCanonicalFileName); - const file = program && program.getSourceFile(path); - // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file - if (!file || file.resolvedPath !== path) { - // Otherwise check the cache (which may hit disk) - return fallbackCache.get(path); - } - return file; - } - - function getPositionOfLineAndCharacterUsingName(fileName: string, directory: string, line: number, character: number) { - const file = getSourceFileLike(fileName, directory); - if (!file) { - return -1; - } - return getPositionOfLineAndCharacter(file, line, character); - } - - function getDecodedMappings() { - return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host)); - } - - function getSourceOrderedMappings() { - return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); - } - - function getGeneratedOrderedMappings() { - return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); - } - - function compareProcessedPositionSourcePositions(a: ProcessedSourceMapPosition, b: ProcessedSourceMapPosition) { - return comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || - compareValues(a.sourcePosition, b.sourcePosition); - } - - function compareProcessedPositionEmittedPositions(a: ProcessedSourceMapPosition, b: ProcessedSourceMapPosition) { - return compareValues(a.emittedPosition, b.emittedPosition); - } - - function processPosition(position: RawSourceMapPosition): ProcessedSourceMapPosition { - const sourcePath = map.sources[position.sourceIndex]; - return { - emittedPosition: getPositionOfLineAndCharacterUsingName(map.file!, currentDirectory, position.emittedLine, position.emittedColumn), - sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), - sourcePath, - // TODO: Consider using `name` field to remap the expected identifier to scan for renames to handle another tool renaming oout output - // name: position.nameIndex ? map.names[position.nameIndex] : undefined - }; - } - } - - /*@internal*/ - export interface MappingsDecoder extends Iterator { - readonly decodingIndex: number; - readonly error: string | undefined; - readonly lastSpan: SourceMapSpan; - } - - /*@internal*/ - export function decodeMappings(map: SourceMapData): MappingsDecoder { - const state: DecoderState = { - encodedText: map.mappings, - currentNameIndex: undefined, - sourceMapNamesLength: map.names ? map.names.length : undefined, - currentEmittedColumn: 0, - currentEmittedLine: 0, - currentSourceColumn: 0, - currentSourceLine: 0, - currentSourceIndex: 0, - decodingIndex: 0 - }; - function captureSpan(): SourceMapSpan { - return { - emittedColumn: state.currentEmittedColumn, - emittedLine: state.currentEmittedLine, - sourceColumn: state.currentSourceColumn, - sourceIndex: state.currentSourceIndex, - sourceLine: state.currentSourceLine, - nameIndex: state.currentNameIndex - }; - } - return { - get decodingIndex() { return state.decodingIndex; }, - get error() { return state.error; }, - get lastSpan() { return captureSpan(); }, - next() { - if (hasCompletedDecoding(state) || state.error) return { done: true, value: undefined as never }; - if (!decodeSinglePosition(state)) return { done: true, value: undefined as never }; - return { done: false, value: captureSpan() }; - } - }; - } - - function calculateDecodedMappings(map: SourceMapData, processPosition: (position: RawSourceMapPosition) => T, host?: { log?(s: string): void }): T[] { - const decoder = decodeMappings(map); - const positions = arrayFrom(decoder, processPosition); - if (decoder.error) { - if (host && host.log) { - host.log(`Encountered error while decoding sourcemap: ${decoder.error}`); - } - return []; - } - return positions; - } - - interface ProcessedSourceMapPosition { - emittedPosition: number; - sourcePosition: number; - sourcePath: string; - } - - interface RawSourceMapPosition { - emittedLine: number; - emittedColumn: number; - sourceLine: number; - sourceColumn: number; - sourceIndex: number; - nameIndex?: number; - } - - interface DecoderState { - decodingIndex: number; - currentEmittedLine: number; - currentEmittedColumn: number; - currentSourceLine: number; - currentSourceColumn: number; - currentSourceIndex: number; - currentNameIndex: number | undefined; - encodedText: string; - sourceMapNamesLength?: number; - error?: string; - } - - function hasCompletedDecoding(state: DecoderState) { - return state.decodingIndex === state.encodedText.length; - } - - function decodeSinglePosition(state: DecoderState): boolean { - while (state.decodingIndex < state.encodedText.length) { - const char = state.encodedText.charCodeAt(state.decodingIndex); - if (char === CharacterCodes.semicolon) { - // New line - state.currentEmittedLine++; - state.currentEmittedColumn = 0; - state.decodingIndex++; - continue; - } - - if (char === CharacterCodes.comma) { - // Next entry is on same line - no action needed - state.decodingIndex++; - continue; - } - - // Read the current position - // 1. Column offset from prev read jsColumn - state.currentEmittedColumn += base64VLQFormatDecode(); - // Incorrect emittedColumn dont support this map - if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { - return false; - } - - // 2. Relative sourceIndex - state.currentSourceIndex += base64VLQFormatDecode(); - // Incorrect sourceIndex dont support this map - if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { - return false; - } - // Dont support reading mappings that dont have information about original source position - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { - return false; - } - - // 3. Relative sourceLine 0 based - state.currentSourceLine += base64VLQFormatDecode(); - // Incorrect sourceLine dont support this map - if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { - return false; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { - return false; - } - - // 4. Relative sourceColumn 0 based - state.currentSourceColumn += base64VLQFormatDecode(); - // Incorrect sourceColumn dont support this map - if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { - return false; - } - // 5. Check if there is name: - if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { - if (state.currentNameIndex === undefined) { - state.currentNameIndex = 0; - } - state.currentNameIndex += base64VLQFormatDecode(); - // Incorrect nameIndex dont support this map - // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap - // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { - // return; - // } - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { - return false; - } - - // Entry should be complete - return true; - } - - createErrorIfCondition(/*condition*/ true, "No encoded entry found"); - return false; - - function createErrorIfCondition(condition: boolean, errormsg: string) { - if (state.error) { - // An error was already reported - return true; - } - - if (condition) { - state.error = errormsg; - } - - return condition; - } - - function base64VLQFormatDecode(): number { - let moreDigits = true; - let shiftCount = 0; - let value = 0; - - for (; moreDigits; state.decodingIndex++) { - if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return undefined!; // TODO: GH#18217 - } - - // 6 digit number - const currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); - - // If msb is set, we still have more bits to continue - moreDigits = (currentByte & 32) !== 0; - - // least significant 5 bits are the next msbs in the final value. - value = value | ((currentByte & 31) << shiftCount); - shiftCount += 5; - } - - // Least significant bit if 1 represents negative and rest of the msb is actual absolute value - if ((value & 1) === 0) { - // + number - value = value >> 1; - } - else { - // - number - value = value >> 1; - value = -value; - } - - return value; - } - } - - function base64FormatDecode(char: string) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); - } - - function isSourceMappingSegmentEnd(encodedText: string, pos: number) { - return (pos === encodedText.length || - encodedText.charCodeAt(pos) === CharacterCodes.comma || - encodedText.charCodeAt(pos) === CharacterCodes.semicolon); - } -} diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index eaa910a0b5c..35e9a9ec35f 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -2,6 +2,16 @@ declare function setTimeout(handler: (...args: any[]) => void, timeout: number): declare function clearTimeout(handle: any): void; namespace ts { + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + /* @internal */ + export function generateDjb2Hash(data: string): string { + const chars = data.split("").map(str => str.charCodeAt(0)); + return `${chars.reduce((prev, curr) => ((prev << 5) + prev) + curr, 5381)}`; + } + /** * Set a high stack trace limit to provide more information in case of an error. * Called for command-line and server use cases. @@ -36,23 +46,6 @@ namespace ts { Low = 250 } - function getPriorityValues(highPriorityValue: number): [number, number, number] { - const mediumPriorityValue = highPriorityValue * 2; - const lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - - function pollingInterval(watchPriority: PollingInterval): number { - return pollingIntervalsForPriority[watchPriority]; - } - - const pollingIntervalsForPriority = getPriorityValues(250); - - /* @internal */ - export function watchFileUsingPriorityPollingInterval(host: System, fileName: string, callback: FileWatcherCallback, watchPriority: PollingInterval): FileWatcher { - return host.watchFile!(fileName, callback, pollingInterval(watchPriority)); - } - /* @internal */ export type HostWatchFile = (fileName: string, callback: FileWatcherCallback, pollingInterval: PollingInterval | undefined) => FileWatcher; /* @internal */ @@ -317,18 +310,22 @@ namespace ts { const newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - const eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } + /*@internal*/ + export function getFileWatcherEventKind(oldTime: number, newTime: number) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + /*@internal*/ export interface RecursiveDirectoryWatcherHost { watchDirectory: HostWatchDirectory; @@ -792,11 +789,10 @@ namespace ts { dirName, (_eventName: string, relativeFileName) => { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - const fileName = !isString(relativeFileName) - ? undefined! // TODO: GH#18217 - : getNormalizedAbsolutePath(relativeFileName, dirName); + if (!isString(relativeFileName)) { return; } + const fileName = getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - const callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + const callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (const fileCallback of callbacks) { fileCallback(fileName, FileWatcherEventKind.Changed); @@ -843,7 +839,7 @@ namespace ts { } } - type FsWatchCallback = (eventName: "rename" | "change", relativeFileName: string) => void; + type FsWatchCallback = (eventName: "rename" | "change", relativeFileName: string | undefined) => void; function createFileWatcherCallback(callback: FsWatchCallback): FileWatcherCallback { return (_fileName, eventKind) => callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); @@ -1129,15 +1125,6 @@ namespace ts { } } - /** - * djb2 hashing algorithm - * http://www.cse.yorku.ca/~oz/hash.html - */ - function generateDjb2Hash(data: string): string { - const chars = data.split("").map(str => str.charCodeAt(0)); - return `${chars.reduce((prev, curr) => ((prev << 5) + prev) + curr, 5381)}`; - } - function createMD5HashUsingNativeCrypto(data: string): string { const hash = _crypto!.createHash("md5"); hash.update(data); diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index b78202e0c3d..fdcaadb4040 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -68,6 +68,14 @@ namespace ts { return transformers; } + export function noEmitSubstitution(_hint: EmitHint, node: Node) { + return node; + } + + export function noEmitNotification(hint: EmitHint, node: Node, callback: (hint: EmitHint, node: Node) => void) { + callback(hint, node); + } + /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -87,8 +95,8 @@ namespace ts { let lexicalEnvironmentStackOffset = 0; let lexicalEnvironmentSuspended = false; let emitHelpers: EmitHelper[] | undefined; - let onSubstituteNode: TransformationContext["onSubstituteNode"] = (_, node) => node; - let onEmitNode: TransformationContext["onEmitNode"] = (hint, node, callback) => callback(hint, node); + let onSubstituteNode: TransformationContext["onSubstituteNode"] = noEmitSubstitution; + let onEmitNode: TransformationContext["onEmitNode"] = noEmitNotification; let state = TransformationState.Uninitialized; const diagnostics: DiagnosticWithLocation[] = []; diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index f31058743a2..d03c3b8d30b 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -1,11 +1,11 @@ /*@internal*/ namespace ts { export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, file: SourceFile | undefined): DiagnosticWithLocation[] | undefined { - if (file && isSourceFileJavaScript(file)) { + if (file && isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } const compilerOptions = host.getCompilerOptions(); - const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } @@ -45,6 +45,7 @@ namespace ts { reportInaccessibleThisError, reportInaccessibleUniqueSymbolError, reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode @@ -153,11 +154,19 @@ namespace ts { } } + function reportLikelyUnsafeImportRequiredError(specifier: string) { + if (errorNameNode) { + context.addDiagnostic(createDiagnosticForNode(errorNameNode, Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, + declarationNameToString(errorNameNode), + specifier)); + } + } + function transformRoot(node: Bundle): Bundle; function transformRoot(node: SourceFile): SourceFile; function transformRoot(node: SourceFile | Bundle): SourceFile | Bundle; function transformRoot(node: SourceFile | Bundle) { - if (node.kind === SyntaxKind.SourceFile && (node.isDeclarationFile || isSourceFileJavaScript(node))) { + if (node.kind === SyntaxKind.SourceFile && (node.isDeclarationFile || isSourceFileJS(node))) { return node; } @@ -168,7 +177,7 @@ namespace ts { let hasNoDefaultLib = false; const bundle = createBundle(map(node.sourceFiles, sourceFile => { - if (sourceFile.isDeclarationFile || isSourceFileJavaScript(sourceFile)) return undefined!; // Omit declaration files from bundle results, too // TODO: GH#18217 + if (sourceFile.isDeclarationFile || isSourceFileJS(sourceFile)) return undefined!; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; @@ -275,7 +284,7 @@ namespace ts { else { if (isBundledEmit && contains((node as Bundle).sourceFiles, file)) return; // Omit references to files which are being merged const paths = getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { @@ -289,6 +298,13 @@ namespace ts { if (startsWith(fileName, "./") && hasExtension(fileName)) { fileName = fileName.substring(2); } + + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } + references.push({ pos: -1, end: -1, fileName }); } }; @@ -296,7 +312,7 @@ namespace ts { } function collectReferences(sourceFile: SourceFile, ret: Map) { - if (noResolve || isSourceFileJavaScript(sourceFile)) return ret; + if (noResolve || isSourceFileJS(sourceFile)) return ret; forEach(sourceFile.referencedFiles, f => { const elem = tryResolveScriptReference(host, sourceFile, f); if (elem) { @@ -366,7 +382,7 @@ namespace ts { function ensureNoInitializer(node: CanHaveLiteralInitializer) { if (shouldPrintWithInitializer(node)) { - return resolver.createLiteralConstValue(getParseTreeNode(node) as CanHaveLiteralInitializer); // TODO: Make safe + return resolver.createLiteralConstValue(getParseTreeNode(node) as CanHaveLiteralInitializer, symbolTracker); // TODO: Make safe } return undefined; } @@ -618,7 +634,10 @@ namespace ts { if (!isLateVisibilityPaintedStatement(i)) { return Debug.fail(`Late replaced statement was found which is not handled by the declaration transformer!: ${(ts as any).SyntaxKind ? (ts as any).SyntaxKind[(i as any).kind] : (i as any).kind}`); } + const priorNeedsDeclare = needsDeclare; + needsDeclare = i.parent && isSourceFile(i.parent) && !(isExternalModule(i.parent) && isBundledEmit); const result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + needsDeclare = priorNeedsDeclare; lateStatementReplacementMap.set("" + getOriginalNodeId(i), result); } @@ -982,7 +1001,7 @@ namespace ts { ensureType(input, input.type), /*body*/ undefined )); - if (clean && resolver.isJSContainerFunctionDeclaration(input)) { + if (clean && resolver.isExpandoFunctionDeclaration(input)) { const declarations = mapDefined(resolver.getPropertiesOfContainerFunction(input), p => { if (!isPropertyAccessExpression(p.valueDeclaration)) { return undefined; @@ -1036,7 +1055,7 @@ namespace ts { const modifiers = createNodeArray(ensureModifiers(input, isPrivate)); const typeParameters = ensureTypeParams(input, input.typeParameters); const ctor = getFirstConstructorWithBody(input); - let parameterProperties: PropertyDeclaration[] | undefined; + let parameterProperties: ReadonlyArray | undefined; if (ctor) { const oldDiag = getSymbolAccessibilityDiagnostic; parameterProperties = compact(flatMap(ctor.parameters, param => { @@ -1084,7 +1103,8 @@ namespace ts { if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== SyntaxKind.NullKeyword) { // We must add a temporary declaration for the extends clause expression - const newId = createOptimisticUniqueName(`${unescapeLeadingUnderscores(input.name!.escapedText)}_base`); // TODO: GH#18217 + const oldId = input.name ? unescapeLeadingUnderscores(input.name.escapedText) : "default"; + const newId = createOptimisticUniqueName(`${oldId}_base`); getSymbolAccessibilityDiagnostic = () => ({ diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause, diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 0865861414e..b4c72c79012 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -389,6 +389,7 @@ namespace ts { diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; + case SyntaxKind.ConstructorType: case SyntaxKind.ConstructSignature: diagnosticMessage = Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; @@ -410,6 +411,7 @@ namespace ts { } break; + case SyntaxKind.FunctionType: case SyntaxKind.FunctionDeclaration: diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; @@ -434,7 +436,7 @@ namespace ts { // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = (node as ExpressionWithTypeArguments).parent.token === SyntaxKind.ImplementsKeyword ? + diagnosticMessage = isHeritageClause(node.parent) && node.parent.token === SyntaxKind.ImplementsKeyword ? Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -446,7 +448,7 @@ namespace ts { return { diagnosticMessage, errorNode: node, - typeName: getNameOfDeclaration((node as ExpressionWithTypeArguments).parent.parent) + typeName: getNameOfDeclaration(node.parent.parent as Declaration) }; } @@ -466,4 +468,4 @@ namespace ts { }; } } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/destructuring.ts b/src/compiler/transformers/destructuring.ts index 14d1659dc76..cde5ee290a3 100644 --- a/src/compiler/transformers/destructuring.ts +++ b/src/compiler/transformers/destructuring.ts @@ -307,8 +307,8 @@ namespace ts { if (!getRestIndicatorOfBindingOrAssignmentElement(element)) { const propertyName = getPropertyNameOfBindingOrAssignmentElement(element)!; if (flattenContext.level >= FlattenLevel.ObjectRest - && !(element.transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest)) - && !(getTargetOfBindingOrAssignmentElement(element)!.transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest)) + && !(element.transformFlags & (TransformFlags.ContainsRestOrSpread | TransformFlags.ContainsObjectRestOrSpread)) + && !(getTargetOfBindingOrAssignmentElement(element)!.transformFlags & (TransformFlags.ContainsRestOrSpread | TransformFlags.ContainsObjectRestOrSpread)) && !isComputedPropertyName(propertyName)) { bindingElements = append(bindingElements, element); } @@ -384,7 +384,7 @@ namespace ts { if (flattenContext.level >= FlattenLevel.ObjectRest) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & TransformFlags.ContainsObjectRest) { + if (element.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { const temp = createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index dcb0d9ac208..f97cec89cdf 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -46,10 +46,16 @@ namespace ts { * so nobody can observe this new value. */ interface LoopOutParameter { + flags: LoopOutParameterFlags; originalName: Identifier; outParamName: Identifier; } + const enum LoopOutParameterFlags { + Body = 1 << 0, // Modified in the body of the iteration statement + Initializer = 1 << 1, // Set in the initializer of a ForStatement + } + const enum CopyDirection { ToOriginal, ToOutParameter @@ -129,10 +135,14 @@ namespace ts { */ hoistedLocalVariables?: Identifier[]; + conditionVariable?: Identifier; + + loopParameters: ParameterDeclaration[]; + /** * List of loop out parameters - detailed descripion can be found in the comment to LoopOutParameter */ - loopOutParameters?: LoopOutParameter[]; + loopOutParameters: LoopOutParameter[]; } const enum SuperCaptureResult { @@ -347,7 +357,7 @@ namespace ts { return (node.transformFlags & TransformFlags.ContainsES2015) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & HierarchyFacts.ConstructorWithCapturedSuper && (isStatement(node) || (node.kind === SyntaxKind.Block))) - || (isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (getEmitFlags(node) & EmitFlags.TypeScriptClassWrapper) !== 0; } @@ -646,8 +656,8 @@ namespace ts { } } let returnExpression: Expression = createLiteral(labelMarker); - if (convertedLoopState.loopOutParameters!.length) { - const outParams = convertedLoopState.loopOutParameters!; + if (convertedLoopState.loopOutParameters.length) { + const outParams = convertedLoopState.loopOutParameters; let expr: Expression | undefined; for (let i = 0; i < outParams.length; i++) { const copyExpr = copyOutParameter(outParams[i], CopyDirection.ToOutParameter); @@ -770,7 +780,7 @@ namespace ts { enableSubstitutionsForBlockScopedBindings(); } - const extendsClauseElement = getEffectiveBaseTypeNode(node); + const extendsClauseElement = getClassExtendsHeritageElement(node); const classFunction = createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -1340,8 +1350,8 @@ namespace ts { * part of a constructor declaration with a * synthesized call to `super` */ - function shouldAddRestParameter(node: ParameterDeclaration | undefined, inConstructorWithSynthesizedSuper: boolean) { - return node && node.dotDotDotToken && node.name.kind === SyntaxKind.Identifier && !inConstructorWithSynthesizedSuper; + function shouldAddRestParameter(node: ParameterDeclaration | undefined, inConstructorWithSynthesizedSuper: boolean): node is ParameterDeclaration { + return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper); } /** @@ -1360,11 +1370,11 @@ namespace ts { } // `declarationName` is the name of the local declaration for the parameter. - const declarationName = getMutableClone(parameter!.name); + const declarationName = parameter.name.kind === SyntaxKind.Identifier ? getMutableClone(parameter.name) : createTempVariable(/*recordTempVariable*/ undefined); setEmitFlags(declarationName, EmitFlags.NoSourceMap); // `expressionName` is the name of the parameter used in expressions. - const expressionName = getSynthesizedClone(parameter!.name); + const expressionName = parameter.name.kind === SyntaxKind.Identifier ? getSynthesizedClone(parameter.name) : declarationName; const restIndex = node.parameters.length - 1; const temp = createLoopVariable(); @@ -1429,6 +1439,24 @@ namespace ts { setEmitFlags(forStatement, EmitFlags.CustomPrologue); startOnNewLine(forStatement); statements.push(forStatement); + + if (parameter.name.kind !== SyntaxKind.Identifier) { + // do the actual destructuring of the rest parameter if necessary + statements.push( + setEmitFlags( + setTextRange( + createVariableStatement( + /*modifiers*/ undefined, + createVariableDeclarationList( + flattenDestructuringBinding(parameter, visitor, context, FlattenLevel.All, expressionName), + ) + ), + parameter + ), + EmitFlags.CustomPrologue + ) + ); + } } /** @@ -2610,7 +2638,40 @@ namespace ts { return visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node: IterationStatement): boolean { + interface ForStatementWithConvertibleInitializer extends ForStatement { + initializer: VariableDeclarationList; + } + + interface ForStatementWithConvertibleCondition extends ForStatement { + condition: Expression; + } + + interface ForStatementWithConvertibleIncrementor extends ForStatement { + incrementor: Expression; + } + + function shouldConvertPartOfIterationStatement(node: Node) { + return (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ContainsCapturedBlockScopeBinding) !== 0; + } + + function shouldConvertInitializerOfForStatement(node: IterationStatement): node is ForStatementWithConvertibleInitializer { + return isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + + function shouldConvertConditionOfForStatement(node: IterationStatement): node is ForStatementWithConvertibleCondition { + return isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + + function shouldConvertIncrementorOfForStatement(node: IterationStatement): node is ForStatementWithConvertibleIncrementor { + return isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + + function shouldConvertIterationStatement(node: IterationStatement) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + + function shouldConvertBodyOfIterationStatement(node: IterationStatement): boolean { return (resolver.getNodeCheckFlags(node) & NodeCheckFlags.LoopWithCapturedBlockScopedBinding) !== 0; } @@ -2639,7 +2700,7 @@ namespace ts { } function convertIterationStatementBodyIfNecessary(node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, convert?: LoopConverter): VisitResult { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { let saveAllowedNonLabeledJumps: Jump | undefined; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -2658,7 +2719,102 @@ namespace ts { return result; } - const functionName = createUniqueName("_loop"); + const currentState = createConvertedLoopState(node); + const statements: Statement[] = []; + + const outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + + const initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + const bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + + convertedLoopState = outerConvertedLoopState; + + if (initializerFunction) statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) statements.push(bodyFunction.functionDeclaration); + + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + + let loop: Statement; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + const clone = convertIterationStatementCore(node, initializerFunction, createBlock(bodyFunction.part, /*multiLine*/ true)); + aggregateTransformFlags(clone); + loop = restoreEnclosingLabel(clone, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + const clone = convertIterationStatementCore(node, initializerFunction, visitNode(node.statement, visitor, isStatement, liftToBlock)); + aggregateTransformFlags(clone); + loop = restoreEnclosingLabel(clone, outermostLabeledStatement, convertedLoopState && resetLabel); + } + + statements.push(loop); + return statements; + } + + function convertIterationStatementCore(node: IterationStatement, initializerFunction: IterationStatementPartFunction | undefined, convertedLoopBody: Statement) { + switch (node.kind) { + case SyntaxKind.ForStatement: return convertForStatement(node as ForStatement, initializerFunction, convertedLoopBody); + case SyntaxKind.ForInStatement: return convertForInStatement(node as ForInStatement, convertedLoopBody); + case SyntaxKind.ForOfStatement: return convertForOfStatement(node as ForOfStatement, convertedLoopBody); + case SyntaxKind.DoStatement: return convertDoStatement(node as DoStatement, convertedLoopBody); + case SyntaxKind.WhileStatement: return convertWhileStatement(node as WhileStatement, convertedLoopBody); + default: return Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + + function convertForStatement(node: ForStatement, initializerFunction: IterationStatementPartFunction | undefined, convertedLoopBody: Statement) { + const shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + const shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return updateFor( + node, + visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, isForInitializer), + visitNode(shouldConvertCondition ? undefined : node.condition, visitor, isExpression), + visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, isExpression), + convertedLoopBody + ); + } + + function convertForOfStatement(node: ForOfStatement, convertedLoopBody: Statement) { + return updateForOf( + node, + /*awaitModifier*/ undefined, + visitNode(node.initializer, visitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + convertedLoopBody); + } + + function convertForInStatement(node: ForInStatement, convertedLoopBody: Statement) { + return updateForIn( + node, + visitNode(node.initializer, visitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + convertedLoopBody); + } + + function convertDoStatement(node: DoStatement, convertedLoopBody: Statement) { + return updateDo( + node, + convertedLoopBody, + visitNode(node.expression, visitor, isExpression)); + } + + function convertWhileStatement(node: WhileStatement, convertedLoopBody: Statement) { + return updateWhile( + node, + visitNode(node.expression, visitor, isExpression), + convertedLoopBody); + } + + function createConvertedLoopState(node: IterationStatement) { let loopInitializer: VariableDeclarationList | undefined; switch (node.kind) { case SyntaxKind.ForStatement: @@ -2670,74 +2826,311 @@ namespace ts { } break; } + // variables that will be passed to the loop as parameters const loopParameters: ParameterDeclaration[] = []; // variables declared in the loop initializer that will be changed inside the loop const loopOutParameters: LoopOutParameter[] = []; if (loopInitializer && (getCombinedNodeFlags(loopInitializer) & NodeFlags.BlockScoped)) { + const hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (const decl of loopInitializer.declarations) { - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - const outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters }; - if (outerConvertedLoopState) { + const currentState: ConvertedLoopState = { loopParameters, loopOutParameters }; + if (convertedLoopState) { // 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 - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.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 = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; + } + } + return currentState; + } + + function addExtraDeclarationsForConvertedLoop(statements: Statement[], state: ConvertedLoopState, outerState: ConvertedLoopState | undefined) { + let extraVariableDeclarations: VariableDeclaration[] | undefined; + // propagate state from the inner loop to the outer loop if necessary + if (state.argumentsName) { + // if alias for arguments is set + if (outerState) { + // pass it to outer converted loop + outerState.argumentsName = state.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push( + createVariableDeclaration( + state.argumentsName, + /*type*/ undefined, + createIdentifier("arguments") + ) + ); } } + if (state.thisName) { + // if alias for this is set + if (outerState) { + // pass it to outer converted loop + outerState.thisName = state.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'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push( + createVariableDeclaration( + state.thisName, + /*type*/ undefined, + createIdentifier("this") + ) + ); + } + } + + if (state.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerState) { + // pass them to outer converted loop + outerState.hoistedLocalVariables = state.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (const identifier of state.hoistedLocalVariables) { + extraVariableDeclarations.push(createVariableDeclaration(identifier)); + } + } + } + + // add extra variables to hold out parameters if necessary + if (state.loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (const outParam of state.loopOutParameters) { + extraVariableDeclarations.push(createVariableDeclaration(outParam.outParamName)); + } + } + + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(createVariableDeclaration(state.conditionVariable, /*type*/ undefined, createFalse())); + } + + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(createVariableStatement( + /*modifiers*/ undefined, + createVariableDeclarationList(extraVariableDeclarations) + )); + } + } + + interface IterationStatementPartFunction { + functionName: Identifier; + functionDeclaration: Statement; + containsYield: boolean; + part: T; + } + + function createOutVariable(p: LoopOutParameter) { + return createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node: ForStatementWithConvertibleInitializer, currentState: ConvertedLoopState): IterationStatementPartFunction { + const functionName = createUniqueName("_loop_init"); + + const containsYield = (node.initializer.transformFlags & TransformFlags.ContainsYield) !== 0; + let emitFlags = EmitFlags.None; + if (currentState.containsLexicalThis) emitFlags |= EmitFlags.CapturesThis; + if (containsYield && hierarchyFacts & HierarchyFacts.AsyncFunctionBody) emitFlags |= EmitFlags.AsyncFunctionBody; + + const statements: Statement[] = []; + statements.push(createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, LoopOutParameterFlags.Initializer, CopyDirection.ToOutParameter, statements); + + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + + const functionDeclaration = createVariableStatement( + /*modifiers*/ undefined, + setEmitFlags( + createVariableDeclarationList([ + createVariableDeclaration( + functionName, + /*type*/ undefined, + setEmitFlags( + createFunctionExpression( + /*modifiers*/ undefined, + containsYield ? createToken(SyntaxKind.AsteriskToken) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, + visitNode( + createBlock(statements, /*multiLine*/ true), + visitor, + isBlock + ) + ), + emitFlags + ) + ) + ]), + EmitFlags.NoHoisting + ) + ); + + const part = createVariableDeclarationList(map(currentState.loopOutParameters, createOutVariable)); + return { functionName, containsYield, functionDeclaration, part }; + } + + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node: IterationStatement, currentState: ConvertedLoopState, outerState: ConvertedLoopState | undefined): IterationStatementPartFunction { + const functionName = createUniqueName("_loop"); startLexicalEnvironment(); - let loopBody = visitNode(node.statement, visitor, isStatement, liftToBlock); + const statement = visitNode(node.statement, visitor, isStatement, liftToBlock); const lexicalEnvironment = endLexicalEnvironment(); - const currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; + const statements: Statement[] = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. - if (loopOutParameters.length || lexicalEnvironment) { - const statements = isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, CopyDirection.ToOutParameter, statements); + currentState.conditionVariable = createUniqueName("inc"); + statements.push(createIf( + currentState.conditionVariable, + createStatement(visitNode(node.incrementor, visitor, isExpression)), + createStatement(createAssignment(currentState.conditionVariable, createTrue())) + )); + + if (shouldConvertConditionOfForStatement(node)) { + statements.push(createIf( + createPrefix(SyntaxKind.ExclamationToken, visitNode(node.condition, visitor, isExpression)), + visitNode(createBreak(), visitor, isStatement) + )); } - addStatementsAfterPrologue(statements, lexicalEnvironment); - loopBody = createBlock(statements, /*multiline*/ true); } - if (isBlock(loopBody)) { - loopBody.multiLine = true; + if (isBlock(statement)) { + addRange(statements, statement.statements); } else { - loopBody = createBlock([loopBody], /*multiline*/ true); + statements.push(statement); } + copyOutParameters(currentState.loopOutParameters, LoopOutParameterFlags.Body, CopyDirection.ToOutParameter, statements); + addStatementsAfterPrologue(statements, lexicalEnvironment); + + const loopBody = createBlock(statements, /*multiLine*/ true); + if (isBlock(statement)) setOriginalNode(loopBody, statement); + const containsYield = (node.statement.transformFlags & TransformFlags.ContainsYield) !== 0; - const isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & HierarchyFacts.AsyncFunctionBody) !== 0; - let loopBodyFlags: EmitFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= EmitFlags.CapturesThis; - } + let emitFlags: EmitFlags = 0; + if (currentState.containsLexicalThis) emitFlags |= EmitFlags.CapturesThis; + if (containsYield && (hierarchyFacts & HierarchyFacts.AsyncFunctionBody) !== 0) emitFlags |= EmitFlags.AsyncFunctionBody; - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= EmitFlags.AsyncFunctionBody; - } + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } - const convertedLoopVariable = + const functionDeclaration = createVariableStatement( /*modifiers*/ undefined, setEmitFlags( @@ -2752,11 +3145,11 @@ namespace ts { containsYield ? createToken(SyntaxKind.AsteriskToken) : undefined, /*name*/ undefined, /*typeParameters*/ undefined, - loopParameters, + currentState.loopParameters, /*type*/ undefined, - loopBody + loopBody ), - loopBodyFlags + emitFlags ) ) ] @@ -2765,106 +3158,8 @@ namespace ts { ) ); - const statements: Statement[] = [convertedLoopVariable]; - - let extraVariableDeclarations: VariableDeclaration[] | undefined; - // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { - // if alias for arguments is set - if (outerConvertedLoopState) { - // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; - } - else { - // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push( - createVariableDeclaration( - currentState.argumentsName, - /*type*/ undefined, - createIdentifier("arguments") - ) - ); - } - } - - if (currentState.thisName) { - // if alias for this is set - if (outerConvertedLoopState) { - // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.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'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push( - createVariableDeclaration( - currentState.thisName, - /*type*/ undefined, - createIdentifier("this") - ) - ); - } - } - - if (currentState.hoistedLocalVariables) { - // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { - // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; - } - else { - if (!extraVariableDeclarations) { - extraVariableDeclarations = []; - } - // hoist collected variable declarations - for (const identifier of currentState.hoistedLocalVariables) { - extraVariableDeclarations.push(createVariableDeclaration(identifier)); - } - } - } - - // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { - if (!extraVariableDeclarations) { - extraVariableDeclarations = []; - } - for (const outParam of loopOutParameters) { - extraVariableDeclarations.push(createVariableDeclaration(outParam.outParamName)); - } - } - - // create variable statement to hold all introduced variable declarations - if (extraVariableDeclarations) { - statements.push(createVariableStatement( - /*modifiers*/ undefined, - createVariableDeclarationList(extraVariableDeclarations) - )); - } - - const convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - - let loop: Statement; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); - } - else { - let clone = getMutableClone(node); - // clean statement part - clone.statement = undefined!; - // visit childnodes to transform initializer/condition/incrementor parts - clone = visitEachChild(clone, visitor, context); - // set loop statement - clone.statement = createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone.transformFlags = 0; - aggregateTransformFlags(clone); - loop = restoreEnclosingLabel(clone, outermostLabeledStatement, convertedLoopState && resetLabel); - } - - statements.push(loop); - return statements; + const part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName, containsYield, functionDeclaration, part }; } function copyOutParameter(outParam: LoopOutParameter, copyDirection: CopyDirection): BinaryExpression { @@ -2873,14 +3168,26 @@ namespace ts { return createBinary(target, SyntaxKind.EqualsToken, source); } - function copyOutParameters(outParams: LoopOutParameter[], copyDirection: CopyDirection, statements: Statement[]): void { + function copyOutParameters(outParams: LoopOutParameter[], partFlags: LoopOutParameterFlags, copyDirection: CopyDirection, statements: Statement[]): void { for (const outParam of outParams) { - statements.push(createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName: Identifier, parameters: ParameterDeclaration[], state: ConvertedLoopState, isAsyncBlockContainingAwait: boolean): Statement[] { - const outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName: Identifier, containsYield: boolean): Statement { + const call = createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + const callResult = containsYield + ? createYield( + createToken(SyntaxKind.AsteriskToken), + setEmitFlags(call, EmitFlags.Iterator) + ) + : call; + return createStatement(callResult); + } + + function generateCallToConvertedLoop(loopFunctionExpressionName: Identifier, state: ConvertedLoopState, outerState: ConvertedLoopState | undefined, containsYield: boolean): Statement[] { const statements: Statement[] = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop @@ -2891,8 +3198,8 @@ namespace ts { !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - const call = createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, map(parameters, p => p.name)); - const callResult = isAsyncBlockContainingAwait + const call = createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, map(state.loopParameters, p => p.name)); + const callResult = containsYield ? createYield( createToken(SyntaxKind.AsteriskToken), setEmitFlags(call, EmitFlags.Iterator) @@ -2900,7 +3207,7 @@ namespace ts { : call; if (isSimpleLoop) { statements.push(createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters!, CopyDirection.ToOriginal, statements); + copyOutParameters(state.loopOutParameters, LoopOutParameterFlags.Body, CopyDirection.ToOriginal, statements); } else { const loopResultName = createUniqueName("state"); @@ -2911,12 +3218,12 @@ namespace ts { ) ); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters!, CopyDirection.ToOriginal, statements); + copyOutParameters(state.loopOutParameters, LoopOutParameterFlags.Body, CopyDirection.ToOriginal, statements); if (state.nonLocalJumps! & Jump.Return) { let returnStatement: ReturnStatement; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps! |= Jump.Return; + if (outerState) { + outerState.nonLocalJumps! |= Jump.Return; returnStatement = createReturn(loopResultName); } else { @@ -2949,8 +3256,8 @@ namespace ts { if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { const caseClauses: CaseClause[] = []; - processLabeledJumps(state.labeledNonLocalBreaks!, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues!, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks!, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues!, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push( createSwitch( loopResultName, @@ -2998,20 +3305,28 @@ namespace ts { }); } - function processLoopVariableDeclaration(decl: VariableDeclaration | BindingElement, loopParameters: ParameterDeclaration[], loopOutParameters: LoopOutParameter[]) { + function processLoopVariableDeclaration(container: IterationStatement, decl: VariableDeclaration | BindingElement, loopParameters: ParameterDeclaration[], loopOutParameters: LoopOutParameter[], hasCapturedBindingsInForInitializer: boolean) { const name = decl.name; if (isBindingPattern(name)) { for (const element of name.elements) { if (!isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & NodeCheckFlags.NeedsLoopOutParameter) { + const checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & NodeCheckFlags.NeedsLoopOutParameter || hasCapturedBindingsInForInitializer) { const outParamName = createUniqueName("out_" + idText(name)); - loopOutParameters.push({ originalName: name, outParamName }); + let flags: LoopOutParameterFlags = 0; + if (checkFlags & NodeCheckFlags.NeedsLoopOutParameter) { + flags |= LoopOutParameterFlags.Body; + } + if (isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= LoopOutParameterFlags.Initializer; + } + loopOutParameters.push({ flags, originalName: name, outParamName }); } } } @@ -3432,7 +3747,7 @@ namespace ts { function visitCallExpressionWithPotentialCapturedThisAssignment(node: CallExpression, assignToCapturedThis: boolean): CallExpression | BinaryExpression { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & TransformFlags.ContainsSpread || + if (node.transformFlags & TransformFlags.ContainsRestOrSpread || node.expression.kind === SyntaxKind.SuperKeyword || isSuperProperty(skipOuterExpressions(node.expression))) { @@ -3442,7 +3757,7 @@ namespace ts { } let resultingCall: CallExpression | BinaryExpression; - if (node.transformFlags & TransformFlags.ContainsSpread) { + if (node.transformFlags & TransformFlags.ContainsRestOrSpread) { // [source] // f(...a, b) // x.m(...a, b) @@ -3505,7 +3820,7 @@ namespace ts { * @param node A NewExpression node. */ function visitNewExpression(node: NewExpression): LeftHandSideExpression { - if (node.transformFlags & TransformFlags.ContainsSpread) { + if (node.transformFlags & TransformFlags.ContainsRestOrSpread) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -4079,7 +4394,7 @@ namespace ts { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index f58a24fb0a9..b509c6dd003 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -32,6 +32,15 @@ namespace ts { let enclosingFunctionParameterNames: UnderscoreEscapedMap; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + let capturedSuperProperties: UnderscoreEscapedMap; + /** Whether the async function contains an element access on super (`super[x]`). */ + let hasSuperElementAccess: boolean; + /** A set of node IDs for generated super accessors (variable statements). */ + const substitutedSuperAccessors: boolean[] = []; + // Save the previous transformation hooks. const previousOnEmitNode = context.onEmitNode; const previousOnSubstituteNode = context.onSubstituteNode; @@ -56,7 +65,6 @@ namespace ts { if ((node.transformFlags & TransformFlags.ContainsES2017) === 0) { return node; } - switch (node.kind) { case SyntaxKind.AsyncKeyword: // ES2017 async modifier should be elided for targets < ES2017 @@ -77,6 +85,18 @@ namespace ts { case SyntaxKind.ArrowFunction: return visitArrowFunction(node); + case SyntaxKind.PropertyAccessExpression: + if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return visitEachChild(node, visitor, context); + + case SyntaxKind.ElementAccessExpression: + if (capturedSuperProperties && (node).expression.kind === SyntaxKind.SuperKeyword) { + hasSuperElementAccess = true; + } + return visitEachChild(node, visitor, context); + default: return visitEachChild(node, visitor, context); } @@ -398,6 +418,11 @@ namespace ts { recordDeclarationName(parameter, enclosingFunctionParameterNames); } + const savedCapturedSuperProperties = capturedSuperProperties; + const savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + let result: ConciseBody; if (!isArrowFunction) { const statements: Statement[] = []; @@ -415,18 +440,26 @@ namespace ts { addStatementsAfterPrologue(statements, endLexicalEnvironment()); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 && resolver.getNodeCheckFlags(node) & (NodeCheckFlags.AsyncMethodWithSuperBinding | NodeCheckFlags.AsyncMethodWithSuper); + + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + const variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[getNodeId(variableStatement)] = true; + addStatementsAfterPrologue(statements, [variableStatement]); + } + const block = createBlock(statements, /*multiLine*/ true); setTextRange(block, node.body); - // Minor optimization, emit `_super` helper to capture `super` access in an arrow. - // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= ScriptTarget.ES2015) { + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) { - enableSubstitutionForAsyncMethodsWithSuper(); addEmitHelper(block, advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) { - enableSubstitutionForAsyncMethodsWithSuper(); addEmitHelper(block, asyncSuperHelper); } } @@ -452,6 +485,8 @@ namespace ts { } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } @@ -493,6 +528,8 @@ namespace ts { context.enableEmitNotification(SyntaxKind.GetAccessor); context.enableEmitNotification(SyntaxKind.SetAccessor); context.enableEmitNotification(SyntaxKind.Constructor); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(SyntaxKind.VariableStatement); } } @@ -516,6 +553,14 @@ namespace ts { return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) { + const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } @@ -548,8 +593,10 @@ namespace ts { function substitutePropertyAccessExpression(node: PropertyAccessExpression) { if (node.expression.kind === SyntaxKind.SuperKeyword) { - return createSuperAccessInAsyncMethod( - createLiteral(idText(node.name)), + return setTextRange( + createPropertyAccess( + createFileLevelUniqueName("_super"), + node.name), node ); } @@ -558,7 +605,7 @@ namespace ts { function substituteElementAccessExpression(node: ElementAccessExpression) { if (node.expression.kind === SyntaxKind.SuperKeyword) { - return createSuperAccessInAsyncMethod( + return createSuperElementAccessInAsyncMethod( node.argumentExpression, node ); @@ -593,12 +640,12 @@ namespace ts { || kind === SyntaxKind.SetAccessor; } - function createSuperAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression { + function createSuperElementAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression { if (enclosingSuperContainerFlags & NodeCheckFlags.AsyncMethodWithSuperBinding) { return setTextRange( createPropertyAccess( createCall( - createFileLevelUniqueName("_super"), + createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression] ), @@ -610,7 +657,7 @@ namespace ts { else { return setTextRange( createCall( - createFileLevelUniqueName("_super"), + createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression] ), @@ -620,6 +667,89 @@ namespace ts { } } + /** Creates a variable named `_super` with accessor properties for the given property names. */ + export function createSuperAccessVariableStatement(resolver: EmitResolver, node: FunctionLikeDeclaration, names: UnderscoreEscapedMap) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + const hasBinding = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) !== 0; + const accessors: PropertyAssignment[] = []; + names.forEach((_, key) => { + const name = unescapeLeadingUnderscores(key); + const getterAndSetter: PropertyAssignment[] = []; + getterAndSetter.push(createPropertyAssignment( + "get", + createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, + createPropertyAccess( + createSuper(), + name + ) + ) + )); + if (hasBinding) { + getterAndSetter.push( + createPropertyAssignment( + "set", + createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, + "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined + ) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, + createAssignment( + createPropertyAccess( + createSuper(), + name), + createIdentifier("v") + ) + ) + ) + ); + } + accessors.push( + createPropertyAssignment( + name, + createObjectLiteral(getterAndSetter), + ) + ); + }); + return createVariableStatement( + /* modifiers */ undefined, + createVariableDeclarationList( + [ + createVariableDeclaration( + createFileLevelUniqueName("_super"), + /* type */ undefined, + createCall( + createPropertyAccess( + createIdentifier("Object"), + "create" + ), + /* typeArguments */ undefined, + [ + createNull(), + createObjectLiteral(accessors, /* multiline */ true) + ] + ) + ) + ], + NodeFlags.Const)); + } + const awaiterHelper: EmitHelper = { name: "typescript:awaiter", scoped: false, @@ -667,14 +797,14 @@ namespace ts { name: "typescript:async-super", scoped: true, text: helperString` - const ${"_super"} = name => super[name];` + const ${"_superIndex"} = name => super[name];` }; export const advancedAsyncSuperHelper: EmitHelper = { name: "typescript:advanced-async-super", scoped: true, text: helperString` - const ${"_super"} = (function (geti, seti) { + const ${"_superIndex"} = (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);` diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index b121eb315db..cd62cca2c9d 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -26,6 +26,13 @@ namespace ts { let enclosingFunctionFlags: FunctionFlags; let enclosingSuperContainerFlags: NodeCheckFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + let capturedSuperProperties: UnderscoreEscapedMap; + /** Whether the async function contains an element access on super (`super[x]`). */ + let hasSuperElementAccess: boolean; + /** A set of node IDs for generated super accessors. */ + const substitutedSuperAccessors: boolean[] = []; + return chainBundle(transformSourceFile); function transformSourceFile(node: SourceFile) { @@ -57,7 +64,6 @@ namespace ts { if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) { return node; } - switch (node.kind) { case SyntaxKind.AwaitExpression: return visitAwaitExpression(node as AwaitExpression); @@ -101,6 +107,16 @@ namespace ts { return visitParenthesizedExpression(node as ParenthesizedExpression, noDestructuringValue); case SyntaxKind.CatchClause: return visitCatchClause(node as CatchClause); + case SyntaxKind.PropertyAccessExpression: + if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return visitEachChild(node, visitor, context); + case SyntaxKind.ElementAccessExpression: + if (capturedSuperProperties && (node).expression.kind === SyntaxKind.SuperKeyword) { + hasSuperElementAccess = true; + } + return visitEachChild(node, visitor, context); default: return visitEachChild(node, visitor, context); } @@ -210,7 +226,7 @@ namespace ts { } function visitObjectLiteralExpression(node: ObjectLiteralExpression): Expression { - if (node.transformFlags & TransformFlags.ContainsObjectSpread) { + if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -250,7 +266,7 @@ namespace ts { * @param node A BinaryExpression node. */ function visitBinaryExpression(node: BinaryExpression, noDestructuringValue: boolean): Expression { - if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.ContainsObjectRest) { + if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { return flattenDestructuringAssignment( node, visitor, @@ -276,7 +292,7 @@ namespace ts { */ function visitVariableDeclaration(node: VariableDeclaration): VisitResult { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (isBindingPattern(node.name) && node.name.transformFlags & TransformFlags.ContainsObjectRest) { + if (isBindingPattern(node.name) && node.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { return flattenDestructuringBinding( node, visitor, @@ -307,7 +323,7 @@ namespace ts { * @param node A ForOfStatement. */ function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined): VisitResult { - if (node.initializer.transformFlags & TransformFlags.ContainsObjectRest) { + if (node.initializer.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -499,7 +515,7 @@ namespace ts { } function visitParameter(node: ParameterDeclaration): ParameterDeclaration { - if (node.transformFlags & TransformFlags.ContainsObjectRest) { + if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return updateParameter( @@ -655,41 +671,57 @@ namespace ts { const statementOffset = addPrologue(statements, node.body!.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push( - createReturn( - createAsyncGeneratorHelper( - context, - createFunctionExpression( - /*modifiers*/ undefined, - createToken(SyntaxKind.AsteriskToken), - node.name && getGeneratedNameForNode(node.name), - /*typeParameters*/ undefined, - /*parameters*/ [], - /*type*/ undefined, - updateBlock( - node.body!, - visitLexicalEnvironment(node.body!.statements, visitor, context, statementOffset) - ) + const savedCapturedSuperProperties = capturedSuperProperties; + const savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + + const returnStatement = createReturn( + createAsyncGeneratorHelper( + context, + createFunctionExpression( + /*modifiers*/ undefined, + createToken(SyntaxKind.AsteriskToken), + node.name && getGeneratedNameForNode(node.name), + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + updateBlock( + node.body!, + visitLexicalEnvironment(node.body!.statements, visitor, context, statementOffset) ) ) ) ); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 && resolver.getNodeCheckFlags(node) & (NodeCheckFlags.AsyncMethodWithSuperBinding | NodeCheckFlags.AsyncMethodWithSuper); + + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + const variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[getNodeId(variableStatement)] = true; + addStatementsAfterPrologue(statements, [variableStatement]); + } + + statements.push(returnStatement); + addStatementsAfterPrologue(statements, endLexicalEnvironment()); const block = updateBlock(node.body!, statements); - // Minor optimization, emit `_super` helper to capture `super` access in an arrow. - // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= ScriptTarget.ES2015) { + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) { - enableSubstitutionForAsyncMethodsWithSuper(); addEmitHelper(block, advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) { - enableSubstitutionForAsyncMethodsWithSuper(); addEmitHelper(block, asyncSuperHelper); } } + + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return block; } @@ -716,7 +748,7 @@ namespace ts { function appendObjectRestAssignmentsIfNeeded(statements: Statement[] | undefined, node: FunctionLikeDeclaration): Statement[] | undefined { for (const parameter of node.parameters) { - if (parameter.transformFlags & TransformFlags.ContainsObjectRest) { + if (parameter.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { const temp = getGeneratedNameForNode(parameter); const declarations = flattenDestructuringBinding( parameter, @@ -758,6 +790,8 @@ namespace ts { context.enableEmitNotification(SyntaxKind.GetAccessor); context.enableEmitNotification(SyntaxKind.SetAccessor); context.enableEmitNotification(SyntaxKind.Constructor); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(SyntaxKind.VariableStatement); } } @@ -781,6 +815,14 @@ namespace ts { return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) { + const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0 as NodeCheckFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } @@ -813,8 +855,10 @@ namespace ts { function substitutePropertyAccessExpression(node: PropertyAccessExpression) { if (node.expression.kind === SyntaxKind.SuperKeyword) { - return createSuperAccessInAsyncMethod( - createLiteral(idText(node.name)), + return setTextRange( + createPropertyAccess( + createFileLevelUniqueName("_super"), + node.name), node ); } @@ -823,7 +867,7 @@ namespace ts { function substituteElementAccessExpression(node: ElementAccessExpression) { if (node.expression.kind === SyntaxKind.SuperKeyword) { - return createSuperAccessInAsyncMethod( + return createSuperElementAccessInAsyncMethod( node.argumentExpression, node ); @@ -858,12 +902,12 @@ namespace ts { || kind === SyntaxKind.SetAccessor; } - function createSuperAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression { + function createSuperElementAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression { if (enclosingSuperContainerFlags & NodeCheckFlags.AsyncMethodWithSuperBinding) { return setTextRange( createPropertyAccess( createCall( - createIdentifier("_super"), + createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression] ), @@ -875,7 +919,7 @@ namespace ts { else { return setTextRange( createCall( - createIdentifier("_super"), + createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression] ), diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 7af0b7c5ad7..a22c6df8d06 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -973,9 +973,11 @@ namespace ts { // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - const hasInstancePropertyWithInitializer = forEach(node.members, isInstanceInitializedProperty); - const hasParameterPropertyAssignments = node.transformFlags & TransformFlags.ContainsParameterPropertyAssignments; const constructor = getFirstConstructorWithBody(node); + const hasInstancePropertyWithInitializer = forEach(node.members, isInstanceInitializedProperty); + const hasParameterPropertyAssignments = constructor && + constructor.transformFlags & TransformFlags.ContainsTypeScriptClassSyntax && + forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. @@ -1896,9 +1898,13 @@ namespace ts { case SyntaxKind.StringLiteral: return createIdentifier("String"); + case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.NumericLiteral: return createIdentifier("Number"); + case SyntaxKind.BigIntLiteral: + return getGlobalBigIntNameWithFallback(); + case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: return createIdentifier("Boolean"); @@ -1910,6 +1916,9 @@ namespace ts { case SyntaxKind.NumberKeyword: return createIdentifier("Number"); + case SyntaxKind.BigIntKeyword: + return getGlobalBigIntNameWithFallback(); + case SyntaxKind.SymbolKeyword: return languageVersion < ScriptTarget.ES2015 ? getGlobalSymbolNameWithFallback() @@ -1920,7 +1929,10 @@ namespace ts { case SyntaxKind.IntersectionType: case SyntaxKind.UnionType: - return serializeUnionOrIntersectionType(node); + return serializeTypeList((node).types); + + case SyntaxKind.ConditionalType: + return serializeTypeList([(node).trueType, (node).falseType]); case SyntaxKind.TypeQuery: case SyntaxKind.TypeOperator: @@ -1933,6 +1945,7 @@ namespace ts { case SyntaxKind.ImportType: break; + default: return Debug.failBadSyntaxKind(node); } @@ -1940,11 +1953,11 @@ namespace ts { return createIdentifier("Object"); } - function serializeUnionOrIntersectionType(node: UnionOrIntersectionTypeNode): SerializedTypeNode { + function serializeTypeList(types: ReadonlyArray): SerializedTypeNode { // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced let serializedUnion: SerializedTypeNode | undefined; - for (let typeNode of node.types) { + for (let typeNode of types) { while (typeNode.kind === SyntaxKind.ParenthesizedType) { typeNode = (typeNode as ParenthesizedTypeNode).type; // Skip parens if need be } @@ -1990,6 +2003,11 @@ namespace ts { const kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (findAncestor(node, n => n.parent && isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n))) { + return createIdentifier("Object"); + } + const serialized = serializeEntityNameAsExpressionFallback(node.typeName); const temp = createTempVariable(hoistVariableDeclaration); return createConditional( @@ -2004,6 +2022,9 @@ namespace ts { case TypeReferenceSerializationKind.VoidNullableOrNeverType: return createVoidZero(); + case TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); + case TypeReferenceSerializationKind.BooleanType: return createIdentifier("Boolean"); @@ -2113,6 +2134,20 @@ namespace ts { ); } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback(): SerializedTypeNode { + return languageVersion < ScriptTarget.ESNext + ? createConditional( + createTypeCheck(createIdentifier("BigInt"), "function"), + createIdentifier("BigInt"), + createIdentifier("Object") + ) + : createIdentifier("BigInt"); + } + /** * A simple inlinable expression is an expression which can be copied into multiple locations * without risk of repeating any sideeffects and whose value could not possibly change between diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 4ddda98a41f..01c4801b106 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -11,52 +11,29 @@ namespace ts { message(diag: DiagnosticMessage, ...args: string[]): void; } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - export interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - diagnostics?: FileMap; // TODO(shkamat): this should be really be diagnostics but thats for later time - - invalidateProject(project: ResolvedConfigFileName, dependencyGraph: DependencyGraph | undefined): void; - getNextInvalidatedProject(): ResolvedConfigFileName | undefined; - hasPendingInvalidatedProjects(): boolean; - missingRoots: Map; - } - - type Mapper = ReturnType; interface DependencyGraph { buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; + /** value in config File map is true if project is referenced using prepend */ + referencingProjectsMap: ConfigFileMap>; } - export interface BuildOptions { + export interface BuildOptions extends OptionsBase { dry?: boolean; force?: boolean; verbose?: boolean; + /*@internal*/ clean?: boolean; /*@internal*/ watch?: boolean; /*@internal*/ help?: boolean; + preserveWatchOutput?: boolean; + listEmittedFiles?: boolean; + listFiles?: boolean; + pretty?: boolean; + + traceResolution?: boolean; + /* @internal */ diagnostics?: boolean; + /* @internal */ extendedDiagnostics?: boolean; } enum BuildResultFlags { @@ -76,8 +53,9 @@ namespace ts { SyntaxErrors = 1 << 3, TypeErrors = 1 << 4, DeclarationEmitErrors = 1 << 5, + EmitErrors = 1 << 6, - AnyErrors = ConfigFileErrors | SyntaxErrors | TypeErrors | DeclarationEmitErrors + AnyErrors = ConfigFileErrors | SyntaxErrors | TypeErrors | DeclarationEmitErrors | EmitErrors } export enum UpToDateStatusType { @@ -94,6 +72,7 @@ namespace ts { OutOfDateWithUpstream, UpstreamOutOfDate, UpstreamBlocked, + ComputingUpstream, /** * Projects with no outputs (i.e. "solution" files) @@ -109,6 +88,7 @@ namespace ts { | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked + | Status.ComputingUpstream | Status.ContainerOnly; export namespace Status { @@ -139,7 +119,7 @@ namespace ts { newestDeclarationFileContentChangedTime?: Date; newestOutputFileTime?: Date; newestOutputFileName?: string; - oldestOutputFileName?: string; + oldestOutputFileName: string; } /** @@ -178,6 +158,13 @@ namespace ts { upstreamProjectName: string; } + /** + * Computing status of upstream projects referenced + */ + export interface ComputingUpstream { + type: UpToDateStatusType.ComputingUpstream; + } + /** * One or more of the project's outputs is older than the newest output of * an upstream project. @@ -189,120 +176,90 @@ namespace ts { } } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; + interface FileMap { + setValue(fileName: U, value: T): void; + getValue(fileName: U): T | undefined; + hasKey(fileName: U): boolean; + removeKey(fileName: U): void; + forEach(action: (value: T, key: V) => void): void; getSize(): number; + clear(): void; } + type ResolvedConfigFilePath = ResolvedConfigFileName & Path; + type ConfigFileMap = FileMap; + type ToResolvedConfigFilePath = (fileName: ResolvedConfigFileName) => ResolvedConfigFilePath; + type ToPath = (fileName: string) => Path; + /** * A FileMap maintains a normalized-key to value relationship */ - function createFileMap(): FileMap { + function createFileMap(toPath: ToResolvedConfigFilePath): ConfigFileMap; + function createFileMap(toPath: ToPath): FileMap; + function createFileMap(toPath: (fileName: U) => V): FileMap { // tslint:disable-next-line:no-null-keyword const lookup = createMap(); return { setValue, getValue, - getValueOrUndefined, removeKey, - getKeys, + forEach, hasKey, - getSize + getSize, + clear }; - function getKeys(): string[] { - return Object.keys(lookup); + function forEach(action: (value: T, key: V) => void) { + lookup.forEach(action); } - function hasKey(fileName: string) { - return lookup.has(normalizePath(fileName)); + function hasKey(fileName: U) { + return lookup.has(toPath(fileName)); } - function removeKey(fileName: string) { - lookup.delete(normalizePath(fileName)); + function removeKey(fileName: U) { + lookup.delete(toPath(fileName)); } - function setValue(fileName: string, value: T) { - lookup.set(normalizePath(fileName), value); + function setValue(fileName: U, value: T) { + lookup.set(toPath(fileName), value); } - function getValue(fileName: string): T | never { - const f = normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f)!; - } - else { - throw new Error(`No value corresponding to ${fileName} exists in this map`); - } - } - - function getValueOrUndefined(fileName: string): T | undefined { - const f = normalizePath(fileName); - return lookup.get(f); + function getValue(fileName: U): T | undefined { + return lookup.get(toPath(fileName)); } function getSize() { return lookup.size; } + + function clear() { + lookup.clear(); + } } - function createDependencyMapper() { - const childToParents = createFileMap(); - const parentToChildren = createFileMap(); - const allKeys = createFileMap(); - - function addReference(childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName): void { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap: ConfigFileMap, resolved: ResolvedConfigFileName, createT: () => T): T { + const existingValue = configFileMap.getValue(resolved); + let newValue: T | undefined; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - - function getReferencesTo(parentConfigFileName: ResolvedConfigFileName): ResolvedConfigFileName[] { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - - function getReferencesOf(childConfigFileName: ResolvedConfigFileName): ResolvedConfigFileName[] { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - - function getKeys(): ReadonlyArray { - return allKeys.getKeys() as ResolvedConfigFileName[]; - } - - function addEntry(mapToAddTo: typeof childToParents | typeof parentToChildren, key: ResolvedConfigFileName, element: ResolvedConfigFileName) { - key = normalizePath(key) as ResolvedConfigFileName; - element = normalizePath(element) as ResolvedConfigFileName; - let arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - - return { - addReference, - getReferencesTo, - getReferencesOf, - getKeys - }; + return existingValue || newValue!; } - function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine) { + function getOrCreateValueMapFromConfigFileMap(configFileMap: ConfigFileMap>, resolved: ResolvedConfigFileName): Map { + return getOrCreateValueFromConfigFileMap>(configFileMap, resolved, createMap); + } + + export function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine) { const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true); const outputPath = resolvePath(configFile.options.declarationDir || configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath); return changeExtension(outputPath, Extension.Dts); } - function getOutputJavaScriptFileName(inputFileName: string, configFile: ParsedCommandLine) { + function getOutputJSFileName(inputFileName: string, configFile: ParsedCommandLine) { const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true); const outputPath = resolvePath(configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath); const newExtension = fileExtensionIs(inputFileName, Extension.Json) ? Extension.Json : @@ -317,7 +274,7 @@ namespace ts { } const outputs: string[] = []; - const js = getOutputJavaScriptFileName(inputFileName, configFile); + const js = getOutputJSFileName(inputFileName, configFile); outputs.push(js); if (configFile.options.sourceMap) { outputs.push(`${js}.map`); @@ -333,16 +290,17 @@ namespace ts { } function getOutFileOutputs(project: ParsedCommandLine): ReadonlyArray { - if (!project.options.outFile) { + const out = project.options.outFile || project.options.out; + if (!out) { return Debug.fail("outFile must be set"); } const outputs: string[] = []; - outputs.push(project.options.outFile); + outputs.push(out); if (project.options.sourceMap) { - outputs.push(`${project.options.outFile}.map`); + outputs.push(`${out}.map`); } if (getEmitDeclarations(project.options)) { - const dts = changeExtension(project.options.outFile, Extension.Dts); + const dts = changeExtension(out, Extension.Dts); outputs.push(dts); if (project.options.declarationMap) { outputs.push(`${dts}.map`); @@ -355,32 +313,6 @@ namespace ts { return opts.rootDir || getDirectoryPath(configFileName); } - function createConfigFileCache(host: CompilerHost) { - const cache = createFileMap(); - const configParseHost = parseConfigHostFromCompilerHost(host); - - function parseConfigFile(configFilePath: ResolvedConfigFileName) { - const sourceFile = host.getSourceFile(configFilePath, ScriptTarget.JSON) as JsonSourceFile; - if (sourceFile === undefined) { - return undefined; - } - - const parsed = parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - - function removeKey(configFilePath: ResolvedConfigFileName) { - cache.removeKey(configFilePath); - } - - return { - parseConfigFile, - removeKey - }; - } - function newer(date1: Date, date2: Date): Date { return date2 > date1 ? date2 : date1; } @@ -389,79 +321,46 @@ namespace ts { return fileExtensionIs(fileName, Extension.Dts); } - export function createBuildContext(options: BuildOptions): BuildContext { - const invalidatedProjectQueue = [] as ResolvedConfigFileName[]; - let nextIndex = 0; - const projectPendingBuild = createFileMap(); - const missingRoots = createMap(); - const diagnostics = options.watch ? createFileMap() : undefined; - - return { - options, - projectStatus: createFileMap(), - diagnostics, - unchangedOutputs: createFileMap(), - invalidateProject, - getNextInvalidatedProject, - hasPendingInvalidatedProjects, - missingRoots - }; - - function invalidateProject(proj: ResolvedConfigFileName, dependencyGraph: DependencyGraph | undefined) { - if (!projectPendingBuild.hasKey(proj)) { - addProjToQueue(proj); - if (dependencyGraph) { - queueBuildForDownstreamReferences(proj, dependencyGraph); - } - } - } - - function addProjToQueue(proj: ResolvedConfigFileName) { - Debug.assert(!projectPendingBuild.hasKey(proj)); - projectPendingBuild.setValue(proj, true); - invalidatedProjectQueue.push(proj); - } - - function getNextInvalidatedProject() { - if (nextIndex < invalidatedProjectQueue.length) { - const proj = invalidatedProjectQueue[nextIndex]; - nextIndex++; - projectPendingBuild.removeKey(proj); - if (!projectPendingBuild.getSize()) { - invalidatedProjectQueue.length = 0; - nextIndex = 0; - } - return proj; - } - } - - function hasPendingInvalidatedProjects() { - return !!projectPendingBuild.getSize(); - } - - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root: ResolvedConfigFileName, dependencyGraph: DependencyGraph) { - const deps = dependencyGraph.dependencyMap.getReferencesTo(root); - for (const ref of deps) { - // Can skip circular references - if (!projectPendingBuild.hasKey(ref)) { - addProjToQueue(ref); - queueBuildForDownstreamReferences(ref, dependencyGraph); - } - } - } - } - - export interface SolutionBuilderHost extends CompilerHost { + export interface SolutionBuilderHostBase extends ProgramHost { getModifiedTime(fileName: string): Date | undefined; setModifiedTime(fileName: string, date: Date): void; deleteFile(fileName: string): void; reportDiagnostic: DiagnosticReporter; // Technically we want to move it out and allow steps of actions on Solution, but for now just merge stuff in build host here reportSolutionBuilderStatus: DiagnosticReporter; + + // TODO: To do better with watch mode and normal build mode api that creates program and emits files + // This currently helps enable --diagnostics and --extendedDiagnostics + afterProgramEmitAndDiagnostics?(program: T): void; + + // For testing + now?(): Date; } - export interface SolutionBuilderWithWatchHost extends SolutionBuilderHost, WatchHost { + export interface SolutionBuilderHost extends SolutionBuilderHostBase { + reportErrorSummary?: ReportEmitErrorSummary; + } + + export interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { + } + + export interface SolutionBuilder { + buildAllProjects(): ExitStatus; + cleanAllProjects(): ExitStatus; + + // TODO:: All the below ones should technically only be in watch mode. but thats for later time + /*@internal*/ resolveProjectName(name: string): ResolvedConfigFileName; + /*@internal*/ getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus; + /*@internal*/ getBuildGraph(configFileNames: ReadonlyArray): DependencyGraph; + + /*@internal*/ invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel): void; + /*@internal*/ buildInvalidatedProject(): void; + + /*@internal*/ resetBuildContext(opts?: BuildOptions): void; + } + + export interface SolutionBuilderWithWatch extends SolutionBuilder { + /*@internal*/ startWatching(): void; } /** @@ -475,8 +374,8 @@ namespace ts { }; } - export function createSolutionBuilderHost(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter) { - const host = createCompilerHostWorker({}, /*setParentNodes*/ undefined, system) as SolutionBuilderHost; + function createSolutionBuilderHostBase(system: System, createProgram: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter) { + const host = createProgramHost(system, createProgram) as SolutionBuilderHostBase; host.getModifiedTime = system.getModifiedTime ? path => system.getModifiedTime!(path) : () => undefined; host.setModifiedTime = system.setModifiedTime ? (path, date) => system.setModifiedTime!(path, date) : noop; host.deleteFile = system.deleteFile ? path => system.deleteFile!(path) : noop; @@ -485,34 +384,78 @@ namespace ts { return host; } - export function createSolutionBuilderWithWatchHost(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) { - const host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost; - const watchHost = createWatchHost(system, reportWatchStatus); - host.onWatchStatusChange = watchHost.onWatchStatusChange; - host.watchFile = watchHost.watchFile; - host.watchDirectory = watchHost.watchDirectory; - host.setTimeout = watchHost.setTimeout; - host.clearTimeout = watchHost.clearTimeout; + export function createSolutionBuilderHost(system = sys, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportErrorSummary?: ReportEmitErrorSummary) { + const host = createSolutionBuilderHostBase(system, createProgram || createAbstractBuilder as any as CreateProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderHost; + host.reportErrorSummary = reportErrorSummary; return host; } + export function createSolutionBuilderWithWatchHost(system = sys, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) { + const host = createSolutionBuilderHostBase(system, createProgram || createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost; + const watchHost = createWatchHost(system, reportWatchStatus); + copyProperties(host, watchHost); + return host; + } + + function getCompilerOptionsOfBuildOptions(buildOptions: BuildOptions): CompilerOptions { + const result = {} as CompilerOptions; + commonOptionsWithBuild.forEach(option => { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references * TODO: use SolutionBuilderWithWatchHost => watchedSolution * use SolutionBuilderHost => Solution */ - export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions) { - const hostWithWatch = host as SolutionBuilderWithWatchHost; - const configFileCache = createConfigFileCache(host); - let context = createBuildContext(defaultOptions); + export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilder; + export function createSolutionBuilder(host: SolutionBuilderWithWatchHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilderWithWatch; + export function createSolutionBuilder(host: SolutionBuilderHost | SolutionBuilderWithWatchHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilderWithWatch { + const hostWithWatch = host as SolutionBuilderWithWatchHost; + const currentDirectory = host.getCurrentDirectory(); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host); + + // State of the solution + let options = defaultOptions; + let baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + type ConfigFileCacheEntry = ParsedCommandLine | Diagnostic; + const configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + const unchangedOutputs = createFileMap(toPath as ToPath); + /** Map from config file name to up-to-date status */ + const projectStatus = createFileMap(toPath); + const missingRoots = createMap(); + let globalDependencyGraph: DependencyGraph | undefined; + const writeFileName = (s: string) => host.trace && host.trace(s); + let readFileWithCache = (f: string) => host.readFile(f); + let projectCompilerOptions = baseCompilerOptions; + const compilerHost = createCompilerHostFromProgramHost(host, () => projectCompilerOptions); + const originalGetSourceFile = compilerHost.getSourceFile; + const computeHash = host.createHash || generateDjb2Hash; + updateGetSourceFile(); + + // Watch state + const builderPrograms = createFileMap(toPath); + const diagnostics = createFileMap>(toPath); + const projectPendingBuild = createFileMap(toPath); + const projectErrorsReported = createFileMap(toPath); + const invalidatedProjectQueue = [] as ResolvedConfigFileName[]; + let nextProjectToBuild = 0; let timerToBuildInvalidatedProject: any; let reportFileChangeDetected = false; + const { watchFile, watchFilePath, watchDirectory, writeLog } = createWatchFactory(host, options); + + // Watches for the solution + const allWatchedWildcardDirectories = createFileMap>(toPath); + const allWatchedInputFiles = createFileMap>(toPath); + const allWatchedConfigFiles = createFileMap(toPath); - const existingWatchersForWildcards = createMap(); return { buildAllProjects, - getUpToDateStatus, getUpToDateStatusOfFile, cleanAllProjects, resetBuildContext, @@ -526,87 +469,217 @@ namespace ts { startWatching }; + function toPath(fileName: ResolvedConfigFileName): ResolvedConfigFilePath; + function toPath(fileName: string): Path; + function toPath(fileName: string) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + + function resetBuildContext(opts = defaultOptions) { + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + clearMap(allWatchedWildcardDirectories, wildCardWatches => clearMap(wildCardWatches, closeFileWatcherOf)); + clearMap(allWatchedInputFiles, inputFileWatches => clearMap(inputFileWatches, closeFileWatcher)); + clearMap(allWatchedConfigFiles, closeFileWatcher); + builderPrograms.clear(); + updateGetSourceFile(); + } + + function updateGetSourceFile() { + if (options.watch) { + if (compilerHost.getSourceFile === originalGetSourceFile) { + compilerHost.getSourceFile = (...args) => { + const result = originalGetSourceFile.call(compilerHost, ...args); + if (result && options.watch) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + } + else { + if (compilerHost.getSourceFile !== originalGetSourceFile) { + compilerHost.getSourceFile = originalGetSourceFile; + } + } + } + + function isParsedCommandLine(entry: ConfigFileCacheEntry): entry is ParsedCommandLine { + return !!(entry as ParsedCommandLine).options; + } + + function parseConfigFile(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined { + const value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + + let diagnostic: Diagnostic | undefined; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = d => diagnostic = d; + const parsed = getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop; + configFileCache.setValue(configFilePath, parsed || diagnostic!); + return parsed; + } + function reportStatus(message: DiagnosticMessage, ...args: string[]) { host.reportSolutionBuilderStatus(createCompilerDiagnostic(message, ...args)); } - function storeErrors(proj: ResolvedConfigFileName, diagnostics: ReadonlyArray) { - if (context.options.watch) { - storeErrorSummary(proj, diagnostics.filter(diagnostic => diagnostic.category === DiagnosticCategory.Error).length); - } - } - - function storeErrorSummary(proj: ResolvedConfigFileName, errorCount: number) { - if (context.options.watch) { - context.diagnostics!.setValue(proj, errorCount); - } - } - function reportWatchStatus(message: DiagnosticMessage, ...args: (string | number | undefined)[]) { if (hostWithWatch.onWatchStatusChange) { - hostWithWatch.onWatchStatusChange(createCompilerDiagnostic(message, ...args), host.getNewLine(), { preserveWatchOutput: context.options.preserveWatchOutput }); + hostWithWatch.onWatchStatusChange(createCompilerDiagnostic(message, ...args), host.getNewLine(), baseCompilerOptions); } } function startWatching() { - const graph = getGlobalDependencyGraph()!; - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - + const graph = getGlobalDependencyGraph(); for (const resolved of graph.buildQueue) { - const cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - hostWithWatch.watchFile(resolved, () => { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); + // Watch this file + watchConfigFile(resolved); + const cfg = parseConfigFile(resolved); + if (cfg) { // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - updateWatchingWildcardDirectories(existingWatchersForWildcards, createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), (dir, flags) => { - return hostWithWatch.watchDirectory(dir, () => { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & WatchDirectoryFlags.Recursive)); - }); - } + watchWildCardDirectories(resolved, cfg); // Watch input files - for (const input of cfg.fileNames) { - hostWithWatch.watchFile(input, () => { - invalidateProjectAndScheduleBuilds(resolved); - }); - } + watchInputFiles(resolved, cfg); } } } - function invalidateProjectAndScheduleBuilds(resolved: ResolvedConfigFileName) { + function watchConfigFile(resolved: ResolvedConfigFileName) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, watchFile( + hostWithWatch, + resolved, + () => { + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Full); + }, + PollingInterval.High, + WatchType.ConfigFile, + resolved + )); + } + } + + function watchWildCardDirectories(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { + if (!options.watch) return; + updateWatchingWildcardDirectories( + getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), + createMapFromTemplate(parsed.configFileSpecs!.wildcardDirectories), + (dir, flags) => { + return watchDirectory( + hostWithWatch, + dir, + fileOrDirectory => { + const fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + writeLog(`Project: ${resolved} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + + if (isOutputFile(fileOrDirectory, parsed)) { + writeLog(`${fileOrDirectory} is output file`); + return; + } + + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Partial); + }, + flags, + WatchType.WildcardDirectory, + resolved + ); + } + ); + } + + function watchInputFiles(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { + if (!options.watch) return; + mutateMap( + getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), + arrayToMap(parsed.fileNames, toPath), + { + createNewValue: (path, input) => watchFilePath( + hostWithWatch, + input, + () => invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.None), + PollingInterval.Low, + path as Path, + WatchType.SourceFile, + resolved + ), + onDeleteValue: closeFileWatcher, + } + ); + } + + function isOutputFile(fileName: string, configFile: ParsedCommandLine) { + if (configFile.options.noEmit) return false; + + // ts or tsx files are not output + if (!fileExtensionIs(fileName, Extension.Dts) && + (fileExtensionIs(fileName, Extension.Ts) || fileExtensionIs(fileName, Extension.Tsx))) { + return false; + } + + // If options have --outFile or --out, check if its that + const out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, removeFileExtension(out) + Extension.Dts))) { + return true; + } + + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + + // If --outDir, check if file is in that directory + if (configFile.options.outDir && containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + + return !forEach(configFile.fileNames, inputFile => isSameFile(fileName, inputFile)); + } + + function isSameFile(file1: string, file2: string) { + return comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === Comparison.EqualTo; + } + + function invalidateProjectAndScheduleBuilds(resolved: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel) { reportFileChangeDetected = true; - invalidateProject(resolved); + invalidateResolvedProject(resolved, reloadLevel); scheduleBuildInvalidatedProject(); } - function resetBuildContext(opts = defaultOptions) { - context = createBuildContext(opts); - } - function getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames: ReadonlyArray) { - const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) return undefined; - - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project: ParsedCommandLine | undefined): UpToDateStatus { @@ -614,13 +687,13 @@ namespace ts { return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; } - const prior = context.projectStatus.getValueOrUndefined(project.options.configFilePath!); + const prior = projectStatus.getValue(project.options.configFilePath as ResolvedConfigFilePath); if (prior !== undefined) { return prior; } const actual = getUpToDateStatusWorker(project); - context.projectStatus.setValue(project.options.configFilePath!, actual); + projectStatus.setValue(project.options.configFilePath as ResolvedConfigFilePath, actual); return actual; } @@ -691,7 +764,7 @@ namespace ts { // had its file touched but not had its contents changed - this allows us // to skip a downstream typecheck if (isDeclarationFile(output)) { - const unchangedTime = context.unchangedOutputs.getValueOrUndefined(output); + const unchangedTime = unchangedOutputs.getValue(output); if (unchangedTime !== undefined) { newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } @@ -706,10 +779,16 @@ namespace ts { let usesPrepend = false; let upstreamChangedProject: string | undefined; if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath as ResolvedConfigFileName, { type: UpToDateStatusType.ComputingUpstream }); for (const ref of project.projectReferences) { usesPrepend = usesPrepend || !!(ref.prepend); - const resolvedRef = resolveProjectReferencePath(host, ref); - const refStatus = getUpToDateStatus(configFileCache.parseConfigFile(resolvedRef)); + const resolvedRef = resolveProjectReferencePath(ref); + const refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } // An upstream project is blocked if (refStatus.type === UpToDateStatusType.Unbuildable) { @@ -786,24 +865,51 @@ namespace ts { }; } - function invalidateProject(configFileName: string) { - const resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist + function invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } - // TODO: do those things - return; + function invalidateResolvedProject(resolved: ResolvedConfigFileName, reloadLevel?: ConfigFileProgramReloadLevel) { + if (reloadLevel === ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); - configFileCache.removeKey(resolved); - context.projectStatus.removeKey(resolved); - if (context.options.watch) { - context.diagnostics!.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + + /** + * return true if new addition + */ + function addProjToQueue(proj: ResolvedConfigFileName, reloadLevel?: ConfigFileProgramReloadLevel) { + const value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); } + else if (value < (reloadLevel || ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); + } + } - context.invalidateProject(resolved, getGlobalDependencyGraph()); + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + const project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + const reloadLevel = projectPendingBuild.getValue(project)!; + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project, reloadLevel }; + } + } + + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); } function scheduleBuildInvalidatedProject() { @@ -820,254 +926,326 @@ namespace ts { timerToBuildInvalidatedProject = undefined; if (reportFileChangeDetected) { reportFileChangeDetected = false; + projectErrorsReported.clear(); reportWatchStatus(Diagnostics.File_change_detected_Starting_incremental_compilation); } - const buildProject = context.getNextInvalidatedProject(); - buildSomeProjects(p => p === buildProject); - if (context.hasPendingInvalidatedProjects()) { - if (!timerToBuildInvalidatedProject) { - scheduleBuildInvalidatedProject(); + const buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); } - } - else { - reportErrorSummary(); } } function reportErrorSummary() { - if (context.options.watch) { - let errorCount = 0; - context.diagnostics!.getKeys().forEach(resolved => errorCount += context.diagnostics!.getValue(resolved)); - reportWatchStatus(errorCount === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount); - } - } - - function buildSomeProjects(predicate: (projName: ResolvedConfigFileName) => boolean) { - const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(rootNames); - if (resolvedNames === undefined) return; - - const graph = createDependencyGraph(resolvedNames)!; - for (const next of graph.buildQueue) { - if (!predicate(next)) continue; - - const resolved = resolveProjectName(next); - if (!resolved) continue; // ?? - const proj = configFileCache.parseConfigFile(resolved); - if (!proj) continue; // ? - - const status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + if (options.watch || (host as SolutionBuilderHost).reportErrorSummary) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(project => { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || emptyArray); + } + }); + let totalErrors = 0; + diagnostics.forEach(singleProjectErrors => totalErrors += getErrorCountForSummary(singleProjectErrors)); + if (options.watch) { + reportWatchStatus(getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors); + } + else { + (host as SolutionBuilderHost).reportErrorSummary!(totalErrors); } - - buildSingleProject(next); } } - function createDependencyGraph(roots: ResolvedConfigFileName[]): DependencyGraph | undefined { - const temporaryMarks: { [path: string]: true } = {}; - const permanentMarks: { [path: string]: true } = {}; + function buildSingleInvalidatedProject(resolved: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel) { + const proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + + if (reloadLevel === ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ConfigFileProgramReloadLevel.Partial) { + // Update file names + const result = getFileNamesFromConfigSpecs(proj.configFileSpecs!, getDirectoryPath(resolved), proj.options, parseConfigFileHost); + updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs!, proj.errors, canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + + const status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes) { + // Fake that files have been built by updating output file stamps + updateOutputTimestamps(proj); + return; + } + + const buildResult = buildSingleProject(resolved); + if (buildResult & BuildResultFlags.AnyErrors) return; + + const { referencingProjectsMap, buildQueue } = getGlobalDependencyGraph(); + const referencingProjects = referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; + + // Always use build order to queue projects + for (let index = buildQueue.indexOf(resolved) + 1; index < buildQueue.length; index++) { + const project = buildQueue[index]; + const prepend = referencingProjects.getValue(project); + if (prepend !== undefined) { + // If the project is referenced with prepend, always build downstream projects, + // If declaration output is changed, build the project + // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps + const status = projectStatus.getValue(project); + if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { + if (status && (status.type === UpToDateStatusType.UpToDate || status.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) { + projectStatus.setValue(project, { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: status.oldestOutputFileName, + newerProjectName: resolved + }); + } + } + else if (status && status.type === UpToDateStatusType.UpToDate) { + status.type = UpToDateStatusType.UpToDateWithUpstreamTypes; + } + addProjToQueue(project); + } + } + } + + function createDependencyGraph(roots: ResolvedConfigFileName[]): DependencyGraph { + const temporaryMarks = createFileMap(toPath); + const permanentMarks = createFileMap(toPath); const circularityReportStack: string[] = []; const buildOrder: ResolvedConfigFileName[] = []; - const graph = createDependencyMapper(); - - let hadError = false; - + const referencingProjectsMap = createFileMap>(toPath); for (const root of roots) { visit(root); } - if (hadError) { - return undefined; - } - return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap }; - function visit(projPath: ResolvedConfigFileName, inCircularContext = false) { + function visit(projPath: ResolvedConfigFileName, inCircularContext?: boolean) { // Already visited - if (permanentMarks[projPath]) return; + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - // TODO(shkamat): Account for this error + // TODO:: Do we report this as error? reportStatus(Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; } - } - - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - const parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + const parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (const ref of parsed.projectReferences) { const resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + const referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, () => createFileMap(toPath)); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj: ResolvedConfigFileName): BuildResultFlags { - if (context.options.dry) { + if (options.dry) { reportStatus(Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) reportStatus(Diagnostics.Building_project_0, proj); + if (options.verbose) reportStatus(Diagnostics.Building_project_0, proj); let resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - const configFile = configFileCache.parseConfigFile(proj); + const configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - storeErrorSummary(proj, 1); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } - if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } - const programOptions: CreateProgramOptions = { - projectReferences: configFile.projectReferences, - host, - rootNames: configFile.fileNames, - options: configFile.options - }; - const program = createProgram(programOptions); + // TODO: handle resolve module name to cache result in project reference redirect + projectCompilerOptions = configFile.options; + const program = host.createProgram( + configFile.fileNames, + configFile.options, + compilerHost, + builderPrograms.getValue(proj), + configFile.errors, + configFile.projectReferences + ); + projectCompilerOptions = baseCompilerOptions; // Don't emit anything in the presence of syntactic errors or options diagnostics const syntaxDiagnostics = [ - ...program.getOptionsDiagnostics(), ...program.getConfigFileParsingDiagnostics(), + ...program.getOptionsDiagnostics(), + ...program.getGlobalDiagnostics(), ...program.getSyntacticDiagnostics()]; if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (const diag of syntaxDiagnostics) { - host.reportDiagnostic(diag); - } - storeErrors(proj, syntaxDiagnostics); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; - } - - // Don't emit .d.ts if there are decl file errors - if (getEmitDeclarations(program.getCompilerOptions())) { - const declDiagnostics = program.getDeclarationDiagnostics(); - if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (const diag of declDiagnostics) { - host.reportDiagnostic(diag); - } - storeErrors(proj, declDiagnostics); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; - } + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Same as above but now for semantic diagnostics const semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (const diag of semanticDiagnostics) { - host.reportDiagnostic(diag); - } - storeErrors(proj, semanticDiagnostics); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } + // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly + program.backupState(); let newestDeclarationFileContentChangedTime = minimumDate; let anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, (fileName, content, writeBom, onError) => { - let priorChangeTime: Date | undefined; + let declDiagnostics: Diagnostic[] | undefined; + const reportDeclarationDiagnostics = (d: Diagnostic) => (declDiagnostics || (declDiagnostics = [])).push(d); + const outputFiles: OutputFile[] = []; + emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, (name, text, writeByteOrderMark) => outputFiles.push({ name, text, writeByteOrderMark })); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + program.restoreState(); + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } - if (!anyDtsChanged && isDeclarationFile(fileName) && host.fileExists(fileName)) { - if (host.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = host.getModifiedTime(fileName); + // Actual Emit + const emitterDiagnostics = createDiagnosticCollection(); + const emittedOutputs = createFileMap(toPath as ToPath); + outputFiles.forEach(({ name, text, writeByteOrderMark }) => { + let priorChangeTime: Date | undefined; + if (!anyDtsChanged && isDeclarationFile(name)) { + // Check for unchanged .d.ts files + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - host.writeFile(fileName, content, writeBom, onError, emptyArray); + emittedOutputs.setValue(name, true); + writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(name, priorChangeTime); } }); + const emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } + + // Update time stamps for rest of the outputs + newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(configFile, newestDeclarationFileContentChangedTime, Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); + const status: UpToDateStatus = { type: UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime, + oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile) }; - context.projectStatus.setValue(proj, status); + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + afterProgramCreate(proj, program); return resultFlags; + + function buildErrors(diagnostics: ReadonlyArray, errorFlags: BuildResultFlags, errorType: string) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: `${errorType} errors` }); + afterProgramCreate(proj, program); + return resultFlags; + } + } + + function afterProgramCreate(proj: ResolvedConfigFileName, program: T) { + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + if (options.watch) { + program.releaseProgram(); + builderPrograms.setValue(proj, program); + } } function updateOutputTimestamps(proj: ParsedCommandLine) { - if (context.options.dry) { + if (options.dry) { return reportStatus(Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath!); } - - if (context.options.verbose) { - reportStatus(Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath!); - } - - const now = new Date(); - const outputs = getAllProjectOutputs(proj); - let priorNewestUpdateTime = minimumDate; - for (const file of outputs) { - if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || missingFileModifiedTime); - } - - host.setModifiedTime(file, now); - } - - context.projectStatus.setValue(proj.options.configFilePath!, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); + const priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, Diagnostics.Updating_output_timestamps_of_project_0); + projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); } - function getFilesToClean(configFileNames: ReadonlyArray): string[] | undefined { - const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) return undefined; + function updateOutputTimestampsWorker(proj: ParsedCommandLine, priorNewestUpdateTime: Date, verboseMessage: DiagnosticMessage, skipOutputs?: FileMap) { + const outputs = getAllProjectOutputs(proj); + if (!skipOutputs || outputs.length !== skipOutputs.getSize()) { + if (options.verbose) { + reportStatus(verboseMessage, proj.options.configFilePath!); + } + const now = host.now ? host.now() : new Date(); + for (const file of outputs) { + if (skipOutputs && skipOutputs.hasKey(file)) { + continue; + } + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || missingFileModifiedTime); + } + + host.setModifiedTime(file, now); + if (proj.options.listEmittedFiles) { + writeFileName(`TSFILE: ${file}`); + } + } + } + + return priorNewestUpdateTime; + } + + function getFilesToClean(): string[] { // Get the same graph for cleaning we'd use for building - const graph = createDependencyGraph(resolvedNames); - if (graph === undefined) return undefined; - + const graph = getGlobalDependencyGraph(); const filesToDelete: string[] = []; for (const proj of graph.buildQueue) { - const parsed = configFileCache.parseConfigFile(proj); + const parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } const outputs = getAllProjectOutputs(parsed); @@ -1080,28 +1258,9 @@ namespace ts { return filesToDelete; } - function getAllProjectsInScope(): ReadonlyArray | undefined { - const resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) return undefined; - const graph = createDependencyGraph(resolvedNames); - if (graph === undefined) return undefined; - return graph.buildQueue; - } - function cleanAllProjects() { - const resolvedNames: ReadonlyArray | undefined = getAllProjectsInScope(); - if (resolvedNames === undefined) { - reportStatus(Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - - const filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - reportStatus(Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - - if (context.options.dry) { + const filesToDelete = getFilesToClean(); + if (options.dry) { reportStatus(Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(f => `\r\n * ${f}`).join("")); return ExitStatus.Success; } @@ -1113,55 +1272,47 @@ namespace ts { return ExitStatus.Success; } - function resolveProjectName(name: string): ResolvedConfigFileName | undefined { - const fullPath = resolvePath(host.getCurrentDirectory(), name); - if (host.fileExists(fullPath)) { - return fullPath as ResolvedConfigFileName; - } - const fullPathWithTsconfig = combinePaths(fullPath, "tsconfig.json"); - if (host.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig as ResolvedConfigFileName; - } - // TODO(shkamat): right now this is accounted as 1 error in config file, but we need to do better - host.reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_0_not_found, relName(fullPath))); - return undefined; + function resolveProjectName(name: string): ResolvedConfigFileName { + return resolveConfigFileProjectName(resolvePath(host.getCurrentDirectory(), name)); } - function resolveProjectNames(configFileNames: ReadonlyArray): ResolvedConfigFileName[] | undefined { - const resolvedNames: ResolvedConfigFileName[] = []; - for (const name of configFileNames) { - const resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + function resolveProjectNames(configFileNames: ReadonlyArray): ResolvedConfigFileName[] { + return configFileNames.map(resolveProjectName); } function buildAllProjects(): ExitStatus { - if (context.options.watch) { reportWatchStatus(Diagnostics.Starting_compilation_in_watch_mode); } + if (options.watch) { reportWatchStatus(Diagnostics.Starting_compilation_in_watch_mode); } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + const savedReadFileWithCache = readFileWithCache; + const savedGetSourceFile = compilerHost.getSourceFile; + + const { originalReadFile, originalFileExists, originalDirectoryExists, + originalCreateDirectory, originalWriteFile, getSourceFileWithCache, + readFileWithCache: newReadFileWithCache + } = changeCompilerHostLikeToUseCache(host, toPath, (...args) => savedGetSourceFile.call(compilerHost, ...args)); + readFileWithCache = newReadFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache!; + const graph = getGlobalDependencyGraph(); - if (graph === undefined) { - reportErrorSummary(); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - - const queue = graph.buildQueue; reportBuildQueue(graph); - let anyFailed = false; - for (const next of queue) { - const proj = configFileCache.parseConfigFile(next); + for (const next of graph.buildQueue) { + const proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + + // report errors early when using continue or break statements + const errors = proj.errors; const status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); const projName = proj.options.configFilePath!; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact @@ -1170,18 +1321,21 @@ namespace ts { continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } @@ -1190,37 +1344,62 @@ namespace ts { anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + compilerHost.getSourceFile = savedGetSourceFile; + readFileWithCache = savedReadFileWithCache; return anyFailed ? ExitStatus.DiagnosticsPresent_OutputsSkipped : ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj: ResolvedConfigFileName) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj) as Diagnostic]); + } + + function reportAndStoreErrors(proj: ResolvedConfigFileName, errors: ReadonlyArray) { + reportErrors(errors); + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + + function reportErrors(errors: ReadonlyArray) { + errors.forEach(err => host.reportDiagnostic(err)); + } + /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph: DependencyGraph) { - if (!context.options.verbose) return; - - const names: string[] = []; - for (const name of graph.buildQueue) { - names.push(name); + if (options.verbose) { + reportStatus(Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(s => "\r\n * " + relName(s)).join("")); } - if (context.options.verbose) reportStatus(Diagnostics.Projects_in_this_build_Colon_0, names.map(s => "\r\n * " + relName(s)).join("")); } function relName(path: string): string { - return convertToRelativePath(path, host.getCurrentDirectory(), f => host.getCanonicalFileName(f)); + return convertToRelativePath(path, host.getCurrentDirectory(), f => compilerHost.getCanonicalFileName(f)); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName: string, status: UpToDateStatus) { - if (!context.options.verbose) return; + if (!options.verbose) return; return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } + export function resolveConfigFileProjectName(project: string): ResolvedConfigFileName { + if (fileExtensionIs(project, Extension.Json)) { + return project as ResolvedConfigFileName; + } + + return combinePaths(project, "tsconfig.json") as ResolvedConfigFileName; + } + export function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -1232,6 +1411,20 @@ namespace ts { } } + function getFirstProjectOutput(project: ParsedCommandLine): string { + if (project.options.outFile || project.options.out) { + return first(getOutFileOutputs(project)); + } + + for (const inputFile of project.fileNames) { + const outputs = getOutputFileNames(inputFile, project); + if (outputs.length) { + return first(outputs); + } + } + return Debug.fail(`project ${project.options.configFilePath} expected to have at least one output`); + } + export function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T) { switch (status.type) { case UpToDateStatusType.OutOfDateWithSelf: @@ -1274,6 +1467,8 @@ namespace ts { status.reason); case UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: assertType(status); diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index 20b97c1b778..c41f47f3c4a 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -9,6 +9,7 @@ "files": [ "core.ts", "performance.ts", + "semver.ts", "types.ts", "sys.ts", @@ -24,7 +25,7 @@ "checker.ts", "factory.ts", "visitor.ts", - "sourcemapDecoder.ts", + "sourcemap.ts", "transformers/utilities.ts", "transformers/destructuring.ts", "transformers/ts.ts", @@ -41,8 +42,6 @@ "transformers/declarations/diagnostics.ts", "transformers/declarations.ts", "transformer.ts", - "sourcemap.ts", - "comments.ts", "emitter.ts", "watchUtilities.ts", "program.ts", @@ -51,6 +50,7 @@ "resolutionCache.ts", "moduleSpecifiers.ts", "watch.ts", - "tsbuild.ts" + "tsbuild.ts", + "inspectValue.ts", ] } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 279fef73d5e..d213e862299 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -24,7 +24,85 @@ namespace ts { | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral - | SyntaxKind.Unknown; + | SyntaxKind.Unknown + | KeywordSyntaxKind; + + export type KeywordSyntaxKind = + | SyntaxKind.AbstractKeyword + | SyntaxKind.AnyKeyword + | SyntaxKind.AsKeyword + | SyntaxKind.BigIntKeyword + | SyntaxKind.BooleanKeyword + | SyntaxKind.BreakKeyword + | SyntaxKind.CaseKeyword + | SyntaxKind.CatchKeyword + | SyntaxKind.ClassKeyword + | SyntaxKind.ContinueKeyword + | SyntaxKind.ConstKeyword + | SyntaxKind.ConstructorKeyword + | SyntaxKind.DebuggerKeyword + | SyntaxKind.DeclareKeyword + | SyntaxKind.DefaultKeyword + | SyntaxKind.DeleteKeyword + | SyntaxKind.DoKeyword + | SyntaxKind.ElseKeyword + | SyntaxKind.EnumKeyword + | SyntaxKind.ExportKeyword + | SyntaxKind.ExtendsKeyword + | SyntaxKind.FalseKeyword + | SyntaxKind.FinallyKeyword + | SyntaxKind.ForKeyword + | SyntaxKind.FromKeyword + | SyntaxKind.FunctionKeyword + | SyntaxKind.GetKeyword + | SyntaxKind.IfKeyword + | SyntaxKind.ImplementsKeyword + | SyntaxKind.ImportKeyword + | SyntaxKind.InKeyword + | SyntaxKind.InferKeyword + | SyntaxKind.InstanceOfKeyword + | SyntaxKind.InterfaceKeyword + | SyntaxKind.IsKeyword + | SyntaxKind.KeyOfKeyword + | SyntaxKind.LetKeyword + | SyntaxKind.ModuleKeyword + | SyntaxKind.NamespaceKeyword + | SyntaxKind.NeverKeyword + | SyntaxKind.NewKeyword + | SyntaxKind.NullKeyword + | SyntaxKind.NumberKeyword + | SyntaxKind.ObjectKeyword + | SyntaxKind.PackageKeyword + | SyntaxKind.PrivateKeyword + | SyntaxKind.ProtectedKeyword + | SyntaxKind.PublicKeyword + | SyntaxKind.ReadonlyKeyword + | SyntaxKind.RequireKeyword + | SyntaxKind.GlobalKeyword + | SyntaxKind.ReturnKeyword + | SyntaxKind.SetKeyword + | SyntaxKind.StaticKeyword + | SyntaxKind.StringKeyword + | SyntaxKind.SuperKeyword + | SyntaxKind.SwitchKeyword + | SyntaxKind.SymbolKeyword + | SyntaxKind.ThisKeyword + | SyntaxKind.ThrowKeyword + | SyntaxKind.TrueKeyword + | SyntaxKind.TryKeyword + | SyntaxKind.TypeKeyword + | SyntaxKind.TypeOfKeyword + | SyntaxKind.UndefinedKeyword + | SyntaxKind.UniqueKeyword + | SyntaxKind.UnknownKeyword + | SyntaxKind.VarKeyword + | SyntaxKind.VoidKeyword + | SyntaxKind.WhileKeyword + | SyntaxKind.WithKeyword + | SyntaxKind.YieldKeyword + | SyntaxKind.AsyncKeyword + | SyntaxKind.AwaitKeyword + | SyntaxKind.OfKeyword; export type JsxTokenSyntaxKind = | SyntaxKind.LessThanSlashToken @@ -51,6 +129,7 @@ namespace ts { ConflictMarkerTrivia, // Literals NumericLiteral, + BigIntLiteral, StringLiteral, JsxText, JsxTextAllWhiteSpaces, @@ -194,6 +273,7 @@ namespace ts { UnknownKeyword, FromKeyword, GlobalKeyword, + BigIntKeyword, OfKeyword, // LastKeyword and LastToken and LastContextualKeyword // Parse tree nodes @@ -639,7 +719,6 @@ namespace ts { export type AsteriskToken = Token; export type EqualsGreaterThanToken = Token; export type EndOfFileToken = Token & JSDocContainer; - export type AtToken = Token; export type ReadonlyToken = Token; export type AwaitKeywordToken = Token; export type PlusToken = Token; @@ -713,7 +792,7 @@ namespace ts { export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; - export type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; + export type DeclarationName = Identifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | BindingPattern; export interface Declaration extends Node { _declarationBrand: any; @@ -1032,6 +1111,7 @@ namespace ts { kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword + | SyntaxKind.BigIntKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword @@ -1582,7 +1662,7 @@ namespace ts { OctalSpecifier = 1 << 8, // e.g. `0o777` ContainsSeparator = 1 << 9, // e.g. `0b1100_0101` BinaryOrOctalSpecifier = BinarySpecifier | OctalSpecifier, - NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinarySpecifier | OctalSpecifier | ContainsSeparator + NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinaryOrOctalSpecifier | ContainsSeparator } export interface NumericLiteral extends LiteralExpression { @@ -1591,6 +1671,10 @@ namespace ts { numericLiteralFlags: TokenFlags; } + export interface BigIntLiteral extends LiteralExpression { + kind: SyntaxKind.BigIntLiteral; + } + export interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; parent: TemplateExpression; @@ -1661,6 +1745,9 @@ namespace ts { export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; + /* @internal */ + export type AccessExpression = PropertyAccessExpression | ElementAccessExpression; + export interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; @@ -1697,6 +1784,9 @@ namespace ts { arguments: NodeArray; } + /** @internal */ + export type BindableObjectDefinePropertyCall = CallExpression & { arguments: { 0: EntityNameExpression, 1: StringLiteralLike | NumericLiteral, 2: ObjectLiteralExpression } }; + // see: https://tc39.github.io/ecma262/#prod-SuperCall export interface SuperCall extends CallExpression { expression: SuperExpression; @@ -1708,7 +1798,7 @@ namespace ts { export interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } @@ -2333,7 +2423,6 @@ namespace ts { export interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; - atToken: AtToken; tagName: Identifier; comment?: string; } @@ -2367,7 +2456,7 @@ namespace ts { export interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; - constraint: TypeNode | undefined; + constraint: JSDocTypeExpression | undefined; typeParameters: NodeArray; } @@ -2528,6 +2617,8 @@ namespace ts { export interface SourceFileLike { readonly text: string; lineMap?: ReadonlyArray; + /* @internal */ + getPositionOfLineAndCharacter?(line: number, character: number, allowEdits?: true): number; } @@ -2551,7 +2642,18 @@ namespace ts { fileName: string; /* @internal */ path: Path; text: string; + /** Resolved path can be different from path property, + * when file is included through project reference is mapped to its output instead of source + * in that case resolvedPath = path to output file + * path = input file's path + */ /* @internal */ resolvedPath: Path; + /** Original file name that can be different from fileName, + * when file is included through project reference is mapped to its output instead of source + * in that case originalFileName = name of input file + * fileName = output file's name + */ + /* @internal */ originalFileName: string; /** * If two source files are for the same version of the same package, one will redirect to the other. @@ -2593,6 +2695,8 @@ namespace ts { /* @internal */ externalModuleIndicator?: Node; // The first node that causes this file to be a CommonJS module /* @internal */ commonJsModuleIndicator?: Node; + // JS identifier-declarations that are intended to merge with globals + /* @internal */ jsGlobalAugmentations?: SymbolTable; /* @internal */ identifiers: Map; // Map from a string to an interned string /* @internal */ nodeCount: number; @@ -2621,7 +2725,7 @@ namespace ts { // It is used to resolve module names in the checker. // Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead /* @internal */ resolvedModules?: Map; - /* @internal */ resolvedTypeReferenceDirectiveNames: Map; + /* @internal */ resolvedTypeReferenceDirectiveNames: Map; /* @internal */ imports: ReadonlyArray; /** * When a file's references are redirected due to project reference directives, @@ -2700,7 +2804,7 @@ namespace ts { export interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; /** * Gets a value indicating whether the specified path exists and is a file. @@ -2709,6 +2813,7 @@ namespace ts { fileExists(path: string): boolean; readFile(path: string): string | undefined; + trace?(s: string): void; } /** @@ -2722,7 +2827,7 @@ namespace ts { fileName: string, data: string, writeByteOrderMark: boolean, - onError: ((message: string) => void) | undefined, + onError?: (message: string) => void, sourceFiles?: ReadonlyArray, ) => void; @@ -2796,7 +2901,7 @@ namespace ts { /* @internal */ getTypeCount(): number; /* @internal */ getFileProcessingDiagnostics(): DiagnosticCollection; - /* @internal */ getResolvedTypeReferenceDirectives(): Map; + /* @internal */ getResolvedTypeReferenceDirectives(): Map; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; @@ -2815,7 +2920,12 @@ namespace ts { /* @internal */ getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): ReadonlyArray | undefined; + /*@internal*/ getProjectReferenceRedirect(fileName: string): string | undefined; + /*@internal*/ getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined; + /*@internal*/ forEachResolvedProjectReference(cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined): T | undefined; + /*@internal*/ getResolvedProjectReferenceByPath(projectReferencePath: Path): ResolvedProjectReference | undefined; } /* @internal */ @@ -2824,6 +2934,7 @@ namespace ts { export interface ResolvedProjectReference { commandLine: ParsedCommandLine; sourceFile: SourceFile; + references?: ReadonlyArray; } /* @internal */ @@ -2857,16 +2968,10 @@ namespace ts { sourceIndex: number; } - export interface SourceMapData { - sourceMapFilePath: string; // Where the sourcemap file is written - jsSourceMappingURL: string; // source map URL written in the .js file - sourceMapFile: string; // Source map's file field - .js file name - sourceMapSourceRoot: string; // Source map's sourceRoot field - location where the sources will be present if not "" - sourceMapSources: string[]; // Source map's sources field - list of sources that can be indexed in this source map - sourceMapSourcesContent?: (string | null)[]; // Source map's sourcesContent field - list of the sources' text to be embedded in the source map - inputSourceFileNames: string[]; // Input source file (which one can use on program to get the file), 1:1 mapping with the sourceMapSources list - sourceMapNames?: string[]; // Source map's names field - list of names that can be indexed in this source map - sourceMapMappings: string; // Source map's mapping field - encoded source map spans + /* @internal */ + export interface SourceMapEmitResult { + inputSourceFileNames: ReadonlyArray; // Input source file (which one can use on program to get the file), 1:1 mapping with the sourceMap.sources list + sourceMap: RawSourceMap; } /** Return code used by getEmitOutput function to indicate status of the function */ @@ -2888,17 +2993,17 @@ namespace ts { /** Contains declaration emit diagnostics */ diagnostics: ReadonlyArray; emittedFiles?: string[]; // Array of files the compiler wrote to disk - /* @internal */ sourceMaps?: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps + /* @internal */ sourceMaps?: SourceMapEmitResult[]; // Array of sourceMapData if compiler emitted sourcemaps /* @internal */ exportedModulesFromDeclarationEmit?: ExportedModulesFromDeclarationEmit; } /* @internal */ - export interface TypeCheckerHost { + export interface TypeCheckerHost extends ModuleSpecifierResolutionHost { getCompilerOptions(): CompilerOptions; getSourceFiles(): ReadonlyArray; getSourceFile(fileName: string): SourceFile | undefined; - getResolvedTypeReferenceDirectives(): ReadonlyMap; + getResolvedTypeReferenceDirectives(): ReadonlyMap; readonly redirectTargetsMap: RedirectTargetsMap; } @@ -2932,8 +3037,10 @@ namespace ts { /* @internal */ typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker): TypeNode | undefined; // tslint:disable-line unified-signatures /** Note that the resulting nodes cannot be checked. */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration & {typeArguments?: NodeArray} | undefined; + /* @internal */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker): SignatureDeclaration & {typeArguments?: NodeArray} | undefined; // tslint:disable-line unified-signatures /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; + /* @internal */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker): IndexSignatureDeclaration | undefined; // tslint:disable-line unified-signatures /** Note that the resulting nodes cannot be checked. */ symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined; /** Note that the resulting nodes cannot be checked. */ @@ -2979,7 +3086,7 @@ namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; + getRootSymbols(symbol: Symbol): ReadonlyArray; getContextualType(node: Expression): Type | undefined; /* @internal */ getContextualTypeForObjectLiteralElement(element: ObjectLiteralElementLike): Type | undefined; /* @internal */ getContextualTypeForArgumentAtIndex(call: CallLikeExpression, argIndex: number): Type | undefined; @@ -3003,7 +3110,7 @@ namespace ts { getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; /** Exclude accesses to private properties or methods with a `this` parameter that `type` doesn't satisfy. */ - /* @internal */ isValidPropertyAccessForCompletions(node: PropertyAccessExpression | ImportTypeNode, type: Type, property: Symbol): boolean; + /* @internal */ isValidPropertyAccessForCompletions(node: PropertyAccessExpression | ImportTypeNode | QualifiedName, type: Type, property: Symbol): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; /** Follow a *single* alias to get the immediately aliased symbol. */ @@ -3011,8 +3118,6 @@ namespace ts { getExportsOfModule(moduleSymbol: Symbol): Symbol[]; /** Unlike `getExportsOfModule`, this includes properties of an `export =` value. */ /* @internal */ getExportsAndPropertiesOfModule(moduleSymbol: Symbol): Symbol[]; - - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; @@ -3034,8 +3139,8 @@ namespace ts { /* @internal */ getStringType(): Type; /* @internal */ getNumberType(): Type; /* @internal */ getBooleanType(): Type; - /* @internal */ getFalseType(): Type; - /* @internal */ getTrueType(): Type; + /* @internal */ getFalseType(fresh?: boolean): Type; + /* @internal */ getTrueType(fresh?: boolean): Type; /* @internal */ getVoidType(): Type; /* @internal */ getUndefinedType(): Type; /* @internal */ getNullType(): Type; @@ -3043,6 +3148,7 @@ namespace ts { /* @internal */ getNeverType(): Type; /* @internal */ getUnionType(types: Type[], subtypeReduction?: UnionReduction): Type; /* @internal */ createArrayType(elementType: Type): Type; + /* @internal */ getElementTypeOfArrayType(arrayType: Type): Type | undefined; /* @internal */ createPromiseType(type: Type): Type; /* @internal */ createAnonymousType(symbol: Symbol, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): Type; @@ -3075,11 +3181,13 @@ namespace ts { /* @internal */ getTypeCount(): number; /* @internal */ isArrayLikeType(type: Type): boolean; + /* @internal */ getObjectFlags(type: Type): ObjectFlags; + /** * True if `contextualType` should not be considered for completions because * e.g. it specifies `kind: "a"` and obj has `kind: "b"`. */ - /* @internal */ isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression): boolean; + /* @internal */ isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes): boolean; /** * For a union, will include a property if it's defined in *any* of the member types. * So for `{ a } | { b }`, this will include both `a` and `b`. @@ -3161,7 +3269,11 @@ namespace ts { AllowUniqueESSymbolType = 1 << 20, AllowEmptyIndexInfoType = 1 << 21, - IgnoreErrors = AllowThisInObjectLiteral | AllowQualifedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple | AllowEmptyIndexInfoType, + // Errors (cont.) + AllowNodeModulesRelativePaths = 1 << 26, + /* @internal */ DoNotIncludeSymbolChain = 1 << 27, // Skip looking up and printing an accessible symbol chain + + IgnoreErrors = AllowThisInObjectLiteral | AllowQualifedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple | AllowEmptyIndexInfoType | AllowNodeModulesRelativePaths, // State InObjectTypeLiteral = 1 << 22, @@ -3230,6 +3342,9 @@ namespace ts { // Prefer aliases which are not directly visible UseAliasDefinedOutsideCurrentScope = 0x00000008, + + // Skip building an accessible symbol chain + /* @internal */ DoNotIncludeSymbolChain = 0x00000010, } /* @internal */ @@ -3356,6 +3471,7 @@ namespace ts { // of a type, such as the global `Promise` type in lib.d.ts). VoidNullableOrNeverType, // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type. NumberLikeType, // The TypeReferenceNode resolves to a Number-like type. + BigIntLikeType, // The TypeReferenceNode resolves to a BigInt-like type. StringLikeType, // The TypeReferenceNode resolves to a String-like type. BooleanType, // The TypeReferenceNode resolves to a Boolean-like type. ArrayLikeType, // The TypeReferenceNode resolves to an Array-like type. @@ -3383,12 +3499,12 @@ namespace ts { isImplementationOfOverload(node: FunctionLike): boolean | undefined; isRequiredInitializedParameter(node: ParameterDeclaration): boolean; isOptionalUninitializedParameterProperty(node: ParameterDeclaration): boolean; - isJSContainerFunctionDeclaration(node: FunctionDeclaration): boolean; + isExpandoFunctionDeclaration(node: FunctionDeclaration): boolean; getPropertiesOfContainerFunction(node: Declaration): Symbol[]; createTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration | PropertyAccessExpression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker, addUndefined?: boolean): TypeNode | undefined; createReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined; createTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined; - createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): Expression; + createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, tracker: SymbolTracker): Expression; isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags | undefined, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; // Returns the constant value this property access resolves to, or 'undefined' for a non-constant @@ -3405,6 +3521,7 @@ namespace ts { getJsxFactoryEntity(location?: Node): EntityName | undefined; getAllAccessorDeclarations(declaration: AccessorDeclaration): AllAccessorDeclarations; getSymbolOfExternalModuleSpecifier(node: StringLiteralLike): Symbol | undefined; + isBindingCapturedByNode(node: Node, decl: VariableDeclaration | BindingElement): boolean; } export const enum SymbolFlags { @@ -3435,7 +3552,7 @@ namespace ts { ExportStar = 1 << 23, // Export * declaration Optional = 1 << 24, // Optional property Transient = 1 << 25, // Transient symbol (created during type check) - JSContainer = 1 << 26, // Contains Javascript special declarations + Assignment = 1 << 26, // Assignment treated as declaration (eg `this.prop = 1`) ModuleExports = 1 << 27, // Symbol for CommonJS `module` of `module.exports` /* @internal */ @@ -3444,8 +3561,8 @@ namespace ts { Enum = RegularEnum | ConstEnum, Variable = FunctionScopedVariable | BlockScopedVariable, - Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor | JSContainer, - Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias | JSContainer, + Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor | Assignment, + Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias | Assignment, Namespace = ValueModule | NamespaceModule | Enum, Module = ValueModule | NamespaceModule, Accessor = GetAccessor | SetAccessor, @@ -3466,7 +3583,7 @@ namespace ts { InterfaceExcludes = Type & ~(Interface | Class), RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums - ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule | JSContainer), + ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule | Assignment), NamespaceModuleExcludes = 0, MethodExcludes = Value & ~Method, GetAccessorExcludes = Value & ~SetAccessor, @@ -3520,6 +3637,7 @@ namespace ts { type?: Type; // Type of value symbol uniqueESSymbolType?: Type; // UniqueESSymbol type for a symbol declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter + resolvedJSDocType?: Type; // Resolved type of a JSDoc type reference typeParameters?: TypeParameter[]; // Type parameters of type alias (undefined if non-generic) outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type inferredClassType?: Type; // Type of an inferred ES5 class @@ -3542,6 +3660,9 @@ namespace ts { originatingImport?: ImportDeclaration | ImportCall; // Import declaration which produced the symbol, present if the symbol is marked as uncallable but had call signatures in `resolveESModuleSymbol` lateSymbol?: Symbol; // Late-bound symbol for a computed property specifierCache?: Map; // For symbols corresponding to external modules, a cache of incoming path -> module specifier name mappings + extendedContainers?: Symbol[]; // Containers (other than the parent) which this symbol is aliased in + extendedContainersByFile?: Map; // Containers (other than the parent) which this symbol is aliased in + variances?: Variance[]; // Alias symbol type argument variance cache } /* @internal */ @@ -3558,15 +3679,17 @@ namespace ts { Readonly = 1 << 3, // Readonly transient symbol Partial = 1 << 4, // Synthetic property present in some but not all constituents HasNonUniformType = 1 << 5, // Synthetic property with non-uniform type in constituents - ContainsPublic = 1 << 6, // Synthetic property with public constituent(s) - ContainsProtected = 1 << 7, // Synthetic property with protected constituent(s) - ContainsPrivate = 1 << 8, // Synthetic property with private constituent(s) - ContainsStatic = 1 << 9, // Synthetic property with static constituent(s) - Late = 1 << 10, // Late-bound symbol for a computed property with a dynamic name - ReverseMapped = 1 << 11, // Property of reverse-inferred homomorphic mapped type - OptionalParameter = 1 << 12, // Optional parameter - RestParameter = 1 << 13, // Rest parameter - Synthetic = SyntheticProperty | SyntheticMethod + HasLiteralType = 1 << 6, // Synthetic property with at least one literal type in constituents + ContainsPublic = 1 << 7, // Synthetic property with public constituent(s) + ContainsProtected = 1 << 8, // Synthetic property with protected constituent(s) + ContainsPrivate = 1 << 9, // Synthetic property with private constituent(s) + ContainsStatic = 1 << 10, // Synthetic property with static constituent(s) + Late = 1 << 11, // Late-bound symbol for a computed property with a dynamic name + ReverseMapped = 1 << 12, // Property of reverse-inferred homomorphic mapped type + OptionalParameter = 1 << 13, // Optional parameter + RestParameter = 1 << 14, // Rest parameter + Synthetic = SyntheticProperty | SyntheticMethod, + Discriminant = HasNonUniformType | HasLiteralType } /* @internal */ @@ -3578,6 +3701,7 @@ namespace ts { export interface ReverseMappedSymbol extends TransientSymbol { propertyType: Type; mappedType: MappedType; + constraintType: IndexType; } export const enum InternalSymbolName { @@ -3653,22 +3777,23 @@ namespace ts { EnumValuesComputed = 0x00004000, // Values for enum members have been computed, and any errors have been reported for them. LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration. LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure - CapturedBlockScopedBinding = 0x00020000, // Block-scoped binding that is captured in some function - BlockScopedBindingInLoop = 0x00040000, // Block-scoped binding with declaration nested inside iteration statement - ClassWithBodyScopedClassBinding = 0x00080000, // Decorated class that contains a binding to itself inside of the class body. - BodyScopedClassBinding = 0x00100000, // Binding to a decorated class inside of the class's body. - NeedsLoopOutParameter = 0x00200000, // Block scoped binding whose value should be explicitly copied outside of the converted loop - AssignmentsMarked = 0x00400000, // Parameter assignments have been marked - ClassWithConstructorReference = 0x00800000, // Class that contains a binding to its constructor inside of the class body. - ConstructorReferenceInClass = 0x01000000, // Binding to a class constructor inside of the class's body. + ContainsCapturedBlockScopeBinding = 0x00020000, // Part of a loop that contains block scoped variable captured in closure + CapturedBlockScopedBinding = 0x00040000, // Block-scoped binding that is captured in some function + BlockScopedBindingInLoop = 0x00080000, // Block-scoped binding with declaration nested inside iteration statement + ClassWithBodyScopedClassBinding = 0x00100000, // Decorated class that contains a binding to itself inside of the class body. + BodyScopedClassBinding = 0x00200000, // Binding to a decorated class inside of the class's body. + NeedsLoopOutParameter = 0x00400000, // Block scoped binding whose value should be explicitly copied outside of the converted loop + AssignmentsMarked = 0x00800000, // Parameter assignments have been marked + ClassWithConstructorReference = 0x01000000, // Class that contains a binding to its constructor inside of the class body. + ConstructorReferenceInClass = 0x02000000, // Binding to a class constructor inside of the class's body. } /* @internal */ export interface NodeLinks { flags: NodeCheckFlags; // Set of flags specific to Node resolvedType?: Type; // Cached type of type node + resolvedEnumType?: Type; // Cached constraint type from enum jsdoc tag resolvedSignature?: Signature; // Cached signature of signature node or call expression - resolvedSignatures?: Map; // Cached signatures of jsx node resolvedSymbol?: Symbol; // Cached name resolution result resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate @@ -3684,6 +3809,8 @@ namespace ts { switchTypes?: Type[]; // Cached array of switch case expression types jsxNamespace?: Symbol | false; // Resolved jsx namespace symbol for this node contextFreeType?: Type; // Cached context-free type used by the first pass of inference; used when a function's return is partially contextually sensitive + deferredNodes?: Map; // Set of nodes whose checking has been deferred + capturedBlockScopeBindings?: Symbol[]; // Block-scoped bindings captured beneath this part of an IterationStatement } export const enum TypeFlags { @@ -3693,29 +3820,27 @@ namespace ts { Number = 1 << 3, Boolean = 1 << 4, Enum = 1 << 5, - StringLiteral = 1 << 6, - NumberLiteral = 1 << 7, - BooleanLiteral = 1 << 8, - EnumLiteral = 1 << 9, // Always combined with StringLiteral, NumberLiteral, or Union - ESSymbol = 1 << 10, // Type of symbol primitive introduced in ES6 - UniqueESSymbol = 1 << 11, // unique symbol - Void = 1 << 12, - Undefined = 1 << 13, - Null = 1 << 14, - Never = 1 << 15, // Never type - TypeParameter = 1 << 16, // Type parameter - Object = 1 << 17, // Object type - Union = 1 << 18, // Union (T | U) - Intersection = 1 << 19, // Intersection (T & U) - Index = 1 << 20, // keyof T - IndexedAccess = 1 << 21, // T[K] - Conditional = 1 << 22, // T extends U ? X : Y - Substitution = 1 << 23, // Type parameter substitution - NonPrimitive = 1 << 24, // intrinsic object type - /* @internal */ - FreshLiteral = 1 << 25, // Fresh literal or unique type - /* @internal */ - UnionOfPrimitiveTypes = 1 << 26, // Type is union of primitive types + BigInt = 1 << 6, + StringLiteral = 1 << 7, + NumberLiteral = 1 << 8, + BooleanLiteral = 1 << 9, + EnumLiteral = 1 << 10, // Always combined with StringLiteral, NumberLiteral, or Union + BigIntLiteral = 1 << 11, + ESSymbol = 1 << 12, // Type of symbol primitive introduced in ES6 + UniqueESSymbol = 1 << 13, // unique symbol + Void = 1 << 14, + Undefined = 1 << 15, + Null = 1 << 16, + Never = 1 << 17, // Never type + TypeParameter = 1 << 18, // Type parameter + Object = 1 << 19, // Object type + Union = 1 << 20, // Union (T | U) + Intersection = 1 << 21, // Intersection (T & U) + Index = 1 << 22, // keyof T + IndexedAccess = 1 << 23, // T[K] + Conditional = 1 << 24, // T extends U ? X : Y + Substitution = 1 << 25, // Type parameter substitution + NonPrimitive = 1 << 26, // intrinsic object type /* @internal */ ContainsWideningType = 1 << 27, // Type is or contains undefined or null widening type /* @internal */ @@ -3727,26 +3852,27 @@ namespace ts { AnyOrUnknown = Any | Unknown, /* @internal */ Nullable = Undefined | Null, - Literal = StringLiteral | NumberLiteral | BooleanLiteral, + Literal = StringLiteral | NumberLiteral | BigIntLiteral | BooleanLiteral, Unit = Literal | UniqueESSymbol | Nullable, StringOrNumberLiteral = StringLiteral | NumberLiteral, /* @internal */ - StringOrNumberLiteralOrUnique = StringOrNumberLiteral | UniqueESSymbol, + StringOrNumberLiteralOrUnique = StringLiteral | NumberLiteral | UniqueESSymbol, /* @internal */ - DefinitelyFalsy = StringLiteral | NumberLiteral | BooleanLiteral | Void | Undefined | Null, - PossiblyFalsy = DefinitelyFalsy | String | Number | Boolean, + DefinitelyFalsy = StringLiteral | NumberLiteral | BigIntLiteral | BooleanLiteral | Void | Undefined | Null, + PossiblyFalsy = DefinitelyFalsy | String | Number | BigInt | Boolean, /* @internal */ - Intrinsic = Any | Unknown | String | Number | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never | NonPrimitive, + Intrinsic = Any | Unknown | String | Number | BigInt | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never | NonPrimitive, /* @internal */ - Primitive = String | Number | Boolean | Enum | EnumLiteral | ESSymbol | Void | Undefined | Null | Literal | UniqueESSymbol, + Primitive = String | Number | BigInt | Boolean | Enum | EnumLiteral | ESSymbol | Void | Undefined | Null | Literal | UniqueESSymbol, StringLike = String | StringLiteral, NumberLike = Number | NumberLiteral | Enum, + BigIntLike = BigInt | BigIntLiteral, BooleanLike = Boolean | BooleanLiteral, EnumLike = Enum | EnumLiteral, ESSymbolLike = ESSymbol | UniqueESSymbol, VoidLike = Void | Undefined, /* @internal */ - DisjointDomains = NonPrimitive | StringLike | NumberLike | BooleanLike | ESSymbolLike | VoidLike | Null, + DisjointDomains = NonPrimitive | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbolLike | VoidLike | Null, UnionOrIntersection = Union | Intersection, StructuredType = Object | Union | Intersection, TypeVariable = TypeParameter | IndexedAccess, @@ -3757,7 +3883,7 @@ namespace ts { // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive, + Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive, NotUnionOrUnit = Any | Unknown | ESSymbol | Object | NonPrimitive, /* @internal */ NotPrimitiveUnion = Any | Unknown | Enum | Void | Never | StructuredOrInstantiable, @@ -3790,8 +3916,11 @@ namespace ts { pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any) aliasSymbol?: Symbol; // Alias associated with type aliasTypeArguments?: ReadonlyArray; // Alias type arguments (if any) + /* @internal */ aliasTypeArgumentsContainsMarker?: boolean; // Alias type arguments (if any) /* @internal */ - wildcardInstantiation?: Type; // Instantiation with type parameters mapped to wildcard type + permissiveInstantiation?: Type; // Instantiation with type parameters mapped to wildcard type + /* @internal */ + restrictiveInstantiation?: Type; // Instantiation with type parameters mapped to unconstrained form /* @internal */ immediateBaseConstraint?: Type; // Immediate base constraint cache } @@ -3802,12 +3931,22 @@ namespace ts { intrinsicName: string; // Name of intrinsic type } + /* @internal */ + export interface FreshableIntrinsicType extends IntrinsicType { + freshType: IntrinsicType; // Fresh version of type + regularType: IntrinsicType; // Regular version of type + } + + /* @internal */ + export type FreshableType = LiteralType | FreshableIntrinsicType; + // String literal types (TypeFlags.StringLiteral) // Numeric literal types (TypeFlags.NumberLiteral) + // BigInt literal types (TypeFlags.BigIntLiteral) export interface LiteralType extends Type { - value: string | number; // Value of literal - freshType: LiteralType; // Fresh version of type - regularType: LiteralType; // Regular version of type + value: string | number | PseudoBigInt; // Value of literal + freshType: LiteralType; // Fresh version of type + regularType: LiteralType; // Regular version of type } // Unique symbol types (TypeFlags.UniqueESSymbol) @@ -3823,6 +3962,10 @@ namespace ts { value: number; } + export interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } + // Enum types (TypeFlags.Enum) export interface EnumType extends Type { } @@ -3843,6 +3986,7 @@ namespace ts { JsxAttributes = 1 << 12, // Jsx attributes type MarkerType = 1 << 13, // Marker type used for variance probing JSLiteral = 1 << 14, // Object type declared in JS - disables errors on read/write of nonexisting members + FreshLiteral = 1 << 15, // Fresh object literal ClassOrInterface = Class | Interface } @@ -3938,7 +4082,10 @@ namespace ts { couldContainTypeVariables: boolean; } - export interface UnionType extends UnionOrIntersectionType { } + export interface UnionType extends UnionOrIntersectionType { + /* @internal */ + primitiveTypesOnly: boolean; + } export interface IntersectionType extends UnionOrIntersectionType { /* @internal */ @@ -3962,6 +4109,7 @@ namespace ts { templateType?: Type; modifiersType?: Type; resolvedApparentType?: Type; + instantiating?: boolean; } export interface EvolvingArrayType extends ObjectType { @@ -3973,6 +4121,7 @@ namespace ts { export interface ReverseMappedType extends ObjectType { source: Type; mappedType: MappedType; + constraintType: IndexType; } /* @internal */ @@ -4097,6 +4246,13 @@ namespace ts { substitute: Type; // Type to substitute for type parameter } + /* @internal */ + export const enum JsxReferenceKind { + Component, + Function, + Mixed + } + export const enum SignatureKind { Call, Construct, @@ -4219,7 +4375,7 @@ namespace ts { } /* @internal */ - export const enum SpecialPropertyAssignmentKind { + export const enum AssignmentDeclarationKind { None, /// exports.name = expr ExportsProperty, @@ -4233,6 +4389,15 @@ namespace ts { Property, // F.prototype = { ... } Prototype, + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + ObjectDefinePropertyValue, + // Object.defineProperty(exports || module.exports, 'name', ...); + ObjectDefinePropertyExports, + // Object.defineProperty(Foo.prototype, 'name', ...); + ObjectDefinePrototypeProperty, } /** @deprecated Use FileExtensionInfo instead. */ @@ -4402,6 +4567,7 @@ namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; // Always combine with strict property + strictBindCallApply?: boolean; // Always combine with strict property strictNullChecks?: boolean; // Always combine with strict property strictPropertyInitialization?: boolean; // Always combine with strict property stripInternal?: boolean; @@ -4417,6 +4583,7 @@ namespace ts { /*@internal*/ version?: boolean; /*@internal*/ watch?: boolean; esModuleInterop?: boolean; + /* @internal */ showConfig?: boolean; [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; } @@ -4516,7 +4683,6 @@ namespace ts { /* @internal */ export interface ConfigFileSpecs { filesSpecs: ReadonlyArray | undefined; - referencesSpecs: ReadonlyArray | undefined; /** * Present to report errors (user specified specs), validatedIncludeSpecs are used for file name matching */ @@ -4532,7 +4698,6 @@ namespace ts { export interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; /* @internal */ spec: ConfigFileSpecs; } @@ -4559,6 +4724,9 @@ namespace ts { showInSimplifiedHelpView?: boolean; category?: DiagnosticMessage; strictFlag?: true; // true if the option is one of the flag under strict + affectsSourceFile?: true; // true if we should recreate SourceFiles after this option changes + affectsModuleResolution?: true; // currently same effect as `affectsSourceFile` + affectsBindDiagnostics?: true; // true if this affects binding (currently same effect as `affectsSourceFile`) affectsSemanticDiagnostics?: true; // true if option affects semantic diagnostics } @@ -4814,6 +4982,8 @@ namespace ts { // The location of the .d.ts file we located, or undefined if resolution failed resolvedFileName: string | undefined; packageId?: PackageId; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; } export interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { @@ -4832,7 +5002,6 @@ namespace ts { getDefaultLibLocation?(): string; writeFile: WriteFileCallback; getCurrentDirectory(): string; - getDirectories(path: string): string[]; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; @@ -4845,16 +5014,19 @@ namespace ts { * If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just * 'throw new Error("NotImplemented")' */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string | undefined; - /* @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions): void; + /* @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions, hasSourceFileByPath: boolean): void; /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution; /* @internal */ hasChangedAutomaticTypeDirectiveNames?: boolean; createHash?(data: string): string; + + // TODO: later handle this in better way in builder host instead once the api for tsbuild finalizes and doesnt use compilerHost as base + /*@internal*/createDirectory?(directory: string): void; } /* @internal */ @@ -4878,25 +5050,21 @@ namespace ts { // Markers // - Flags used to indicate that a subtree contains a specific transformation. - ContainsDecorators = 1 << 12, - ContainsPropertyInitializer = 1 << 13, - ContainsLexicalThis = 1 << 14, - ContainsCapturedLexicalThis = 1 << 15, - ContainsLexicalThisInComputedPropertyName = 1 << 16, - ContainsDefaultValueAssignments = 1 << 17, - ContainsParameterPropertyAssignments = 1 << 18, - ContainsSpread = 1 << 19, - ContainsObjectSpread = 1 << 20, - ContainsRest = ContainsSpread, - ContainsObjectRest = ContainsObjectSpread, - ContainsComputedPropertyName = 1 << 21, - ContainsBlockScopedBinding = 1 << 22, - ContainsBindingPattern = 1 << 23, - ContainsYield = 1 << 24, - ContainsHoistedDeclarationOrCompletion = 1 << 25, - ContainsDynamicImport = 1 << 26, - Super = 1 << 27, - ContainsSuper = 1 << 28, + ContainsTypeScriptClassSyntax = 1 << 12, // Decorators, Property Initializers, Parameter Property Initializers + ContainsLexicalThis = 1 << 13, + ContainsCapturedLexicalThis = 1 << 14, + ContainsLexicalThisInComputedPropertyName = 1 << 15, + ContainsDefaultValueAssignments = 1 << 16, + ContainsRestOrSpread = 1 << 17, + ContainsObjectRestOrSpread = 1 << 18, + ContainsComputedPropertyName = 1 << 19, + ContainsBlockScopedBinding = 1 << 20, + ContainsBindingPattern = 1 << 21, + ContainsYield = 1 << 22, + ContainsHoistedDeclarationOrCompletion = 1 << 23, + ContainsDynamicImport = 1 << 24, + Super = 1 << 25, + ContainsSuper = 1 << 26, // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. @@ -4920,23 +5088,22 @@ namespace ts { OuterExpressionExcludes = TypeScript | ES2015 | DestructuringAssignment | Generator | HasComputedFlags, PropertyAccessExcludes = OuterExpressionExcludes | Super, NodeExcludes = PropertyAccessExcludes | ContainsSuper, - ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, - FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, - ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, - MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, - ClassExcludes = NodeExcludes | ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsParameterPropertyAssignments | ContainsLexicalThisInComputedPropertyName, - ModuleExcludes = NodeExcludes | ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion, + ArrowFunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread, + FunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread, + ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread, + MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread, + ClassExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName, + ModuleExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion, TypeExcludes = ~ContainsTypeScript, - ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName | ContainsObjectSpread, - ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpread, - VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRest, + ObjectLiteralExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName | ContainsObjectRestOrSpread, + ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsRestOrSpread, + VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRestOrSpread, ParameterExcludes = NodeExcludes, - CatchClauseExcludes = NodeExcludes | ContainsObjectRest, - BindingPatternExcludes = NodeExcludes | ContainsRest, + CatchClauseExcludes = NodeExcludes | ContainsObjectRestOrSpread, + BindingPatternExcludes = NodeExcludes | ContainsRestOrSpread, // Masks // - Additional bitmasks - TypeScriptClassSyntaxMask = ContainsParameterPropertyAssignments | ContainsPropertyInitializer | ContainsDecorators, ES2015FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments, } @@ -4954,7 +5121,7 @@ namespace ts { /* @internal */ export interface EmitNode { annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup. - flags: EmitFlags; // Flags that customize emit + flags: EmitFlags; // Flags that customize emit leadingComments?: SynthesizedComment[]; // Synthesized leading comments trailingComments?: SynthesizedComment[]; // Synthesized trailing comments commentRange?: TextRange; // The text range to use when emitting leading or trailing comments @@ -5061,6 +5228,7 @@ namespace ts { IdentifierName, // Emitting an IdentifierName MappedTypeParameter, // Emitting a TypeParameterDeclaration inside of a MappedTypeNode Unspecified, // Emitting an otherwise unspecified node + EmbeddedStatement, // Emitting an embedded statement } /* @internal */ @@ -5069,7 +5237,6 @@ namespace ts { useCaseSensitiveFileNames(): boolean; getCurrentDirectory(): string; - /* @internal */ isSourceFileFromExternalLibrary(file: SourceFile): boolean; getLibFileFromReference(ref: FileReference): SourceFile | undefined; @@ -5231,8 +5398,8 @@ namespace ts { printBundle(bundle: Bundle): string; /*@internal*/ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void; /*@internal*/ writeList(format: ListFormat, list: NodeArray | undefined, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void; - /*@internal*/ writeFile(sourceFile: SourceFile, writer: EmitTextWriter): void; - /*@internal*/ writeBundle(bundle: Bundle, writer: EmitTextWriter, info?: BundleInfo): void; + /*@internal*/ writeFile(sourceFile: SourceFile, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void; + /*@internal*/ writeBundle(bundle: Bundle, info: BundleInfo | undefined, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void; } /** @@ -5312,14 +5479,90 @@ namespace ts { /*@internal*/ target?: CompilerOptions["target"]; /*@internal*/ sourceMap?: boolean; /*@internal*/ inlineSourceMap?: boolean; + /*@internal*/ inlineSources?: boolean; /*@internal*/ extendedDiagnostics?: boolean; /*@internal*/ onlyPrintJsDocStyle?: boolean; + /*@internal*/ neverAsciiEscape?: boolean; + } + + /* @internal */ + export interface RawSourceMap { + version: 3; + file: string; + sourceRoot?: string | null; + sources: string[]; + sourcesContent?: (string | null)[] | null; + mappings: string; + names?: string[] | null; + } + + /** + * Generates a source map. + */ + /* @internal */ + export interface SourceMapGenerator { + getSources(): ReadonlyArray; + /** + * Adds a source to the source map. + */ + addSource(fileName: string): number; + /** + * Set the content for a source. + */ + setSourceContent(sourceIndex: number, content: string | null): void; + /** + * Adds a name. + */ + addName(name: string): number; + /** + * Adds a mapping without source information. + */ + addMapping(generatedLine: number, generatedCharacter: number): void; + /** + * Adds a mapping with source information. + */ + addMapping(generatedLine: number, generatedCharacter: number, sourceIndex: number, sourceLine: number, sourceCharacter: number, nameIndex?: number): void; + /** + * Appends a source map. + */ + appendSourceMap(generatedLine: number, generatedCharacter: number, sourceMap: RawSourceMap, sourceMapPath: string): void; + /** + * Gets the source map as a `RawSourceMap` object. + */ + toJSON(): RawSourceMap; + /** + * Gets the string representation of the source map. + */ + toString(): string; + } + + /* @internal */ + export interface DocumentPositionMapperHost { + getSourceFileLike(fileName: string): SourceFileLike | undefined; + getCanonicalFileName(path: string): string; + log(text: string): void; + } + + /** + * Maps positions between source and generated files. + */ + /* @internal */ + export interface DocumentPositionMapper { + getSourcePosition(input: DocumentPosition): DocumentPosition; + getGeneratedPosition(input: DocumentPosition): DocumentPosition; + } + + /* @internal */ + export interface DocumentPosition { + fileName: string; + pos: number; } /* @internal */ export interface EmitTextWriter extends SymbolWriter { write(s: string): void; - writeTextOfNode(text: string, node: Node): void; + writeTrailingSemicolon(text: string): void; + writeComment(text: string): void; getText(): string; rawWrite(s: string): void; writeLiteral(s: string): void; @@ -5351,7 +5594,8 @@ namespace ts { reportInaccessibleThisError?(): void; reportPrivateInBaseOfClassExpression?(propertyName: string): void; reportInaccessibleUniqueSymbolError?(): void; - moduleResolverHost?: EmitHost; + reportLikelyUnsafeImportRequiredError?(specifier: string): void; + moduleResolverHost?: ModuleSpecifierResolutionHost & { getSourceFiles(): ReadonlyArray, getCommonSourceDirectory(): string }; trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void; trackExternalModuleSymbolOfImportTypeNode?(symbol: Symbol): void; } @@ -5404,33 +5648,34 @@ namespace ts { BarDelimited = 1 << 2, // Each list item is space-and-bar (" |") delimited. AmpersandDelimited = 1 << 3, // Each list item is space-and-ampersand (" &") delimited. CommaDelimited = 1 << 4, // Each list item is comma (",") delimited. - DelimitersMask = BarDelimited | AmpersandDelimited | CommaDelimited, + AsteriskDelimited = 1 << 5, // Each list item is asterisk ("\n *") delimited, used with JSDoc. + DelimitersMask = BarDelimited | AmpersandDelimited | CommaDelimited | AsteriskDelimited, - AllowTrailingComma = 1 << 5, // Write a trailing comma (",") if present. + AllowTrailingComma = 1 << 6, // Write a trailing comma (",") if present. // Whitespace - Indented = 1 << 6, // The list should be indented. - SpaceBetweenBraces = 1 << 7, // Inserts a space after the opening brace and before the closing brace. - SpaceBetweenSiblings = 1 << 8, // Inserts a space between each sibling node. + Indented = 1 << 7, // The list should be indented. + SpaceBetweenBraces = 1 << 8, // Inserts a space after the opening brace and before the closing brace. + SpaceBetweenSiblings = 1 << 9, // Inserts a space between each sibling node. // Brackets/Braces - Braces = 1 << 9, // The list is surrounded by "{" and "}". - Parenthesis = 1 << 10, // The list is surrounded by "(" and ")". - AngleBrackets = 1 << 11, // The list is surrounded by "<" and ">". - SquareBrackets = 1 << 12, // The list is surrounded by "[" and "]". + Braces = 1 << 10, // The list is surrounded by "{" and "}". + Parenthesis = 1 << 11, // The list is surrounded by "(" and ")". + AngleBrackets = 1 << 12, // The list is surrounded by "<" and ">". + SquareBrackets = 1 << 13, // The list is surrounded by "[" and "]". BracketsMask = Braces | Parenthesis | AngleBrackets | SquareBrackets, - OptionalIfUndefined = 1 << 13, // Do not emit brackets if the list is undefined. - OptionalIfEmpty = 1 << 14, // Do not emit brackets if the list is empty. + OptionalIfUndefined = 1 << 14, // Do not emit brackets if the list is undefined. + OptionalIfEmpty = 1 << 15, // Do not emit brackets if the list is empty. Optional = OptionalIfUndefined | OptionalIfEmpty, // Other - PreferNewLine = 1 << 15, // Prefer adding a LineTerminator between synthesized nodes. - NoTrailingNewLine = 1 << 16, // Do not emit a trailing NewLine for a MultiLine list. - NoInterveningComments = 1 << 17, // Do not emit comments between each node + PreferNewLine = 1 << 16, // Prefer adding a LineTerminator between synthesized nodes. + NoTrailingNewLine = 1 << 17, // Do not emit a trailing NewLine for a MultiLine list. + NoInterveningComments = 1 << 18, // Do not emit comments between each node - NoSpaceIfEmpty = 1 << 18, // If the literal is empty, do not add spaces between braces. - SingleElement = 1 << 19, + NoSpaceIfEmpty = 1 << 19, // If the literal is empty, do not add spaces between braces. + SingleElement = 1 << 20, // Precomputed Formats Modifiers = SingleLine | SpaceBetweenSiblings | NoInterveningComments, @@ -5470,6 +5715,7 @@ namespace ts { TypeParameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | AngleBrackets | Optional, Parameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis, IndexSignatureParameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented | SquareBrackets, + JSDocComment = MultiLine | AsteriskDelimited, } /* @internal */ @@ -5585,15 +5831,15 @@ namespace ts { type ConcretePragmaSpecs = typeof commentPragmas; /* @internal */ - export type PragmaPsuedoMap = {[K in keyof ConcretePragmaSpecs]?: {arguments: PragmaArgumentType, range: CommentRange}}; + export type PragmaPseudoMap = {[K in keyof ConcretePragmaSpecs]?: {arguments: PragmaArgumentType, range: CommentRange}}; /* @internal */ - export type PragmaPsuedoMapEntry = {[K in keyof PragmaPsuedoMap]: {name: K, args: PragmaPsuedoMap[K]}}[keyof PragmaPsuedoMap]; + export type PragmaPseudoMapEntry = {[K in keyof PragmaPseudoMap]: {name: K, args: PragmaPseudoMap[K]}}[keyof PragmaPseudoMap]; /* @internal */ - export interface ReadonlyPragmaMap extends ReadonlyMap { - get(key: TKey): PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]; - forEach(action: (value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][], key: TKey) => void): void; + export interface ReadonlyPragmaMap extends ReadonlyMap { + get(key: TKey): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]; + forEach(action: (value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey) => void): void; } /** @@ -5602,10 +5848,10 @@ namespace ts { * in multiple places */ /* @internal */ - export interface PragmaMap extends Map, ReadonlyPragmaMap { - set(key: TKey, value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]): this; - get(key: TKey): PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]; - forEach(action: (value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][], key: TKey) => void): void; + export interface PragmaMap extends Map, ReadonlyPragmaMap { + set(key: TKey, value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]): this; + get(key: TKey): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]; + forEach(action: (value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey) => void): void; } export interface UserPreferences { @@ -5617,5 +5863,12 @@ namespace ts { /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; + readonly providePrefixAndSuffixTextForRename?: boolean; + } + + /** Represents a bigint literal value without requiring bigint support */ + export interface PseudoBigInt { + negative: boolean; + base10Value: string; } } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 7a128a41c69..33a902b8035 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1,4 +1,3 @@ -/** Non-internal stuff goes here */ namespace ts { export function isExternalModuleNameRelative(moduleName: string): boolean { // TypeScript 1.0 spec (April 2014): 11.2.1 @@ -7,14 +6,13 @@ namespace ts { return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } - export function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[] { + export function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray { return sortAndDeduplicate(diagnostics, compareDiagnostics); } } /* @internal */ namespace ts { - export const emptyArray: never[] = [] as never[]; export const resolvingEmptyArray: never[] = [] as never[]; export const emptyMap = createMap() as ReadonlyMap & ReadonlyPragmaMap; export const emptyUnderscoreEscapedMap: ReadonlyUnderscoreEscapedMap = emptyMap as ReadonlyUnderscoreEscapedMap; @@ -65,7 +63,6 @@ namespace ts { getText: () => str, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -74,7 +71,9 @@ namespace ts { writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, - writeSymbol: writeText, + writeSymbol: (s, _) => writeText(s), + writeTrailingSemicolon: writeText, + writeComment: writeText, getTextPos: () => str.length, getLine: () => 0, getColumn: () => 0, @@ -102,22 +101,8 @@ namespace ts { } export function changesAffectModuleResolution(oldOptions: CompilerOptions, newOptions: CompilerOptions): boolean { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || moduleResolutionOptionDeclarations.some(o => + !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o))); } /** @@ -242,14 +227,20 @@ namespace ts { sourceFile.resolvedModules.set(moduleNameText, resolvedModule); } - export function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective): void { + export function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective?: ResolvedTypeReferenceDirective): void { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = createMap(); + sourceFile.resolvedTypeReferenceDirectiveNames = createMap(); } sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } + export function projectReferenceIsEqualTo(oldRef: ProjectReference, newRef: ProjectReference) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + export function moduleResolutionIsEqualTo(oldResolution: ResolvedModuleFull, newResolution: ResolvedModuleFull): boolean { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -533,14 +524,17 @@ namespace ts { return emitNode && emitNode.flags || 0; } - export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile) { + export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, neverAsciiEscape: boolean | undefined) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent && !(isNumericLiteral(node) && node.numericLiteralFlags & TokenFlags.ContainsSeparator)) { + if (!nodeIsSynthesized(node) && node.parent && !( + (isNumericLiteral(node) && node.numericLiteralFlags & TokenFlags.ContainsSeparator) || + isBigIntLiteral(node) + )) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - const escapeText = getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? escapeString : escapeNonAsciiString; + const escapeText = neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. @@ -563,6 +557,7 @@ namespace ts { case SyntaxKind.TemplateTail: return "}" + escapeText(node.text, CharacterCodes.backtick) + "`"; case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.RegularExpressionLiteral: return node.text; } @@ -774,12 +769,13 @@ namespace ts { return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } - export function getTextOfPropertyName(name: PropertyName): __String { + export function getTextOfPropertyName(name: PropertyName | NoSubstitutionTemplateLiteral): __String { switch (name.kind) { case SyntaxKind.Identifier: return name.escapedText; case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.NoSubstitutionTemplateLiteral: return escapeLeadingUnderscores(name.text); case SyntaxKind.ComputedPropertyName: return isStringOrNumericLiteralLike(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined!; // TODO: GH#18217 Almost all uses of this assume the result to be defined! @@ -892,7 +888,7 @@ namespace ts { } const isMissing = nodeIsMissing(errorNode); - const pos = isMissing + const pos = isMissing || isJsxText(node) ? errorNode.pos : skipTrivia(sourceFile.text, errorNode.pos); @@ -984,9 +980,11 @@ namespace ts { case SyntaxKind.AnyKeyword: case SyntaxKind.UnknownKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: + case SyntaxKind.ObjectKeyword: case SyntaxKind.UndefinedKeyword: case SyntaxKind.NeverKeyword: return true; @@ -1606,6 +1604,7 @@ namespace ts { } // falls through case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.ThisKeyword: return isInExpressionContext(node); @@ -1679,15 +1678,15 @@ namespace ts { return node.kind === SyntaxKind.ImportEqualsDeclaration && (node).moduleReference.kind !== SyntaxKind.ExternalModuleReference; } - export function isSourceFileJavaScript(file: SourceFile): boolean { - return isInJavaScriptFile(file); + export function isSourceFileJS(file: SourceFile): boolean { + return isInJSFile(file); } - export function isSourceFileNotJavaScript(file: SourceFile): boolean { - return !isInJavaScriptFile(file); + export function isSourceFileNotJS(file: SourceFile): boolean { + return !isInJSFile(file); } - export function isInJavaScriptFile(node: Node | undefined): boolean { + export function isInJSFile(node: Node | undefined): boolean { return !!node && !!(node.flags & NodeFlags.JavaScriptFile); } @@ -1739,14 +1738,14 @@ namespace ts { return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === CharacterCodes.doubleQuote; } - export function getDeclarationOfJSInitializer(node: Node): Node | undefined { + export function getDeclarationOfExpando(node: Node): Node | undefined { if (!node.parent) { return undefined; } let name: Expression | BindingName | undefined; let decl: Node | undefined; if (isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -1771,19 +1770,19 @@ namespace ts { } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } export function isAssignmentDeclaration(decl: Declaration) { - return isBinaryExpression(decl) || isPropertyAccessExpression(decl) || isIdentifier(decl); + return isBinaryExpression(decl) || isPropertyAccessExpression(decl) || isIdentifier(decl) || isCallExpression(decl); } /** Get the initializer, taking into account defaulted Javascript initializers */ export function getEffectiveInitializer(node: HasExpressionInitializer) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === SyntaxKind.BarBarToken && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -1791,26 +1790,36 @@ namespace ts { return node.initializer; } - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - export function getDeclaredJavascriptInitializer(node: HasExpressionInitializer) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + export function getDeclaredExpandoInitializer(node: HasExpressionInitializer) { const init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); + } + + function hasExpandoValueProperty(node: ObjectLiteralExpression, isPrototypeAssignment: boolean) { + return forEach(node.properties, p => isPropertyAssignment(p) && isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment)); } /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - export function getAssignedJavascriptInitializer(node: Node) { + export function getAssignedExpandoInitializer(node: Node | undefined) { if (node && node.parent && isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken) { const isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left as EntityNameExpression, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left as EntityNameExpression, node.parent.right, isPrototypeAssignment); + } + if (node && isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + const result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } } } /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -1819,7 +1828,7 @@ namespace ts { * * This function returns the provided initializer, or undefined if it is not valid. */ - export function getJavascriptInitializer(initializer: Node, isPrototypeAssignment: boolean): Expression | undefined { + export function getExpandoInitializer(initializer: Node, isPrototypeAssignment: boolean): Expression | undefined { if (isCallExpression(initializer)) { const e = skipParentheses(initializer.expression); return e.kind === SyntaxKind.FunctionExpression || e.kind === SyntaxKind.ArrowFunction ? initializer : undefined; @@ -1835,29 +1844,29 @@ namespace ts { } /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name: EntityNameExpression, initializer: Expression, isPrototypeAssignment: boolean) { - const e = isBinaryExpression(initializer) && initializer.operatorToken.kind === SyntaxKind.BarBarToken && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name: EntityNameExpression, initializer: Expression, isPrototypeAssignment: boolean) { + const e = isBinaryExpression(initializer) && initializer.operatorToken.kind === SyntaxKind.BarBarToken && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, (initializer as BinaryExpression).left as EntityNameExpression)) { return e; } } - export function isDefaultedJavascriptInitializer(node: BinaryExpression) { + export function isDefaultedExpandoInitializer(node: BinaryExpression) { const name = isVariableDeclaration(node.parent) ? node.parent.name : isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - export function getOuterNameOfJsInitializer(node: Declaration): DeclarationName | undefined { + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + export function getNameOfExpando(node: Declaration): DeclarationName | undefined { if (isBinaryExpression(node.parent)) { const parent = (node.parent.operatorToken.kind === SyntaxKind.BarBarToken && isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === SyntaxKind.EqualsToken && isIdentifier(parent.left)) { @@ -1913,36 +1922,59 @@ namespace ts { /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - export function getSpecialPropertyAssignmentKind(expr: BinaryExpression): SpecialPropertyAssignmentKind { - const special = getSpecialPropertyAssignmentKindWorker(expr); - return special === SpecialPropertyAssignmentKind.Property || isInJavaScriptFile(expr) ? special : SpecialPropertyAssignmentKind.None; + export function getAssignmentDeclarationKind(expr: BinaryExpression | CallExpression): AssignmentDeclarationKind { + const special = getAssignmentDeclarationKindWorker(expr); + return special === AssignmentDeclarationKind.Property || isInJSFile(expr) ? special : AssignmentDeclarationKind.None; } - function getSpecialPropertyAssignmentKindWorker(expr: BinaryExpression): SpecialPropertyAssignmentKind { + export function isBindableObjectDefinePropertyCall(expr: CallExpression): expr is BindableObjectDefinePropertyCall { + return length(expr.arguments) === 3 && + isPropertyAccessExpression(expr.expression) && + isIdentifier(expr.expression.expression) && + idText(expr.expression.expression) === "Object" && + idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + + function getAssignmentDeclarationKindWorker(expr: BinaryExpression | CallExpression): AssignmentDeclarationKind { + if (isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return AssignmentDeclarationKind.None; + } + const entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return AssignmentDeclarationKind.ObjectDefinePropertyExports; + } + if (isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return AssignmentDeclarationKind.ObjectDefinePrototypeProperty; + } + return AssignmentDeclarationKind.ObjectDefinePropertyValue; + } if (expr.operatorToken.kind !== SyntaxKind.EqualsToken || !isPropertyAccessExpression(expr.left)) { - return SpecialPropertyAssignmentKind.None; + return AssignmentDeclarationKind.None; } const lhs = expr.left; if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { // F.prototype = { ... } - return SpecialPropertyAssignmentKind.Prototype; + return AssignmentDeclarationKind.Prototype; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - export function getSpecialPropertyAccessKind(lhs: PropertyAccessExpression): SpecialPropertyAssignmentKind { + export function getAssignmentDeclarationPropertyAccessKind(lhs: PropertyAccessExpression): AssignmentDeclarationKind { if (lhs.expression.kind === SyntaxKind.ThisKeyword) { - return SpecialPropertyAssignmentKind.ThisProperty; + return AssignmentDeclarationKind.ThisProperty; } - else if (isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + else if (isModuleExportsPropertyAccessExpression(lhs)) { // module.exports = expr - return SpecialPropertyAssignmentKind.ModuleExports; + return AssignmentDeclarationKind.ModuleExports; } else if (isEntityNameExpression(lhs.expression)) { if (isPrototypeAccess(lhs.expression)) { // F.G....prototype.x = expr - return SpecialPropertyAssignmentKind.PrototypeProperty; + return AssignmentDeclarationKind.PrototypeProperty; } let nextToLast = lhs; @@ -1954,13 +1986,13 @@ namespace ts { if (id.escapedText === "exports" || id.escapedText === "module" && nextToLast.name.escapedText === "exports") { // exports.name = expr OR module.exports.name = expr - return SpecialPropertyAssignmentKind.ExportsProperty; + return AssignmentDeclarationKind.ExportsProperty; } // F.G...x = expr - return SpecialPropertyAssignmentKind.Property; + return AssignmentDeclarationKind.Property; } - return SpecialPropertyAssignmentKind.None; + return AssignmentDeclarationKind.None; } export function getInitializerOfBinaryExpression(expr: BinaryExpression) { @@ -1971,11 +2003,11 @@ namespace ts { } export function isPrototypePropertyAssignment(node: Node): boolean { - return isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === SpecialPropertyAssignmentKind.PrototypeProperty; + return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.PrototypeProperty; } export function isSpecialPropertyDeclaration(expr: PropertyAccessExpression): boolean { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === SyntaxKind.ExpressionStatement && !!getJSDocTypeTag(expr.parent); } @@ -2000,7 +2032,7 @@ namespace ts { case SyntaxKind.ExternalModuleReference: return (node.parent as ExternalModuleReference).parent as AnyValidImportOrReExport; case SyntaxKind.CallExpression: - return node.parent as AnyValidImportOrReExport; + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent as RequireOrImportCall : undefined; case SyntaxKind.LiteralType: Debug.assert(isStringLiteral(node)); return tryCast(node.parent.parent, isImportTypeNode) as ValidImportTypeNode | undefined; @@ -2058,10 +2090,9 @@ namespace ts { } export function isJSDocConstructSignature(node: Node) { - return node.kind === SyntaxKind.JSDocFunctionType && - (node as JSDocFunctionType).parameters.length > 0 && - (node as JSDocFunctionType).parameters[0].name && - ((node as JSDocFunctionType).parameters[0].name as Identifier).escapedText === "new"; + const param = isJSDocFunctionType(node) ? firstOrUndefined(node.parameters) : undefined; + const name = tryCast(param && param.name, isIdentifier); + return !!name && name.escapedText === "new"; } export function isJSDocTypeAlias(node: Node): node is JSDocTypedefTag | JSDocCallbackTag { @@ -2083,14 +2114,14 @@ namespace ts { function getSourceOfDefaultedAssignment(node: Node): Node | undefined { return isExpressionStatement(node) && isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== SpecialPropertyAssignmentKind.None && + getAssignmentDeclarationKind(node.expression) !== AssignmentDeclarationKind.None && isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === SyntaxKind.BarBarToken ? node.expression.right.right : undefined; } - function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node: Node): Expression | undefined { + export function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node: Node): Expression | undefined { switch (node.kind) { case SyntaxKind.VariableStatement: const v = getSingleVariableOfVariableStatement(node); @@ -2403,7 +2434,7 @@ namespace ts { else { const binExp = parent.parent; return isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== SpecialPropertyAssignmentKind.None && + getAssignmentDeclarationKind(binExp) !== AssignmentDeclarationKind.None && (binExp.left.symbol || binExp.symbol) && getNameOfDeclaration(binExp) === name ? binExp @@ -2464,6 +2495,7 @@ namespace ts { // export { x as } from ... // export = // export default + // module.exports = export function isAliasSymbolDeclaration(node: Node): boolean { return node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.NamespaceExportDeclaration || @@ -2472,7 +2504,7 @@ namespace ts { node.kind === SyntaxKind.ImportSpecifier || node.kind === SyntaxKind.ExportSpecifier || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) || - isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === SpecialPropertyAssignmentKind.ModuleExports; + isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports && exportAssignmentIsAlias(node); } export function exportAssignmentIsAlias(node: ExportAssignment | BinaryExpression): boolean { @@ -2481,7 +2513,7 @@ namespace ts { } export function getEffectiveBaseTypeNode(node: ClassLikeDeclaration | InterfaceDeclaration) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. const tag = getJSDocAugmentsTag(node); if (tag) { @@ -2559,6 +2591,10 @@ namespace ts { return token !== undefined && isNonContextualKeyword(token); } + export function isIdentifierANonContextualKeyword({ originalKeywordKind }: Identifier): boolean { + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + export type TriviaKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia @@ -2874,6 +2910,7 @@ namespace ts { case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.ObjectLiteralExpression: @@ -2895,7 +2932,6 @@ namespace ts { } } - /* @internal */ export function getBinaryOperatorPrecedence(kind: SyntaxKind): number { switch (kind) { case SyntaxKind.BarBarToken: @@ -3012,7 +3048,7 @@ namespace ts { return fileDiagnostics.get(fileName) || []; } - const fileDiags: Diagnostic[] = flatMap(filesWithDiagnostics, f => fileDiagnostics.get(f)); + const fileDiags: Diagnostic[] = flatMapToMutable(filesWithDiagnostics, f => fileDiagnostics.get(f)); if (!nonFileDiagnostics.length) { return fileDiags; } @@ -3073,7 +3109,7 @@ namespace ts { export function isIntrinsicJsxName(name: __String | string) { const ch = (name as string).charCodeAt(0); - return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || (name as string).indexOf("-") > -1; + return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || stringContains((name as string), "-"); } function get16BitUnicodeEscapeSequence(charCode: number): string { @@ -3164,18 +3200,11 @@ namespace ts { } } - function writeTextOfNode(text: string, node: Node) { - const s = getTextOfNodeFromSourceText(text, node); - write(s); - updateLineCountAndPosFor(s); - } - reset(); return { write, rawWrite, - writeTextOfNode, writeLiteral, writeLine, increaseIndent: () => { indent++; }, @@ -3198,7 +3227,79 @@ namespace ts { writePunctuation: write, writeSpace: write, writeStringLiteral: write, - writeSymbol: write + writeSymbol: (s, _) => write(s), + writeTrailingSemicolon: write, + writeComment: write + }; + } + + export function getTrailingSemicolonOmittingWriter(writer: EmitTextWriter): EmitTextWriter { + let pendingTrailingSemicolon = false; + + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + + return { + ...writer, + writeTrailingSemicolon() { + pendingTrailingSemicolon = true; + }, + writeLiteral(s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral(s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol(s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation(s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword(s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator(s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter(s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace(s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty(s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment(s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine() { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent() { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent() { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } }; } @@ -3253,7 +3354,7 @@ namespace ts { } export interface EmitFileNames { - jsFilePath: string; + jsFilePath: string | undefined; sourceMapFilePath: string | undefined; declarationFilePath: string | undefined; declarationMapPath: string | undefined; @@ -3274,7 +3375,7 @@ namespace ts { const isSourceFileFromExternalLibrary = (file: SourceFile) => host.isSourceFileFromExternalLibrary(file); if (options.outFile || options.out) { const moduleKind = getEmitModuleKind(options); - const moduleEmitEnabled = moduleKind === ModuleKind.AMD || moduleKind === ModuleKind.System; + const moduleEmitEnabled = options.emitDeclarationOnly || moduleKind === ModuleKind.AMD || moduleKind === ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return filter(host.getSourceFiles(), sourceFile => (moduleEmitEnabled || !isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary)); @@ -3287,7 +3388,7 @@ namespace ts { /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ export function sourceFileMayBeEmitted(sourceFile: SourceFile, options: CompilerOptions, isSourceFileFromExternalLibrary: (file: SourceFile) => boolean) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } export function getSourceFilePathInNewDir(fileName: string, host: EmitHost, newDirPath: string): string { @@ -3301,7 +3402,7 @@ namespace ts { return combinePaths(newDirPath, sourceFilePath); } - export function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: ReadonlyArray) { + export function writeFile(host: { writeFile: WriteFileCallback; }, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: ReadonlyArray) { host.writeFile(fileName, data, writeByteOrderMark, hostErrorMessage => { diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }, sourceFiles); @@ -3411,7 +3512,7 @@ namespace ts { */ export function getEffectiveTypeAnnotationNode(node: Node): TypeNode | undefined { const type = (node as HasType).type; - if (type || !isInJavaScriptFile(node)) return type; + if (type || !isInJSFile(node)) return type; return isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : getJSDocType(node); } @@ -3426,7 +3527,7 @@ namespace ts { export function getEffectiveReturnTypeNode(node: SignatureDeclaration | JSDocSignature): TypeNode | undefined { return isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? getJSDocReturnType(node) : undefined); } export function getJSDocTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray { @@ -3478,13 +3579,13 @@ namespace ts { writeComment: (text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void) { if (comments && comments.length > 0) { if (leadingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } let emitInterveningSeparator = false; for (const comment of comments) { if (emitInterveningSeparator) { - writer.write(" "); + writer.writeSpace(" "); emitInterveningSeparator = false; } @@ -3498,7 +3599,7 @@ namespace ts { } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -3632,7 +3733,7 @@ namespace ts { } else { // Single line comment of style //.... - writer.write(text.substring(commentPos, commentEnd)); + writer.writeComment(text.substring(commentPos, commentEnd)); } } @@ -3641,14 +3742,14 @@ namespace ts { const currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { // trimmed forward and ending spaces text - writer.write(currentLineText); + writer.writeComment(currentLineText); if (end !== commentEnd) { writer.writeLine(); } } else { // Empty string - make sure we write empty line - writer.writeLiteral(newLine); + writer.rawWrite(newLine); } } @@ -3743,11 +3844,20 @@ namespace ts { /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ export function tryGetClassExtendingExpressionWithTypeArguments(node: Node): ClassLikeDeclaration | undefined { - if (isExpressionWithTypeArguments(node) && - node.parent.token === SyntaxKind.ExtendsKeyword && - isClassLike(node.parent.parent)) { - return node.parent.parent; - } + const cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; + } + + export interface ClassImplementingOrExtendingExpressionWithTypeArguments { + readonly class: ClassLikeDeclaration; + readonly isImplements: boolean; + } + export function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node: Node): ClassImplementingOrExtendingExpressionWithTypeArguments | undefined { + return isExpressionWithTypeArguments(node) + && isHeritageClause(node.parent) + && isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === SyntaxKind.ImplementsKeyword } + : undefined; } export function isAssignmentExpression(node: Node, excludeCompoundAssignment: true): node is AssignmentExpression; @@ -3774,15 +3884,6 @@ namespace ts { return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } - export function isExpressionWithTypeArgumentsInClassImplementsClause(node: Node): node is ExpressionWithTypeArguments { - return node.kind === SyntaxKind.ExpressionWithTypeArguments - && isEntityNameExpression((node as ExpressionWithTypeArguments).expression) - && node.parent - && (node.parent).token === SyntaxKind.ImplementsKeyword - && node.parent.parent - && isClassLike(node.parent.parent); - } - export function isEntityNameExpression(node: Node): node is EntityNameExpression { return node.kind === SyntaxKind.Identifier || isPropertyAccessEntityNameExpression(node); } @@ -3819,8 +3920,8 @@ namespace ts { } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - export function tryExtractTypeScriptExtension(fileName: string): string | undefined { - return find(supportedTypescriptExtensionsForExtractExtension, extension => fileExtensionIs(fileName, extension)); + export function tryExtractTSExtension(fileName: string): string | undefined { + return find(supportedTSExtensionsForExtractExtension, extension => fileExtensionIs(fileName, extension)); } /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences @@ -3974,6 +4075,27 @@ namespace ts { return getStringFromExpandedCharCodes(expandedCharCodes); } + export function readJson(path: string, host: { readFile(fileName: string): string | undefined }): object { + try { + const jsonText = host.readFile(path); + if (!jsonText) return {}; + const result = parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + + export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean }): boolean { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + const carriageReturnLineFeed = "\r\n"; const lineFeed = "\n"; export function getNewLineCharacter(options: CompilerOptions | PrinterOptions, getNewLine?: () => string): string { @@ -4309,7 +4431,7 @@ namespace ts { /** * clears already present map by calling onDeleteExistingValue callback before deleting that key/value */ - export function clearMap(map: Map, onDeleteValue: (valueInMap: T, key: string) => void) { + export function clearMap(map: { forEach: Map["forEach"]; clear: Map["clear"]; }, onDeleteValue: (valueInMap: T, key: string) => void) { // Remove all map.forEach(onDeleteValue); map.clear(); @@ -4443,6 +4565,35 @@ namespace ts { export function isObjectTypeDeclaration(node: Node): node is ObjectTypeDeclaration { return isClassLike(node) || isInterfaceDeclaration(node) || isTypeLiteralNode(node); } + + export function isTypeNodeKind(kind: SyntaxKind) { + return (kind >= SyntaxKind.FirstTypeNode && kind <= SyntaxKind.LastTypeNode) + || kind === SyntaxKind.AnyKeyword + || kind === SyntaxKind.UnknownKeyword + || kind === SyntaxKind.NumberKeyword + || kind === SyntaxKind.BigIntKeyword + || kind === SyntaxKind.ObjectKeyword + || kind === SyntaxKind.BooleanKeyword + || kind === SyntaxKind.StringKeyword + || kind === SyntaxKind.SymbolKeyword + || kind === SyntaxKind.ThisKeyword + || kind === SyntaxKind.VoidKeyword + || kind === SyntaxKind.UndefinedKeyword + || kind === SyntaxKind.NullKeyword + || kind === SyntaxKind.NeverKeyword + || kind === SyntaxKind.ExpressionWithTypeArguments + || kind === SyntaxKind.JSDocAllType + || kind === SyntaxKind.JSDocUnknownType + || kind === SyntaxKind.JSDocNullableType + || kind === SyntaxKind.JSDocNonNullableType + || kind === SyntaxKind.JSDocOptionalType + || kind === SyntaxKind.JSDocFunctionType + || kind === SyntaxKind.JSDocVariadicType; + } + + export function isAccessExpression(node: Node): node is AccessExpression { + return node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.ElementAccessExpression; + } } namespace ts { @@ -4964,14 +5115,19 @@ namespace ts { } break; } + case SyntaxKind.CallExpression: case SyntaxKind.BinaryExpression: { - const expr = declaration as BinaryExpression; - switch (getSpecialPropertyAssignmentKind(expr)) { - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.PrototypeProperty: - return (expr.left as PropertyAccessExpression).name; + const expr = declaration as BinaryExpression | CallExpression; + switch (getAssignmentDeclarationKind(expr)) { + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.ThisProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.PrototypeProperty: + return ((expr as BinaryExpression).left as PropertyAccessExpression).name; + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: + return (expr as BindableObjectDefinePropertyCall).arguments[1]; default: return undefined; } @@ -5182,12 +5338,12 @@ namespace ts { } if (isJSDocTypeAlias(node)) { Debug.assert(node.parent.kind === SyntaxKind.JSDocComment); - return flatMap(node.parent.tags, tag => isJSDocTemplateTag(tag) ? tag.typeParameters : undefined) as ReadonlyArray; + return flatMap(node.parent.tags, tag => isJSDocTemplateTag(tag) ? tag.typeParameters : undefined); } if (node.typeParameters) { return node.typeParameters; } - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { const decls = getJSDocTypeParameterDeclarations(node); if (decls.length) { return decls; @@ -5215,6 +5371,10 @@ namespace ts { return node.kind === SyntaxKind.NumericLiteral; } + export function isBigIntLiteral(node: Node): node is BigIntLiteral { + return node.kind === SyntaxKind.BigIntLiteral; + } + export function isStringLiteral(node: Node): node is StringLiteral { return node.kind === SyntaxKind.StringLiteral; } @@ -5979,6 +6139,10 @@ namespace ts { || kind === SyntaxKind.TemplateTail; } + export function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier { + return isImportSpecifier(node) || isExportSpecifier(node); + } + export function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken { return node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind); } @@ -6153,30 +6317,6 @@ namespace ts { // Type - function isTypeNodeKind(kind: SyntaxKind) { - return (kind >= SyntaxKind.FirstTypeNode && kind <= SyntaxKind.LastTypeNode) - || kind === SyntaxKind.AnyKeyword - || kind === SyntaxKind.UnknownKeyword - || kind === SyntaxKind.NumberKeyword - || kind === SyntaxKind.ObjectKeyword - || kind === SyntaxKind.BooleanKeyword - || kind === SyntaxKind.StringKeyword - || kind === SyntaxKind.SymbolKeyword - || kind === SyntaxKind.ThisKeyword - || kind === SyntaxKind.VoidKeyword - || kind === SyntaxKind.UndefinedKeyword - || kind === SyntaxKind.NullKeyword - || kind === SyntaxKind.NeverKeyword - || kind === SyntaxKind.ExpressionWithTypeArguments - || kind === SyntaxKind.JSDocAllType - || kind === SyntaxKind.JSDocUnknownType - || kind === SyntaxKind.JSDocNullableType - || kind === SyntaxKind.JSDocNonNullableType - || kind === SyntaxKind.JSDocOptionalType - || kind === SyntaxKind.JSDocFunctionType - || kind === SyntaxKind.JSDocVariadicType; - } - /** * Node test that determines whether a node is a valid type node. * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* @@ -6340,6 +6480,7 @@ namespace ts { case SyntaxKind.Identifier: case SyntaxKind.RegularExpressionLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TemplateExpression: @@ -6593,7 +6734,7 @@ namespace ts { /* @internal */ export function isDeclaration(node: Node): node is NamedDeclaration { if (node.kind === SyntaxKind.TypeParameter) { - return node.parent.kind !== SyntaxKind.JSDocTemplateTag || isInJavaScriptFile(node); + return node.parent.kind !== SyntaxKind.JSDocTemplateTag || isInJSFile(node); } return isDeclarationKind(node.kind); @@ -6703,7 +6844,7 @@ namespace ts { // TODO: determine what this does before making it public. /* @internal */ - export function isJSDocTag(node: Node): boolean { + export function isJSDocTag(node: Node): node is JSDocTag { return node.kind >= SyntaxKind.FirstJSDocTagNode && node.kind <= SyntaxKind.LastJSDocTagNode; } @@ -6782,7 +6923,6 @@ namespace ts { /* @internal */ namespace ts { - /** @internal */ export function isNamedImportsOrExports(node: Node): node is NamedImportsOrExports { return node.kind === SyntaxKind.NamedImports || node.kind === SyntaxKind.NamedExports; } @@ -6846,9 +6986,8 @@ namespace ts { getSourceMapSourceConstructor: () => SourceMapSource, }; - /* @internal */ - export function formatStringFromArgs(text: string, args: ArrayLike, baseIndex = 0): string { - return text.replace(/{(\d+)}/g, (_match, index: string) => Debug.assertDefined(args[+index + baseIndex])); + export function formatStringFromArgs(text: string, args: ArrayLike, baseIndex = 0): string { + return text.replace(/{(\d+)}/g, (_match, index: string) => "" + Debug.assertDefined(args[+index + baseIndex])); } export let localizedDiagnosticMessages: MapLike | undefined; @@ -6857,7 +6996,6 @@ namespace ts { return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message; } - /* @internal */ export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: (string | number | undefined)[]): DiagnosticWithLocation; export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage): DiagnosticWithLocation { Debug.assertGreaterThanOrEqual(start, 0); @@ -6886,7 +7024,7 @@ namespace ts { }; } - /* @internal */ + export function formatMessage(_dummy: any, message: DiagnosticMessage, ...args: (string | number | undefined)[]): string; export function formatMessage(_dummy: any, message: DiagnosticMessage): string { let text = getLocaleSpecificMessage(message); @@ -6897,7 +7035,6 @@ namespace ts { return text; } - /* @internal */ export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: (string | number | undefined)[]): Diagnostic; export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic { let text = getLocaleSpecificMessage(message); @@ -6918,7 +7055,6 @@ namespace ts { }; } - /* @internal */ export function createCompilerDiagnosticFromMessageChain(chain: DiagnosticMessageChain): Diagnostic { return { file: undefined, @@ -6931,8 +7067,7 @@ namespace ts { }; } - /* @internal */ - export function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage, ...args: (string | undefined)[]): DiagnosticMessageChain; + export function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage, ...args: (string | number | undefined)[]): DiagnosticMessageChain; export function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage): DiagnosticMessageChain { let text = getLocaleSpecificMessage(message); @@ -6963,14 +7098,12 @@ namespace ts { return diagnostic.file ? diagnostic.file.path : undefined; } - /* @internal */ export function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): Comparison { return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || Comparison.EqualTo; } - /* @internal */ export function compareDiagnosticsSkipRelatedInformation(d1: Diagnostic, d2: Diagnostic): Comparison { return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || @@ -7065,28 +7198,27 @@ namespace ts { const moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ModuleKind.None && moduleKind < ModuleKind.ES2015 - : moduleKind === ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ModuleKind.System; } export function getEmitDeclarations(compilerOptions: CompilerOptions): boolean { return !!(compilerOptions.declaration || compilerOptions.composite); } - export type StrictOptionName = "noImplicitAny" | "noImplicitThis" | "strictNullChecks" | "strictFunctionTypes" | "strictPropertyInitialization" | "alwaysStrict"; + export type StrictOptionName = "noImplicitAny" | "noImplicitThis" | "strictNullChecks" | "strictFunctionTypes" | "strictBindCallApply" | "strictPropertyInitialization" | "alwaysStrict"; export function getStrictOptionValue(compilerOptions: CompilerOptions, flag: StrictOptionName): boolean { return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } - export function compilerOptionsAffectSemanticDiagnostics(newOptions: CompilerOptions, oldOptions: CompilerOptions) { - if (oldOptions === newOptions) { - return false; - } + export function compilerOptionsAffectSemanticDiagnostics(newOptions: CompilerOptions, oldOptions: CompilerOptions): boolean { + return oldOptions !== newOptions && + semanticDiagnosticsOptionDeclarations.some(option => !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option))); + } - return optionDeclarations.some(option => (!!option.strictFlag && getStrictOptionValue(newOptions, option.name as StrictOptionName) !== getStrictOptionValue(oldOptions, option.name as StrictOptionName)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name])); + export function getCompilerOptionValue(options: CompilerOptions, option: CommandLineOption): unknown { + return option.strictFlag ? getStrictOptionValue(options, option.name as StrictOptionName) : options[option.name]; } export function hasZeroOrOneAsteriskCharacter(str: string): boolean { @@ -7309,7 +7441,6 @@ namespace ts { return rootLength > 0 && rootLength === path.length; } - /* @internal */ export function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -7561,16 +7692,38 @@ namespace ts { return path; } + // check path for these segments: '', '.'. '..' + const relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a: string, b: string, componentComparer: (a: string, b: string) => Comparison) { if (a === b) return Comparison.EqualTo; if (a === undefined) return Comparison.LessThan; if (b === undefined) return Comparison.GreaterThan; + + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + const aRoot = a.substring(0, getRootLength(a)); + const bRoot = b.substring(0, getRootLength(b)); + const result = compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== Comparison.EqualTo) { + return result; + } + + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + const aRest = a.substring(aRoot.length); + const bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. const aComponents = reducePathComponents(getPathComponents(a)); const bComponents = reducePathComponents(getPathComponents(b)); const sharedLength = Math.min(aComponents.length, bComponents.length); - for (let i = 0; i < sharedLength; i++) { - const stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer; - const result = stringComparer(aComponents[i], bComponents[i]); + for (let i = 1; i < sharedLength; i++) { + const result = componentComparer(aComponents[i], bComponents[i]); if (result !== Comparison.EqualTo) { return result; } @@ -7651,6 +7804,15 @@ namespace ts { // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. const reservedCharacterPattern = /[^\w\s\/]/g; + + export function regExpEscape(text: string) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + + function escapeRegExpCharacter(match: string) { + return "\\" + match; + } + const wildcardCharCodes = [CharacterCodes.asterisk, CharacterCodes.question]; export function hasExtension(fileName: string): boolean { @@ -7717,7 +7879,7 @@ namespace ts { return `^(${pattern})${terminator}`; } - function getRegularExpressionsForWildcards(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string[] | undefined { + export function getRegularExpressionsForWildcards(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): ReadonlyArray | undefined { if (specs === undefined || specs.length === 0) { return undefined; } @@ -7981,48 +8143,60 @@ namespace ts { /** * List of supported extensions in order of file resolution precedence. */ - export const supportedTypeScriptExtensions: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts]; + export const supportedTSExtensions: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts]; + export const supportedTSExtensionsWithJson: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts, Extension.Json]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - export const supportedTypescriptExtensionsForExtractExtension: ReadonlyArray = [Extension.Dts, Extension.Ts, Extension.Tsx]; - export const supportedJavascriptExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx]; - export const supportedJavaScriptAndJsonExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx, Extension.Json]; - const allSupportedExtensions: ReadonlyArray = [...supportedTypeScriptExtensions, ...supportedJavascriptExtensions]; + export const supportedTSExtensionsForExtractExtension: ReadonlyArray = [Extension.Dts, Extension.Ts, Extension.Tsx]; + export const supportedJSExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx]; + export const supportedJSAndJsonExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx, Extension.Json]; + const allSupportedExtensions: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions]; + const allSupportedExtensionsWithJson: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions, Extension.Json]; + export function getSupportedExtensions(options?: CompilerOptions): ReadonlyArray; + export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray; export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray { const needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : supportedTSExtensions; } const extensions = [ - ...needJsExtensions ? allSupportedExtensions : supportedTypeScriptExtensions, - ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined) + ...needJsExtensions ? allSupportedExtensions : supportedTSExtensions, + ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined) ]; return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } - function isJavaScriptLike(scriptKind: ScriptKind | undefined): boolean { + export function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options: CompilerOptions | undefined, supportedExtensions: ReadonlyArray): ReadonlyArray { + if (!options || !options.resolveJsonModule) { return supportedExtensions; } + if (supportedExtensions === allSupportedExtensions) { return allSupportedExtensionsWithJson; } + if (supportedExtensions === supportedTSExtensions) { return supportedTSExtensionsWithJson; } + return [...supportedExtensions, Extension.Json]; + } + + function isJSLike(scriptKind: ScriptKind | undefined): boolean { return scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSX; } - export function hasJavaScriptFileExtension(fileName: string): boolean { - return some(supportedJavascriptExtensions, extension => fileExtensionIs(fileName, extension)); + export function hasJSFileExtension(fileName: string): boolean { + return some(supportedJSExtensions, extension => fileExtensionIs(fileName, extension)); } - export function hasJavaScriptOrJsonFileExtension(fileName: string): boolean { - return supportedJavaScriptAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext)); + export function hasJSOrJsonFileExtension(fileName: string): boolean { + return supportedJSAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext)); } - export function hasTypeScriptFileExtension(fileName: string): boolean { - return some(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension)); + export function hasTSFileExtension(fileName: string): boolean { + return some(supportedTSExtensions, extension => fileExtensionIs(fileName, extension)); } export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: ReadonlyArray) { if (!fileName) { return false; } - for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) { + const supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (const extension of getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions)) { if (fileExtensionIs(fileName, extension)) { return true; } @@ -8152,12 +8326,12 @@ namespace ts { } /** True if an extension is one of the supported TypeScript extensions. */ - export function extensionIsTypeScript(ext: Extension): boolean { + export function extensionIsTS(ext: Extension): boolean { return ext === Extension.Ts || ext === Extension.Tsx || ext === Extension.Dts; } - export function resolutionExtensionIsTypeScriptOrJson(ext: Extension) { - return extensionIsTypeScript(ext) || ext === Extension.Json; + export function resolutionExtensionIsTSOrJson(ext: Extension) { + return extensionIsTS(ext) || ext === Extension.Json; } /** @@ -8345,4 +8519,95 @@ namespace ts { // '/// ' directive. return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } + + export function isJsonEqual(a: unknown, b: unknown): boolean { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && equalOwnProperties(a as MapLike, b as MapLike, isJsonEqual); + } + + export function getOrUpdate(map: Map, key: string, getDefault: () => T): T { + const got = map.get(key); + if (got === undefined) { + const value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + export function parsePseudoBigInt(stringValue: string): string { + let log2Base: number; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case CharacterCodes.b: + case CharacterCodes.B: // 0b or 0B + log2Base = 1; + break; + case CharacterCodes.o: + case CharacterCodes.O: // 0o or 0O + log2Base = 3; + break; + case CharacterCodes.x: + case CharacterCodes.X: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + const nIndex = stringValue.length - 1; + // Skip leading 0s + let nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === CharacterCodes._0) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + + // Omit leading "0b", "0o", or "0x", and trailing "n" + const startIndex = 2, endIndex = stringValue.length - 1; + const bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + const segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (let i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + const segment = bitOffset >>> 4; + const digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + const digit = digitChar <= CharacterCodes._9 + ? digitChar - CharacterCodes._0 + : 10 + digitChar - + (digitChar <= CharacterCodes.F ? CharacterCodes.A : CharacterCodes.a); + const shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + const residual = shiftedDigit >>> 16; + if (residual) segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + let base10Value = ""; + let firstNonzeroSegment = segments.length - 1; + let segmentsRemaining = true; + while (segmentsRemaining) { + let mod10 = 0; + segmentsRemaining = false; + for (let segment = firstNonzeroSegment; segment >= 0; segment--) { + const newSegment = mod10 << 16 | segments[segment]; + const segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + + export function pseudoBigIntToString({negative, base10Value}: PseudoBigInt): string { + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } } diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 2cfb469f152..18b7c3f4a74 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -1111,6 +1111,7 @@ namespace ts { case SyntaxKind.TaggedTemplateExpression: result = reduceNode((node).tag, cbNode, result); + result = reduceNodes((node).typeArguments, cbNodes, result); result = reduceNode((node).template, cbNode, result); break; @@ -1377,6 +1378,7 @@ namespace ts { case SyntaxKind.JsxSelfClosingElement: case SyntaxKind.JsxOpeningElement: result = reduceNode((node).tagName, cbNode, result); + result = reduceNodes((node).typeArguments, cbNode, result); result = reduceNode((node).attributes, cbNode, result); break; diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index c091ad5c30c..827a3279b3b 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -43,7 +43,6 @@ namespace ts { return false; } - /** @internal */ export const screenStartingMessageCodes: number[] = [ Diagnostics.Starting_compilation_in_watch_mode.code, Diagnostics.File_change_detected_Starting_incremental_compilation.code, @@ -89,6 +88,24 @@ namespace ts { return result; } + export type ReportEmitErrorSummary = (errorCount: number) => void; + + export function getErrorCountForSummary(diagnostics: ReadonlyArray) { + return countWhere(diagnostics, diagnostic => diagnostic.category === DiagnosticCategory.Error); + } + + export function getWatchErrorSummaryDiagnosticMessage(errorCount: number) { + return errorCount === 1 ? + Diagnostics.Found_1_error_Watching_for_file_changes : + Diagnostics.Found_0_errors_Watching_for_file_changes; + } + + export function getErrorSummaryText(errorCount: number, newLine: string) { + if (errorCount === 0) return ""; + const d = createCompilerDiagnostic(errorCount === 1 ? Diagnostics.Found_1_error : Diagnostics.Found_0_errors, errorCount); + return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}`; + } + /** * Program structure needed to emit the files and report diagnostics */ @@ -101,15 +118,13 @@ namespace ts { getGlobalDiagnostics(): ReadonlyArray; getSemanticDiagnostics(): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; - emit(): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult; } - export type ReportEmitErrorSummary = (errorCount: number) => void; - /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - export function emitFilesAndReportErrors(program: ProgramToEmitFilesAndReportErrors, reportDiagnostic: DiagnosticReporter, writeFileName?: (s: string) => void, reportSummary?: ReportEmitErrorSummary) { + export function emitFilesAndReportErrors(program: ProgramToEmitFilesAndReportErrors, reportDiagnostic: DiagnosticReporter, writeFileName?: (s: string) => void, reportSummary?: ReportEmitErrorSummary, writeFile?: WriteFileCallback) { // First get and report any syntactic errors. const diagnostics = program.getConfigFileParsingDiagnostics().slice(); const configFileParsingDiagnosticsLength = diagnostics.length; @@ -128,7 +143,7 @@ namespace ts { } // Emit and report any errors we ran into. - const { emittedFiles, emitSkipped, diagnostics: emitDiagnostics } = program.emit(); + const { emittedFiles, emitSkipped, diagnostics: emitDiagnostics } = program.emit(/*targetSourceFile*/ undefined, writeFile); addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { @@ -151,7 +166,7 @@ namespace ts { } if (reportSummary) { - reportSummary(diagnostics.filter(diagnostic => diagnostic.category === DiagnosticCategory.Error).length); + reportSummary(getErrorCountForSummary(diagnostics)); } if (emitSkipped && diagnostics.length > 0) { @@ -172,30 +187,110 @@ namespace ts { const onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { onWatchStatusChange, - watchFile: system.watchFile ? ((path, callback, pollingInterval) => system.watchFile!(path, callback, pollingInterval)) : () => noopFileWatcher, - watchDirectory: system.watchDirectory ? ((path, callback, recursive) => system.watchDirectory!(path, callback, recursive)) : () => noopFileWatcher, - setTimeout: system.setTimeout ? ((callback, ms, ...args: any[]) => system.setTimeout!.call(system, callback, ms, ...args)) : noop, - clearTimeout: system.clearTimeout ? (timeoutId => system.clearTimeout!(timeoutId)) : noop + watchFile: maybeBind(system, system.watchFile) || (() => noopFileWatcher), + watchDirectory: maybeBind(system, system.watchDirectory) || (() => noopFileWatcher), + setTimeout: maybeBind(system, system.setTimeout) || noop, + clearTimeout: maybeBind(system, system.clearTimeout) || noop }; } + export const enum WatchType { + ConfigFile = "Config file", + SourceFile = "Source file", + MissingFile = "Missing file", + WildcardDirectory = "Wild card directory", + FailedLookupLocations = "Failed Lookup Locations", + TypeRoots = "Type roots" + } + + interface WatchFactory extends ts.WatchFactory { + writeLog: (s: string) => void; + } + + export function createWatchFactory(host: { trace?(s: string): void; }, options: { extendedDiagnostics?: boolean; diagnostics?: boolean; }) { + const watchLogLevel = host.trace ? options.extendedDiagnostics ? WatchLogLevel.Verbose : options.diagnostics ? WatchLogLevel.TriggerOnly : WatchLogLevel.None : WatchLogLevel.None; + const writeLog: (s: string) => void = watchLogLevel !== WatchLogLevel.None ? (s => host.trace!(s)) : noop; + const result = getWatchFactory(watchLogLevel, writeLog) as WatchFactory; + result.writeLog = writeLog; + return result; + } + + export function createCompilerHostFromProgramHost(host: ProgramHost, getCompilerOptions: () => CompilerOptions, directoryStructureHost: DirectoryStructureHost = host): CompilerHost { + const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const hostGetNewLine = memoize(() => host.getNewLine()); + return { + getSourceFile: (fileName, languageVersion, onError) => { + let text: string | undefined; + try { + performance.mark("beforeIORead"); + text = host.readFile(fileName, getCompilerOptions().charset); + performance.mark("afterIORead"); + performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + + return text !== undefined ? createSourceFile(fileName, text, languageVersion) : undefined; + }, + getDefaultLibLocation: maybeBind(host, host.getDefaultLibLocation), + getDefaultLibFileName: options => host.getDefaultLibFileName(options), + writeFile, + getCurrentDirectory: memoize(() => host.getCurrentDirectory()), + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, + getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames), + getNewLine: () => getNewLineCharacter(getCompilerOptions(), hostGetNewLine), + fileExists: f => host.fileExists(f), + readFile: f => host.readFile(f), + trace: maybeBind(host, host.trace), + directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: maybeBind(host, host.realpath), + getEnvironmentVariable: maybeBind(host, host.getEnvironmentVariable) || (() => ""), + createHash: maybeBind(host, host.createHash), + readDirectory: maybeBind(host, host.readDirectory), + }; + + function ensureDirectoriesExist(directoryPath: string) { + if (directoryPath.length > getRootLength(directoryPath) && !host.directoryExists!(directoryPath)) { + const parentDirectory = getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (host.createDirectory) host.createDirectory(directoryPath); + } + } + + function writeFile(fileName: string, text: string, writeByteOrderMark: boolean, onError: (message: string) => void) { + try { + performance.mark("beforeIOWrite"); + ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); + + host.writeFile!(fileName, text, writeByteOrderMark); + + performance.mark("afterIOWrite"); + performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ - function createWatchCompilerHost(system = sys, createProgram: CreateProgram | undefined, reportDiagnostic: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHost { - if (!createProgram) { - createProgram = createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram; - } - + export function createProgramHost(system: System, createProgram: CreateProgram): ProgramHost { + const getDefaultLibLocation = memoize(() => getDirectoryPath(normalizePath(system.getExecutingFilePath()))); let host: DirectoryStructureHost = system; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) - const useCaseSensitiveFileNames = () => system.useCaseSensitiveFileNames; - const writeFileName = (s: string) => system.write(s + system.newLine); - const { onWatchStatusChange, watchFile, watchDirectory, setTimeout, clearTimeout } = createWatchHost(system, reportWatchStatus); return { - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: () => system.useCaseSensitiveFileNames, getNewLine: () => system.newLine, - getCurrentDirectory: () => system.getCurrentDirectory(), + getCurrentDirectory: memoize(() => system.getCurrentDirectory()), getDefaultLibLocation, getDefaultLibFileName: options => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options)), fileExists: path => system.fileExists(path), @@ -203,41 +298,40 @@ namespace ts { directoryExists: path => system.directoryExists(path), getDirectories: path => system.getDirectories(path), readDirectory: (path, extensions, exclude, include, depth) => system.readDirectory(path, extensions, exclude, include, depth), - realpath: system.realpath && (path => system.realpath!(path)), - getEnvironmentVariable: system.getEnvironmentVariable && (name => system.getEnvironmentVariable(name)), - watchFile, - watchDirectory, - setTimeout, - clearTimeout, - trace: s => system.write(s), - onWatchStatusChange, + realpath: maybeBind(system, system.realpath), + getEnvironmentVariable: maybeBind(system, system.getEnvironmentVariable), + trace: s => system.write(s + system.newLine), createDirectory: path => system.createDirectory(path), writeFile: (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark), onCachedDirectoryStructureHostCreate: cacheHost => host = cacheHost || system, - createHash: system.createHash && (s => system.createHash!(s)), - createProgram, - afterProgramCreate: emitFilesAndReportErrorUsingBuilder + createHash: maybeBind(system, system.createHash), + createProgram }; + } - function getDefaultLibLocation() { - return getDirectoryPath(normalizePath(system.getExecutingFilePath())); - } - - function emitFilesAndReportErrorUsingBuilder(builderProgram: BuilderProgram) { + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system = sys, createProgram: CreateProgram | undefined, reportDiagnostic: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHost { + const writeFileName = (s: string) => system.write(s + system.newLine); + const result = createProgramHost(system, createProgram || createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram) as WatchCompilerHost; + copyProperties(result, createWatchHost(system, reportWatchStatus)); + result.afterProgramCreate = builderProgram => { const compilerOptions = builderProgram.getCompilerOptions(); const newLine = getNewLineCharacter(compilerOptions, () => system.newLine); - const reportSummary = (errorCount: number) => { - if (errorCount === 1) { - onWatchStatusChange!(createCompilerDiagnostic(Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions); - } - else { - onWatchStatusChange!(createCompilerDiagnostic(Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions); - } - }; - - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary); - } + emitFilesAndReportErrors( + builderProgram, + reportDiagnostic, + writeFileName, + errorCount => result.onWatchStatusChange!( + createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), + newLine, + compilerOptions + ) + ); + }; + return result; } /** @@ -263,10 +357,11 @@ namespace ts { /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - export function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions { + export function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions { const host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus) as WatchCompilerHostOfFilesAndCompilerOptions; host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } } @@ -274,7 +369,8 @@ namespace ts { namespace ts { export type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - export type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; + export type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ export interface WatchHost { /** If provided, called with Diagnostic message that informs about change in watch status */ @@ -289,19 +385,11 @@ namespace ts { /** If provided, will be used to reset existing delayed compilation */ clearTimeout?(timeoutId: any): void; } - export interface WatchCompilerHost extends WatchHost { - // TODO: GH#18217 Optional methods are frequently asserted - + export interface ProgramHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; - /** If provided, callback to invoke after every new program creation */ - afterProgramCreate?(program: T): void; - - // Only for testing - /*@internal*/ - maxNumberOfFilesToIterateForInvalidation?: number; // Sub set of compiler host methods to read and generate new program useCaseSensitiveFileNames(): boolean; @@ -337,20 +425,29 @@ namespace ts { getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } - /** Internal interface used to wire emit through same host */ + /*@internal*/ - export interface WatchCompilerHost { + export interface ProgramHost { // TODO: GH#18217 Optional methods are frequently asserted createDirectory?(path: string): void; writeFile?(path: string, data: string, writeByteOrderMark?: boolean): void; onCachedDirectoryStructureHostCreate?(host: CachedDirectoryStructureHost): void; } + export interface WatchCompilerHost extends ProgramHost, WatchHost { + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + + // Only for testing + /*@internal*/ + maxNumberOfFilesToIterateForInvalidation?: number; + } + /** * Host to create watch with root files and options */ @@ -360,6 +457,9 @@ namespace ts { /** Compiler options */ options: CompilerOptions; + + /** Project References */ + projectReferences?: ReadonlyArray; } /** @@ -413,11 +513,11 @@ namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - export function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; export function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; - export function createWatchCompilerHost(rootFilesOrConfigFileName: string | string[], options: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions | WatchCompilerHostOfConfigFile { + export function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; + export function createWatchCompilerHost(rootFilesOrConfigFileName: string | string[], options: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions | WatchCompilerHostOfConfigFile { if (isArray(rootFilesOrConfigFileName)) { - return createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options!, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options!, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -460,12 +560,11 @@ namespace ts { const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); const currentDirectory = host.getCurrentDirectory(); - const getCurrentDirectory = () => currentDirectory; - const readFile: (path: string, encoding?: string) => string | undefined = (path, encoding) => host.readFile(path, encoding); const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, createProgram } = host; - let { rootFiles: rootFileNames, options: compilerOptions } = host; + let { rootFiles: rootFileNames, options: compilerOptions, projectReferences } = host; let configFileSpecs: ConfigFileSpecs; - let configFileParsingDiagnostics: ReadonlyArray | undefined; + let configFileParsingDiagnostics: Diagnostic[] | undefined; + let canConfigFileJsonReportNoInputFiles = false; let hasChangedConfigFileParsingErrors = false; const cachedDirectoryStructureHost = configFileName === undefined ? undefined : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); @@ -473,14 +572,7 @@ namespace ts { host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } const directoryStructureHost: DirectoryStructureHost = cachedDirectoryStructureHost || host; - const parseConfigFileHost: ParseConfigFileHost = { - useCaseSensitiveFileNames, - readDirectory: (path, extensions, exclude, include, depth) => directoryStructureHost.readDirectory!(path, extensions, exclude, include, depth), - fileExists: path => host.fileExists(path), - readFile, - getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic - }; + const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host, directoryStructureHost); // From tsc we want to get already parsed result and hence check for rootFileNames let newLine = updateNewLine(); @@ -496,54 +588,37 @@ namespace ts { newLine = updateNewLine(); } - const trace = host.trace && ((s: string) => { host.trace!(s + newLine); }); - const watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? WatchLogLevel.Verbose : - compilerOptions.diagnostics ? WatchLogLevel.TriggerOnly : WatchLogLevel.None : WatchLogLevel.None; - const writeLog: (s: string) => void = watchLogLevel !== WatchLogLevel.None ? trace! : noop; // TODO: GH#18217 - const { watchFile, watchFilePath, watchDirectory } = getWatchFactory(watchLogLevel, writeLog); - + const { watchFile, watchFilePath, watchDirectory, writeLog } = createWatchFactory(host, compilerOptions); const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, PollingInterval.High, "Config file"); + watchFile(host, configFileName, scheduleProgramReload, PollingInterval.High, WatchType.ConfigFile); } - const compilerHost: CompilerHost & ResolutionCacheHost = { - // Members for CompilerHost - getSourceFile: (fileName, languageVersion, onError?, shouldCreateNewSourceFile?) => getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile), - getSourceFileByPath: getVersionedSourceFileByPath, - getDefaultLibLocation: host.getDefaultLibLocation && (() => host.getDefaultLibLocation!()), - getDefaultLibFileName: options => host.getDefaultLibFileName(options), - writeFile, - getCurrentDirectory, - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, - getCanonicalFileName, - getNewLine: () => newLine, - fileExists, - readFile, - trace, - directoryExists: directoryStructureHost.directoryExists && (path => directoryStructureHost.directoryExists!(path)), - getDirectories: (directoryStructureHost.getDirectories && ((path: string) => directoryStructureHost.getDirectories!(path)))!, // TODO: GH#18217 - realpath: host.realpath && (s => host.realpath!(s)), - getEnvironmentVariable: host.getEnvironmentVariable ? (name => host.getEnvironmentVariable!(name)) : (() => ""), - onReleaseOldSourceFile, - createHash: host.createHash && (data => host.createHash!(data)), - // Members for ResolutionCacheHost - toPath, - getCompilationSettings: () => compilerOptions, - watchDirectoryOfFailedLookupLocation: (dir, cb, flags) => watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"), - watchTypeRootsDirectory: (dir, cb, flags) => watchDirectory(host, dir, cb, flags, "Type roots"), - getCachedDirectoryStructureHost: () => cachedDirectoryStructureHost, - onInvalidatedResolution: scheduleProgramUpdate, - onChangedAutomaticTypeDirectiveNames: () => { - hasChangedAutomaticTypeDirectiveNames = true; - scheduleProgramUpdate(); - }, - maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, - getCurrentProgram, - writeLog + const compilerHost = createCompilerHostFromProgramHost(host, () => compilerOptions, directoryStructureHost) as CompilerHost & ResolutionCacheHost; + // Members for CompilerHost + const getNewSourceFile = compilerHost.getSourceFile; + compilerHost.getSourceFile = (fileName, ...args) => getVersionedSourceFileByPath(fileName, toPath(fileName), ...args); + compilerHost.getSourceFileByPath = getVersionedSourceFileByPath; + compilerHost.getNewLine = () => newLine; + compilerHost.fileExists = fileExists; + compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + // Members for ResolutionCacheHost + compilerHost.toPath = toPath; + compilerHost.getCompilationSettings = () => compilerOptions; + compilerHost.watchDirectoryOfFailedLookupLocation = (dir, cb, flags) => watchDirectory(host, dir, cb, flags, WatchType.FailedLookupLocations); + compilerHost.watchTypeRootsDirectory = (dir, cb, flags) => watchDirectory(host, dir, cb, flags, WatchType.TypeRoots); + compilerHost.getCachedDirectoryStructureHost = () => cachedDirectoryStructureHost; + compilerHost.onInvalidatedResolution = scheduleProgramUpdate; + compilerHost.onChangedAutomaticTypeDirectiveNames = () => { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); }; + compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation; + compilerHost.getCurrentProgram = getCurrentProgram; + compilerHost.writeLog = writeLog; + // Cache for the module resolution const resolutionCache = createResolutionCache(compilerHost, configFileName ? getDirectoryPath(getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -552,11 +627,11 @@ namespace ts { ); // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names compilerHost.resolveModuleNames = host.resolveModuleNames ? - ((moduleNames, containingFile, reusedNames) => host.resolveModuleNames!(moduleNames, containingFile, reusedNames)) : - ((moduleNames, containingFile, reusedNames) => resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames)); + ((moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(moduleNames, containingFile, reusedNames, redirectedReference)) : + ((moduleNames, containingFile, reusedNames, redirectedReference) => resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference)); compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? - ((typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives!(typeDirectiveNames, containingFile)) : - ((typeDirectiveNames, containingFile) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile)); + ((typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(typeDirectiveNames, containingFile, redirectedReference)) : + ((typeDirectiveNames, containingFile, redirectedReference) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference)); const userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; synchronizeProgram(); @@ -589,9 +664,9 @@ namespace ts { // All resolutions are invalid if user provided resolutions const hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -608,11 +683,9 @@ namespace ts { function createNewProgram(program: Program, hasInvalidatedResolution: HasInvalidatedResolution) { // Compile the program - if (watchLogLevel !== WatchLogLevel.None) { - writeLog("CreatingProgramWith::"); - writeLog(` roots: ${JSON.stringify(rootFileNames)}`); - writeLog(` options: ${JSON.stringify(compilerOptions)}`); - } + writeLog("CreatingProgramWith::"); + writeLog(` roots: ${JSON.stringify(rootFileNames)}`); + writeLog(` options: ${JSON.stringify(compilerOptions)}`); const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; @@ -620,7 +693,7 @@ namespace ts { resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches @@ -686,7 +759,7 @@ namespace ts { // Create new source file if requested or the versions dont match if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { - const sourceFile = getNewSourceFile(); + const sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { if (shouldCreateNewSourceFile) { hostSourceFile.version++; @@ -697,7 +770,7 @@ namespace ts { (hostSourceFile as FilePresentOnHost).sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!(hostSourceFile as FilePresentOnHost).fileWatcher) { - (hostSourceFile as FilePresentOnHost).fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, "Source file"); + (hostSourceFile as FilePresentOnHost).fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, WatchType.SourceFile); } } else { @@ -711,7 +784,7 @@ namespace ts { else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - const fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, "Source file"); + const fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, WatchType.SourceFile); sourceFilesCache.set(path, { sourceFile, version: initialVersion, fileWatcher }); } else { @@ -721,23 +794,6 @@ namespace ts { return sourceFile; } return hostSourceFile.sourceFile; - - function getNewSourceFile() { - let text: string | undefined; - try { - performance.mark("beforeIORead"); - text = host.readFile(fileName, compilerOptions.charset); - performance.mark("afterIORead"); - performance.measure("I/O Read", "beforeIORead", "afterIORead"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - - return text !== undefined ? createSourceFile(fileName, text, languageVersion) : undefined; - } } function nextSourceFileVersion(path: Path) { @@ -758,8 +814,8 @@ namespace ts { return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); } - function onReleaseOldSourceFile(oldSourceFile: SourceFile, _oldOptions: CompilerOptions) { - const hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + function onReleaseOldSourceFile(oldSourceFile: SourceFile, _oldOptions: CompilerOptions, hasSourceFileByPath: boolean) { + const hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); // If this is the source file thats in the cache and new program doesnt need it, // remove the cached entry. // Note we arent deleting entry if file became missing in new program or @@ -773,8 +829,10 @@ namespace ts { if ((hostSourceFileInfo as FilePresentOnHost).fileWatcher) { (hostSourceFileInfo as FilePresentOnHost).fileWatcher.close(); } - sourceFilesCache.delete(oldSourceFile.path); - resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } } } } @@ -824,12 +882,7 @@ namespace ts { function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); const result = getFileNamesFromConfigSpecs(configFileSpecs, getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = filter(configFileParsingDiagnostics, error => !isErrorNoInputFiles(error)); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !some(configFileParsingDiagnostics, isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics!.concat(getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics!, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -861,7 +914,9 @@ namespace ts { rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs!; // TODO: GH#18217 - configFileParsingDiagnostics = getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } @@ -872,6 +927,7 @@ namespace ts { if (eventKind === FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { resolutionCache.invalidateResolutionOfFile(path); } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program @@ -885,7 +941,7 @@ namespace ts { } function watchMissingFilePath(missingFilePath: Path) { - return watchFilePath(host, missingFilePath, onMissingFileChange, PollingInterval.Medium, missingFilePath, "Missing file"); + return watchFilePath(host, missingFilePath, onMissingFileChange, PollingInterval.Medium, missingFilePath, WatchType.MissingFile); } function onMissingFileChange(fileName: string, eventKind: FileWatcherEventKind, missingFilePath: Path) { @@ -931,6 +987,8 @@ namespace ts { } nextSourceFileVersion(fileOrDirectoryPath); + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return; + // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list if (fileOrDirectoryPath !== directory && hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { @@ -947,33 +1005,8 @@ namespace ts { } }, flags, - "Wild card directories" + WatchType.WildcardDirectory ); } - - function ensureDirectoriesExist(directoryPath: string) { - if (directoryPath.length > getRootLength(directoryPath) && !host.directoryExists!(directoryPath)) { - const parentDirectory = getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - host.createDirectory!(directoryPath); - } - } - - function writeFile(fileName: string, text: string, writeByteOrderMark: boolean, onError: (message: string) => void) { - try { - performance.mark("beforeIOWrite"); - ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); - - host.writeFile!(fileName, text, writeByteOrderMark); - - performance.mark("afterIOWrite"); - performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } } } diff --git a/src/compiler/watchUtilities.ts b/src/compiler/watchUtilities.ts index 8fa04e52da3..9bf242e07e8 100644 --- a/src/compiler/watchUtilities.ts +++ b/src/compiler/watchUtilities.ts @@ -343,10 +343,10 @@ namespace ts { export interface WatchDirectoryHost { watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; } - export type WatchFile = (host: WatchFileHost, file: string, callback: FileWatcherCallback, pollingInterval: PollingInterval, detailInfo1?: X, detailInfo2?: Y) => FileWatcher; + export type WatchFile = (host: WatchFileHost, file: string, callback: FileWatcherCallback, pollingInterval: PollingInterval, detailInfo1: X, detailInfo2?: Y) => FileWatcher; export type FilePathWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind, filePath: Path) => void; - export type WatchFilePath = (host: WatchFileHost, file: string, callback: FilePathWatcherCallback, pollingInterval: PollingInterval, path: Path, detailInfo1?: X, detailInfo2?: Y) => FileWatcher; - export type WatchDirectory = (host: WatchDirectoryHost, directory: string, callback: DirectoryWatcherCallback, flags: WatchDirectoryFlags, detailInfo1?: X, detailInfo2?: Y) => FileWatcher; + export type WatchFilePath = (host: WatchFileHost, file: string, callback: FilePathWatcherCallback, pollingInterval: PollingInterval, path: Path, detailInfo1: X, detailInfo2?: Y) => FileWatcher; + export type WatchDirectory = (host: WatchDirectoryHost, directory: string, callback: DirectoryWatcherCallback, flags: WatchDirectoryFlags, detailInfo1: X, detailInfo2?: Y) => FileWatcher; export interface WatchFactory { watchFile: WatchFile; @@ -444,7 +444,7 @@ namespace ts { } function getWatchInfo(file: string, flags: T, detailInfo1: X, detailInfo2: Y | undefined, getDetailWatchInfo: GetDetailWatchInfo | undefined) { - return `WatchInfo: ${file} ${flags} ${getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1}`; + return `WatchInfo: ${file} ${flags} ${getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; } export function closeFileWatcherOf(objWithWatcher: T) { diff --git a/src/harness/client.ts b/src/harness/client.ts index ebe97aea070..1c7c0adb834 100644 --- a/src/harness/client.ts +++ b/src/harness/client.ts @@ -3,12 +3,15 @@ namespace ts.server { writeMessage(message: string): void; } - interface RenameEntry extends RenameInfo { - fileName: string; - position: number; - locations: RenameLocation[]; - findInStrings: boolean; - findInComments: boolean; + interface RenameEntry { + readonly renameInfo: RenameInfo; + readonly inputs: { + readonly fileName: string; + readonly position: number; + readonly findInStrings: boolean; + readonly findInComments: boolean; + }; + readonly locations: RenameLocation[]; } /* @internal */ @@ -34,7 +37,7 @@ namespace ts.server { private sequence = 0; private lineMaps: Map = createMap(); private messages: string[] = []; - private lastRenameEntry: RenameEntry; + private lastRenameEntry: RenameEntry | undefined; constructor(private host: SessionClientHost) { } @@ -381,7 +384,8 @@ namespace ts.server { return notImplemented(); } - getRenameInfo(fileName: string, position: number, findInStrings?: boolean, findInComments?: boolean): RenameInfo { + getRenameInfo(fileName: string, position: number, _options?: RenameInfoOptions, findInStrings?: boolean, findInComments?: boolean): RenameInfo { + // Not passing along 'options' because server should already have those from the 'configure' command const args: protocol.RenameRequestArgs = { ...this.createFileLocationRequestArgs(fileName, position), findInStrings, findInComments }; const request = this.processRequest(CommandNames.Rename, args); @@ -390,37 +394,45 @@ namespace ts.server { const locations: RenameLocation[] = []; for (const entry of body.locs) { const fileName = entry.file; - for (const loc of entry.locs) { - locations.push({ textSpan: this.decodeSpan(loc, fileName), fileName }); + for (const { start, end, ...prefixSuffixText } of entry.locs) { + locations.push({ textSpan: this.decodeSpan({ start, end }, fileName), fileName, ...prefixSuffixText }); } } - return this.lastRenameEntry = { - canRename: body.info.canRename, - displayName: body.info.displayName, - fullDisplayName: body.info.fullDisplayName, - kind: body.info.kind, - kindModifiers: body.info.kindModifiers, - localizedErrorMessage: body.info.localizedErrorMessage, - triggerSpan: createTextSpanFromBounds(position, position), - fileName, - position, - findInStrings: !!findInStrings, - findInComments: !!findInComments, + const renameInfo = body.info.canRename + ? identity({ + canRename: body.info.canRename, + fileToRename: body.info.fileToRename, + displayName: body.info.displayName, + fullDisplayName: body.info.fullDisplayName, + kind: body.info.kind, + kindModifiers: body.info.kindModifiers, + triggerSpan: createTextSpanFromBounds(position, position), + }) + : identity({ canRename: false, localizedErrorMessage: body.info.localizedErrorMessage }); + this.lastRenameEntry = { + renameInfo, + inputs: { + fileName, + position, + findInStrings: !!findInStrings, + findInComments: !!findInComments, + }, locations, }; + return renameInfo; } findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] { if (!this.lastRenameEntry || - this.lastRenameEntry.fileName !== fileName || - this.lastRenameEntry.position !== position || - this.lastRenameEntry.findInStrings !== findInStrings || - this.lastRenameEntry.findInComments !== findInComments) { - this.getRenameInfo(fileName, position, findInStrings, findInComments); + this.lastRenameEntry.inputs.fileName !== fileName || + this.lastRenameEntry.inputs.position !== position || + this.lastRenameEntry.inputs.findInStrings !== findInStrings || + this.lastRenameEntry.inputs.findInComments !== findInComments) { + this.getRenameInfo(fileName, position, { allowRenameOfImportPath: true }, findInStrings, findInComments); } - return this.lastRenameEntry.locations; + return this.lastRenameEntry!.locations; } private decodeNavigationBarItems(items: protocol.NavigationBarItem[] | undefined, fileName: string, lineMap: number[]): NavigationBarItem[] { @@ -683,6 +695,10 @@ namespace ts.server { return response.body!.map(entry => this.decodeSpan(entry, fileName)); // TODO: GH#18217 } + configurePlugin(pluginName: string, configuration: any): void { + this.processRequest("configurePlugin", { pluginName, configuration }); + } + getIndentationAtPosition(_fileName: string, _position: number, _options: EditorOptions): number { return notImplemented(); } diff --git a/src/harness/compiler.ts b/src/harness/compiler.ts index 7d41545708b..70bda90ef32 100644 --- a/src/harness/compiler.ts +++ b/src/harness/compiler.ts @@ -58,7 +58,7 @@ namespace compiler { private _inputs: documents.TextDocument[] = []; private _inputsAndOutputs: collections.SortedMap; - constructor(host: fakes.CompilerHost, options: ts.CompilerOptions, program: ts.Program | undefined, result: ts.EmitResult | undefined, diagnostics: ts.Diagnostic[]) { + constructor(host: fakes.CompilerHost, options: ts.CompilerOptions, program: ts.Program | undefined, result: ts.EmitResult | undefined, diagnostics: ReadonlyArray) { this.host = host; this.program = program; this.result = result; @@ -183,8 +183,9 @@ namespace compiler { } public getSourceMapRecord(): string | undefined { - if (this.result!.sourceMaps && this.result!.sourceMaps!.length > 0) { - return Harness.SourceMapRecorder.getSourceMapRecord(this.result!.sourceMaps!, this.program!, Array.from(this.js.values()).filter(d => !ts.fileExtensionIs(d.file, ts.Extension.Json)), Array.from(this.dts.values())); + const maps = this.result!.sourceMaps; + if (maps && maps.length > 0) { + return Harness.SourceMapRecorder.getSourceMapRecord(maps, this.program!, Array.from(this.js.values()).filter(d => !ts.fileExtensionIs(d.file, ts.Extension.Json)), Array.from(this.dts.values())); } } diff --git a/src/harness/fakes.ts b/src/harness/fakes.ts index bd9d62f90e5..e8c81617052 100644 --- a/src/harness/fakes.ts +++ b/src/harness/fakes.ts @@ -215,7 +215,7 @@ namespace fakes { private _setParentNodes: boolean; private _sourceFiles: collections.SortedMap; - private _parseConfigHost: ParseConfigHost; + private _parseConfigHost: ParseConfigHost | undefined; private _newLine: string; constructor(sys: System | vfs.FileSystem, options = ts.getDefaultCompilerOptions(), setParentNodes = false) { @@ -375,7 +375,12 @@ namespace fakes { } } - export class SolutionBuilderHost extends CompilerHost implements ts.SolutionBuilderHost { + export class SolutionBuilderHost extends CompilerHost implements ts.SolutionBuilderHost { + createProgram = ts.createAbstractBuilder; + now() { + return new Date(this.sys.vfs.time()); + } + diagnostics: ts.Diagnostic[] = []; reportDiagnostic(diagnostic: ts.Diagnostic) { diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 214e1f295ab..2b04b4bd8cd 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -158,7 +158,7 @@ namespace FourSlash { public lastKnownMarker = ""; // The file that's currently 'opened' - public activeFile: FourSlashFile; + public activeFile!: FourSlashFile; // Whether or not we should format on keystrokes public enableFormatting = true; @@ -329,29 +329,7 @@ namespace FourSlash { }); } - this.formatCodeSettings = { - baseIndentSize: 0, - indentSize: 4, - tabSize: 4, - newLineCharacter: "\n", - convertTabsToSpaces: true, - indentStyle: ts.IndentStyle.Smart, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterConstructor: false, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceAfterTypeAssertion: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - insertSpaceBeforeTypeAnnotation: false - }; + this.formatCodeSettings = ts.testFormatSettings; // Open the first file by default this.openFile(0); @@ -420,12 +398,12 @@ namespace FourSlash { } } - public goToEachRange(action: () => void) { + public goToEachRange(action: (range: Range) => void) { const ranges = this.getRanges(); assert(ranges.length); for (const range of ranges) { this.selectRange(range); - action(); + action(range); } } @@ -513,7 +491,7 @@ namespace FourSlash { ]; } - private getAllDiagnostics(): ts.Diagnostic[] { + private getAllDiagnostics(): ReadonlyArray { return ts.flatMap(this.languageServiceAdapterHost.getFilenames(), fileName => { if (!ts.isAnySupportedFileExtension(fileName)) { return []; @@ -554,7 +532,7 @@ namespace FourSlash { predicate(start!, start! + length!, startMarker.position, endMarker === undefined ? undefined : endMarker.position)); // TODO: GH#18217 } - private printErrorLog(expectErrors: boolean, errors: ts.Diagnostic[]) { + private printErrorLog(expectErrors: boolean, errors: ReadonlyArray): void { if (expectErrors) { Harness.IO.log("Expected error not found. Error list is:"); } @@ -593,7 +571,8 @@ namespace FourSlash { public verifyNoErrors() { ts.forEachKey(this.inputFiles, fileName => { if (!ts.isAnySupportedFileExtension(fileName) - || !this.getProgram().getCompilerOptions().allowJs && !ts.extensionIsTypeScript(ts.extensionFromPath(fileName))) return; + || Harness.getConfigNameFromFileName(fileName) + || !this.getProgram().getCompilerOptions().allowJs && !ts.resolutionExtensionIsTSOrJson(ts.extensionFromPath(fileName))) return; const errors = this.getDiagnostics(fileName).filter(e => e.category !== ts.DiagnosticCategory.Suggestion); if (errors.length) { this.printErrorLog(/*expectErrors*/ false, errors); @@ -621,7 +600,7 @@ namespace FourSlash { throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName); } - const evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)(); + const evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)(); // tslint:disable-line:function-constructor if (evaluation !== value) { this.raiseError(`Expected evaluation of expression "${expr}" to equal "${value}", but got "${evaluation}"`); } @@ -635,7 +614,7 @@ namespace FourSlash { this.verifyGoToX(arg0, endMarkerNames, () => this.getGoToDefinitionAndBoundSpan()); } - private getGoToDefinition(): ts.DefinitionInfo[] { + private getGoToDefinition(): ReadonlyArray { return this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; } @@ -648,7 +627,7 @@ namespace FourSlash { this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition)); } - private verifyGoToX(arg0: any, endMarkerNames: ArrayOrSingle | undefined, getDefs: () => ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { + private verifyGoToX(arg0: any, endMarkerNames: ArrayOrSingle | undefined, getDefs: () => ReadonlyArray | ts.DefinitionInfoAndBoundSpan | undefined) { if (endMarkerNames) { this.verifyGoToXPlain(arg0, endMarkerNames, getDefs); } @@ -668,7 +647,7 @@ namespace FourSlash { } } - private verifyGoToXPlain(startMarkerNames: ArrayOrSingle, endMarkerNames: ArrayOrSingle, getDefs: () => ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { + private verifyGoToXPlain(startMarkerNames: ArrayOrSingle, endMarkerNames: ArrayOrSingle, getDefs: () => ReadonlyArray | ts.DefinitionInfoAndBoundSpan | undefined) { for (const start of toArray(startMarkerNames)) { this.verifyGoToXSingle(start, endMarkerNames, getDefs); } @@ -751,97 +730,6 @@ namespace FourSlash { }); } - public verifyCompletionListCount(expectedCount: number, negative: boolean) { - if (expectedCount === 0 && negative) { - this.verifyCompletionListIsEmpty(/*negative*/ false); - return; - } - - const members = this.getCompletionListAtCaret(); - - if (members) { - const match = members.entries.length === expectedCount; - - if ((!match && !negative) || (match && negative)) { - this.raiseError("Member list count was " + members.entries.length + ". Expected " + expectedCount); - } - } - else if (expectedCount) { - this.raiseError("Member list count was 0. Expected " + expectedCount); - } - } - - public verifyCompletionListItemsCountIsGreaterThan(count: number, negative: boolean) { - const completions = this.getCompletionListAtCaret(); - const itemsCount = completions ? completions.entries.length : 0; - - if (negative) { - if (itemsCount > count) { - this.raiseError(`Expected completion list items count to not be greater than ${count}, but is actually ${itemsCount}`); - } - } - else { - if (itemsCount <= count) { - this.raiseError(`Expected completion list items count to be greater than ${count}, but is actually ${itemsCount}`); - } - } - } - - public verifyCompletionListStartsWithItemsInOrder(items: string[]): void { - if (items.length === 0) { - return; - } - - const entries = this.getCompletionListAtCaret()!.entries; - assert.isTrue(items.length <= entries.length, `Amount of expected items in completion list [ ${items.length} ] is greater than actual number of items in list [ ${entries.length} ]`); - ts.zipWith(entries, items, (entry, item) => { - assert.equal(entry.name, item, `Unexpected item in completion list`); - }); - } - - public noItemsWithSameNameButDifferentKind(): void { - const completions = this.getCompletionListAtCaret()!; - const uniqueItems = ts.createMap(); - for (const item of completions.entries) { - const uniqueItem = uniqueItems.get(item.name); - if (!uniqueItem) { - uniqueItems.set(item.name, item.kind); - } - else { - assert.equal(item.kind, uniqueItem, `Items should have the same kind, got ${item.kind} and ${uniqueItem}`); - } - } - } - - public verifyCompletionListIsEmpty(negative: boolean) { - const completions = this.getCompletionListAtCaret(); - if ((!completions || completions.entries.length === 0) && negative) { - this.raiseError("Completion list is empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition); - } - else if (completions && completions.entries.length !== 0 && !negative) { - this.raiseError(`Completion list is not empty at caret at position ${this.activeFile.fileName} ${this.currentCaretPosition}\n` + - `Completion List contains: ${stringify(completions.entries.map(e => e.name))}`); - } - } - - public verifyCompletionListAllowsNewIdentifier(negative: boolean) { - const completions = this.getCompletionListAtCaret(); - - if ((completions && !completions.isNewIdentifierLocation) && !negative) { - this.raiseError("Expected builder completion entry"); - } - else if ((completions && completions.isNewIdentifierLocation) && negative) { - this.raiseError("Un-expected builder completion entry"); - } - } - - public verifyCompletionListIsGlobal(expected: boolean) { - const completions = this.getCompletionListAtCaret(); - if (completions && completions.isGlobalCompletion !== expected) { - this.raiseError(`verifyCompletionListIsGlobal failed - expected result to be ${completions.isGlobalCompletion}`); - } - } - public verifyCompletions(options: FourSlashInterface.VerifyCompletionsOptions) { if (options.marker === undefined) { this.verifyCompletionsWorker(options); @@ -865,13 +753,21 @@ namespace FourSlash { this.raiseError(`Expected 'isNewIdentifierLocation' to be ${options.isNewIdentifierLocation || false}, got ${actualCompletions.isNewIdentifierLocation}`); } - const actualByName = ts.createMap(); + if ("isGlobalCompletion" in options && actualCompletions.isGlobalCompletion !== options.isGlobalCompletion) { + this.raiseError(`Expected 'isGlobalCompletion to be ${options.isGlobalCompletion}, got ${actualCompletions.isGlobalCompletion}`); + } + + const nameToEntries = ts.createMap(); for (const entry of actualCompletions.entries) { - if (actualByName.has(entry.name)) { - this.raiseError(`Duplicate (${actualCompletions.entries.filter(a => a.name === entry.name).length}) completions for ${entry.name}`); + const entries = nameToEntries.get(entry.name); + if (!entries) { + nameToEntries.set(entry.name, [entry]); } else { - actualByName.set(entry.name, entry); + if (entries.some(e => e.source === entry.source)) { + this.raiseError(`Duplicate completions for ${entry.name}`); + } + entries.push(entry); } } @@ -884,23 +780,17 @@ namespace FourSlash { if (options.includes) { for (const include of toArray(options.includes)) { const name = typeof include === "string" ? include : include.name; - const found = actualByName.get(name); + const found = nameToEntries.get(name); if (!found) throw this.raiseError(`No completion ${name} found`); - this.verifyCompletionEntry(found, include); + assert(found.length === 1); // Must use 'exact' for multiple completions with same name + this.verifyCompletionEntry(ts.first(found), include); } } if (options.excludes) { for (const exclude of toArray(options.excludes)) { - if (typeof exclude === "string") { - if (actualByName.has(exclude)) { - this.raiseError(`Did not expect to get a completion named ${exclude}`); - } - } - else { - const found = actualByName.get(exclude.name); - if (found && found.source === exclude.source) { - this.raiseError(`Did not expect to get a completion named ${exclude.name} with source ${exclude.source}`); - } + assert(typeof exclude === "string"); + if (nameToEntries.has(exclude)) { + this.raiseError(`Did not expect to get a completion named ${exclude}`); } } } @@ -908,8 +798,8 @@ namespace FourSlash { } private verifyCompletionEntry(actual: ts.CompletionEntry, expected: FourSlashInterface.ExpectedCompletionEntry) { - const { insertText, replacementSpan, hasAction, isRecommended, kind, text, documentation, source, sourceDisplay } = typeof expected === "string" - ? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, text: undefined, documentation: undefined, source: undefined, sourceDisplay: undefined } + const { insertText, replacementSpan, hasAction, isRecommended, kind, kindModifiers, text, documentation, tags, source, sourceDisplay } = typeof expected === "string" + ? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, kindModifiers: undefined, text: undefined, documentation: undefined, tags: undefined, source: undefined, sourceDisplay: undefined } : expected; if (actual.insertText !== insertText) { @@ -923,13 +813,20 @@ namespace FourSlash { this.raiseError(`Expected completion replacementSpan to be ${stringify(convertedReplacementSpan)}, got ${stringify(actual.replacementSpan)}`); } - if (kind !== undefined) assert.equal(actual.kind, kind); + if (kind !== undefined || kindModifiers !== undefined) { + if (actual.kind !== kind) { + this.raiseError(`Unexpected kind for ${actual.name}: Expected ${kind}, actual ${actual.kind}`); + } + if (actual.kindModifiers !== (kindModifiers || "")) { + this.raiseError(`Bad kind modifiers for ${actual.name}: Expected ${kindModifiers || ""}, actual ${actual.kindModifiers}`); + } + } assert.equal(actual.hasAction, hasAction); assert.equal(actual.isRecommended, isRecommended); assert.equal(actual.source, source); - if (text) { + if (text !== undefined) { const actualDetails = this.getCompletionEntryDetails(actual.name, actual.source)!; assert.equal(ts.displayPartsToString(actualDetails.displayParts), text); assert.equal(ts.displayPartsToString(actualDetails.documentation), documentation || ""); @@ -937,16 +834,16 @@ namespace FourSlash { // assert.equal(actualDetails.kind, actual.kind); assert.equal(actualDetails.kindModifiers, actual.kindModifiers); assert.equal(actualDetails.source && ts.displayPartsToString(actualDetails.source), sourceDisplay); + assert.deepEqual(actualDetails.tags, tags); } else { - assert(documentation === undefined && sourceDisplay === undefined, "If specifying completion details, should specify 'text'"); + assert(documentation === undefined && tags === undefined && sourceDisplay === undefined, "If specifying completion details, should specify 'text'"); } } private verifyCompletionsAreExactly(actual: ReadonlyArray, expected: ReadonlyArray) { - if (actual.length !== expected.length) { - this.raiseError(`Expected ${expected.length} completions, got ${actual.length} (${actual.map(a => a.name)}).`); - } + // First pass: test that names are right. Then we'll test details. + assert.deepEqual(actual.map(a => a.name), expected.map(e => typeof e === "string" ? e : e.name)); ts.zipWith(actual, expected, (completion, expectedCompletion, index) => { const name = typeof expectedCompletion === "string" ? expectedCompletion : expectedCompletion.name; @@ -957,121 +854,10 @@ namespace FourSlash { }); } - public verifyCompletionsAt(markerName: string | ReadonlyArray, expected: ReadonlyArray, options?: FourSlashInterface.CompletionsAtOptions) { - this.verifyCompletions({ - marker: markerName, - exact: expected, - isNewIdentifierLocation: options && options.isNewIdentifierLocation, - preferences: options, - triggerCharacter: options && options.triggerCharacter, - }); - } - - public verifyCompletionListContains(entryId: ts.Completions.CompletionEntryIdentifier, text?: string, documentation?: string, kind?: string | { kind?: string, kindModifiers?: string }, spanIndex?: number, hasAction?: boolean, options?: FourSlashInterface.VerifyCompletionListContainsOptions) { - const completions = this.getCompletionListAtCaret(options); - if (completions) { - this.assertItemInCompletionList(completions.entries, entryId, text, documentation, kind, spanIndex, hasAction, options); - } - else { - this.raiseError(`No completions at position '${this.currentCaretPosition}' when looking for '${JSON.stringify(entryId)}'.`); - } - } - - /** - * Verify that the completion list does NOT contain the given symbol. - * The symbol is considered matched with the symbol in the list if and only if all given parameters must matched. - * When any parameter is omitted, the parameter is ignored during comparison and assumed that the parameter with - * that property of the symbol in the list. - * @param symbol the name of symbol - * @param expectedText the text associated with the symbol - * @param expectedDocumentation the documentation text associated with the symbol - * @param expectedKind the kind of symbol (see ScriptElementKind) - * @param spanIndex the index of the range that the completion item's replacement text span should match - */ - public verifyCompletionListDoesNotContain(entryId: ts.Completions.CompletionEntryIdentifier, expectedText?: string, expectedDocumentation?: string, expectedKind?: string | { kind?: string, kindModifiers?: string }, spanIndex?: number, options?: FourSlashInterface.CompletionsAtOptions) { - let replacementSpan: ts.TextSpan | undefined; - if (spanIndex !== undefined) { - replacementSpan = this.getTextSpanForRangeAtIndex(spanIndex); - } - - const completions = this.getCompletionListAtCaret(options); - if (completions) { - let filterCompletions = completions.entries.filter(e => e.name === entryId.name && e.source === entryId.source); - filterCompletions = expectedKind ? filterCompletions.filter(e => e.kind === expectedKind || (typeof expectedKind === "object" && e.kind === expectedKind.kind)) : filterCompletions; - filterCompletions = filterCompletions.filter(entry => { - const details = this.getCompletionEntryDetails(entry.name); - const documentation = details && ts.displayPartsToString(details.documentation); - const text = details && ts.displayPartsToString(details.displayParts); - - // If any of the expected values are undefined, assume that users don't - // care about them. - if (replacementSpan && !ts.textSpansEqual(replacementSpan, entry.replacementSpan)) { - return false; - } - else if (expectedText && text !== expectedText) { - return false; - } - else if (expectedDocumentation && documentation !== expectedDocumentation) { - return false; - } - - return true; - }); - if (filterCompletions.length !== 0) { - // After filtered using all present criterion, if there are still symbol left in the list - // then these symbols must meet the criterion for Not supposed to be in the list. So we - // raise an error - let error = `Completion list did contain '${JSON.stringify(entryId)}\'.`; - const details = this.getCompletionEntryDetails(filterCompletions[0].name)!; - if (expectedText) { - error += "Expected text: " + expectedText + " to equal: " + ts.displayPartsToString(details.displayParts) + "."; - } - if (expectedDocumentation) { - error += "Expected documentation: " + expectedDocumentation + " to equal: " + ts.displayPartsToString(details.documentation) + "."; - } - if (expectedKind) { - error += "Expected kind: " + expectedKind + " to equal: " + filterCompletions[0].kind + "."; - } - else { - error += "kind: " + filterCompletions[0].kind + "."; - } - if (replacementSpan) { - const spanText = filterCompletions[0].replacementSpan ? stringify(filterCompletions[0].replacementSpan) : undefined; - error += "Expected replacement span: " + stringify(replacementSpan) + " to equal: " + spanText + "."; - } - this.raiseError(error); - } - } - } - - public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]) { - const details = this.getCompletionEntryDetails(entryName)!; - - assert(details, "no completion entry available"); - - assert.equal(ts.displayPartsToString(details.displayParts), expectedText, this.assertionMessageAtLastKnownMarker("completion entry details text")); - - if (expectedDocumentation !== undefined) { - assert.equal(ts.displayPartsToString(details.documentation), expectedDocumentation, this.assertionMessageAtLastKnownMarker("completion entry documentation")); - } - - if (kind !== undefined) { - assert.equal(details.kind, kind, this.assertionMessageAtLastKnownMarker("completion entry kind")); - } - - if (tags !== undefined) { - assert.equal(details.tags!.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags")); - ts.zipWith(tags, details.tags!, (expectedTag, actualTag) => { - assert.equal(actualTag.name, expectedTag.name); - assert.equal(actualTag.text, expectedTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name)); - }); - } - } - /** Use `getProgram` instead of accessing this directly. */ - private _program: ts.Program; + private _program: ts.Program | undefined; /** Use `getChecker` instead of accessing this directly. */ - private _checker: ts.TypeChecker; + private _checker: ts.TypeChecker | undefined; private getProgram(): ts.Program { return this._program || (this._program = this.languageService.getProgram()!); // TODO: GH#18217 @@ -1180,12 +966,7 @@ namespace FourSlash { })); for (const start of toArray(starts)) { - if (typeof start === "string") { - this.goToMarker(start); - } - else { - this.goToRangeStart(start); - } + this.goToMarkerOrRange(start); const fullActual = ts.map(this.findReferencesAtCaret(), ({ definition, references }, i) => { const text = definition.displayParts.map(d => d.text).join(""); return { @@ -1202,15 +983,7 @@ namespace FourSlash { } public verifyNoReferences(markerNameOrRange?: string | Range) { - if (markerNameOrRange) { - if (ts.isString(markerNameOrRange)) { - this.goToMarker(markerNameOrRange); - } - else { - this.goToRangeStart(markerNameOrRange); - } - } - + if (markerNameOrRange) this.goToMarkerOrRange(markerNameOrRange); const refs = this.getReferencesAtCaret(); if (refs && refs.length) { this.raiseError(`Expected getReferences to fail, but saw references: ${stringify(refs)}`); @@ -1327,8 +1100,10 @@ Actual: ${stringify(fullActual)}`); }))); } - public verifyQuickInfoAt(markerName: string, expectedText: string, expectedDocumentation?: string) { - this.goToMarker(markerName); + public verifyQuickInfoAt(markerName: string | Range, expectedText: string, expectedDocumentation?: string) { + if (typeof markerName === "string") this.goToMarker(markerName); + else this.goToRangeStart(markerName); + this.verifyQuickInfoString(expectedText, expectedDocumentation); } @@ -1363,7 +1138,7 @@ Actual: ${stringify(fullActual)}`); public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: TextSpan, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], - tags: ts.JSDocTagInfo[] + tags: ts.JSDocTagInfo[] | undefined ) { const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; @@ -1372,11 +1147,16 @@ Actual: ${stringify(fullActual)}`); assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan")); assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.displayParts), TestState.getDisplayPartsJson(displayParts), this.messageAtLastKnownMarker("QuickInfo displayParts")); assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.documentation), TestState.getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation")); - assert.equal(actualQuickInfo.tags!.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags")); - ts.zipWith(tags, actualQuickInfo.tags!, (expectedTag, actualTag) => { - assert.equal(expectedTag.name, actualTag.name); - assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name)); - }); + if (!actualQuickInfo.tags || !tags) { + assert.equal(actualQuickInfo.tags, tags, this.messageAtLastKnownMarker("QuickInfo tags")); + } + else { + assert.equal(actualQuickInfo.tags.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags")); + ts.zipWith(tags, actualQuickInfo.tags, (expectedTag, actualTag) => { + assert.equal(expectedTag.name, actualTag.name); + assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name)); + }); + } } public verifyRangesAreRenameLocations(options?: Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges?: Range[] }) { @@ -1389,8 +1169,8 @@ Actual: ${stringify(fullActual)}`); } } - public verifyRenameLocations(startRanges: ArrayOrSingle, options: ReadonlyArray | { findInStrings?: boolean, findInComments?: boolean, ranges: ReadonlyArray }) { - const { findInStrings = false, findInComments = false, ranges = this.getRanges() } = ts.isArray(options) ? { findInStrings: false, findInComments: false, ranges: options } : options; + public verifyRenameLocations(startRanges: ArrayOrSingle, options: FourSlashInterface.RenameLocationsOptions) { + const { findInStrings = false, findInComments = false, ranges = this.getRanges(), providePrefixAndSuffixTextForRename = true } = ts.isArray(options) ? { findInStrings: false, findInComments: false, ranges: options, providePrefixAndSuffixTextForRename: true } : options; for (const startRange of toArray(startRanges)) { this.goToRangeStart(startRange); @@ -1402,11 +1182,14 @@ Actual: ${stringify(fullActual)}`); } const references = this.languageService.findRenameLocations( - this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments); + this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments, providePrefixAndSuffixTextForRename); const sort = (locations: ReadonlyArray | undefined) => locations && ts.sort(locations, (r1, r2) => ts.compareStringsCaseSensitive(r1.fileName, r2.fileName) || r1.textSpan.start - r2.textSpan.start); - assert.deepEqual(sort(references), sort(ranges.map((r): ts.RenameLocation => ({ fileName: r.fileName, textSpan: ts.createTextSpanFromRange(r) })))); + assert.deepEqual(sort(references), sort(ranges.map((rangeOrOptions): ts.RenameLocation => { + const { range, ...prefixSuffixText } = "range" in rangeOrOptions ? rangeOrOptions : { range: rangeOrOptions }; + return { fileName: range.fileName, textSpan: ts.createTextSpanFromRange(range), ...prefixSuffixText }; + }))); } } @@ -1525,22 +1308,25 @@ Actual: ${stringify(fullActual)}`); } } - public verifyRenameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string) { - const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + public verifyRenameInfoSucceeded(displayName: string | undefined, fullDisplayName: string | undefined, kind: string | undefined, kindModifiers: string | undefined, fileToRename: string | undefined, expectedRange: Range | undefined, renameInfoOptions: ts.RenameInfoOptions | undefined): void { + const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition, renameInfoOptions || { allowRenameOfImportPath: true }); if (!renameInfo.canRename) { - this.raiseError("Rename did not succeed"); + throw this.raiseError("Rename did not succeed"); } this.validate("displayName", displayName, renameInfo.displayName); this.validate("fullDisplayName", fullDisplayName, renameInfo.fullDisplayName); this.validate("kind", kind, renameInfo.kind); this.validate("kindModifiers", kindModifiers, renameInfo.kindModifiers); + this.validate("fileToRename", fileToRename, renameInfo.fileToRename); - if (this.getRanges().length !== 1) { - this.raiseError("Expected a single range to be selected in the test file."); + if (!expectedRange) { + if (this.getRanges().length !== 1) { + this.raiseError("Expected a single range to be selected in the test file."); + } + expectedRange = this.getRanges()[0]; } - const expectedRange = this.getRanges()[0]; if (renameInfo.triggerSpan.start !== expectedRange.pos || ts.textSpanEnd(renameInfo.triggerSpan) !== expectedRange.end) { this.raiseError("Expected triggerSpan [" + expectedRange.pos + "," + expectedRange.end + "). Got [" + @@ -1548,12 +1334,12 @@ Actual: ${stringify(fullActual)}`); } } - public verifyRenameInfoFailed(message?: string) { - const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + public verifyRenameInfoFailed(message?: string, allowRenameOfImportPath?: boolean) { + allowRenameOfImportPath = allowRenameOfImportPath === undefined ? true : allowRenameOfImportPath; + const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition, { allowRenameOfImportPath }); if (renameInfo.canRename) { - this.raiseError("Rename was expected to fail"); + throw this.raiseError("Rename was expected to fail"); } - this.validate("error", message, renameInfo.localizedErrorMessage); } @@ -2040,6 +1826,15 @@ Actual: ${stringify(fullActual)}`); this.goToPosition(len); } + private goToMarkerOrRange(markerOrRange: string | Range) { + if (typeof markerOrRange === "string") { + this.goToMarker(markerOrRange); + } + else { + this.goToRangeStart(markerOrRange); + } + } + public goToRangeStart({ fileName, pos }: Range) { this.openFile(fileName); this.goToPosition(pos); @@ -2104,7 +1899,7 @@ Actual: ${stringify(fullActual)}`); public verifyRangesInImplementationList(markerName: string) { this.goToMarker(markerName); - const implementations: ImplementationLocationInformation[] = this.languageService.getImplementationAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; + const implementations: ReadonlyArray = this.languageService.getImplementationAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; if (!implementations || !implementations.length) { this.raiseError("verifyRangesInImplementationList failed - expected to find at least one implementation location but got 0"); } @@ -2435,7 +2230,20 @@ Actual: ${stringify(fullActual)}`); */ public getAndApplyCodeActions(errorCode?: number, index?: number) { const fileName = this.activeFile.fileName; - this.applyCodeActions(this.getCodeFixes(fileName, errorCode), index); + const fixes = this.getCodeFixes(fileName, errorCode); + if (index === undefined) { + if (!(fixes && fixes.length === 1)) { + this.raiseError(`Should find exactly one codefix, but ${fixes ? fixes.length : "none"} found. ${fixes ? fixes.map(a => `${Harness.IO.newLine()} "${a.description}"`) : ""}`); + } + index = 0; + } + else { + if (!(fixes && fixes.length >= index + 1)) { + this.raiseError(`Should find at least ${index + 1} codefix(es), but ${fixes ? fixes.length : "none"} found.`); + } + } + + this.applyChanges(fixes[index].changes); } public applyCodeActionFromCompletion(markerName: string, options: FourSlashInterface.VerifyCompletionActionOptions) { @@ -2446,12 +2254,12 @@ Actual: ${stringify(fullActual)}`); if (codeActions.length !== 1) { this.raiseError(`Expected one code action, got ${codeActions.length}`); } + const codeAction = ts.first(codeActions); - if (codeActions[0].description !== options.description) { + if (codeAction.description !== options.description) { this.raiseError(`Expected description to be:\n${options.description}\ngot:\n${codeActions[0].description}`); } - - this.applyCodeActions(codeActions); + this.applyChanges(codeAction.changes); this.verifyNewContentAfterChange(options, ts.flatMap(codeActions, a => a.changes.map(c => c.fileName))); } @@ -2493,29 +2301,7 @@ Actual: ${stringify(fullActual)}`); const { changes, commands } = this.languageService.getCombinedCodeFix({ type: "file", fileName: this.activeFile.fileName }, fixId, this.formatCodeSettings, ts.emptyOptions); assert.deepEqual | undefined>(commands, expectedCommands); - assert(changes.every(c => c.fileName === this.activeFile.fileName), "TODO: support testing codefixes that touch multiple files"); - this.applyChanges(changes); - this.verifyCurrentFileContent(newFileContent); - } - - /** - * Applies fixes for the errors in fileName and compares the results to - * expectedContents after all fixes have been applied. - * - * Note: applying one codefix may generate another (eg: remove duplicate implements - * may generate an extends -> interface conversion fix). - * @param expectedContents The contents of the file after the fixes are applied. - * @param fileName The file to check. If not supplied, the current open file is used. - */ - public verifyFileAfterCodeFix(expectedContents: string, fileName?: string) { - fileName = fileName ? fileName : this.activeFile.fileName; - - this.applyCodeActions(this.getCodeFixes(fileName)); - - const actualContents: string = this.getFileContent(fileName); - if (this.removeWhitespace(actualContents) !== this.removeWhitespace(expectedContents)) { - this.raiseError(`Actual text doesn't match expected text. Actual:\n${actualContents}\n\nExpected:\n${expectedContents}`); - } + this.verifyNewContent({ newFileContent }, changes); } public verifyCodeFix(options: FourSlashInterface.VerifyCodeFixOptions) { @@ -2606,7 +2392,7 @@ Actual: ${stringify(fullActual)}`); * Rerieves a codefix satisfying the parameters, or undefined if no such codefix is found. * @param fileName Path to file where error should be retrieved from. */ - private getCodeFixes(fileName: string, errorCode?: number, preferences: ts.UserPreferences = ts.emptyOptions): ts.CodeFixAction[] { + private getCodeFixes(fileName: string, errorCode?: number, preferences: ts.UserPreferences = ts.emptyOptions): ReadonlyArray { const diagnosticsForCodeFix = this.getDiagnostics(fileName, /*includeSuggestions*/ true).map(diagnostic => ({ start: diagnostic.start, length: diagnostic.length, @@ -2622,22 +2408,6 @@ Actual: ${stringify(fullActual)}`); }); } - private applyCodeActions(actions: ReadonlyArray, index?: number): void { - if (index === undefined) { - if (!(actions && actions.length === 1)) { - this.raiseError(`Should find exactly one codefix, but ${actions ? actions.length : "none"} found. ${actions ? actions.map(a => `${Harness.IO.newLine()} "${a.description}"`) : ""}`); - } - index = 0; - } - else { - if (!(actions && actions.length >= index + 1)) { - this.raiseError(`Should find at least ${index + 1} codefix(es), but ${actions ? actions.length : "none"} found.`); - } - } - - this.applyChanges(actions[index].changes); - } - private applyChanges(changes: ReadonlyArray): void { for (const change of changes) { this.applyEdits(change.fileName, change.textChanges, /*isFormattingEdit*/ false); @@ -3015,11 +2785,6 @@ Actual: ${stringify(fullActual)}`); assert.deepEqual(unique(this.getApplicableRefactorsAtSelection(), r => r.name), names); } - public verifyRefactor({ name, actionName, refactors }: FourSlashInterface.VerifyRefactorOptions) { - const actualRefactors = this.getApplicableRefactorsAtSelection().filter(r => r.name === name && r.actions.some(a => a.name === actionName)); - this.assertObjectsEqual(actualRefactors, refactors); - } - public verifyApplicableRefactorAvailableForRange(negative: boolean) { const ranges = this.getRanges(); if (!(ranges && ranges.length === 1)) { @@ -3210,74 +2975,6 @@ Actual: ${stringify(fullActual)}`); return text.substring(startPos, endPos); } - private assertItemInCompletionList( - items: ts.CompletionEntry[], - entryId: ts.Completions.CompletionEntryIdentifier, - text: string | undefined, - documentation: string | undefined, - kind: string | undefined | { kind?: string, kindModifiers?: string }, - spanIndex: number | undefined, - hasAction: boolean | undefined, - options: FourSlashInterface.VerifyCompletionListContainsOptions | undefined, - ) { - const eq = (a: T, b: T, msg: string) => { - assert.deepEqual(a, b, this.assertionMessageAtLastKnownMarker(msg + " for " + stringify(entryId))); - }; - const matchingItems = items.filter(item => item.name === entryId.name && item.source === entryId.source); - if (matchingItems.length === 0) { - const itemsString = items.map(item => stringify({ name: item.name, source: item.source, kind: item.kind })).join(",\n"); - this.raiseError(`Expected "${stringify({ entryId, text, documentation, kind })}" to be in list [${itemsString}]`); - } - else if (matchingItems.length > 1) { - this.raiseError(`Found duplicate completion items for ${stringify(entryId)}`); - } - const item = matchingItems[0]; - - if (documentation !== undefined || text !== undefined || entryId.source !== undefined) { - const details = this.getCompletionEntryDetails(item.name, item.source)!; - - if (documentation !== undefined) { - eq(ts.displayPartsToString(details.documentation), documentation, "completion item documentation"); - } - if (text !== undefined) { - eq(ts.displayPartsToString(details.displayParts), text, "completion item detail text"); - } - - if (entryId.source === undefined) { - eq(options && options.sourceDisplay, /*b*/ undefined, "source display"); - } - else { - eq(details.source, [ts.textPart(options!.sourceDisplay)], "source display"); - } - } - - if (kind !== undefined) { - if (typeof kind === "string") { - eq(item.kind, kind, "completion item kind"); - } - else { - if (kind.kind) { - eq(item.kind, kind.kind, "completion item kind"); - } - if (kind.kindModifiers !== undefined) { - eq(item.kindModifiers, kind.kindModifiers, "completion item kindModifiers"); - } - } - } - - - - if (spanIndex !== undefined) { - const span = this.getTextSpanForRangeAtIndex(spanIndex); - assert.isTrue(ts.textSpansEqual(span, item.replacementSpan), this.assertionMessageAtLastKnownMarker(stringify(span) + " does not equal " + stringify(item.replacementSpan) + " replacement span for " + stringify(entryId))); - } - - eq(item.hasAction, hasAction, "hasAction"); - eq(item.isRecommended, options && options.isRecommended, "isRecommended"); - eq(item.insertText, options && options.insertText, "insertText"); - eq(item.replacementSpan, options && options.replacementSpan && ts.createTextSpanFromRange(options.replacementSpan), "replacementSpan"); - } - private findFile(indexOrName: string | number): FourSlashFile { if (typeof indexOrName === "number") { const index = indexOrName; @@ -3327,16 +3024,6 @@ Actual: ${stringify(fullActual)}`); return `line ${(pos.line + 1)}, col ${pos.character}`; } - private getTextSpanForRangeAtIndex(index: number): ts.TextSpan { - const ranges = this.getRanges(); - if (ranges.length > index) { - return ts.createTextSpanFromRange(ranges[index]); - } - else { - throw this.raiseError("Supplied span index: " + index + " does not exist in range list of size: " + ranges.length); - } - } - public getMarkerByName(markerName: string) { const markerPos = this.testData.markerPositions.get(markerName); if (markerPos === undefined) { @@ -3380,6 +3067,23 @@ Actual: ${stringify(fullActual)}`); private getApplicableRefactorsWorker(positionOrRange: number | ts.TextRange, fileName: string, preferences = ts.emptyOptions): ReadonlyArray { return this.languageService.getApplicableRefactors(fileName, positionOrRange, preferences) || ts.emptyArray; } + + public generateTypes(examples: ReadonlyArray): void { + for (const { name = "example", value, global, output, outputBaseline } of examples) { + const actual = (global ? ts.generateTypesForGlobal : ts.generateTypesForModule)(name, value, this.formatCodeSettings); + if (outputBaseline) { + if (actual === undefined) throw ts.Debug.fail(); + Harness.Baseline.runBaseline(ts.combinePaths("generateTypes", outputBaseline + ts.Extension.Dts), actual); + } + else { + assert.equal(actual, output, `generateTypes output for ${name} does not match`); + } + } + } + + public configurePlugin(pluginName: string, configuration: any): void { + (this.languageService).configurePlugin(pluginName, configuration); + } } function updateTextRangeForTextChanges({ pos, end }: ts.TextRange, textChanges: ReadonlyArray): ts.TextRange { @@ -3433,7 +3137,7 @@ Actual: ${stringify(fullActual)}`); // Parse out the files and their metadata const testData = parseTestData(absoluteBasePath, content, absoluteFileName); const state = new TestState(absoluteBasePath, testType, testData); - const output = ts.transpileModule(content, { reportDiagnostics: true }); + const output = ts.transpileModule(content, { reportDiagnostics: true, compilerOptions: { target: ts.ScriptTarget.ES2015 } }); if (output.diagnostics!.length > 0) { throw new Error(`Syntax error in ${absoluteBasePath}: ${output.diagnostics![0].messageText}`); } @@ -3443,19 +3147,20 @@ Actual: ${stringify(fullActual)}`); function runCode(code: string, state: TestState): void { // Compile and execute the test const wrappedCode = - `(function(test, goTo, verify, edit, debug, format, cancellation, classification, verifyOperationIsCancelled) { + `(function(test, goTo, plugins, verify, edit, debug, format, cancellation, classification, completion, verifyOperationIsCancelled) { ${code} })`; try { const test = new FourSlashInterface.Test(state); const goTo = new FourSlashInterface.GoTo(state); + const plugins = new FourSlashInterface.Plugins(state); const verify = new FourSlashInterface.Verify(state); const edit = new FourSlashInterface.Edit(state); const debug = new FourSlashInterface.Debug(state); const format = new FourSlashInterface.Format(state); const cancellation = new FourSlashInterface.Cancellation(state); const f = eval(wrappedCode); - f(test, goTo, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, verifyOperationIsCancelled); + f(test, goTo, plugins, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, FourSlashInterface.Completion, verifyOperationIsCancelled); } catch (err) { throw err; @@ -3848,7 +3553,7 @@ ${code} } // put ranges in the correct order - localRanges = localRanges.sort((a, b) => a.pos < b.pos ? -1 : 1); + localRanges = localRanges.sort((a, b) => a.pos < b.pos ? -1 : a.pos === b.pos && a.end > b.end ? -1 : 1); localRanges.forEach((r) => { ranges.push(r); }); return { @@ -3955,6 +3660,15 @@ namespace FourSlashInterface { } } + export class Plugins { + constructor (private state: FourSlash.TestState) { + } + + public configurePlugin(pluginName: string, configuration: any): void { + this.state.configurePlugin(pluginName, configuration); + } + } + export class GoTo { constructor(private state: FourSlash.TestState) { } @@ -3977,7 +3691,7 @@ namespace FourSlashInterface { this.state.goToRangeStart(range); } - public eachRange(action: () => void) { + public eachRange(action: (range: FourSlash.Range) => void) { this.state.goToEachRange(action); } @@ -4021,25 +3735,7 @@ namespace FourSlashInterface { } export class VerifyNegatable { - public not: VerifyNegatable; - public allowedClassElementKeywords = [ - "public", - "private", - "protected", - "static", - "abstract", - "readonly", - "get", - "set", - "constructor", - "async" - ]; - public allowedConstructorParameterKeywords = [ - "public", - "private", - "protected", - "readonly", - ]; + public not: VerifyNegatable | undefined; constructor(protected state: FourSlash.TestState, private negative = false) { if (!negative) { @@ -4047,58 +3743,10 @@ namespace FourSlashInterface { } } - public completionListCount(expectedCount: number) { - this.state.verifyCompletionListCount(expectedCount, this.negative); - } - - // Verifies the completion list contains the specified symbol. The - // completion list is brought up if necessary - public completionListContains(entryId: string | ts.Completions.CompletionEntryIdentifier, text?: string, documentation?: string, kind?: string | { kind?: string, kindModifiers?: string }, spanIndex?: number, hasAction?: boolean, options?: VerifyCompletionListContainsOptions) { - if (typeof entryId === "string") { - entryId = { name: entryId, source: undefined }; - } - if (this.negative) { - this.state.verifyCompletionListDoesNotContain(entryId, text, documentation, kind, spanIndex, options); - } - else { - this.state.verifyCompletionListContains(entryId, text, documentation, kind, spanIndex, hasAction, options); - } - } - - // Verifies the completion list items count to be greater than the specified amount. The - // completion list is brought up if necessary - public completionListItemsCountIsGreaterThan(count: number) { - this.state.verifyCompletionListItemsCountIsGreaterThan(count, this.negative); - } - public assertHasRanges(ranges: FourSlash.Range[]) { assert(ranges.length !== 0, "Array of ranges is expected to be non-empty"); } - public completionListIsEmpty() { - this.state.verifyCompletionListIsEmpty(this.negative); - } - - public completionListContainsClassElementKeywords() { - for (const keyword of this.allowedClassElementKeywords) { - this.completionListContains(keyword, keyword, /*documentation*/ undefined, "keyword"); - } - } - - public completionListContainsConstructorParameterKeywords() { - for (const keyword of this.allowedConstructorParameterKeywords) { - this.completionListContains(keyword, keyword, /*documentation*/ undefined, "keyword"); - } - } - - public completionListIsGlobal(expected: boolean) { - this.state.verifyCompletionListIsGlobal(expected); - } - - public completionListAllowsNewIdentifier() { - this.state.verifyCompletionListAllowsNewIdentifier(this.negative); - } - public noSignatureHelp(...markers: string[]): void { this.state.verifySignatureHelpPresence(/*expectPresent*/ false, /*triggerReason*/ undefined, markers); } @@ -4171,10 +3819,6 @@ namespace FourSlashInterface { this.state.verifyRefactorsAvailable(names); } - public refactor(options: VerifyRefactorOptions) { - this.state.verifyRefactor(options); - } - public refactorAvailable(name: string, actionName?: string) { this.state.verifyRefactorAvailable(this.negative, name, actionName); } @@ -4185,10 +3829,6 @@ namespace FourSlashInterface { super(state); } - public completionsAt(markerName: ArrayOrSingle, completions: ReadonlyArray, options?: CompletionsAtOptions) { - this.state.verifyCompletionsAt(markerName, completions, options); - } - public completions(...optionsArray: VerifyCompletionsOptions[]) { for (const options of optionsArray) { this.state.verifyCompletions(options); @@ -4199,7 +3839,7 @@ namespace FourSlashInterface { this.state.verifyQuickInfoString(expectedText, expectedDocumentation); } - public quickInfoAt(markerName: string, expectedText: string, expectedDocumentation?: string) { + public quickInfoAt(markerName: string | FourSlash.Range, expectedText: string, expectedDocumentation?: string) { this.state.verifyQuickInfoAt(markerName, expectedText, expectedDocumentation); } @@ -4438,10 +4078,6 @@ namespace FourSlashInterface { this.state.verifyNoDocumentHighlights(startRange); } - public completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]) { - this.state.verifyCompletionEntryDetails(entryName, text, documentation, kind, tags); - } - /** * This method *requires* a contiguous, complete, and ordered stream of classifications for a file. */ @@ -4456,15 +4092,15 @@ namespace FourSlashInterface { this.state.verifySemanticClassifications(classifications); } - public renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string) { - this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers); + public renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string, fileToRename?: string, expectedRange?: FourSlash.Range, options?: ts.RenameInfoOptions) { + this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers, fileToRename, expectedRange, options); } - public renameInfoFailed(message?: string) { - this.state.verifyRenameInfoFailed(message); + public renameInfoFailed(message?: string, allowRenameOfImportPath?: boolean) { + this.state.verifyRenameInfoFailed(message, allowRenameOfImportPath); } - public renameLocations(startRanges: ArrayOrSingle, options: FourSlash.Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges: FourSlash.Range[] }) { + public renameLocations(startRanges: ArrayOrSingle, options: RenameLocationsOptions) { this.state.verifyRenameLocations(startRanges, options); } @@ -4503,6 +4139,19 @@ namespace FourSlashInterface { public noMoveToNewFile(): void { this.state.noMoveToNewFile(); } + + public generateTypes(...options: GenerateTypesOptions[]): void { + this.state.generateTypes(options); + } + } + + export interface GenerateTypesOptions { + readonly name?: string; + readonly value: unknown; + readonly global?: boolean; + // Exactly one of these should be set: + readonly output?: string; + readonly outputBaseline?: string; } export class Edit { @@ -4653,7 +4302,7 @@ namespace FourSlashInterface { } public setOption(name: keyof ts.FormatCodeSettings, value: number | string | boolean): void { - this.state.formatCodeSettings[name] = value; + this.state.formatCodeSettings = { ...this.state.formatCodeSettings, [name]: value }; } } @@ -4773,6 +4422,513 @@ namespace FourSlashInterface { return { classificationType, text, textSpan }; } } + export namespace Completion { + const functionEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "function", kindModifiers: "declare" }); + const constEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "const", kindModifiers: "declare" }); + const moduleEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "module", kindModifiers: "declare" }); + const keywordEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "keyword" }); + const methodEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "method", kindModifiers: "declare" }); + const propertyEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "property", kindModifiers: "declare" }); + const interfaceEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "interface", kindModifiers: "declare" }); + const typeEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "type", kindModifiers: "declare" }); + + const res: ExpectedCompletionEntryObject[] = []; + for (let i = ts.SyntaxKind.FirstKeyword; i <= ts.SyntaxKind.LastKeyword; i++) { + res.push({ name: ts.Debug.assertDefined(ts.tokenToString(i)), kind: "keyword" }); + } + export const keywordsWithUndefined: ReadonlyArray = res; + export const keywords: ReadonlyArray = keywordsWithUndefined.filter(k => k.name !== "undefined"); + + export const typeKeywords: ReadonlyArray = + ["false", "null", "true", "void", "any", "boolean", "keyof", "never", "number", "object", "string", "symbol", "undefined", "unique", "unknown", "bigint"].map(keywordEntry); + + const globalTypeDecls: ReadonlyArray = [ + interfaceEntry("Symbol"), + typeEntry("PropertyKey"), + interfaceEntry("PropertyDescriptor"), + interfaceEntry("PropertyDescriptorMap"), + constEntry("Object"), + interfaceEntry("ObjectConstructor"), + constEntry("Function"), + interfaceEntry("FunctionConstructor"), + typeEntry("ThisParameterType"), + typeEntry("OmitThisParameter"), + interfaceEntry("CallableFunction"), + interfaceEntry("NewableFunction"), + interfaceEntry("IArguments"), + constEntry("String"), + interfaceEntry("StringConstructor"), + constEntry("Boolean"), + interfaceEntry("BooleanConstructor"), + constEntry("Number"), + interfaceEntry("NumberConstructor"), + interfaceEntry("TemplateStringsArray"), + interfaceEntry("ImportMeta"), + constEntry("Math"), + constEntry("Date"), + interfaceEntry("DateConstructor"), + interfaceEntry("RegExpMatchArray"), + interfaceEntry("RegExpExecArray"), + constEntry("RegExp"), + interfaceEntry("RegExpConstructor"), + constEntry("Error"), + interfaceEntry("ErrorConstructor"), + constEntry("EvalError"), + interfaceEntry("EvalErrorConstructor"), + constEntry("RangeError"), + interfaceEntry("RangeErrorConstructor"), + constEntry("ReferenceError"), + interfaceEntry("ReferenceErrorConstructor"), + constEntry("SyntaxError"), + interfaceEntry("SyntaxErrorConstructor"), + constEntry("TypeError"), + interfaceEntry("TypeErrorConstructor"), + constEntry("URIError"), + interfaceEntry("URIErrorConstructor"), + constEntry("JSON"), + interfaceEntry("ReadonlyArray"), + interfaceEntry("ConcatArray"), + constEntry("Array"), + interfaceEntry("ArrayConstructor"), + interfaceEntry("TypedPropertyDescriptor"), + typeEntry("ClassDecorator"), + typeEntry("PropertyDecorator"), + typeEntry("MethodDecorator"), + typeEntry("ParameterDecorator"), + typeEntry("PromiseConstructorLike"), + interfaceEntry("PromiseLike"), + interfaceEntry("Promise"), + interfaceEntry("ArrayLike"), + typeEntry("Partial"), + typeEntry("Required"), + typeEntry("Readonly"), + typeEntry("Pick"), + typeEntry("Record"), + typeEntry("Exclude"), + typeEntry("Extract"), + typeEntry("NonNullable"), + typeEntry("Parameters"), + typeEntry("ConstructorParameters"), + typeEntry("ReturnType"), + typeEntry("InstanceType"), + interfaceEntry("ThisType"), + constEntry("ArrayBuffer"), + interfaceEntry("ArrayBufferTypes"), + typeEntry("ArrayBufferLike"), + interfaceEntry("ArrayBufferConstructor"), + interfaceEntry("ArrayBufferView"), + constEntry("DataView"), + interfaceEntry("DataViewConstructor"), + constEntry("Int8Array"), + interfaceEntry("Int8ArrayConstructor"), + constEntry("Uint8Array"), + interfaceEntry("Uint8ArrayConstructor"), + constEntry("Uint8ClampedArray"), + interfaceEntry("Uint8ClampedArrayConstructor"), + constEntry("Int16Array"), + interfaceEntry("Int16ArrayConstructor"), + constEntry("Uint16Array"), + interfaceEntry("Uint16ArrayConstructor"), + constEntry("Int32Array"), + interfaceEntry("Int32ArrayConstructor"), + constEntry("Uint32Array"), + interfaceEntry("Uint32ArrayConstructor"), + constEntry("Float32Array"), + interfaceEntry("Float32ArrayConstructor"), + constEntry("Float64Array"), + interfaceEntry("Float64ArrayConstructor"), + moduleEntry("Intl"), + ]; + + export const globalTypes = globalTypesPlus([]); + + export function globalTypesPlus(plus: ReadonlyArray): ReadonlyArray { + return [ + ...globalTypeDecls, + ...plus, + ...typeKeywords, + ]; + } + + export const classElementKeywords: ReadonlyArray = + ["private", "protected", "public", "static", "abstract", "async", "constructor", "get", "readonly", "set"].map(keywordEntry); + + export const constructorParameterKeywords: ReadonlyArray = + ["private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({ name, kind: "keyword" })); + + export const functionMembers: ReadonlyArray = [ + methodEntry("apply"), + methodEntry("call"), + methodEntry("bind"), + methodEntry("toString"), + propertyEntry("length"), + { name: "arguments", kind: "property", kindModifiers: "declare", text: "(property) Function.arguments: any" }, + propertyEntry("caller"), + ]; + + export const stringMembers: ReadonlyArray = [ + methodEntry("toString"), + methodEntry("charAt"), + methodEntry("charCodeAt"), + methodEntry("concat"), + methodEntry("indexOf"), + methodEntry("lastIndexOf"), + methodEntry("localeCompare"), + methodEntry("match"), + methodEntry("replace"), + methodEntry("search"), + methodEntry("slice"), + methodEntry("split"), + methodEntry("substring"), + methodEntry("toLowerCase"), + methodEntry("toLocaleLowerCase"), + methodEntry("toUpperCase"), + methodEntry("toLocaleUpperCase"), + methodEntry("trim"), + propertyEntry("length"), + methodEntry("substr"), + methodEntry("valueOf"), + ]; + + export const functionMembersWithPrototype: ReadonlyArray = [ + ...functionMembers.slice(0, 4), + propertyEntry("prototype"), + ...functionMembers.slice(4), + ]; + + // TODO: Shouldn't propose type keywords in statement position + export const statementKeywordsWithTypes: ReadonlyArray = [ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + "static", + "yield", + "abstract", + "as", + "any", + "async", + "await", + "boolean", + "constructor", + "declare", + "get", + "infer", + "is", + "keyof", + "module", + "namespace", + "never", + "readonly", + "require", + "number", + "object", + "set", + "string", + "symbol", + "type", + "unique", + "unknown", + "from", + "global", + "bigint", + "of", + ].map(keywordEntry); + + export const statementKeywords: ReadonlyArray = statementKeywordsWithTypes.filter(k => { + const name = k.name; + switch (name) { + case "false": + case "true": + case "null": + case "void": + return true; + case "declare": + case "module": + return false; + default: + return !ts.contains(typeKeywords, k); + } + }); + + export const globalsVars: ReadonlyArray = [ + functionEntry("eval"), + functionEntry("parseInt"), + functionEntry("parseFloat"), + functionEntry("isNaN"), + functionEntry("isFinite"), + functionEntry("decodeURI"), + functionEntry("decodeURIComponent"), + functionEntry("encodeURI"), + functionEntry("encodeURIComponent"), + functionEntry("escape"), + functionEntry("unescape"), + constEntry("NaN"), + constEntry("Infinity"), + constEntry("Object"), + constEntry("Function"), + constEntry("String"), + constEntry("Boolean"), + constEntry("Number"), + constEntry("Math"), + constEntry("Date"), + constEntry("RegExp"), + constEntry("Error"), + constEntry("EvalError"), + constEntry("RangeError"), + constEntry("ReferenceError"), + constEntry("SyntaxError"), + constEntry("TypeError"), + constEntry("URIError"), + constEntry("JSON"), + constEntry("Array"), + constEntry("ArrayBuffer"), + constEntry("DataView"), + constEntry("Int8Array"), + constEntry("Uint8Array"), + constEntry("Uint8ClampedArray"), + constEntry("Int16Array"), + constEntry("Uint16Array"), + constEntry("Int32Array"), + constEntry("Uint32Array"), + constEntry("Float32Array"), + constEntry("Float64Array"), + moduleEntry("Intl"), + ]; + + const globalKeywordsInsideFunction: ReadonlyArray = [ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "implements", + "interface", + "let", + "package", + "yield", + "async", + "await", + ].map(keywordEntry); + + // TODO: many of these are inappropriate to always provide + export const globalsInsideFunction = (plus: ReadonlyArray): ReadonlyArray => [ + { name: "arguments", kind: "local var" }, + ...plus, + ...globalsVars, + { name: "undefined", kind: "var" }, + ...globalKeywordsInsideFunction, + ]; + + // TODO: many of these are inappropriate to always provide + export const globalKeywords: ReadonlyArray = [ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + "static", + "yield", + "abstract", + "as", + "any", + "async", + "await", + "boolean", + "constructor", + "declare", + "get", + "infer", + "is", + "keyof", + "module", + "namespace", + "never", + "readonly", + "require", + "number", + "object", + "set", + "string", + "symbol", + "type", + "unique", + "unknown", + "from", + "global", + "bigint", + "of", + ].map(keywordEntry); + + export const insideMethodKeywords: ReadonlyArray = [ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "implements", + "interface", + "let", + "package", + "yield", + "async", + "await", + ].map(keywordEntry); + + export const globalKeywordsPlusUndefined: ReadonlyArray = (() => { + const i = ts.findIndex(globalKeywords, x => x.name === "unique"); + return [...globalKeywords.slice(0, i), keywordEntry("undefined"), ...globalKeywords.slice(i)]; + })(); + + export const globals: ReadonlyArray = [ + ...globalsVars, + { name: "undefined", kind: "var" }, + ...globalKeywords + ]; + + export function globalsPlus(plus: ReadonlyArray): ReadonlyArray { + return [...globalsVars, ...plus, { name: "undefined", kind: "var" }, ...globalKeywords]; + } + } export interface ReferenceGroup { definition: ReferenceGroupDefinition; @@ -4788,29 +4944,29 @@ namespace FourSlashInterface { newContent: NewFileContent; } - export type ExpectedCompletionEntry = string | { - readonly name: string, - readonly source?: string, - readonly insertText?: string, - readonly replacementSpan?: FourSlash.Range, - readonly hasAction?: boolean, // If not specified, will assert that this is false. + export type ExpectedCompletionEntry = string | ExpectedCompletionEntryObject; + export interface ExpectedCompletionEntryObject { + readonly name: string; + readonly source?: string; + readonly insertText?: string; + readonly replacementSpan?: FourSlash.Range; + readonly hasAction?: boolean; // If not specified, will assert that this is false. readonly isRecommended?: boolean; // If not specified, will assert that this is false. - readonly kind?: string, // If not specified, won't assert about this - readonly text: string; - readonly documentation: string; + readonly kind?: string; // If not specified, won't assert about this + readonly kindModifiers?: string; // Must be paired with 'kind' + readonly text?: string; + readonly documentation?: string; readonly sourceDisplay?: string; - }; - export interface CompletionsAtOptions extends Partial { - triggerCharacter?: ts.CompletionsTriggerCharacter; - isNewIdentifierLocation?: boolean; + readonly tags?: ReadonlyArray; } export interface VerifyCompletionsOptions { readonly marker?: ArrayOrSingle; - readonly isNewIdentifierLocation?: boolean; + readonly isNewIdentifierLocation?: boolean; // Always tested + readonly isGlobalCompletion?: boolean; // Only tested if set readonly exact?: ArrayOrSingle; readonly includes?: ArrayOrSingle; - readonly excludes?: ArrayOrSingle; + readonly excludes?: ArrayOrSingle; readonly preferences?: ts.UserPreferences; readonly triggerCharacter?: ts.CompletionsTriggerCharacter; } @@ -4891,14 +5047,14 @@ namespace FourSlashInterface { export interface VerifyCodeFixAllOptions { fixId: string; fixAllDescription: string; - newFileContent: string; + newFileContent: NewFileContent; commands: ReadonlyArray<{}>; } export interface VerifyRefactorOptions { name: string; actionName: string; - refactors: ts.ApplicableRefactorInfo[]; + refactors: ReadonlyArray; } export interface VerifyCompletionActionOptions extends NewContentOptions { @@ -4926,4 +5082,12 @@ namespace FourSlashInterface { readonly newFileContents: { readonly [fileName: string]: string }; readonly preferences?: ts.UserPreferences; } + + export type RenameLocationsOptions = ReadonlyArray | { + readonly findInStrings?: boolean; + readonly findInComments?: boolean; + readonly ranges: ReadonlyArray; + readonly providePrefixAndSuffixTextForRename?: boolean; + }; + export type RenameLocationOptions = FourSlash.Range | { readonly range: FourSlash.Range, readonly prefixText?: string, readonly suffixText?: string }; } diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 23ee10d7412..13ef2adbf90 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -28,12 +28,10 @@ var assert: typeof _chai.assert = _chai.assert; }; } -var global: NodeJS.Global = Function("return this").call(undefined); +var global: NodeJS.Global = Function("return this").call(undefined); // tslint:disable-line:function-constructor declare var window: {}; -declare var XMLHttpRequest: { - new(): XMLHttpRequest; -}; +declare var XMLHttpRequest: new() => XMLHttpRequest; interface XMLHttpRequest { readonly readyState: number; readonly responseText: string; @@ -490,7 +488,7 @@ namespace Harness { getExecutingFilePath(): string; getWorkspaceRoot(): string; exit(exitCode?: number): void; - readDirectory(path: string, extension?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readDirectory(path: string, extension?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): ReadonlyArray; getAccessibleFileSystemEntries(dirname: string): ts.FileSystemEntries; tryEnableSourceMapsForHost?(): void; getEnvironmentVariable?(name: string): string; @@ -1159,7 +1157,7 @@ namespace Harness { } // If not a primitive, the possible types are specified in what is effectively a map of options. case "list": - return ts.parseListTypeOption(option, value, errors); + return ts.parseListTypeOption(option, value, errors); default: return ts.parseCustomTypeOption(option, value, errors); } @@ -1325,6 +1323,9 @@ namespace Harness { const [, content] = value; outputLines += content; } + if (pretty) { + outputLines += ts.getErrorSummaryText(ts.getErrorCountForSummary(diagnostics), IO.newLine()); + } return outputLines; } @@ -1643,6 +1644,7 @@ namespace Harness { else { sourceMapCode = ""; result.maps.forEach(sourceMap => { + if (sourceMapCode) sourceMapCode += "\r\n"; sourceMapCode += fileOutput(sourceMap, harnessSettings); }); } @@ -1668,6 +1670,9 @@ namespace Harness { let jsCode = ""; result.js.forEach(file => { + if (jsCode.length && jsCode.charCodeAt(jsCode.length - 1) !== ts.CharacterCodes.lineFeed) { + jsCode += "\r\n"; + } jsCode += fileOutput(file, harnessSettings); }); diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index fa9c88d3ffa..a78ef88e5b7 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -1,4 +1,18 @@ namespace Harness.LanguageService { + + export function makeDefaultProxy(info: ts.server.PluginCreateInfo): ts.LanguageService { + // tslint:disable-next-line:no-null-keyword + const proxy = Object.create(/*prototype*/ null); + const langSvc: any = info.languageService; + for (const k of Object.keys(langSvc)) { + // tslint:disable-next-line only-arrow-functions + proxy[k] = function () { + return langSvc[k].apply(langSvc, arguments); + }; + } + return proxy; + } + export class ScriptInfo { public version = 1; public editRanges: { length: number; textChangeRange: ts.TextChangeRange; }[] = []; @@ -268,15 +282,15 @@ namespace Harness.LanguageService { getHost(): LanguageServiceAdapterHost { return this.host; } getLanguageService(): ts.LanguageService { return ts.createLanguageService(this.host); } getClassifier(): ts.Classifier { return ts.createClassifier(); } - getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJavaScriptFileExtension(fileName)); } + getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJSFileExtension(fileName)); } } /// Shim adapter class ShimLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceShimHost, ts.CoreServicesShimHost { private nativeHost: NativeLanguageServiceHost; - public getModuleResolutionsForFile: (fileName: string) => string; - public getTypeReferenceDirectiveResolutionsForFile: (fileName: string) => string; + public getModuleResolutionsForFile: ((fileName: string) => string) | undefined; + public getTypeReferenceDirectiveResolutionsForFile: ((fileName: string) => string) | undefined; constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) { super(cancellationToken, options); @@ -455,11 +469,11 @@ namespace Harness.LanguageService { getSignatureHelpItems(fileName: string, position: number, options: ts.SignatureHelpItemsOptions | undefined): ts.SignatureHelpItems { return unwrapJSONCallResult(this.shim.getSignatureHelpItems(fileName, position, options)); } - getRenameInfo(fileName: string, position: number): ts.RenameInfo { - return unwrapJSONCallResult(this.shim.getRenameInfo(fileName, position)); + getRenameInfo(fileName: string, position: number, options?: ts.RenameInfoOptions): ts.RenameInfo { + return unwrapJSONCallResult(this.shim.getRenameInfo(fileName, position, options)); } - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ts.RenameLocation[] { - return unwrapJSONCallResult(this.shim.findRenameLocations(fileName, position, findInStrings, findInComments)); + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): ts.RenameLocation[] { + return unwrapJSONCallResult(this.shim.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename)); } getDefinitionAtPosition(fileName: string, position: number): ts.DefinitionInfo[] { return unwrapJSONCallResult(this.shim.getDefinitionAtPosition(fileName, position)); @@ -625,7 +639,7 @@ namespace Harness.LanguageService { // Server adapter class SessionClientHost extends NativeLanguageServiceHost implements ts.server.SessionClientHost { - private client: ts.server.SessionClient; + private client!: ts.server.SessionClient; constructor(cancellationToken: ts.HostCancellationToken | undefined, settings: ts.CompilerOptions | undefined) { super(cancellationToken, settings); @@ -833,25 +847,42 @@ namespace Harness.LanguageService { error: undefined }; + // Accepts configurations + case "configurable-diagnostic-adder": + let customMessage = "default message"; + return { + module: () => ({ + create(info: ts.server.PluginCreateInfo) { + customMessage = info.config.message; + const proxy = makeDefaultProxy(info); + proxy.getSemanticDiagnostics = filename => { + const prev = info.languageService.getSemanticDiagnostics(filename); + const sourceFile: ts.SourceFile = info.project.getSourceFile(ts.toPath(filename, /*basePath*/ undefined, ts.createGetCanonicalFileName(info.serverHost.useCaseSensitiveFileNames)))!; + prev.push({ + category: ts.DiagnosticCategory.Error, + file: sourceFile, + code: 9999, + length: 3, + messageText: customMessage, + start: 0 + }); + return prev; + }; + return proxy; + }, + onConfigurationChanged(config: any) { + customMessage = config.message; + } + }), + error: undefined + }; + default: return { module: undefined, error: new Error("Could not resolve module") }; } - - function makeDefaultProxy(info: ts.server.PluginCreateInfo): ts.LanguageService { - // tslint:disable-next-line:no-null-keyword - const proxy = Object.create(/*prototype*/ null); - const langSvc: any = info.languageService; - for (const k of Object.keys(langSvc)) { - // tslint:disable-next-line only-arrow-functions - proxy[k] = function () { - return langSvc[k].apply(langSvc, arguments); - }; - } - return proxy; - } } } diff --git a/src/harness/sourceMapRecorder.ts b/src/harness/sourceMapRecorder.ts index a1aa07f8733..d16aca21d66 100644 --- a/src/harness/sourceMapRecorder.ts +++ b/src/harness/sourceMapRecorder.ts @@ -1,44 +1,36 @@ namespace Harness.SourceMapRecorder { interface SourceMapSpanWithDecodeErrors { - sourceMapSpan: ts.SourceMapSpan; + sourceMapSpan: ts.Mapping; decodeErrors: string[] | undefined; } namespace SourceMapDecoder { let sourceMapMappings: string; let decodingIndex: number; - let mappings: ts.sourcemaps.MappingsDecoder | undefined; + let mappings: ts.MappingsDecoder | undefined; export interface DecodedMapping { - sourceMapSpan: ts.SourceMapSpan; + sourceMapSpan: ts.Mapping; error?: string; } - export function initializeSourceMapDecoding(sourceMapData: ts.SourceMapData) { + export function initializeSourceMapDecoding(sourceMapData: ts.SourceMapEmitResult) { decodingIndex = 0; - sourceMapMappings = sourceMapData.sourceMapMappings; - mappings = ts.sourcemaps.decodeMappings({ - version: 3, - file: sourceMapData.sourceMapFile, - sources: sourceMapData.sourceMapSources, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sourcesContent: sourceMapData.sourceMapSourcesContent, - mappings: sourceMapData.sourceMapMappings, - names: sourceMapData.sourceMapNames - }); + sourceMapMappings = sourceMapData.sourceMap.mappings; + mappings = ts.decodeMappings(sourceMapData.sourceMap.mappings); } export function decodeNextEncodedSourceMapSpan(): DecodedMapping { if (!mappings) return ts.Debug.fail("not initialized"); const result = mappings.next(); - if (result.done) return { error: mappings.error || "No encoded entry found", sourceMapSpan: mappings.lastSpan }; + if (result.done) return { error: mappings.error || "No encoded entry found", sourceMapSpan: mappings.state }; return { sourceMapSpan: result.value }; } export function hasCompletedDecoding() { if (!mappings) return ts.Debug.fail("not initialized"); - return mappings.decodingIndex === sourceMapMappings.length; + return mappings.pos === sourceMapMappings.length; } export function getRemainingDecodeString() { @@ -49,7 +41,7 @@ namespace Harness.SourceMapRecorder { namespace SourceMapSpanWriter { let sourceMapRecorder: Compiler.WriterAggregator; let sourceMapSources: string[]; - let sourceMapNames: string[] | undefined; + let sourceMapNames: string[] | null | undefined; let jsFile: documents.TextDocument; let jsLineMap: ReadonlyArray; @@ -61,10 +53,10 @@ namespace Harness.SourceMapRecorder { let nextJsLineToWrite: number; let spanMarkerContinues: boolean; - export function initializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMapData: ts.SourceMapData, currentJsFile: documents.TextDocument) { + export function initializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMapData: ts.SourceMapEmitResult, currentJsFile: documents.TextDocument) { sourceMapRecorder = sourceMapRecordWriter; - sourceMapSources = sourceMapData.sourceMapSources; - sourceMapNames = sourceMapData.sourceMapNames; + sourceMapSources = sourceMapData.sourceMap.sources; + sourceMapNames = sourceMapData.sourceMap.names; jsFile = currentJsFile; jsLineMap = jsFile.lineStarts; @@ -75,43 +67,39 @@ namespace Harness.SourceMapRecorder { spanMarkerContinues = false; SourceMapDecoder.initializeSourceMapDecoding(sourceMapData); - sourceMapRecorder.WriteLine("==================================================================="); - sourceMapRecorder.WriteLine("JsFile: " + sourceMapData.sourceMapFile); - sourceMapRecorder.WriteLine("mapUrl: " + sourceMapData.jsSourceMappingURL); - sourceMapRecorder.WriteLine("sourceRoot: " + sourceMapData.sourceMapSourceRoot); - sourceMapRecorder.WriteLine("sources: " + sourceMapData.sourceMapSources); - if (sourceMapData.sourceMapSourcesContent) { - sourceMapRecorder.WriteLine("sourcesContent: " + JSON.stringify(sourceMapData.sourceMapSourcesContent)); + sourceMapRecorder.WriteLine("JsFile: " + sourceMapData.sourceMap.file); + sourceMapRecorder.WriteLine("mapUrl: " + ts.tryGetSourceMappingURL(ts.getLineInfo(jsFile.text, jsLineMap))); + sourceMapRecorder.WriteLine("sourceRoot: " + sourceMapData.sourceMap.sourceRoot); + sourceMapRecorder.WriteLine("sources: " + sourceMapData.sourceMap.sources); + if (sourceMapData.sourceMap.sourcesContent) { + sourceMapRecorder.WriteLine("sourcesContent: " + JSON.stringify(sourceMapData.sourceMap.sourcesContent)); } sourceMapRecorder.WriteLine("==================================================================="); } - function getSourceMapSpanString(mapEntry: ts.SourceMapSpan, getAbsentNameIndex?: boolean) { - let mapString = "Emitted(" + (mapEntry.emittedLine + 1) + ", " + (mapEntry.emittedColumn + 1) + ") Source(" + (mapEntry.sourceLine + 1) + ", " + (mapEntry.sourceColumn + 1) + ") + SourceIndex(" + mapEntry.sourceIndex + ")"; - if (mapEntry.nameIndex! >= 0 && mapEntry.nameIndex! < sourceMapNames!.length) { - mapString += " name (" + sourceMapNames![mapEntry.nameIndex!] + ")"; - } - else { - if ((mapEntry.nameIndex && mapEntry.nameIndex !== -1) || getAbsentNameIndex) { - mapString += " nameIndex (" + mapEntry.nameIndex + ")"; + function getSourceMapSpanString(mapEntry: ts.Mapping, getAbsentNameIndex?: boolean) { + let mapString = "Emitted(" + (mapEntry.generatedLine + 1) + ", " + (mapEntry.generatedCharacter + 1) + ")"; + if (ts.isSourceMapping(mapEntry)) { + mapString += " Source(" + (mapEntry.sourceLine + 1) + ", " + (mapEntry.sourceCharacter + 1) + ") + SourceIndex(" + mapEntry.sourceIndex + ")"; + if (mapEntry.nameIndex! >= 0 && mapEntry.nameIndex! < sourceMapNames!.length) { + mapString += " name (" + sourceMapNames![mapEntry.nameIndex!] + ")"; + } + else { + if ((mapEntry.nameIndex && mapEntry.nameIndex !== -1) || getAbsentNameIndex) { + mapString += " nameIndex (" + mapEntry.nameIndex + ")"; + } } } return mapString; } - export function recordSourceMapSpan(sourceMapSpan: ts.SourceMapSpan) { + export function recordSourceMapSpan(sourceMapSpan: ts.Mapping) { // verify the decoded span is same as the new span const decodeResult = SourceMapDecoder.decodeNextEncodedSourceMapSpan(); let decodeErrors: string[] | undefined; - if (typeof decodeResult.error === "string" - || decodeResult.sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine - || decodeResult.sourceMapSpan.emittedColumn !== sourceMapSpan.emittedColumn - || decodeResult.sourceMapSpan.sourceLine !== sourceMapSpan.sourceLine - || decodeResult.sourceMapSpan.sourceColumn !== sourceMapSpan.sourceColumn - || decodeResult.sourceMapSpan.sourceIndex !== sourceMapSpan.sourceIndex - || decodeResult.sourceMapSpan.nameIndex !== sourceMapSpan.nameIndex) { + if (typeof decodeResult.error === "string" || !ts.sameMapping(decodeResult.sourceMapSpan, sourceMapSpan)) { if (decodeResult.error) { decodeErrors = ["!!^^ !!^^ There was decoding error in the sourcemap at this location: " + decodeResult.error]; } @@ -121,7 +109,7 @@ namespace Harness.SourceMapRecorder { decodeErrors.push("!!^^ !!^^ Decoded span from sourcemap's mappings entry: " + getSourceMapSpanString(decodeResult.sourceMapSpan, /*getAbsentNameIndex*/ true) + " Span encoded by the emitter:" + getSourceMapSpanString(sourceMapSpan, /*getAbsentNameIndex*/ true)); } - if (spansOnSingleLine.length && spansOnSingleLine[0].sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine) { + if (spansOnSingleLine.length && spansOnSingleLine[0].sourceMapSpan.generatedLine !== sourceMapSpan.generatedLine) { // On different line from the one that we have been recording till now, writeRecordedSpans(); spansOnSingleLine = []; @@ -129,14 +117,21 @@ namespace Harness.SourceMapRecorder { spansOnSingleLine.push({ sourceMapSpan, decodeErrors }); } - export function recordNewSourceFileSpan(sourceMapSpan: ts.SourceMapSpan, newSourceFileCode: string) { - assert.isTrue(spansOnSingleLine.length === 0 || spansOnSingleLine[0].sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine, "new file source map span should be on new line. We currently handle only that scenario"); + export function recordNewSourceFileSpan(sourceMapSpan: ts.Mapping, newSourceFileCode: string) { + let continuesLine = false; + if (spansOnSingleLine.length > 0 && spansOnSingleLine[0].sourceMapSpan.generatedCharacter === sourceMapSpan.generatedLine) { + writeRecordedSpans(); + spansOnSingleLine = []; + nextJsLineToWrite--; // walk back one line to reprint the line + continuesLine = true; + } + recordSourceMapSpan(sourceMapSpan); assert.isTrue(spansOnSingleLine.length === 1); sourceMapRecorder.WriteLine("-------------------------------------------------------------------"); - sourceMapRecorder.WriteLine("emittedFile:" + jsFile.file); - sourceMapRecorder.WriteLine("sourceFile:" + sourceMapSources[spansOnSingleLine[0].sourceMapSpan.sourceIndex]); + sourceMapRecorder.WriteLine("emittedFile:" + jsFile.file + (continuesLine ? ` (${sourceMapSpan.generatedLine + 1}, ${sourceMapSpan.generatedCharacter + 1})` : "")); + sourceMapRecorder.WriteLine("sourceFile:" + sourceMapSources[spansOnSingleLine[0].sourceMapSpan.sourceIndex!]); sourceMapRecorder.WriteLine("-------------------------------------------------------------------"); tsLineMap = ts.computeLineStarts(newSourceFileCode); @@ -195,7 +190,7 @@ namespace Harness.SourceMapRecorder { prevEmittedCol = 0; for (let i = 0; i < spansOnSingleLine.length; i++) { fn(spansOnSingleLine[i], i); - prevEmittedCol = spansOnSingleLine[i].sourceMapSpan.emittedColumn; + prevEmittedCol = spansOnSingleLine[i].sourceMapSpan.generatedCharacter; } } @@ -206,7 +201,7 @@ namespace Harness.SourceMapRecorder { } } - function writeSourceMapMarker(currentSpan: SourceMapSpanWithDecodeErrors, index: number, endColumn = currentSpan.sourceMapSpan.emittedColumn, endContinues = false) { + function writeSourceMapMarker(currentSpan: SourceMapSpanWithDecodeErrors, index: number, endColumn = currentSpan.sourceMapSpan.generatedCharacter, endContinues = false) { const markerId = getMarkerId(index); markerIds.push(markerId); @@ -223,7 +218,7 @@ namespace Harness.SourceMapRecorder { } function writeSourceMapSourceText(currentSpan: SourceMapSpanWithDecodeErrors, index: number) { - const sourcePos = tsLineMap[currentSpan.sourceMapSpan.sourceLine] + (currentSpan.sourceMapSpan.sourceColumn); + const sourcePos = tsLineMap[currentSpan.sourceMapSpan.sourceLine!] + (currentSpan.sourceMapSpan.sourceCharacter!); let sourceText = ""; if (prevWrittenSourcePos < sourcePos) { // Position that goes forward, get text @@ -255,7 +250,7 @@ namespace Harness.SourceMapRecorder { } if (spansOnSingleLine.length) { - const currentJsLine = spansOnSingleLine[0].sourceMapSpan.emittedLine; + const currentJsLine = spansOnSingleLine[0].sourceMapSpan.generatedLine; // Write js line writeJsFileLines(currentJsLine + 1); @@ -280,14 +275,14 @@ namespace Harness.SourceMapRecorder { } } - export function getSourceMapRecord(sourceMapDataList: ReadonlyArray, program: ts.Program, jsFiles: ReadonlyArray, declarationFiles: ReadonlyArray) { + export function getSourceMapRecord(sourceMapDataList: ReadonlyArray, program: ts.Program, jsFiles: ReadonlyArray, declarationFiles: ReadonlyArray) { const sourceMapRecorder = new Compiler.WriterAggregator(); for (let i = 0; i < sourceMapDataList.length; i++) { const sourceMapData = sourceMapDataList[i]; let prevSourceFile: ts.SourceFile | undefined; let currentFile: documents.TextDocument; - if (ts.endsWith(sourceMapData.sourceMapFile, ts.Extension.Dts)) { + if (ts.endsWith(sourceMapData.sourceMap.file, ts.Extension.Dts)) { if (sourceMapDataList.length > jsFiles.length) { currentFile = declarationFiles[Math.floor(i / 2)]; // When both kinds of source map are present, they alternate js/dts } @@ -305,11 +300,15 @@ namespace Harness.SourceMapRecorder { } SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMapData, currentFile); - const mapper = ts.sourcemaps.decodeMappings({ mappings: sourceMapData.sourceMapMappings, sources: sourceMapData.sourceMapSources }); + const mapper = ts.decodeMappings(sourceMapData.sourceMap.mappings); for (let { value: decodedSourceMapping, done } = mapper.next(); !done; { value: decodedSourceMapping, done } = mapper.next()) { - const currentSourceFile = program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex])!; + const currentSourceFile = ts.isSourceMapping(decodedSourceMapping) + ? program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex]) + : undefined; if (currentSourceFile !== prevSourceFile) { - SourceMapSpanWriter.recordNewSourceFileSpan(decodedSourceMapping, currentSourceFile.text); + if (currentSourceFile) { + SourceMapSpanWriter.recordNewSourceFileSpan(decodedSourceMapping, currentSourceFile.text); + } prevSourceFile = currentSourceFile; } else { diff --git a/src/harness/typeWriter.ts b/src/harness/typeWriter.ts index 67f79a1a1a3..b0b20c92e64 100644 --- a/src/harness/typeWriter.ts +++ b/src/harness/typeWriter.ts @@ -21,7 +21,7 @@ interface TypeWriterResult { } class TypeWriterWalker { - currentSourceFile: ts.SourceFile; + currentSourceFile!: ts.SourceFile; private checker: ts.TypeChecker; diff --git a/src/harness/utils.ts b/src/harness/utils.ts index 4650badadaf..5938db7d62c 100644 --- a/src/harness/utils.ts +++ b/src/harness/utils.ts @@ -7,6 +7,21 @@ namespace utils { return text !== undefined ? text.replace(testPathPrefixRegExp, (_, scheme) => scheme || (retainTrailingDirectorySeparator ? "/" : "")) : undefined!; // TODO: GH#18217 } + function createDiagnosticMessageReplacer string[]>(diagnosticMessage: ts.DiagnosticMessage, replacer: R) { + const messageParts = diagnosticMessage.message.split(/{\d+}/g); + const regExp = new RegExp(`^(?:${messageParts.map(ts.regExpEscape).join("(.*?)")})$`); + type Args = R extends (messageArgs: string[], ...args: infer A) => string[] ? A : []; + return (text: string, ...args: Args) => text.replace(regExp, (_, ...fixedArgs) => ts.formatStringFromArgs(diagnosticMessage.message, replacer(fixedArgs, ...args))); + } + + const replaceTypesVersionsMessage = createDiagnosticMessageReplacer( + ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, + ([entry, , moduleName], compilerVersion) => [entry, compilerVersion, moduleName]); + + export function sanitizeTraceResolutionLogEntry(text: string) { + return text && removeTestPathPrefixes(replaceTypesVersionsMessage(text, "3.1.0-dev")); + } + /** * Removes leading indentation from a template literal string. */ @@ -82,4 +97,16 @@ namespace utils { export function addUTF8ByteOrderMark(text: string) { return getByteOrderMarkLength(text) === 0 ? "\u00EF\u00BB\u00BF" + text : text; } + + export function theory(name: string, cb: (...args: T) => void, data: T[]) { + for (const entry of data) { + it(`${name}(${entry.map(formatTheoryDatum).join(", ")})`, () => cb(...entry)); + } + } + + function formatTheoryDatum(value: any) { + return typeof value === "function" ? value.name || "" : + value === undefined ? "undefined" : + JSON.stringify(value); + } } \ No newline at end of file diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 57fa33a84c2..e82ee36f8fe 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -4,6 +4,8 @@ namespace ts.TestFSWithWatch { content: `/// interface Boolean {} interface Function {} +interface CallableFunction {} +interface NewableFunction {} interface IArguments {} interface Number { toExponential: any; } interface Object {} @@ -126,7 +128,7 @@ interface Array {}` return s && isString((s).symLink); } - function invokeWatcherCallbacks(callbacks: T[], invokeCallback: (cb: T) => void): void { + function invokeWatcherCallbacks(callbacks: ReadonlyArray | undefined, invokeCallback: (cb: T) => void): void { if (callbacks) { // The array copy is made to ensure that even if one of the callback removes the callbacks, // we dont miss any callbacks following it @@ -187,9 +189,10 @@ interface Array {}` } export function checkArray(caption: string, actual: ReadonlyArray, expected: ReadonlyArray) { + checkMapKeys(caption, arrayToMap(actual, identity), expected); assert.equal(actual.length, expected.length, `${caption}: incorrect actual number of files, expected:\r\n${expected.join("\r\n")}\r\ngot: ${actual.join("\r\n")}`); for (const f of expected) { - assert.equal(true, contains(actual, f), `${caption}: expected to find ${f} in ${actual}`); + assert.isTrue(contains(actual, f), `${caption}: expected to find ${f} in ${actual}`); } } @@ -338,6 +341,7 @@ interface Array {}` private readonly currentDirectory: string; private readonly dynamicPriorityWatchFile: HostWatchFile | undefined; private readonly customRecursiveWatchDirectory: HostWatchDirectory | undefined; + public require: ((initialPath: string, moduleName: string) => server.RequireResult) | undefined; constructor(public withSafeList: boolean, public useCaseSensitiveFileNames: boolean, executingFilePath: string, currentDirectory: string, fileOrFolderorSymLinkList: ReadonlyArray, public readonly newLine = "\n", public readonly useWindowsStylePath?: boolean, private readonly environmentVariables?: Map) { this.getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); @@ -584,8 +588,8 @@ interface Array {}` } this.invokeFileWatcher(fileOrDirectory.fullPath, FileWatcherEventKind.Created); if (isFsFolder(fileOrDirectory)) { - this.invokeDirectoryWatcher(fileOrDirectory.fullPath, ""); - this.invokeWatchedDirectoriesRecursiveCallback(fileOrDirectory.fullPath, ""); + this.invokeDirectoryWatcher(fileOrDirectory.fullPath, fileOrDirectory.fullPath); + this.invokeWatchedDirectoriesRecursiveCallback(fileOrDirectory.fullPath, fileOrDirectory.fullPath); } this.invokeDirectoryWatcher(folder.fullPath, fileOrDirectory.fullPath); } @@ -647,15 +651,15 @@ interface Array {}` // For overriding the methods invokeWatchedDirectoriesCallback(folderFullPath: string, relativePath: string) { - invokeWatcherCallbacks(this.watchedDirectories.get(this.toPath(folderFullPath))!, cb => this.directoryCallback(cb, relativePath)); + invokeWatcherCallbacks(this.watchedDirectories.get(this.toPath(folderFullPath)), cb => this.directoryCallback(cb, relativePath)); } invokeWatchedDirectoriesRecursiveCallback(folderFullPath: string, relativePath: string) { - invokeWatcherCallbacks(this.watchedDirectoriesRecursive.get(this.toPath(folderFullPath))!, cb => this.directoryCallback(cb, relativePath)); + invokeWatcherCallbacks(this.watchedDirectoriesRecursive.get(this.toPath(folderFullPath)), cb => this.directoryCallback(cb, relativePath)); } - invokeFileWatcher(fileFullPath: string, eventKind: FileWatcherEventKind, useFileNameInCallback?: boolean) { - invokeWatcherCallbacks(this.watchedFiles.get(this.toPath(fileFullPath))!, ({ cb, fileName }) => cb(useFileNameInCallback ? fileName : fileFullPath, eventKind)); + private invokeFileWatcher(fileFullPath: string, eventKind: FileWatcherEventKind, useFileNameInCallback?: boolean) { + invokeWatcherCallbacks(this.watchedFiles.get(this.toPath(fileFullPath)), ({ cb, fileName }) => cb(useFileNameInCallback ? fileName : fileFullPath, eventKind)); } private getRelativePathToDirectory(directoryFullPath: string, fileFullPath: string) { @@ -934,7 +938,12 @@ interface Array {}` const folder = this.fs.get(base) as FsFolder; Debug.assert(isFsFolder(folder)); - this.addFileOrFolderInFolder(folder, file); + if (!this.fs.has(file.path)) { + this.addFileOrFolderInFolder(folder, file); + } + else { + this.modifyFile(path, content); + } } write(message: string) { @@ -980,4 +989,16 @@ interface Array {}` return this.environmentVariables && this.environmentVariables.get(name) || ""; } } + + export const tsbuildProjectsLocation = "/user/username/projects"; + export function getTsBuildProjectFilePath(project: string, file: string) { + return `${tsbuildProjectsLocation}/${project}/${file}`; + } + + export function getTsBuildProjectFile(project: string, file: string): File { + return { + path: getTsBuildProjectFilePath(project, file), + content: Harness.IO.readFile(`${Harness.IO.getWorkspaceRoot()}/tests/projects/${project}/${file}`)! + }; + } } diff --git a/src/harness/vpath.ts b/src/harness/vpath.ts index 6211fc9278a..68ba0465e50 100644 --- a/src/harness/vpath.ts +++ b/src/harness/vpath.ts @@ -21,8 +21,8 @@ namespace vpath { export import relative = ts.getRelativePathFromDirectory; export import beneath = ts.containsPath; export import changeExtension = ts.changeAnyExtension; - export import isTypeScript = ts.hasTypeScriptFileExtension; - export import isJavaScript = ts.hasJavaScriptFileExtension; + export import isTypeScript = ts.hasTSFileExtension; + export import isJavaScript = ts.hasJSFileExtension; const invalidRootComponentRegExp = /^(?!(\/|\/\/\w+\/|[a-zA-Z]:\/?|)$)/; const invalidNavigableComponentRegExp = /[:*?"<>|]/; @@ -133,4 +133,4 @@ namespace vpath { export function isTsConfigFile(path: string): boolean { return path.indexOf("tsconfig") !== -1 && path.indexOf("json") !== -1; } -} \ No newline at end of file +} diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index e9c96ba2bf6..379ca6491a6 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -21,16 +21,14 @@ namespace ts.JsTyping { export interface CachedTyping { typingLocation: string; - version: Semver; + version: Version; } - /* @internal */ export function isTypingUpToDate(cachedTyping: CachedTyping, availableTypingVersions: MapLike) { - const availableVersion = Semver.parse(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")!); - return !availableVersion.greaterThan(cachedTyping.version); + const availableVersion = new Version(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")!); + return availableVersion.compareTo(cachedTyping.version) <= 0; } - /* @internal */ export const nodeCoreModuleList: ReadonlyArray = [ "assert", "async_hooks", @@ -70,7 +68,6 @@ namespace ts.JsTyping { "zlib" ]; - /* @internal */ export const nodeCoreModules = arrayToSet(nodeCoreModuleList); /** @@ -122,7 +119,7 @@ namespace ts.JsTyping { // Only infer typings for .js and .jsx files fileNames = mapDefined(fileNames, fileName => { const path = normalizePath(fileName); - if (hasJavaScriptFileExtension(path)) { + if (hasJSFileExtension(path)) { return path; } }); @@ -218,7 +215,7 @@ namespace ts.JsTyping { */ function getTypingNamesFromSourceFileNames(fileNames: string[]) { const fromFileNames = mapDefined(fileNames, j => { - if (!hasJavaScriptFileExtension(j)) return undefined; + if (!hasJSFileExtension(j)) return undefined; const inferredTypingName = removeFileExtension(getBaseFileName(j.toLowerCase())); const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); diff --git a/src/jsTyping/semver.ts b/src/jsTyping/semver.ts deleted file mode 100644 index 1c58da8c8f7..00000000000 --- a/src/jsTyping/semver.ts +++ /dev/null @@ -1,61 +0,0 @@ -/* @internal */ -namespace ts { - function stringToInt(str: string): number { - const n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error(`Error in parseInt(${JSON.stringify(str)})`); - } - return n; - } - - const isPrereleaseRegex = /^(.*)-next.\d+/; - const prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - const semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - - export class Semver { - static parse(semver: string): Semver { - const isPrerelease = isPrereleaseRegex.test(semver); - const result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error(`Unexpected semver: ${semver} (isPrerelease: ${isPrerelease})`); - } - return result; - } - - static fromRaw({ major, minor, patch, isPrerelease }: Semver): Semver { - return new Semver(major, minor, patch, isPrerelease); - } - - // This must parse the output of `versionString`. - private static tryParse(semver: string, isPrerelease: boolean): Semver | undefined { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - const rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - const match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - } - - private constructor( - readonly major: number, readonly minor: number, readonly patch: number, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - readonly isPrerelease: boolean) { } - - get versionString(): string { - return this.isPrerelease ? `${this.major}.${this.minor}.0-next.${this.patch}` : `${this.major}.${this.minor}.${this.patch}`; - } - - equals(sem: Semver): boolean { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - } - - greaterThan(sem: Semver): boolean { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - } - } -} \ No newline at end of file diff --git a/src/jsTyping/shared.ts b/src/jsTyping/shared.ts index 54b34193d06..8dc4c02e9c4 100644 --- a/src/jsTyping/shared.ts +++ b/src/jsTyping/shared.ts @@ -4,6 +4,7 @@ namespace ts.server { export const ActionSet: ActionSet = "action::set"; export const ActionInvalidate: ActionInvalidate = "action::invalidate"; export const ActionPackageInstalled: ActionPackageInstalled = "action::packageInstalled"; + export const ActionValueInspected: ActionValueInspected = "action::valueInspected"; export const EventTypesRegistry: EventTypesRegistry = "event::typesRegistry"; export const EventBeginInstallTypes: EventBeginInstallTypes = "event::beginInstallTypes"; export const EventEndInstallTypes: EventEndInstallTypes = "event::endInstallTypes"; @@ -33,7 +34,6 @@ namespace ts.server { : undefined; } - /*@internal*/ export function nowString() { // E.g. "12:34:56.789" const d = new Date(); diff --git a/src/jsTyping/tsconfig.json b/src/jsTyping/tsconfig.json index 4886463e163..ac5b8b19c29 100644 --- a/src/jsTyping/tsconfig.json +++ b/src/jsTyping/tsconfig.json @@ -16,7 +16,6 @@ "files": [ "shared.ts", "types.ts", - "jsTyping.ts", - "semver.ts" + "jsTyping.ts" ] } diff --git a/src/jsTyping/types.ts b/src/jsTyping/types.ts index 4e00c2eb6f5..6bc3e667f87 100644 --- a/src/jsTyping/types.ts +++ b/src/jsTyping/types.ts @@ -2,17 +2,14 @@ declare namespace ts.server { export type ActionSet = "action::set"; export type ActionInvalidate = "action::invalidate"; export type ActionPackageInstalled = "action::packageInstalled"; + export type ActionValueInspected = "action::valueInspected"; export type EventTypesRegistry = "event::typesRegistry"; export type EventBeginInstallTypes = "event::beginInstallTypes"; export type EventEndInstallTypes = "event::endInstallTypes"; export type EventInitializationFailed = "event::initializationFailed"; - export interface SortedReadonlyArray extends ReadonlyArray { - " __sortedArrayBrand": any; - } - export interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } export interface TypingInstallerRequestWithProjectName { @@ -20,7 +17,7 @@ declare namespace ts.server { } /* @internal */ - export type TypingInstallerRequestUnion = DiscoverTypings | CloseProject | TypesRegistryRequest | InstallPackageRequest; + export type TypingInstallerRequestUnion = DiscoverTypings | CloseProject | TypesRegistryRequest | InstallPackageRequest | InspectValueRequest; export interface DiscoverTypings extends TypingInstallerRequestWithProjectName { readonly fileNames: string[]; @@ -47,6 +44,12 @@ declare namespace ts.server { readonly projectRootPath: Path; } + /* @internal */ + export interface InspectValueRequest { + readonly kind: "inspectValue"; + readonly options: InspectValueOptions; + } + /* @internal */ export interface TypesRegistryResponse extends TypingInstallerResponse { readonly kind: EventTypesRegistry; @@ -59,6 +62,12 @@ declare namespace ts.server { readonly message: string; } + /* @internal */ + export interface InspectValueResponse { + readonly kind: ActionValueInspected; + readonly result: ValueInfo; + } + export interface InitializationFailedResponse extends TypingInstallerResponse { readonly kind: EventInitializationFailed; readonly message: string; @@ -106,5 +115,5 @@ declare namespace ts.server { } /* @internal */ - export type TypingInstallerResponseUnion = SetTypings | InvalidateCachedTypings | TypesRegistryResponse | PackageInstalledResponse | InstallTypes | InitializationFailedResponse; + export type TypingInstallerResponseUnion = SetTypings | InvalidateCachedTypings | TypesRegistryResponse | PackageInstalledResponse | InspectValueResponse | InstallTypes | InitializationFailedResponse; } diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index 2746b0466d9..03eb2a4a961 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -142,6 +142,7 @@ interface BiquadFilterOptions extends AudioNodeOptions { } interface BlobPropertyBag { + endings?: EndingType; type?: string; } @@ -200,11 +201,12 @@ interface ComputedEffectTiming extends EffectTiming { progress?: number | null; } -interface ComputedKeyframe extends Record { - composite?: CompositeOperation | null; - computedOffset?: number; - easing?: string; - offset?: number | null; +interface ComputedKeyframe { + composite: CompositeOperationOrAuto; + computedOffset: number; + easing: string; + offset: number | null; + [property: string]: string | number | null | undefined; } interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { @@ -566,10 +568,11 @@ interface KeyboardEventInit extends EventModifierInit { repeat?: boolean; } -interface Keyframe extends Record { - composite?: CompositeOperation | null; +interface Keyframe { + composite?: CompositeOperationOrAuto; easing?: string; offset?: number | null; + [property: string]: string | number | null | undefined; } interface KeyframeAnimationOptions extends KeyframeEffectOptions { @@ -887,6 +890,12 @@ interface PeriodicWaveOptions extends PeriodicWaveConstraints { real?: number[] | Float32Array; } +interface PipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + preventClose?: boolean; +} + interface PointerEventInit extends MouseEventInit { height?: number; isPrimary?: boolean; @@ -921,10 +930,11 @@ interface PromiseRejectionEventInit extends EventInit { reason?: any; } -interface PropertyIndexedKeyframes extends Record { - composite?: CompositeOperation | (CompositeOperation | null)[]; +interface PropertyIndexedKeyframes { + composite?: CompositeOperationOrAuto | CompositeOperationOrAuto[]; easing?: string | string[]; offset?: number | (number | null)[]; + [property: string]: string | string[] | number | null | (number | null)[] | undefined; } interface PushSubscriptionJSON { @@ -938,9 +948,9 @@ interface PushSubscriptionOptionsInit { userVisibleOnly?: boolean; } -interface QueuingStrategy { +interface QueuingStrategy { highWaterMark?: number; - size?: WritableStreamChunkCallback; + size?: QueuingStrategySizeCallback; } interface RTCAnswerOptions extends RTCOfferAnswerOptions { @@ -1496,6 +1506,14 @@ interface TrackEventInit extends EventInit { track?: VideoTrack | AudioTrack | TextTrack | null; } +interface Transformer { + flush?: TransformStreamDefaultControllerCallback; + readableType?: undefined; + start?: TransformStreamDefaultControllerCallback; + transform?: TransformStreamDefaultControllerTransformCallback; + writableType?: undefined; +} + interface TransitionEventInit extends EventInit { elapsedTime?: number; propertyName?: string; @@ -1507,11 +1525,27 @@ interface UIEventInit extends EventInit { view?: Window | null; } -interface UnderlyingSink { +interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; +} + +interface UnderlyingSink { abort?: WritableStreamErrorCallback; - close?: WritableStreamDefaultControllerCallback; - start: WritableStreamDefaultControllerCallback; - write?: WritableStreamChunkCallback; + close?: WritableStreamDefaultControllerCloseCallback; + start?: WritableStreamDefaultControllerStartCallback; + type?: undefined; + write?: WritableStreamDefaultControllerWriteCallback; +} + +interface UnderlyingSource { + cancel?: ReadableStreamErrorCallback; + pull?: ReadableStreamDefaultControllerCallback; + start?: ReadableStreamDefaultControllerCallback; + type?: undefined; } interface VRDisplayEventInit extends EventInit { @@ -1561,6 +1595,12 @@ interface WheelEventInit extends MouseEventInit { deltaZ?: number; } +interface WorkerOptions { + credentials?: RequestCredentials; + name?: string; + type?: WorkerType; +} + interface WorkletOptions { credentials?: RequestCredentials; } @@ -1570,18 +1610,12 @@ interface EventListener { } interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; + drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void; + drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void; + vertexAttribDivisorANGLE(index: GLuint, divisor: GLuint): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum; } -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -}; - interface AbortController { /** * Returns the AbortSignal object associated with this object. @@ -2168,7 +2202,7 @@ declare var Blob: { }; interface Body { - readonly body: ReadableStream | null; + readonly body: ReadableStream | null; readonly bodyUsed: boolean; arrayBuffer(): Promise; blob(): Promise; @@ -2213,14 +2247,14 @@ interface BroadcastChannelEventMap { messageerror: MessageEvent; } -interface ByteLengthQueuingStrategy { +interface ByteLengthQueuingStrategy extends QueuingStrategy { highWaterMark: number; - size(chunk?: any): number; + size(chunk: ArrayBufferView): number; } declare var ByteLengthQueuingStrategy: { prototype: ByteLengthQueuingStrategy; - new(strategy: QueuingStrategy): ByteLengthQueuingStrategy; + new(options: { highWaterMark: number }): ByteLengthQueuingStrategy; }; interface CDATASection extends Text { @@ -2383,15 +2417,15 @@ interface CSSStyleDeclaration { alignItems: string | null; alignSelf: string | null; alignmentBaseline: string | null; - animation: string | null; - animationDelay: string | null; - animationDirection: string | null; - animationDuration: string | null; - animationFillMode: string | null; - animationIterationCount: string | null; - animationName: string | null; - animationPlayState: string | null; - animationTimingFunction: string | null; + animation: string; + animationDelay: string; + animationDirection: string; + animationDuration: string; + animationFillMode: string; + animationIterationCount: string; + animationName: string; + animationPlayState: string; + animationTimingFunction: string; backfaceVisibility: string | null; background: string | null; backgroundAttachment: string | null; @@ -2634,6 +2668,7 @@ interface CSSStyleDeclaration { rubyOverhang: string | null; rubyPosition: string | null; scale: string | null; + scrollBehavior: string; stopColor: string | null; stopOpacity: string | null; stroke: string | null; @@ -2659,50 +2694,79 @@ interface CSSStyleDeclaration { textTransform: string | null; textUnderlinePosition: string | null; top: string | null; - touchAction: string | null; + touchAction: string; transform: string | null; transformOrigin: string | null; transformStyle: string | null; - transition: string | null; - transitionDelay: string | null; - transitionDuration: string | null; - transitionProperty: string | null; - transitionTimingFunction: string | null; + transition: string; + transitionDelay: string; + transitionDuration: string; + transitionProperty: string; + transitionTimingFunction: string; translate: string | null; unicodeBidi: string | null; userSelect: string | null; verticalAlign: string | null; visibility: string | null; - webkitAlignContent: string | null; - webkitAlignItems: string | null; - webkitAlignSelf: string | null; - webkitAnimation: string | null; - webkitAnimationDelay: string | null; - webkitAnimationDirection: string | null; - webkitAnimationDuration: string | null; - webkitAnimationFillMode: string | null; - webkitAnimationIterationCount: string | null; - webkitAnimationName: string | null; - webkitAnimationPlayState: string | null; - webkitAnimationTimingFunction: string | null; - webkitAppearance: string | null; - webkitBackfaceVisibility: string | null; - webkitBackgroundClip: string | null; - webkitBackgroundOrigin: string | null; - webkitBackgroundSize: string | null; - webkitBorderBottomLeftRadius: string | null; - webkitBorderBottomRightRadius: string | null; + /** @deprecated */ + webkitAlignContent: string; + /** @deprecated */ + webkitAlignItems: string; + /** @deprecated */ + webkitAlignSelf: string; + /** @deprecated */ + webkitAnimation: string; + /** @deprecated */ + webkitAnimationDelay: string; + /** @deprecated */ + webkitAnimationDirection: string; + /** @deprecated */ + webkitAnimationDuration: string; + /** @deprecated */ + webkitAnimationFillMode: string; + /** @deprecated */ + webkitAnimationIterationCount: string; + /** @deprecated */ + webkitAnimationName: string; + /** @deprecated */ + webkitAnimationPlayState: string; + /** @deprecated */ + webkitAnimationTimingFunction: string; + /** @deprecated */ + webkitAppearance: string; + /** @deprecated */ + webkitBackfaceVisibility: string; + /** @deprecated */ + webkitBackgroundClip: string; + /** @deprecated */ + webkitBackgroundOrigin: string; + /** @deprecated */ + webkitBackgroundSize: string; + /** @deprecated */ + webkitBorderBottomLeftRadius: string; + /** @deprecated */ + webkitBorderBottomRightRadius: string; webkitBorderImage: string | null; - webkitBorderRadius: string | null; - webkitBorderTopLeftRadius: string | null; - webkitBorderTopRightRadius: string | null; - webkitBoxAlign: string | null; + /** @deprecated */ + webkitBorderRadius: string; + /** @deprecated */ + webkitBorderTopLeftRadius: string; + /** @deprecated */ + webkitBorderTopRightRadius: string; + /** @deprecated */ + webkitBoxAlign: string; webkitBoxDirection: string | null; - webkitBoxFlex: string | null; - webkitBoxOrdinalGroup: string | null; + /** @deprecated */ + webkitBoxFlex: string; + /** @deprecated */ + webkitBoxOrdinalGroup: string; webkitBoxOrient: string | null; - webkitBoxPack: string | null; - webkitBoxSizing: string | null; + /** @deprecated */ + webkitBoxPack: string; + /** @deprecated */ + webkitBoxShadow: string; + /** @deprecated */ + webkitBoxSizing: string; webkitColumnBreakAfter: string | null; webkitColumnBreakBefore: string | null; webkitColumnBreakInside: string | null; @@ -2715,32 +2779,85 @@ interface CSSStyleDeclaration { webkitColumnSpan: string | null; webkitColumnWidth: any; webkitColumns: string | null; - webkitFilter: string | null; - webkitFlex: string | null; - webkitFlexBasis: string | null; - webkitFlexDirection: string | null; - webkitFlexFlow: string | null; - webkitFlexGrow: string | null; - webkitFlexShrink: string | null; - webkitFlexWrap: string | null; - webkitJustifyContent: string | null; - webkitOrder: string | null; - webkitPerspective: string | null; - webkitPerspectiveOrigin: string | null; + /** @deprecated */ + webkitFilter: string; + /** @deprecated */ + webkitFlex: string; + /** @deprecated */ + webkitFlexBasis: string; + /** @deprecated */ + webkitFlexDirection: string; + /** @deprecated */ + webkitFlexFlow: string; + /** @deprecated */ + webkitFlexGrow: string; + /** @deprecated */ + webkitFlexShrink: string; + /** @deprecated */ + webkitFlexWrap: string; + /** @deprecated */ + webkitJustifyContent: string; + /** @deprecated */ + webkitMask: string; + /** @deprecated */ + webkitMaskBoxImage: string; + /** @deprecated */ + webkitMaskBoxImageOutset: string; + /** @deprecated */ + webkitMaskBoxImageRepeat: string; + /** @deprecated */ + webkitMaskBoxImageSlice: string; + /** @deprecated */ + webkitMaskBoxImageSource: string; + /** @deprecated */ + webkitMaskBoxImageWidth: string; + /** @deprecated */ + webkitMaskClip: string; + /** @deprecated */ + webkitMaskComposite: string; + /** @deprecated */ + webkitMaskImage: string; + /** @deprecated */ + webkitMaskOrigin: string; + /** @deprecated */ + webkitMaskPosition: string; + /** @deprecated */ + webkitMaskRepeat: string; + /** @deprecated */ + webkitMaskSize: string; + /** @deprecated */ + webkitOrder: string; + /** @deprecated */ + webkitPerspective: string; + /** @deprecated */ + webkitPerspectiveOrigin: string; webkitTapHighlightColor: string | null; - webkitTextFillColor: string | null; - webkitTextSizeAdjust: any; - webkitTextStroke: string | null; - webkitTextStrokeColor: string | null; - webkitTextStrokeWidth: string | null; - webkitTransform: string | null; - webkitTransformOrigin: string | null; - webkitTransformStyle: string | null; - webkitTransition: string | null; - webkitTransitionDelay: string | null; - webkitTransitionDuration: string | null; - webkitTransitionProperty: string | null; - webkitTransitionTimingFunction: string | null; + /** @deprecated */ + webkitTextFillColor: string; + /** @deprecated */ + webkitTextSizeAdjust: string; + /** @deprecated */ + webkitTextStroke: string; + /** @deprecated */ + webkitTextStrokeColor: string; + /** @deprecated */ + webkitTextStrokeWidth: string; + /** @deprecated */ + webkitTransform: string; + /** @deprecated */ + webkitTransformOrigin: string; + /** @deprecated */ + webkitTransformStyle: string; + /** @deprecated */ + webkitTransition: string; + /** @deprecated */ + webkitTransitionDelay: string; + /** @deprecated */ + webkitTransitionDuration: string; + /** @deprecated */ + webkitTransitionProperty: string; + /** @deprecated */ + webkitTransitionTimingFunction: string; webkitUserModify: string | null; webkitUserSelect: string | null; webkitWritingMode: string | null; @@ -3221,14 +3338,14 @@ interface Coordinates { readonly speed: number | null; } -interface CountQueuingStrategy { +interface CountQueuingStrategy extends QueuingStrategy { highWaterMark: number; - size(): number; + size(chunk: any): 1; } declare var CountQueuingStrategy: { prototype: CountQueuingStrategy; - new(strategy: QueuingStrategy): CountQueuingStrategy; + new(options: { highWaterMark: number }): CountQueuingStrategy; }; interface Crypto { @@ -3984,7 +4101,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** * Gets a reference to the root node of the document. */ - readonly documentElement: HTMLElement | null; + readonly documentElement: HTMLElement; /** * Returns document's URL. */ @@ -4016,7 +4133,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** * Returns the head element. */ - readonly head: HTMLHeadElement | null; + readonly head: HTMLHeadElement; readonly hidden: boolean; /** * Retrieves a collection, in source order, of img objects in the document. @@ -4046,7 +4163,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** * Contains information about the current URL. */ - location: Location | null; + location: Location; onfullscreenchange: ((this: Document, ev: Event) => any) | null; onfullscreenerror: ((this: Document, ev: Event) => any) | null; /** @@ -4096,6 +4213,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** @deprecated */ captureEvents(): void; caretPositionFromPoint(x: number, y: number): CaretPosition | null; + /** @deprecated */ caretRangeFromPoint(x: number, y: number): Range; /** @deprecated */ clear(): void; @@ -4149,6 +4267,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par 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: "cursor"): SVGCursorElement; 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; @@ -4321,7 +4440,9 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par * @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 | null, entityReferenceExpansion?: boolean): TreeWalker; + createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter | null): TreeWalker; + /** @deprecated */ + createTreeWalker(root: Node, whatToShow: number, filter: NodeFilter | null, entityReferenceExpansion?: boolean): TreeWalker; /** * Returns the element for the specified x coordinate and the specified y coordinate. * @param x The x-offset @@ -4329,7 +4450,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par */ elementFromPoint(x: number, y: number): Element | null; elementsFromPoint(x: number, y: number): Element[]; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | ((prefix: string) => string | null) | null, type: number, result: XPathResult | null): XPathResult; /** * Executes a command on the current document, current selection, or the given range. * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. @@ -4550,6 +4671,9 @@ interface DocumentOrShadowRoot { * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. */ readonly styleSheets: StyleSheetList; + caretPositionFromPoint(x: number, y: number): CaretPosition | null; + /** @deprecated */ + caretRangeFromPoint(x: number, y: number): Range; elementFromPoint(x: number, y: number): Element | null; elementsFromPoint(x: number, y: number): Element[]; getSelection(): Selection | null; @@ -4601,35 +4725,28 @@ declare var DynamicsCompressorNode: { }; interface EXT_blend_minmax { - readonly MAX_EXT: number; - readonly MIN_EXT: number; + readonly MAX_EXT: GLenum; + readonly MIN_EXT: GLenum; } interface EXT_frag_depth { } interface EXT_sRGB { - readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; - readonly SRGB8_ALPHA8_EXT: number; - readonly SRGB_ALPHA_EXT: number; - readonly SRGB_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: GLenum; + readonly SRGB8_ALPHA8_EXT: GLenum; + readonly SRGB_ALPHA_EXT: GLenum; + readonly SRGB_EXT: GLenum; } interface EXT_shader_texture_lod { } interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: GLenum; + readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum; } -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -}; - interface ElementEventMap { "fullscreenchange": Event; "fullscreenerror": Event; @@ -4847,6 +4964,7 @@ interface Event { */ readonly isTrusted: boolean; returnValue: boolean; + /** @deprecated */ readonly srcElement: Element | null; /** * Returns the object to which event is dispatched (its target). @@ -5013,7 +5131,7 @@ interface FileReader extends EventTarget { readAsArrayBuffer(blob: Blob): void; readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, label?: string): void; + readAsText(blob: Blob, encoding?: string): void; readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; @@ -6500,6 +6618,7 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the frame name. */ name: string; + readonly referrerPolicy: ReferrerPolicy; readonly sandbox: DOMTokenList; /** * Sets or retrieves whether the frame can be scrolled. @@ -7135,7 +7254,7 @@ interface HTMLMediaElement extends HTMLElement { */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + * Gets a flag that indicates whether the client is currently moving to a new playback position in the media resource. */ readonly seeking: boolean; /** @@ -9284,7 +9403,9 @@ interface Location { /** * Reloads the current page. */ - reload(forcedReload?: boolean): void; + reload(): void; + /** @deprecated */ + reload(forcedReload: boolean): void; /** * Removes the current page from the session history and navigates to the given URL. */ @@ -9705,7 +9826,7 @@ interface MediaQueryList extends EventTarget { /** @deprecated */ addListener(listener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null): void; /** @deprecated */ - removeListener(listener: EventListenerOrEventListenerObject | null): void; + removeListener(listener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null): void; addEventListener(type: K, listener: (this: MediaQueryList, ev: MediaQueryListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: MediaQueryList, ev: MediaQueryListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -10258,6 +10379,7 @@ interface Node extends EventTarget { * Returns the last child. */ readonly lastChild: ChildNode | null; + /** @deprecated */ readonly namespaceURI: string | null; /** * Returns the next sibling. @@ -10530,61 +10652,29 @@ declare var Notification: { interface OES_element_index_uint { } -declare var OES_element_index_uint: { - prototype: OES_element_index_uint; - new(): OES_element_index_uint; -}; - interface OES_standard_derivatives { - readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GLenum; } -declare var OES_standard_derivatives: { - prototype: OES_standard_derivatives; - new(): OES_standard_derivatives; - readonly 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 OES_texture_half_float { - readonly HALF_FLOAT_OES: number; + readonly HALF_FLOAT_OES: GLenum; } -declare var OES_texture_half_float: { - prototype: OES_texture_half_float; - new(): OES_texture_half_float; - readonly HALF_FLOAT_OES: number; -}; - interface OES_texture_half_float_linear { } -declare var OES_texture_half_float_linear: { - prototype: OES_texture_half_float_linear; - new(): OES_texture_half_float_linear; -}; - interface OES_vertex_array_object { - readonly VERTEX_ARRAY_BINDING_OES: number; - bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; - createVertexArrayOES(): WebGLVertexArrayObjectOES; - deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; - isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES | null; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + isVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): GLboolean; + readonly VERTEX_ARRAY_BINDING_OES: GLenum; } interface OfflineAudioCompletionEvent extends Event { @@ -11774,20 +11864,70 @@ declare var Range: { readonly START_TO_START: number; }; -interface ReadableStream { +interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; +} + +interface ReadableStream { readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + pipeThrough({ writable, readable }: { writable: WritableStream, readable: ReadableStream }, options?: PipeOptions): ReadableStream; + pipeTo(dest: WritableStream, options?: PipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; } declare var ReadableStream: { prototype: ReadableStream; - new(): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number, size?: undefined }): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; -interface ReadableStreamReader { +interface ReadableStreamBYOBReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(view: T): Promise>; + releaseLock(): void; +} + +declare var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; +}; + +interface ReadableStreamBYOBRequest { + readonly view: ArrayBufferView; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBufferView): void; +} + +interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: R): void; + error(error?: any): void; +} + +interface ReadableStreamDefaultReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} + +interface ReadableStreamReadResult { + done: boolean; + value: T; +} + +interface ReadableStreamReader { cancel(): Promise; - read(): Promise; + read(): Promise>; releaseLock(): void; } @@ -11799,7 +11939,7 @@ declare var ReadableStreamReader: { interface Request extends Body { /** * Returns the cache mode associated with request, which is a string indicating - * how the the request will interact with the browser's cache when fetching. + * how the request will interact with the browser's cache when fetching. */ readonly cache: RequestCache; /** @@ -11937,6 +12077,42 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_UNSPECIFIED: number; }; +interface SVGAnimateElement extends SVGAnimationElement { + addEventListener(type: K, listener: (this: SVGAnimateElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimateElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimateElement: { + prototype: SVGAnimateElement; + new(): SVGAnimateElement; +}; + +interface SVGAnimateMotionElement extends SVGAnimationElement { + addEventListener(type: K, listener: (this: SVGAnimateMotionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimateMotionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimateMotionElement: { + prototype: SVGAnimateMotionElement; + new(): SVGAnimateMotionElement; +}; + +interface SVGAnimateTransformElement extends SVGAnimationElement { + addEventListener(type: K, listener: (this: SVGAnimateTransformElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimateTransformElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimateTransformElement: { + prototype: SVGAnimateTransformElement; + new(): SVGAnimateTransformElement; +}; + interface SVGAnimatedAngle { readonly animVal: SVGAngle; readonly baseVal: SVGAngle; @@ -12062,6 +12238,22 @@ declare var SVGAnimatedTransformList: { new(): SVGAnimatedTransformList; }; +interface SVGAnimationElement extends SVGElement { + readonly targetElement: SVGElement; + getCurrentTime(): number; + getSimpleDuration(): number; + getStartTime(): number; + addEventListener(type: K, listener: (this: SVGAnimationElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAnimationElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAnimationElement: { + prototype: SVGAnimationElement; + new(): SVGAnimationElement; +}; + interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; readonly cy: SVGAnimatedLength; @@ -12121,6 +12313,20 @@ declare var SVGComponentTransferFunctionElement: { readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; }; +interface SVGCursorElement extends SVGElement { + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGCursorElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCursorElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGCursorElement: { + prototype: SVGCursorElement; + new(): SVGCursorElement; +}; + interface SVGDefsElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -14778,6 +14984,23 @@ declare var TrackEvent: { new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; }; +interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; +} + +declare var TransformStream: { + prototype: TransformStream; + new(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy): TransformStream; +}; + +interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk: O): void; + error(reason?: any): void; + terminate(): void; +} + interface TransitionEvent extends Event { readonly elapsedTime: number; readonly propertyName: string; @@ -15095,129 +15318,106 @@ declare var VideoTrackList: { }; interface WEBGL_color_buffer_float { - readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; - readonly RGB32F_EXT: number; - readonly RGBA32F_EXT: number; - readonly UNSIGNED_NORMALIZED_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: GLenum; + readonly RGBA32F_EXT: GLenum; + readonly UNSIGNED_NORMALIZED_EXT: GLenum; } interface WEBGL_compressed_texture_astc { - readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number; - readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number; - readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number; - readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number; - readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number; - readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; - readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number; - readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number; - readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number; - readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number; - readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number; - readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number; - readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number; - readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number; - readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number; getSupportedProfiles(): string[]; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: GLenum; } interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: GLenum; } -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -}; - interface WEBGL_compressed_texture_s3tc_srgb { - readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: GLenum; } interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; + readonly UNMASKED_RENDERER_WEBGL: GLenum; + readonly UNMASKED_VENDOR_WEBGL: GLenum; } -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -}; - interface WEBGL_debug_shaders { getTranslatedShaderSource(shader: WebGLShader): string; } interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; + readonly UNSIGNED_INT_24_8_WEBGL: GLenum; } -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -}; - interface WEBGL_draw_buffers { - readonly COLOR_ATTACHMENT0_WEBGL: number; - readonly COLOR_ATTACHMENT10_WEBGL: number; - readonly COLOR_ATTACHMENT11_WEBGL: number; - readonly COLOR_ATTACHMENT12_WEBGL: number; - readonly COLOR_ATTACHMENT13_WEBGL: number; - readonly COLOR_ATTACHMENT14_WEBGL: number; - readonly COLOR_ATTACHMENT15_WEBGL: number; - readonly COLOR_ATTACHMENT1_WEBGL: number; - readonly COLOR_ATTACHMENT2_WEBGL: number; - readonly COLOR_ATTACHMENT3_WEBGL: number; - readonly COLOR_ATTACHMENT4_WEBGL: number; - readonly COLOR_ATTACHMENT5_WEBGL: number; - readonly COLOR_ATTACHMENT6_WEBGL: number; - readonly COLOR_ATTACHMENT7_WEBGL: number; - readonly COLOR_ATTACHMENT8_WEBGL: number; - readonly COLOR_ATTACHMENT9_WEBGL: number; - readonly DRAW_BUFFER0_WEBGL: number; - readonly DRAW_BUFFER10_WEBGL: number; - readonly DRAW_BUFFER11_WEBGL: number; - readonly DRAW_BUFFER12_WEBGL: number; - readonly DRAW_BUFFER13_WEBGL: number; - readonly DRAW_BUFFER14_WEBGL: number; - readonly DRAW_BUFFER15_WEBGL: number; - readonly DRAW_BUFFER1_WEBGL: number; - readonly DRAW_BUFFER2_WEBGL: number; - readonly DRAW_BUFFER3_WEBGL: number; - readonly DRAW_BUFFER4_WEBGL: number; - readonly DRAW_BUFFER5_WEBGL: number; - readonly DRAW_BUFFER6_WEBGL: number; - readonly DRAW_BUFFER7_WEBGL: number; - readonly DRAW_BUFFER8_WEBGL: number; - readonly DRAW_BUFFER9_WEBGL: number; - readonly MAX_COLOR_ATTACHMENTS_WEBGL: number; - readonly MAX_DRAW_BUFFERS_WEBGL: number; - drawBuffersWEBGL(buffers: number[]): void; + drawBuffersWEBGL(buffers: GLenum[]): void; + readonly COLOR_ATTACHMENT0_WEBGL: GLenum; + readonly COLOR_ATTACHMENT10_WEBGL: GLenum; + readonly COLOR_ATTACHMENT11_WEBGL: GLenum; + readonly COLOR_ATTACHMENT12_WEBGL: GLenum; + readonly COLOR_ATTACHMENT13_WEBGL: GLenum; + readonly COLOR_ATTACHMENT14_WEBGL: GLenum; + readonly COLOR_ATTACHMENT15_WEBGL: GLenum; + readonly COLOR_ATTACHMENT1_WEBGL: GLenum; + readonly COLOR_ATTACHMENT2_WEBGL: GLenum; + readonly COLOR_ATTACHMENT3_WEBGL: GLenum; + readonly COLOR_ATTACHMENT4_WEBGL: GLenum; + readonly COLOR_ATTACHMENT5_WEBGL: GLenum; + readonly COLOR_ATTACHMENT6_WEBGL: GLenum; + readonly COLOR_ATTACHMENT7_WEBGL: GLenum; + readonly COLOR_ATTACHMENT8_WEBGL: GLenum; + readonly COLOR_ATTACHMENT9_WEBGL: GLenum; + readonly DRAW_BUFFER0_WEBGL: GLenum; + readonly DRAW_BUFFER10_WEBGL: GLenum; + readonly DRAW_BUFFER11_WEBGL: GLenum; + readonly DRAW_BUFFER12_WEBGL: GLenum; + readonly DRAW_BUFFER13_WEBGL: GLenum; + readonly DRAW_BUFFER14_WEBGL: GLenum; + readonly DRAW_BUFFER15_WEBGL: GLenum; + readonly DRAW_BUFFER1_WEBGL: GLenum; + readonly DRAW_BUFFER2_WEBGL: GLenum; + readonly DRAW_BUFFER3_WEBGL: GLenum; + readonly DRAW_BUFFER4_WEBGL: GLenum; + readonly DRAW_BUFFER5_WEBGL: GLenum; + readonly DRAW_BUFFER6_WEBGL: GLenum; + readonly DRAW_BUFFER7_WEBGL: GLenum; + readonly DRAW_BUFFER8_WEBGL: GLenum; + readonly DRAW_BUFFER9_WEBGL: GLenum; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: GLenum; + readonly MAX_DRAW_BUFFERS_WEBGL: GLenum; } interface WEBGL_lose_context { @@ -16119,7 +16319,7 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; -interface WebGLVertexArrayObjectOES { +interface WebGLVertexArrayObjectOES extends WebGLObject { } interface WebKitPoint { @@ -16176,9 +16376,6 @@ interface WheelEvent extends MouseEvent { readonly deltaX: number; readonly deltaY: number; readonly deltaZ: number; - readonly wheelDelta: number; - readonly wheelDeltaX: number; - readonly wheelDeltaY: 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; readonly DOM_DELTA_LINE: number; @@ -16525,7 +16722,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; - new(stringUrl: string): Worker; + new(stringUrl: string, options?: WorkerOptions): Worker; }; interface Worklet { @@ -16537,41 +16734,31 @@ declare var Worklet: { new(): Worklet; }; -interface WritableStream { +interface WritableStream { readonly locked: boolean; abort(reason?: any): Promise; - getWriter(): WritableStreamDefaultWriter; + getWriter(): WritableStreamDefaultWriter; } declare var WritableStream: { prototype: WritableStream; - new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; }; interface WritableStreamDefaultController { error(error?: any): void; } -declare var WritableStreamDefaultController: { - prototype: WritableStreamDefaultController; - new(): WritableStreamDefaultController; -}; - -interface WritableStreamDefaultWriter { +interface WritableStreamDefaultWriter { readonly closed: Promise; - readonly desiredSize: number; + readonly desiredSize: number | null; readonly ready: Promise; abort(reason?: any): Promise; close(): Promise; releaseLock(): void; - write(chunk?: any): Promise; + write(chunk: W): Promise; } -declare var WritableStreamDefaultWriter: { - prototype: WritableStreamDefaultWriter; - new(): WritableStreamDefaultWriter; -}; - interface XMLDocument extends Document { addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -16752,7 +16939,7 @@ declare var XMLSerializer: { interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver?: Node): XPathNSResolver; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | ((prefix: string) => string | null) | null, type: number, result: XPathResult | null): XPathResult; } declare var XPathEvaluator: { @@ -16770,7 +16957,7 @@ declare var XPathExpression: { }; interface XPathNSResolver { - lookupNamespaceURI(prefix: string): string; + lookupNamespaceURI(prefix: string): string | null; } declare var XPathNSResolver: { @@ -16921,6 +17108,10 @@ interface PositionErrorCallback { (positionError: PositionError): void; } +interface QueuingStrategySizeCallback { + (chunk: T): number; +} + interface RTCPeerConnectionErrorCallback { (error: DOMException): void; } @@ -16933,20 +17124,44 @@ interface RTCStatsCallback { (report: RTCStatsReport): void; } +interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; +} + +interface ReadableStreamDefaultControllerCallback { + (controller: ReadableStreamDefaultController): void | PromiseLike; +} + +interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; +} + +interface TransformStreamDefaultControllerCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; +} + +interface TransformStreamDefaultControllerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; +} + interface VoidFunction { (): void; } -interface WritableStreamChunkCallback { - (chunk: any, controller: WritableStreamDefaultController): void; +interface WritableStreamDefaultControllerCloseCallback { + (): void | PromiseLike; } -interface WritableStreamDefaultControllerCallback { - (controller: WritableStreamDefaultController): void; +interface WritableStreamDefaultControllerStartCallback { + (controller: WritableStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamDefaultControllerWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; } interface WritableStreamErrorCallback { - (reason: string): void; + (reason: any): void | PromiseLike; } interface HTMLElementTagNameMap { @@ -17580,7 +17795,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type BlobPart = BufferSource | Blob | string; type HeadersInit = Headers | string[][] | Record; -type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; +type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; type RequestInfo = Request | string; type DOMHighResTimeStamp = number; type RenderingContext = CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext; @@ -17626,6 +17841,7 @@ type IDBKeyPath = string; type Transferable = ArrayBuffer | MessagePort | ImageBitmap; type RTCIceGatherCandidate = RTCIceCandidateDictionary | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; +/** @deprecated */ type MouseWheelEvent = WheelEvent; type WindowProxy = Window; type AlignSetting = "start" | "center" | "end" | "left" | "right"; @@ -17648,11 +17864,13 @@ type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type CompositeOperation = "replace" | "add" | "accumulate"; +type CompositeOperationOrAuto = "replace" | "add" | "accumulate" | "auto"; type DirectionSetting = "" | "rl" | "lr"; type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; type DocumentReadyState = "loading" | "interactive" | "complete"; type EndOfStreamError = "network" | "decode"; +type EndingType = "transparent" | "native"; type FillMode = "none" | "forwards" | "backwards" | "both" | "auto"; type GamepadHand = "" | "left" | "right"; type GamepadHapticActuatorType = "vibration"; @@ -17731,7 +17949,7 @@ type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; type RequestRedirect = "follow" | "error" | "manual"; type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; -type ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollBehavior = "auto" | "smooth"; type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type ScrollRestoration = "auto" | "manual"; type ScrollSetting = "" | "up"; diff --git a/src/lib/es2015.collection.d.ts b/src/lib/es2015.collection.d.ts index 46bb7af0c8f..34afa3d1b2b 100644 --- a/src/lib/es2015.collection.d.ts +++ b/src/lib/es2015.collection.d.ts @@ -9,7 +9,8 @@ interface Map { } interface MapConstructor { - new (entries?: ReadonlyArray<[K, V]> | null): Map; + new(): Map; + new(entries?: ReadonlyArray<[K, V]> | null): Map; readonly prototype: Map; } declare var Map: MapConstructor; diff --git a/src/lib/es2015.iterable.d.ts b/src/lib/es2015.iterable.d.ts index 568d3596dda..f0a38dff3fe 100644 --- a/src/lib/es2015.iterable.d.ts +++ b/src/lib/es2015.iterable.d.ts @@ -135,7 +135,7 @@ interface MapConstructor { interface WeakMap { } interface WeakMapConstructor { - new (iterable: Iterable<[K, V]>): WeakMap; + new (iterable: Iterable<[K, V]>): WeakMap; } interface Set { diff --git a/src/lib/es2015.promise.d.ts b/src/lib/es2015.promise.d.ts index 14602c0b5ed..2a98f215193 100644 --- a/src/lib/es2015.promise.d.ts +++ b/src/lib/es2015.promise.d.ts @@ -7,7 +7,7 @@ interface PromiseConstructor { /** * 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, + * a resolve callback used to 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; @@ -193,4 +193,4 @@ interface PromiseConstructor { resolve(): Promise; } -declare var Promise: PromiseConstructor; \ No newline at end of file +declare var Promise: PromiseConstructor; diff --git a/src/lib/es2015.symbol.wellknown.d.ts b/src/lib/es2015.symbol.wellknown.d.ts index 948c8129a92..efaef1a63ce 100644 --- a/src/lib/es2015.symbol.wellknown.d.ts +++ b/src/lib/es2015.symbol.wellknown.d.ts @@ -63,7 +63,7 @@ interface SymbolConstructor { } interface Symbol { - readonly [Symbol.toStringTag]: "Symbol"; + readonly [Symbol.toStringTag]: string; } interface Array { @@ -107,23 +107,23 @@ interface Date { } interface Map { - readonly [Symbol.toStringTag]: "Map"; + readonly [Symbol.toStringTag]: string; } interface WeakMap { - readonly [Symbol.toStringTag]: "WeakMap"; + readonly [Symbol.toStringTag]: string; } interface Set { - readonly [Symbol.toStringTag]: "Set"; + readonly [Symbol.toStringTag]: string; } interface WeakSet { - readonly [Symbol.toStringTag]: "WeakSet"; + readonly [Symbol.toStringTag]: string; } interface JSON { - readonly [Symbol.toStringTag]: "JSON"; + readonly [Symbol.toStringTag]: string; } interface Function { @@ -138,15 +138,15 @@ interface Function { } interface GeneratorFunction { - readonly [Symbol.toStringTag]: "GeneratorFunction"; + readonly [Symbol.toStringTag]: string; } interface Math { - readonly [Symbol.toStringTag]: "Math"; + readonly [Symbol.toStringTag]: string; } interface Promise { - readonly [Symbol.toStringTag]: "Promise"; + readonly [Symbol.toStringTag]: string; } interface PromiseConstructor { @@ -241,11 +241,11 @@ interface String { } interface ArrayBuffer { - readonly [Symbol.toStringTag]: "ArrayBuffer"; + readonly [Symbol.toStringTag]: string; } interface DataView { - readonly [Symbol.toStringTag]: "DataView"; + readonly [Symbol.toStringTag]: string; } interface Int8Array { diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 015eec5c3e0..308af721af6 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -295,6 +295,76 @@ interface FunctionConstructor { declare const Function: FunctionConstructor; +/** + * Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter. + */ +type ThisParameterType = T extends (this: unknown, ...args: any[]) => any ? unknown : T extends (this: infer U, ...args: any[]) => any ? U : unknown; + +/** + * Removes the 'this' parameter from a function type. + */ +type OmitThisParameter = unknown extends ThisParameterType ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T; + +interface CallableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: (this: T) => R, thisArg: T): R; + apply(this: (this: T, ...args: A) => R, thisArg: T, args: A): R; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R; + + /** + * 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 The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: T, thisArg: ThisParameterType): OmitThisParameter; + bind(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R; + bind(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R; +} + +interface NewableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: new () => T, thisArg: T): void; + apply(this: new (...args: A) => T, thisArg: T, args: A): void; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: new (...args: A) => T, thisArg: T, ...args: A): void; + + /** + * 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 The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: T, thisArg: any): T; + bind(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2, arg3: A3): new (...args: A) => R; + bind(this: new (...args: AX[]) => R, thisArg: any, ...args: AX[]): new (...args: AX[]) => R; +} + interface IArguments { [index: number]: any; length: number; @@ -1350,7 +1420,7 @@ type Readonly = { }; /** - * From T pick a set of properties K + * From T, pick a set of properties whose keys are in the union K */ type Pick = { [P in K]: T[P]; diff --git a/src/lib/esnext.bigint.d.ts b/src/lib/esnext.bigint.d.ts new file mode 100644 index 00000000000..667422bf890 --- /dev/null +++ b/src/lib/esnext.bigint.d.ts @@ -0,0 +1,609 @@ +interface BigInt { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. + */ + toString(radix?: number): string; + + /** Returns a string representation appropriate to the host environment's current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): bigint; + + readonly [Symbol.toStringTag]: "BigInt"; +} + +interface BigIntConstructor { + (value?: any): bigint; + readonly prototype: BigInt; + + /** + * Interprets the low bits of a BigInt as a 2's-complement signed integer. + * All higher bits are discarded. + * @param bits The number of low bits to use + * @param int The BigInt whose bits to extract + */ + asIntN(bits: number, int: bigint): bigint; + /** + * Interprets the low bits of a BigInt as an unsigned integer. + * All higher bits are discarded. + * @param bits The number of low bits to use + * @param int The BigInt whose bits to extract + */ + asUintN(bits: number, int: bigint): bigint; +} + +declare const BigInt: BigIntConstructor; + +/** + * A typed array of 64-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 BigInt64Array { + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** The ArrayBuffer instance referenced by the array. */ + readonly buffer: ArrayBufferLike; + + /** 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): this; + + /** Yields index, value pairs for every entry in the array. */ + entries(): IterableIterator<[number, bigint]>; + + /** + * 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 the array 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: bigint, index: number, array: BigInt64Array) => 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: bigint, start?: number, end?: number): this; + + /** + * 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: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array; + + /** + * 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: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => 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: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void; + + /** + * 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: bigint, fromIndex?: number): boolean; + + /** + * 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: bigint, 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; + + /** Yields each index in the array. */ + keys(): IterableIterator; + + /** + * 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: bigint, 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: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array; + + /** + * 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: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; + + /** + * 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: bigint, currentIndex: number, array: BigInt64Array) => 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: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; + + /** + * 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: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; + + /** Reverses the elements in the array. */ + reverse(): this; + + /** + * 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): BigInt64Array; + + /** + * 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 the array 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: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts the array. + * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. + */ + sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; + + /** + * Gets a new BigInt64Array 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): BigInt64Array; + + /** Converts the array to a string by using the current locale. */ + toLocaleString(): string; + + /** Returns a string representation of the array. */ + toString(): string; + + /** Yields each value in the array. */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; + + readonly [Symbol.toStringTag]: "BigInt64Array"; + + [index: number]: bigint; +} + +interface BigInt64ArrayConstructor { + readonly prototype: BigInt64Array; + new(length?: number): BigInt64Array; + new(array: Iterable): BigInt64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; + + /** 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: bigint[]): BigInt64Array; + + /** + * 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): BigInt64Array; + from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array; +} + +declare const BigInt64Array: BigInt64ArrayConstructor; + +/** + * A typed array of 64-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 BigUint64Array { + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** The ArrayBuffer instance referenced by the array. */ + readonly buffer: ArrayBufferLike; + + /** 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): this; + + /** Yields index, value pairs for every entry in the array. */ + entries(): IterableIterator<[number, bigint]>; + + /** + * 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 the array 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: bigint, index: number, array: BigUint64Array) => 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: bigint, start?: number, end?: number): this; + + /** + * 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: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array; + + /** + * 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: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: bigint, index: number, array: BigUint64Array) => 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: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void; + + /** + * 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: bigint, fromIndex?: number): boolean; + + /** + * 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: bigint, 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; + + /** Yields each index in the array. */ + keys(): IterableIterator; + + /** + * 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: bigint, 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: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array; + + /** + * 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: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; + + /** + * 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: bigint, currentIndex: number, array: BigUint64Array) => 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: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; + + /** + * 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: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; + + /** Reverses the elements in the array. */ + reverse(): this; + + /** + * 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): BigUint64Array; + + /** + * 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 the array 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: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts the array. + * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. + */ + sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; + + /** + * Gets a new BigUint64Array 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): BigUint64Array; + + /** Converts the array to a string by using the current locale. */ + toLocaleString(): string; + + /** Returns a string representation of the array. */ + toString(): string; + + /** Yields each value in the array. */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; + + readonly [Symbol.toStringTag]: "BigUint64Array"; + + [index: number]: bigint; +} + +interface BigUint64ArrayConstructor { + readonly prototype: BigUint64Array; + new(length?: number): BigUint64Array; + new(array: Iterable): BigUint64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; + + /** 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: bigint[]): BigUint64Array; + + /** + * 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): BigUint64Array; + from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array; +} + +declare const BigUint64Array: BigUint64ArrayConstructor; + +interface DataView { + /** + * Gets the BigInt64 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. + */ + getBigInt64(byteOffset: number, littleEndian?: boolean): bigint; + + /** + * Gets the BigUint64 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. + */ + getBigUint64(byteOffset: number, littleEndian?: boolean): bigint; + + /** + * Stores a BigInt64 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. + */ + setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void; + + /** + * Stores a BigUint64 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. + */ + setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void; +} \ No newline at end of file diff --git a/src/lib/esnext.d.ts b/src/lib/esnext.d.ts index 970e1b32b3e..45d7e1d96c9 100644 --- a/src/lib/esnext.d.ts +++ b/src/lib/esnext.d.ts @@ -1,5 +1,6 @@ /// /// /// +/// /// /// diff --git a/src/lib/libs.json b/src/lib/libs.json index 1f2079e33a3..3077181af6e 100644 --- a/src/lib/libs.json +++ b/src/lib/libs.json @@ -34,6 +34,7 @@ "es2018.intl", "esnext.asynciterable", "esnext.array", + "esnext.bigint", "esnext.symbol", "esnext.intl", // Default libraries diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index 16e5d85d20b..568c79ef900 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -39,6 +39,7 @@ interface Algorithm { } interface BlobPropertyBag { + endings?: EndingType; type?: string; } @@ -282,6 +283,12 @@ interface PerformanceObserverInit { entryTypes: string[]; } +interface PipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + preventClose?: boolean; +} + interface ProgressEventInit extends EventInit { lengthComputable?: boolean; loaded?: number; @@ -313,6 +320,11 @@ interface PushSubscriptionOptionsInit { userVisibleOnly?: boolean; } +interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySizeCallback; +} + interface RegistrationOptions { scope?: string; type?: WorkerType; @@ -387,10 +399,69 @@ interface TextDecoderOptions { ignoreBOM?: boolean; } +interface Transformer { + flush?: TransformStreamDefaultControllerCallback; + readableType?: undefined; + start?: TransformStreamDefaultControllerCallback; + transform?: TransformStreamDefaultControllerTransformCallback; + writableType?: undefined; +} + +interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; +} + +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCloseCallback; + start?: WritableStreamDefaultControllerStartCallback; + type?: undefined; + write?: WritableStreamDefaultControllerWriteCallback; +} + +interface UnderlyingSource { + cancel?: ReadableStreamErrorCallback; + pull?: ReadableStreamDefaultControllerCallback; + start?: ReadableStreamDefaultControllerCallback; + type?: undefined; +} + +interface WebGLContextAttributes { + alpha?: GLboolean; + antialias?: GLboolean; + depth?: GLboolean; + failIfMajorPerformanceCaveat?: boolean; + powerPreference?: WebGLPowerPreference; + premultipliedAlpha?: GLboolean; + preserveDrawingBuffer?: GLboolean; + stencil?: GLboolean; +} + +interface WebGLContextEventInit extends EventInit { + statusMessage?: string; +} + +interface WorkerOptions { + credentials?: RequestCredentials; + name?: string; + type?: WorkerType; +} + interface EventListener { (evt: Event): void; } +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void; + drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void; + vertexAttribDivisorANGLE(index: GLuint, divisor: GLuint): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum; +} + interface AbortController { /** * Returns the AbortSignal object associated with this object. @@ -462,7 +533,7 @@ declare var Blob: { }; interface Body { - readonly body: ReadableStream | null; + readonly body: ReadableStream | null; readonly bodyUsed: boolean; arrayBuffer(): Promise; blob(): Promise; @@ -507,6 +578,16 @@ interface BroadcastChannelEventMap { messageerror: MessageEvent; } +interface ByteLengthQueuingStrategy extends QueuingStrategy { + highWaterMark: number; + size(chunk: ArrayBufferView): number; +} + +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(options: { highWaterMark: number }): ByteLengthQueuingStrategy; +}; + interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; @@ -655,6 +736,16 @@ declare var Console: { new(): Console; }; +interface CountQueuingStrategy extends QueuingStrategy { + highWaterMark: number; + size(chunk: any): 1; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(options: { highWaterMark: number }): CountQueuingStrategy; +}; + interface Crypto { readonly subtle: SubtleCrypto; getRandomValues(array: T): T; @@ -982,6 +1073,29 @@ interface DhKeyGenParams extends Algorithm { prime: Uint8Array; } +interface EXT_blend_minmax { + readonly MAX_EXT: GLenum; + readonly MIN_EXT: GLenum; +} + +interface EXT_frag_depth { +} + +interface EXT_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: GLenum; + readonly SRGB8_ALPHA8_EXT: GLenum; + readonly SRGB_ALPHA_EXT: GLenum; + readonly SRGB_EXT: GLenum; +} + +interface EXT_shader_texture_lod { +} + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: GLenum; + readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum; +} + interface ErrorEvent extends Event { readonly colno: number; readonly error: any; @@ -1019,7 +1133,6 @@ interface Event { */ readonly isTrusted: boolean; returnValue: boolean; - readonly srcElement: object | null; /** * Returns the object to which event is dispatched (its target). */ @@ -1197,7 +1310,7 @@ interface FileReader extends EventTarget { readAsArrayBuffer(blob: Blob): void; readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, label?: string): void; + readAsText(blob: Blob, encoding?: string): void; readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; @@ -1219,7 +1332,7 @@ interface FileReaderSync { readAsArrayBuffer(blob: Blob): ArrayBuffer; readAsBinaryString(blob: Blob): string; readAsDataURL(blob: Blob): string; - readAsText(blob: Blob, label?: string): string; + readAsText(blob: Blob, encoding?: string): string; } declare var FileReaderSync: { @@ -1974,6 +2087,34 @@ declare var NotificationEvent: { new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; }; +interface OES_element_index_uint { +} + +interface OES_standard_derivatives { + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GLenum; +} + +interface OES_texture_float { +} + +interface OES_texture_float_linear { +} + +interface OES_texture_half_float { + readonly HALF_FLOAT_OES: GLenum; +} + +interface OES_texture_half_float_linear { +} + +interface OES_vertex_array_object { + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES | null; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; + isVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): GLboolean; + readonly VERTEX_ARRAY_BINDING_OES: GLenum; +} + interface Path2D extends CanvasPath { addPath(path: Path2D, transform?: DOMMatrix2DInit): void; } @@ -2177,20 +2318,70 @@ declare var PushSubscriptionOptions: { new(): PushSubscriptionOptions; }; -interface ReadableStream { +interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; +} + +interface ReadableStream { readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + pipeThrough({ writable, readable }: { writable: WritableStream, readable: ReadableStream }, options?: PipeOptions): ReadableStream; + pipeTo(dest: WritableStream, options?: PipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; } declare var ReadableStream: { prototype: ReadableStream; - new(): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number, size?: undefined }): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; -interface ReadableStreamReader { +interface ReadableStreamBYOBReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(view: T): Promise>; + releaseLock(): void; +} + +declare var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; +}; + +interface ReadableStreamBYOBRequest { + readonly view: ArrayBufferView; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBufferView): void; +} + +interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: R): void; + error(error?: any): void; +} + +interface ReadableStreamDefaultReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} + +interface ReadableStreamReadResult { + done: boolean; + value: T; +} + +interface ReadableStreamReader { cancel(): Promise; - read(): Promise; + read(): Promise>; releaseLock(): void; } @@ -2202,7 +2393,7 @@ declare var ReadableStreamReader: { interface Request extends Body { /** * Returns the cache mode associated with request, which is a string indicating - * how the the request will interact with the browser's cache when fetching. + * how the request will interact with the browser's cache when fetching. */ readonly cache: RequestCache; /** @@ -2524,6 +2715,46 @@ declare var TextEncoder: { new(): TextEncoder; }; +interface TextMetrics { + readonly actualBoundingBoxAscent: number; + readonly actualBoundingBoxDescent: number; + readonly actualBoundingBoxLeft: number; + readonly actualBoundingBoxRight: number; + readonly alphabeticBaseline: number; + readonly emHeightAscent: number; + readonly emHeightDescent: number; + readonly fontBoundingBoxAscent: number; + readonly fontBoundingBoxDescent: number; + readonly hangingBaseline: number; + /** + * Returns the measurement described below. + */ + readonly ideographicBaseline: number; + readonly width: number; +} + +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +}; + +interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; +} + +declare var TransformStream: { + prototype: TransformStream; + new(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy): TransformStream; +}; + +interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk: O): void; + error(reason?: any): void; + terminate(): void; +} + interface URL { hash: string; host: string; @@ -2581,6 +2812,978 @@ declare var URLSearchParams: { new(init?: string[][] | Record | string | URLSearchParams): URLSearchParams; }; +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: GLenum; + readonly RGBA32F_EXT: GLenum; + readonly UNSIGNED_NORMALIZED_EXT: GLenum; +} + +interface WEBGL_compressed_texture_astc { + getSupportedProfiles(): string[]; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: GLenum; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: GLenum; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: GLenum; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: GLenum; + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: GLenum; +} + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: GLenum; + readonly UNMASKED_VENDOR_WEBGL: GLenum; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: GLenum; +} + +interface WEBGL_draw_buffers { + drawBuffersWEBGL(buffers: GLenum[]): void; + readonly COLOR_ATTACHMENT0_WEBGL: GLenum; + readonly COLOR_ATTACHMENT10_WEBGL: GLenum; + readonly COLOR_ATTACHMENT11_WEBGL: GLenum; + readonly COLOR_ATTACHMENT12_WEBGL: GLenum; + readonly COLOR_ATTACHMENT13_WEBGL: GLenum; + readonly COLOR_ATTACHMENT14_WEBGL: GLenum; + readonly COLOR_ATTACHMENT15_WEBGL: GLenum; + readonly COLOR_ATTACHMENT1_WEBGL: GLenum; + readonly COLOR_ATTACHMENT2_WEBGL: GLenum; + readonly COLOR_ATTACHMENT3_WEBGL: GLenum; + readonly COLOR_ATTACHMENT4_WEBGL: GLenum; + readonly COLOR_ATTACHMENT5_WEBGL: GLenum; + readonly COLOR_ATTACHMENT6_WEBGL: GLenum; + readonly COLOR_ATTACHMENT7_WEBGL: GLenum; + readonly COLOR_ATTACHMENT8_WEBGL: GLenum; + readonly COLOR_ATTACHMENT9_WEBGL: GLenum; + readonly DRAW_BUFFER0_WEBGL: GLenum; + readonly DRAW_BUFFER10_WEBGL: GLenum; + readonly DRAW_BUFFER11_WEBGL: GLenum; + readonly DRAW_BUFFER12_WEBGL: GLenum; + readonly DRAW_BUFFER13_WEBGL: GLenum; + readonly DRAW_BUFFER14_WEBGL: GLenum; + readonly DRAW_BUFFER15_WEBGL: GLenum; + readonly DRAW_BUFFER1_WEBGL: GLenum; + readonly DRAW_BUFFER2_WEBGL: GLenum; + readonly DRAW_BUFFER3_WEBGL: GLenum; + readonly DRAW_BUFFER4_WEBGL: GLenum; + readonly DRAW_BUFFER5_WEBGL: GLenum; + readonly DRAW_BUFFER6_WEBGL: GLenum; + readonly DRAW_BUFFER7_WEBGL: GLenum; + readonly DRAW_BUFFER8_WEBGL: GLenum; + readonly DRAW_BUFFER9_WEBGL: GLenum; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: GLenum; + readonly MAX_DRAW_BUFFERS_WEBGL: GLenum; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + +interface WebGLActiveInfo { + readonly name: string; + readonly size: GLint; + readonly type: GLenum; +} + +declare var WebGLActiveInfo: { + prototype: WebGLActiveInfo; + new(): WebGLActiveInfo; +}; + +interface WebGLBuffer extends WebGLObject { +} + +declare var WebGLBuffer: { + prototype: WebGLBuffer; + new(): WebGLBuffer; +}; + +interface WebGLContextEvent extends Event { + readonly statusMessage: string; +} + +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new(type: string, eventInit?: WebGLContextEventInit): 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 extends WebGLRenderingContextBase { +} + +declare var WebGLRenderingContext: { + prototype: WebGLRenderingContext; + new(): WebGLRenderingContext; + readonly ACTIVE_ATTRIBUTES: GLenum; + readonly ACTIVE_TEXTURE: GLenum; + readonly ACTIVE_UNIFORMS: GLenum; + readonly ALIASED_LINE_WIDTH_RANGE: GLenum; + readonly ALIASED_POINT_SIZE_RANGE: GLenum; + readonly ALPHA: GLenum; + readonly ALPHA_BITS: GLenum; + readonly ALWAYS: GLenum; + readonly ARRAY_BUFFER: GLenum; + readonly ARRAY_BUFFER_BINDING: GLenum; + readonly ATTACHED_SHADERS: GLenum; + readonly BACK: GLenum; + readonly BLEND: GLenum; + readonly BLEND_COLOR: GLenum; + readonly BLEND_DST_ALPHA: GLenum; + readonly BLEND_DST_RGB: GLenum; + readonly BLEND_EQUATION: GLenum; + readonly BLEND_EQUATION_ALPHA: GLenum; + readonly BLEND_EQUATION_RGB: GLenum; + readonly BLEND_SRC_ALPHA: GLenum; + readonly BLEND_SRC_RGB: GLenum; + readonly BLUE_BITS: GLenum; + readonly BOOL: GLenum; + readonly BOOL_VEC2: GLenum; + readonly BOOL_VEC3: GLenum; + readonly BOOL_VEC4: GLenum; + readonly BROWSER_DEFAULT_WEBGL: GLenum; + readonly BUFFER_SIZE: GLenum; + readonly BUFFER_USAGE: GLenum; + readonly BYTE: GLenum; + readonly CCW: GLenum; + readonly CLAMP_TO_EDGE: GLenum; + readonly COLOR_ATTACHMENT0: GLenum; + readonly COLOR_BUFFER_BIT: GLenum; + readonly COLOR_CLEAR_VALUE: GLenum; + readonly COLOR_WRITEMASK: GLenum; + readonly COMPILE_STATUS: GLenum; + readonly COMPRESSED_TEXTURE_FORMATS: GLenum; + readonly CONSTANT_ALPHA: GLenum; + readonly CONSTANT_COLOR: GLenum; + readonly CONTEXT_LOST_WEBGL: GLenum; + readonly CULL_FACE: GLenum; + readonly CULL_FACE_MODE: GLenum; + readonly CURRENT_PROGRAM: GLenum; + readonly CURRENT_VERTEX_ATTRIB: GLenum; + readonly CW: GLenum; + readonly DECR: GLenum; + readonly DECR_WRAP: GLenum; + readonly DELETE_STATUS: GLenum; + readonly DEPTH_ATTACHMENT: GLenum; + readonly DEPTH_BITS: GLenum; + readonly DEPTH_BUFFER_BIT: GLenum; + readonly DEPTH_CLEAR_VALUE: GLenum; + readonly DEPTH_COMPONENT: GLenum; + readonly DEPTH_COMPONENT16: GLenum; + readonly DEPTH_FUNC: GLenum; + readonly DEPTH_RANGE: GLenum; + readonly DEPTH_STENCIL: GLenum; + readonly DEPTH_STENCIL_ATTACHMENT: GLenum; + readonly DEPTH_TEST: GLenum; + readonly DEPTH_WRITEMASK: GLenum; + readonly DITHER: GLenum; + readonly DONT_CARE: GLenum; + readonly DST_ALPHA: GLenum; + readonly DST_COLOR: GLenum; + readonly DYNAMIC_DRAW: GLenum; + readonly ELEMENT_ARRAY_BUFFER: GLenum; + readonly ELEMENT_ARRAY_BUFFER_BINDING: GLenum; + readonly EQUAL: GLenum; + readonly FASTEST: GLenum; + readonly FLOAT: GLenum; + readonly FLOAT_MAT2: GLenum; + readonly FLOAT_MAT3: GLenum; + readonly FLOAT_MAT4: GLenum; + readonly FLOAT_VEC2: GLenum; + readonly FLOAT_VEC3: GLenum; + readonly FLOAT_VEC4: GLenum; + readonly FRAGMENT_SHADER: GLenum; + readonly FRAMEBUFFER: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; + readonly FRAMEBUFFER_BINDING: GLenum; + readonly FRAMEBUFFER_COMPLETE: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_UNSUPPORTED: GLenum; + readonly FRONT: GLenum; + readonly FRONT_AND_BACK: GLenum; + readonly FRONT_FACE: GLenum; + readonly FUNC_ADD: GLenum; + readonly FUNC_REVERSE_SUBTRACT: GLenum; + readonly FUNC_SUBTRACT: GLenum; + readonly GENERATE_MIPMAP_HINT: GLenum; + readonly GEQUAL: GLenum; + readonly GREATER: GLenum; + readonly GREEN_BITS: GLenum; + readonly HIGH_FLOAT: GLenum; + readonly HIGH_INT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_TYPE: GLenum; + readonly INCR: GLenum; + readonly INCR_WRAP: GLenum; + readonly INT: GLenum; + readonly INT_VEC2: GLenum; + readonly INT_VEC3: GLenum; + readonly INT_VEC4: GLenum; + readonly INVALID_ENUM: GLenum; + readonly INVALID_FRAMEBUFFER_OPERATION: GLenum; + readonly INVALID_OPERATION: GLenum; + readonly INVALID_VALUE: GLenum; + readonly INVERT: GLenum; + readonly KEEP: GLenum; + readonly LEQUAL: GLenum; + readonly LESS: GLenum; + readonly LINEAR: GLenum; + readonly LINEAR_MIPMAP_LINEAR: GLenum; + readonly LINEAR_MIPMAP_NEAREST: GLenum; + readonly LINES: GLenum; + readonly LINE_LOOP: GLenum; + readonly LINE_STRIP: GLenum; + readonly LINE_WIDTH: GLenum; + readonly LINK_STATUS: GLenum; + readonly LOW_FLOAT: GLenum; + readonly LOW_INT: GLenum; + readonly LUMINANCE: GLenum; + readonly LUMINANCE_ALPHA: GLenum; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; + readonly MAX_RENDERBUFFER_SIZE: GLenum; + readonly MAX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_TEXTURE_SIZE: GLenum; + readonly MAX_VARYING_VECTORS: GLenum; + readonly MAX_VERTEX_ATTRIBS: GLenum; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_VERTEX_UNIFORM_VECTORS: GLenum; + readonly MAX_VIEWPORT_DIMS: GLenum; + readonly MEDIUM_FLOAT: GLenum; + readonly MEDIUM_INT: GLenum; + readonly MIRRORED_REPEAT: GLenum; + readonly NEAREST: GLenum; + readonly NEAREST_MIPMAP_LINEAR: GLenum; + readonly NEAREST_MIPMAP_NEAREST: GLenum; + readonly NEVER: GLenum; + readonly NICEST: GLenum; + readonly NONE: GLenum; + readonly NOTEQUAL: GLenum; + readonly NO_ERROR: GLenum; + readonly ONE: GLenum; + readonly ONE_MINUS_CONSTANT_ALPHA: GLenum; + readonly ONE_MINUS_CONSTANT_COLOR: GLenum; + readonly ONE_MINUS_DST_ALPHA: GLenum; + readonly ONE_MINUS_DST_COLOR: GLenum; + readonly ONE_MINUS_SRC_ALPHA: GLenum; + readonly ONE_MINUS_SRC_COLOR: GLenum; + readonly OUT_OF_MEMORY: GLenum; + readonly PACK_ALIGNMENT: GLenum; + readonly POINTS: GLenum; + readonly POLYGON_OFFSET_FACTOR: GLenum; + readonly POLYGON_OFFSET_FILL: GLenum; + readonly POLYGON_OFFSET_UNITS: GLenum; + readonly RED_BITS: GLenum; + readonly RENDERBUFFER: GLenum; + readonly RENDERBUFFER_ALPHA_SIZE: GLenum; + readonly RENDERBUFFER_BINDING: GLenum; + readonly RENDERBUFFER_BLUE_SIZE: GLenum; + readonly RENDERBUFFER_DEPTH_SIZE: GLenum; + readonly RENDERBUFFER_GREEN_SIZE: GLenum; + readonly RENDERBUFFER_HEIGHT: GLenum; + readonly RENDERBUFFER_INTERNAL_FORMAT: GLenum; + readonly RENDERBUFFER_RED_SIZE: GLenum; + readonly RENDERBUFFER_STENCIL_SIZE: GLenum; + readonly RENDERBUFFER_WIDTH: GLenum; + readonly RENDERER: GLenum; + readonly REPEAT: GLenum; + readonly REPLACE: GLenum; + readonly RGB: GLenum; + readonly RGB565: GLenum; + readonly RGB5_A1: GLenum; + readonly RGBA: GLenum; + readonly RGBA4: GLenum; + readonly SAMPLER_2D: GLenum; + readonly SAMPLER_CUBE: GLenum; + readonly SAMPLES: GLenum; + readonly SAMPLE_ALPHA_TO_COVERAGE: GLenum; + readonly SAMPLE_BUFFERS: GLenum; + readonly SAMPLE_COVERAGE: GLenum; + readonly SAMPLE_COVERAGE_INVERT: GLenum; + readonly SAMPLE_COVERAGE_VALUE: GLenum; + readonly SCISSOR_BOX: GLenum; + readonly SCISSOR_TEST: GLenum; + readonly SHADER_TYPE: GLenum; + readonly SHADING_LANGUAGE_VERSION: GLenum; + readonly SHORT: GLenum; + readonly SRC_ALPHA: GLenum; + readonly SRC_ALPHA_SATURATE: GLenum; + readonly SRC_COLOR: GLenum; + readonly STATIC_DRAW: GLenum; + readonly STENCIL_ATTACHMENT: GLenum; + readonly STENCIL_BACK_FAIL: GLenum; + readonly STENCIL_BACK_FUNC: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_BACK_REF: GLenum; + readonly STENCIL_BACK_VALUE_MASK: GLenum; + readonly STENCIL_BACK_WRITEMASK: GLenum; + readonly STENCIL_BITS: GLenum; + readonly STENCIL_BUFFER_BIT: GLenum; + readonly STENCIL_CLEAR_VALUE: GLenum; + readonly STENCIL_FAIL: GLenum; + readonly STENCIL_FUNC: GLenum; + readonly STENCIL_INDEX8: GLenum; + readonly STENCIL_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_REF: GLenum; + readonly STENCIL_TEST: GLenum; + readonly STENCIL_VALUE_MASK: GLenum; + readonly STENCIL_WRITEMASK: GLenum; + readonly STREAM_DRAW: GLenum; + readonly SUBPIXEL_BITS: GLenum; + readonly TEXTURE: GLenum; + readonly TEXTURE0: GLenum; + readonly TEXTURE1: GLenum; + readonly TEXTURE10: GLenum; + readonly TEXTURE11: GLenum; + readonly TEXTURE12: GLenum; + readonly TEXTURE13: GLenum; + readonly TEXTURE14: GLenum; + readonly TEXTURE15: GLenum; + readonly TEXTURE16: GLenum; + readonly TEXTURE17: GLenum; + readonly TEXTURE18: GLenum; + readonly TEXTURE19: GLenum; + readonly TEXTURE2: GLenum; + readonly TEXTURE20: GLenum; + readonly TEXTURE21: GLenum; + readonly TEXTURE22: GLenum; + readonly TEXTURE23: GLenum; + readonly TEXTURE24: GLenum; + readonly TEXTURE25: GLenum; + readonly TEXTURE26: GLenum; + readonly TEXTURE27: GLenum; + readonly TEXTURE28: GLenum; + readonly TEXTURE29: GLenum; + readonly TEXTURE3: GLenum; + readonly TEXTURE30: GLenum; + readonly TEXTURE31: GLenum; + readonly TEXTURE4: GLenum; + readonly TEXTURE5: GLenum; + readonly TEXTURE6: GLenum; + readonly TEXTURE7: GLenum; + readonly TEXTURE8: GLenum; + readonly TEXTURE9: GLenum; + readonly TEXTURE_2D: GLenum; + readonly TEXTURE_BINDING_2D: GLenum; + readonly TEXTURE_BINDING_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; + readonly TEXTURE_MAG_FILTER: GLenum; + readonly TEXTURE_MIN_FILTER: GLenum; + readonly TEXTURE_WRAP_S: GLenum; + readonly TEXTURE_WRAP_T: GLenum; + readonly TRIANGLES: GLenum; + readonly TRIANGLE_FAN: GLenum; + readonly TRIANGLE_STRIP: GLenum; + readonly UNPACK_ALIGNMENT: GLenum; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; + readonly UNPACK_FLIP_Y_WEBGL: GLenum; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; + readonly UNSIGNED_BYTE: GLenum; + readonly UNSIGNED_INT: GLenum; + readonly UNSIGNED_SHORT: GLenum; + readonly UNSIGNED_SHORT_4_4_4_4: GLenum; + readonly UNSIGNED_SHORT_5_5_5_1: GLenum; + readonly UNSIGNED_SHORT_5_6_5: GLenum; + readonly VALIDATE_STATUS: GLenum; + readonly VENDOR: GLenum; + readonly VERSION: GLenum; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_POINTER: GLenum; + readonly VERTEX_ATTRIB_ARRAY_SIZE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_TYPE: GLenum; + readonly VERTEX_SHADER: GLenum; + readonly VIEWPORT: GLenum; + readonly ZERO: GLenum; +}; + +interface WebGLRenderingContextBase { + readonly drawingBufferHeight: GLsizei; + readonly drawingBufferWidth: GLsizei; + activeTexture(texture: GLenum): void; + attachShader(program: WebGLProgram, shader: WebGLShader): void; + bindAttribLocation(program: WebGLProgram, index: GLuint, name: string): void; + bindBuffer(target: GLenum, buffer: WebGLBuffer | null): void; + bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer | null): void; + bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer | null): void; + bindTexture(target: GLenum, texture: WebGLTexture | null): void; + blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf): void; + blendEquation(mode: GLenum): void; + blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum): void; + blendFunc(sfactor: GLenum, dfactor: GLenum): void; + blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum): void; + bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum): void; + bufferData(target: GLenum, data: BufferSource | null, usage: GLenum): void; + bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource): void; + checkFramebufferStatus(target: GLenum): GLenum; + clear(mask: GLbitfield): void; + clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf): void; + clearDepth(depth: GLclampf): void; + clearStencil(s: GLint): void; + colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean): void; + compileShader(shader: WebGLShader): void; + compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView): void; + compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView): void; + copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint): void; + copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + createBuffer(): WebGLBuffer | null; + createFramebuffer(): WebGLFramebuffer | null; + createProgram(): WebGLProgram | null; + createRenderbuffer(): WebGLRenderbuffer | null; + createShader(type: GLenum): WebGLShader | null; + createTexture(): WebGLTexture | null; + cullFace(mode: GLenum): void; + deleteBuffer(buffer: WebGLBuffer | null): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; + deleteProgram(program: WebGLProgram | null): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; + deleteShader(shader: WebGLShader | null): void; + deleteTexture(texture: WebGLTexture | null): void; + depthFunc(func: GLenum): void; + depthMask(flag: GLboolean): void; + depthRange(zNear: GLclampf, zFar: GLclampf): void; + detachShader(program: WebGLProgram, shader: WebGLShader): void; + disable(cap: GLenum): void; + disableVertexAttribArray(index: GLuint): void; + drawArrays(mode: GLenum, first: GLint, count: GLsizei): void; + drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr): void; + enable(cap: GLenum): void; + enableVertexAttribArray(index: GLuint): void; + finish(): void; + flush(): void; + framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer | null): void; + framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture | null, level: GLint): void; + frontFace(mode: GLenum): void; + generateMipmap(target: GLenum): void; + getActiveAttrib(program: WebGLProgram, index: GLuint): WebGLActiveInfo | null; + getActiveUniform(program: WebGLProgram, index: GLuint): WebGLActiveInfo | null; + getAttachedShaders(program: WebGLProgram): WebGLShader[] | null; + getAttribLocation(program: WebGLProgram, name: string): GLint; + getBufferParameter(target: GLenum, pname: GLenum): any; + getContextAttributes(): WebGLContextAttributes | null; + getError(): GLenum; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; + getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum): any; + getParameter(pname: GLenum): any; + getProgramInfoLog(program: WebGLProgram): string | null; + getProgramParameter(program: WebGLProgram, pname: GLenum): any; + getRenderbufferParameter(target: GLenum, pname: GLenum): any; + getShaderInfoLog(shader: WebGLShader): string | null; + getShaderParameter(shader: WebGLShader, pname: GLenum): any; + getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum): WebGLShaderPrecisionFormat | null; + getShaderSource(shader: WebGLShader): string | null; + getSupportedExtensions(): string[] | null; + getTexParameter(target: GLenum, pname: GLenum): any; + getUniform(program: WebGLProgram, location: WebGLUniformLocation): any; + getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation | null; + getVertexAttrib(index: GLuint, pname: GLenum): any; + getVertexAttribOffset(index: GLuint, pname: GLenum): GLintptr; + hint(target: GLenum, mode: GLenum): void; + isBuffer(buffer: WebGLBuffer | null): GLboolean; + isContextLost(): boolean; + isEnabled(cap: GLenum): GLboolean; + isFramebuffer(framebuffer: WebGLFramebuffer | null): GLboolean; + isProgram(program: WebGLProgram | null): GLboolean; + isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): GLboolean; + isShader(shader: WebGLShader | null): GLboolean; + isTexture(texture: WebGLTexture | null): GLboolean; + lineWidth(width: GLfloat): void; + linkProgram(program: WebGLProgram): void; + pixelStorei(pname: GLenum, param: GLint): void; + polygonOffset(factor: GLfloat, units: GLfloat): void; + readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei): void; + sampleCoverage(value: GLclampf, invert: GLboolean): void; + scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + shaderSource(shader: WebGLShader, source: string): void; + stencilFunc(func: GLenum, ref: GLint, mask: GLuint): void; + stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint): void; + stencilMask(mask: GLuint): void; + stencilMaskSeparate(face: GLenum, mask: GLuint): void; + stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum): void; + stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum): void; + texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource): void; + texParameterf(target: GLenum, pname: GLenum, param: GLfloat): void; + texParameteri(target: GLenum, pname: GLenum, param: GLint): void; + texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource): void; + uniform1f(location: WebGLUniformLocation | null, x: GLfloat): void; + uniform1fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform1i(location: WebGLUniformLocation | null, x: GLint): void; + uniform1iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform2f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat): void; + uniform2fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform2i(location: WebGLUniformLocation | null, x: GLint, y: GLint): void; + uniform2iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform3f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat, z: GLfloat): void; + uniform3fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform3i(location: WebGLUniformLocation | null, x: GLint, y: GLint, z: GLint): void; + uniform3iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform4f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat): void; + uniform4fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform4i(location: WebGLUniformLocation | null, x: GLint, y: GLint, z: GLint, w: GLint): void; + uniform4iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + useProgram(program: WebGLProgram | null): void; + validateProgram(program: WebGLProgram): void; + vertexAttrib1f(index: GLuint, x: GLfloat): void; + vertexAttrib1fv(index: GLuint, values: Float32List): void; + vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat): void; + vertexAttrib2fv(index: GLuint, values: Float32List): void; + vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat): void; + vertexAttrib3fv(index: GLuint, values: Float32List): void; + vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat): void; + vertexAttrib4fv(index: GLuint, values: Float32List): void; + vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr): void; + viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + readonly ACTIVE_ATTRIBUTES: GLenum; + readonly ACTIVE_TEXTURE: GLenum; + readonly ACTIVE_UNIFORMS: GLenum; + readonly ALIASED_LINE_WIDTH_RANGE: GLenum; + readonly ALIASED_POINT_SIZE_RANGE: GLenum; + readonly ALPHA: GLenum; + readonly ALPHA_BITS: GLenum; + readonly ALWAYS: GLenum; + readonly ARRAY_BUFFER: GLenum; + readonly ARRAY_BUFFER_BINDING: GLenum; + readonly ATTACHED_SHADERS: GLenum; + readonly BACK: GLenum; + readonly BLEND: GLenum; + readonly BLEND_COLOR: GLenum; + readonly BLEND_DST_ALPHA: GLenum; + readonly BLEND_DST_RGB: GLenum; + readonly BLEND_EQUATION: GLenum; + readonly BLEND_EQUATION_ALPHA: GLenum; + readonly BLEND_EQUATION_RGB: GLenum; + readonly BLEND_SRC_ALPHA: GLenum; + readonly BLEND_SRC_RGB: GLenum; + readonly BLUE_BITS: GLenum; + readonly BOOL: GLenum; + readonly BOOL_VEC2: GLenum; + readonly BOOL_VEC3: GLenum; + readonly BOOL_VEC4: GLenum; + readonly BROWSER_DEFAULT_WEBGL: GLenum; + readonly BUFFER_SIZE: GLenum; + readonly BUFFER_USAGE: GLenum; + readonly BYTE: GLenum; + readonly CCW: GLenum; + readonly CLAMP_TO_EDGE: GLenum; + readonly COLOR_ATTACHMENT0: GLenum; + readonly COLOR_BUFFER_BIT: GLenum; + readonly COLOR_CLEAR_VALUE: GLenum; + readonly COLOR_WRITEMASK: GLenum; + readonly COMPILE_STATUS: GLenum; + readonly COMPRESSED_TEXTURE_FORMATS: GLenum; + readonly CONSTANT_ALPHA: GLenum; + readonly CONSTANT_COLOR: GLenum; + readonly CONTEXT_LOST_WEBGL: GLenum; + readonly CULL_FACE: GLenum; + readonly CULL_FACE_MODE: GLenum; + readonly CURRENT_PROGRAM: GLenum; + readonly CURRENT_VERTEX_ATTRIB: GLenum; + readonly CW: GLenum; + readonly DECR: GLenum; + readonly DECR_WRAP: GLenum; + readonly DELETE_STATUS: GLenum; + readonly DEPTH_ATTACHMENT: GLenum; + readonly DEPTH_BITS: GLenum; + readonly DEPTH_BUFFER_BIT: GLenum; + readonly DEPTH_CLEAR_VALUE: GLenum; + readonly DEPTH_COMPONENT: GLenum; + readonly DEPTH_COMPONENT16: GLenum; + readonly DEPTH_FUNC: GLenum; + readonly DEPTH_RANGE: GLenum; + readonly DEPTH_STENCIL: GLenum; + readonly DEPTH_STENCIL_ATTACHMENT: GLenum; + readonly DEPTH_TEST: GLenum; + readonly DEPTH_WRITEMASK: GLenum; + readonly DITHER: GLenum; + readonly DONT_CARE: GLenum; + readonly DST_ALPHA: GLenum; + readonly DST_COLOR: GLenum; + readonly DYNAMIC_DRAW: GLenum; + readonly ELEMENT_ARRAY_BUFFER: GLenum; + readonly ELEMENT_ARRAY_BUFFER_BINDING: GLenum; + readonly EQUAL: GLenum; + readonly FASTEST: GLenum; + readonly FLOAT: GLenum; + readonly FLOAT_MAT2: GLenum; + readonly FLOAT_MAT3: GLenum; + readonly FLOAT_MAT4: GLenum; + readonly FLOAT_VEC2: GLenum; + readonly FLOAT_VEC3: GLenum; + readonly FLOAT_VEC4: GLenum; + readonly FRAGMENT_SHADER: GLenum; + readonly FRAMEBUFFER: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; + readonly FRAMEBUFFER_BINDING: GLenum; + readonly FRAMEBUFFER_COMPLETE: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_UNSUPPORTED: GLenum; + readonly FRONT: GLenum; + readonly FRONT_AND_BACK: GLenum; + readonly FRONT_FACE: GLenum; + readonly FUNC_ADD: GLenum; + readonly FUNC_REVERSE_SUBTRACT: GLenum; + readonly FUNC_SUBTRACT: GLenum; + readonly GENERATE_MIPMAP_HINT: GLenum; + readonly GEQUAL: GLenum; + readonly GREATER: GLenum; + readonly GREEN_BITS: GLenum; + readonly HIGH_FLOAT: GLenum; + readonly HIGH_INT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_TYPE: GLenum; + readonly INCR: GLenum; + readonly INCR_WRAP: GLenum; + readonly INT: GLenum; + readonly INT_VEC2: GLenum; + readonly INT_VEC3: GLenum; + readonly INT_VEC4: GLenum; + readonly INVALID_ENUM: GLenum; + readonly INVALID_FRAMEBUFFER_OPERATION: GLenum; + readonly INVALID_OPERATION: GLenum; + readonly INVALID_VALUE: GLenum; + readonly INVERT: GLenum; + readonly KEEP: GLenum; + readonly LEQUAL: GLenum; + readonly LESS: GLenum; + readonly LINEAR: GLenum; + readonly LINEAR_MIPMAP_LINEAR: GLenum; + readonly LINEAR_MIPMAP_NEAREST: GLenum; + readonly LINES: GLenum; + readonly LINE_LOOP: GLenum; + readonly LINE_STRIP: GLenum; + readonly LINE_WIDTH: GLenum; + readonly LINK_STATUS: GLenum; + readonly LOW_FLOAT: GLenum; + readonly LOW_INT: GLenum; + readonly LUMINANCE: GLenum; + readonly LUMINANCE_ALPHA: GLenum; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; + readonly MAX_RENDERBUFFER_SIZE: GLenum; + readonly MAX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_TEXTURE_SIZE: GLenum; + readonly MAX_VARYING_VECTORS: GLenum; + readonly MAX_VERTEX_ATTRIBS: GLenum; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_VERTEX_UNIFORM_VECTORS: GLenum; + readonly MAX_VIEWPORT_DIMS: GLenum; + readonly MEDIUM_FLOAT: GLenum; + readonly MEDIUM_INT: GLenum; + readonly MIRRORED_REPEAT: GLenum; + readonly NEAREST: GLenum; + readonly NEAREST_MIPMAP_LINEAR: GLenum; + readonly NEAREST_MIPMAP_NEAREST: GLenum; + readonly NEVER: GLenum; + readonly NICEST: GLenum; + readonly NONE: GLenum; + readonly NOTEQUAL: GLenum; + readonly NO_ERROR: GLenum; + readonly ONE: GLenum; + readonly ONE_MINUS_CONSTANT_ALPHA: GLenum; + readonly ONE_MINUS_CONSTANT_COLOR: GLenum; + readonly ONE_MINUS_DST_ALPHA: GLenum; + readonly ONE_MINUS_DST_COLOR: GLenum; + readonly ONE_MINUS_SRC_ALPHA: GLenum; + readonly ONE_MINUS_SRC_COLOR: GLenum; + readonly OUT_OF_MEMORY: GLenum; + readonly PACK_ALIGNMENT: GLenum; + readonly POINTS: GLenum; + readonly POLYGON_OFFSET_FACTOR: GLenum; + readonly POLYGON_OFFSET_FILL: GLenum; + readonly POLYGON_OFFSET_UNITS: GLenum; + readonly RED_BITS: GLenum; + readonly RENDERBUFFER: GLenum; + readonly RENDERBUFFER_ALPHA_SIZE: GLenum; + readonly RENDERBUFFER_BINDING: GLenum; + readonly RENDERBUFFER_BLUE_SIZE: GLenum; + readonly RENDERBUFFER_DEPTH_SIZE: GLenum; + readonly RENDERBUFFER_GREEN_SIZE: GLenum; + readonly RENDERBUFFER_HEIGHT: GLenum; + readonly RENDERBUFFER_INTERNAL_FORMAT: GLenum; + readonly RENDERBUFFER_RED_SIZE: GLenum; + readonly RENDERBUFFER_STENCIL_SIZE: GLenum; + readonly RENDERBUFFER_WIDTH: GLenum; + readonly RENDERER: GLenum; + readonly REPEAT: GLenum; + readonly REPLACE: GLenum; + readonly RGB: GLenum; + readonly RGB565: GLenum; + readonly RGB5_A1: GLenum; + readonly RGBA: GLenum; + readonly RGBA4: GLenum; + readonly SAMPLER_2D: GLenum; + readonly SAMPLER_CUBE: GLenum; + readonly SAMPLES: GLenum; + readonly SAMPLE_ALPHA_TO_COVERAGE: GLenum; + readonly SAMPLE_BUFFERS: GLenum; + readonly SAMPLE_COVERAGE: GLenum; + readonly SAMPLE_COVERAGE_INVERT: GLenum; + readonly SAMPLE_COVERAGE_VALUE: GLenum; + readonly SCISSOR_BOX: GLenum; + readonly SCISSOR_TEST: GLenum; + readonly SHADER_TYPE: GLenum; + readonly SHADING_LANGUAGE_VERSION: GLenum; + readonly SHORT: GLenum; + readonly SRC_ALPHA: GLenum; + readonly SRC_ALPHA_SATURATE: GLenum; + readonly SRC_COLOR: GLenum; + readonly STATIC_DRAW: GLenum; + readonly STENCIL_ATTACHMENT: GLenum; + readonly STENCIL_BACK_FAIL: GLenum; + readonly STENCIL_BACK_FUNC: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_BACK_REF: GLenum; + readonly STENCIL_BACK_VALUE_MASK: GLenum; + readonly STENCIL_BACK_WRITEMASK: GLenum; + readonly STENCIL_BITS: GLenum; + readonly STENCIL_BUFFER_BIT: GLenum; + readonly STENCIL_CLEAR_VALUE: GLenum; + readonly STENCIL_FAIL: GLenum; + readonly STENCIL_FUNC: GLenum; + readonly STENCIL_INDEX8: GLenum; + readonly STENCIL_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_REF: GLenum; + readonly STENCIL_TEST: GLenum; + readonly STENCIL_VALUE_MASK: GLenum; + readonly STENCIL_WRITEMASK: GLenum; + readonly STREAM_DRAW: GLenum; + readonly SUBPIXEL_BITS: GLenum; + readonly TEXTURE: GLenum; + readonly TEXTURE0: GLenum; + readonly TEXTURE1: GLenum; + readonly TEXTURE10: GLenum; + readonly TEXTURE11: GLenum; + readonly TEXTURE12: GLenum; + readonly TEXTURE13: GLenum; + readonly TEXTURE14: GLenum; + readonly TEXTURE15: GLenum; + readonly TEXTURE16: GLenum; + readonly TEXTURE17: GLenum; + readonly TEXTURE18: GLenum; + readonly TEXTURE19: GLenum; + readonly TEXTURE2: GLenum; + readonly TEXTURE20: GLenum; + readonly TEXTURE21: GLenum; + readonly TEXTURE22: GLenum; + readonly TEXTURE23: GLenum; + readonly TEXTURE24: GLenum; + readonly TEXTURE25: GLenum; + readonly TEXTURE26: GLenum; + readonly TEXTURE27: GLenum; + readonly TEXTURE28: GLenum; + readonly TEXTURE29: GLenum; + readonly TEXTURE3: GLenum; + readonly TEXTURE30: GLenum; + readonly TEXTURE31: GLenum; + readonly TEXTURE4: GLenum; + readonly TEXTURE5: GLenum; + readonly TEXTURE6: GLenum; + readonly TEXTURE7: GLenum; + readonly TEXTURE8: GLenum; + readonly TEXTURE9: GLenum; + readonly TEXTURE_2D: GLenum; + readonly TEXTURE_BINDING_2D: GLenum; + readonly TEXTURE_BINDING_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; + readonly TEXTURE_MAG_FILTER: GLenum; + readonly TEXTURE_MIN_FILTER: GLenum; + readonly TEXTURE_WRAP_S: GLenum; + readonly TEXTURE_WRAP_T: GLenum; + readonly TRIANGLES: GLenum; + readonly TRIANGLE_FAN: GLenum; + readonly TRIANGLE_STRIP: GLenum; + readonly UNPACK_ALIGNMENT: GLenum; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; + readonly UNPACK_FLIP_Y_WEBGL: GLenum; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; + readonly UNSIGNED_BYTE: GLenum; + readonly UNSIGNED_INT: GLenum; + readonly UNSIGNED_SHORT: GLenum; + readonly UNSIGNED_SHORT_4_4_4_4: GLenum; + readonly UNSIGNED_SHORT_5_5_5_1: GLenum; + readonly UNSIGNED_SHORT_5_6_5: GLenum; + readonly VALIDATE_STATUS: GLenum; + readonly VENDOR: GLenum; + readonly VERSION: GLenum; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_POINTER: GLenum; + readonly VERTEX_ATTRIB_ARRAY_SIZE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_TYPE: GLenum; + readonly VERTEX_SHADER: GLenum; + readonly VIEWPORT: GLenum; + readonly ZERO: GLenum; +} + +interface WebGLShader extends WebGLObject { +} + +declare var WebGLShader: { + prototype: WebGLShader; + new(): WebGLShader; +}; + +interface WebGLShaderPrecisionFormat { + readonly precision: GLint; + readonly rangeMax: GLint; + readonly rangeMin: GLint; +} + +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 WebGLVertexArrayObjectOES extends WebGLObject { +} + interface WebSocketEventMap { "close": CloseEvent; "error": Event; @@ -2676,7 +3879,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; - new(stringUrl: string): Worker; + new(stringUrl: string, options?: WorkerOptions): Worker; }; interface WorkerGlobalScopeEventMap { @@ -2736,6 +3939,31 @@ interface WorkerUtils extends WindowBase64 { importScripts(...urls: string[]): void; } +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk: W): Promise; +} + interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; } @@ -2897,6 +4125,46 @@ interface PerformanceObserverCallback { (entries: PerformanceObserverEntryList, observer: PerformanceObserver): void; } +interface QueuingStrategySizeCallback { + (chunk: T): number; +} + +interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; +} + +interface ReadableStreamDefaultControllerCallback { + (controller: ReadableStreamDefaultController): void | PromiseLike; +} + +interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; +} + +interface TransformStreamDefaultControllerCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; +} + +interface TransformStreamDefaultControllerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamDefaultControllerCloseCallback { + (): void | PromiseLike; +} + +interface WritableStreamDefaultControllerStartCallback { + (controller: WritableStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamDefaultControllerWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; +} + +interface WritableStreamErrorCallback { + (reason: any): void | PromiseLike; +} + declare var onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null; declare function close(): void; declare function postMessage(message: any, transfer?: Transferable[]): void; @@ -2946,7 +4214,7 @@ declare function removeEventListener; -type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; +type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; type RequestInfo = Request | string; type DOMHighResTimeStamp = number; type CanvasImageSource = ImageBitmap; @@ -2960,6 +4228,19 @@ type AlgorithmIdentifier = string | Algorithm; type HashAlgorithmIdentifier = AlgorithmIdentifier; type BigInteger = Uint8Array; type NamedCurve = string; +type GLenum = number; +type GLboolean = boolean; +type GLbitfield = number; +type GLint = number; +type GLsizei = number; +type GLintptr = number; +type GLsizeiptr = number; +type GLuint = number; +type GLfloat = number; +type GLclampf = number; +type TexImageSource = ImageBitmap | ImageData; +type Float32List = Float32Array | GLfloat[]; +type Int32List = Int32Array | GLint[]; type BufferSource = ArrayBufferView | ArrayBuffer; type DOMTimeStamp = number; type FormDataEntryValue = File | string; @@ -2967,6 +4248,7 @@ type IDBValidKey = number | string | Date | BufferSource | IDBArrayKey; type Transferable = ArrayBuffer | MessagePort | ImageBitmap; type BinaryType = "blob" | "arraybuffer"; type ClientTypes = "window" | "worker" | "sharedworker" | "all"; +type EndingType = "transparent" | "native"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; @@ -2987,5 +4269,6 @@ type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaquer type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type ServiceWorkerUpdateViaCache = "imports" | "all" | "none"; type VisibilityState = "hidden" | "visible" | "prerender"; +type WebGLPowerPreference = "default" | "low-power" | "high-performance"; type WorkerType = "classic" | "module"; type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index c735834474e..32430664b71 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,4 +1,4 @@ - + @@ -2083,7 +2083,7 @@ - + @@ -3766,7 +3766,7 @@ - + @@ -3775,7 +3775,7 @@ - + @@ -3784,7 +3784,7 @@ - + @@ -3793,7 +3793,7 @@ - + @@ -3802,7 +3802,7 @@ - + @@ -5437,7 +5437,7 @@ - + @@ -7567,7 +7567,7 @@ - + @@ -9172,7 +9172,7 @@ - + diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index f46e461c240..1760da2a463 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,10151 +1,10151 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - or -. For example '{0}' or '{1}'.]]> - - o -. Por ejemplo, '{0}' o '{1}'.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - type.]]> - - global.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ()' instead.]]> - - ()" en su lugar.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + or -. For example '{0}' or '{1}'.]]> + + o -. Por ejemplo, '{0}' o '{1}'.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type.]]> + + global.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ()' instead.]]> + + ()" en su lugar.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index 9d03da8d9b3..0078e878dbc 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,10139 +1,10139 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - or -. For example '{0}' or '{1}'.]]> - - 또는 - 형식이어야 합니다. 예를 들어 '{0}' 또는 '{1}'입니다.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - type.]]> - - 형식이어야 합니다.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ()' instead.]]> - - ()'를 사용하세요.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + or -. For example '{0}' or '{1}'.]]> + + 또는 - 형식이어야 합니다. 예를 들어 '{0}' 또는 '{1}'입니다.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type.]]> + + 형식이어야 합니다.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ()' instead.]]> + + ()'를 사용하세요.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7fade1f0ae3..0b60df175fe 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,10132 +1,10132 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - or -. For example '{0}' or '{1}'.]]> - - veya - biçiminde olmalıdır. Örneğin, '{0}' veya '{1}'.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - type.]]> - - türü olmalıdır.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ()' instead.]]> - - ()' kullanın.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + or -. For example '{0}' or '{1}'.]]> + + veya - biçiminde olmalıdır. Örneğin, '{0}' veya '{1}'.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type.]]> + + türü olmalıdır.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ()' instead.]]> + + ()' kullanın.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index ddbfd8ac389..51833bb2e6e 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -5,6 +5,8 @@ namespace ts.server { // tslint:disable variable-name export const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + export const ProjectLoadingStartEvent = "projectLoadingStart"; + export const ProjectLoadingFinishEvent = "projectLoadingFinish"; export const SurveyReady = "surveyReady"; export const LargeFileReferencedEvent = "largeFileReferenced"; export const ConfigFileDiagEvent = "configFileDiag"; @@ -18,6 +20,16 @@ namespace ts.server { data: { openFiles: string[]; }; } + export interface ProjectLoadingStartEvent { + eventName: typeof ProjectLoadingStartEvent; + data: { project: Project; reason: string; }; + } + + export interface ProjectLoadingFinishEvent { + eventName: typeof ProjectLoadingFinishEvent; + data: { project: Project; }; + } + export interface SurveyReady { eventName: typeof SurveyReady; data: { surveyId: string; }; @@ -44,6 +56,24 @@ namespace ts.server { readonly data: ProjectInfoTelemetryEventData; } +/* __GDPR__ + "projectInfo" : { + "${include}": ["${TypeScriptCommonProperties}"], + "projectId": { "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight", "endpoint": "ProjectId" }, + "fileStats": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "compilerOptions": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "extends": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "files": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "include": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "exclude": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "compileOnSave": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "typeAcquisition": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "configFileName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "projectType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "languageServiceEnabled": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "version": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } + } + */ export interface ProjectInfoTelemetryEventData { /** Cryptographically secure hash of project file location. */ readonly projectId: string; @@ -93,18 +123,37 @@ namespace ts.server { export interface FileStats { readonly js: number; + readonly jsSize?: number; + readonly jsx: number; + readonly jsxSize?: number; + readonly ts: number; + readonly tsSize?: number; + readonly tsx: number; + readonly tsxSize?: number; + readonly dts: number; + readonly dtsSize?: number; + readonly deferred: number; + readonly deferredSize?: number; } export interface OpenFileInfo { readonly checkJs: boolean; } - export type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + export type ProjectServiceEvent = LargeFileReferencedEvent | + SurveyReady | + ProjectsUpdatedInBackgroundEvent | + ProjectLoadingStartEvent | + ProjectLoadingFinishEvent | + ConfigFileDiagEvent | + ProjectLanguageServiceStateEvent | + ProjectInfoTelemetryEvent | + OpenFileInfoTelemetryEvent; export type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; @@ -283,17 +332,6 @@ namespace ts.server { } } - /* @internal */ - export const enum WatchType { - ConfigFilePath = "Config file for the program", - MissingFilePath = "Missing file from program", - WildcardDirectories = "Wild card directory", - ClosedScriptInfo = "Closed Script info", - ConfigFileForInferredRoot = "Config file for the inferred project root", - FailedLookupLocation = "Directory of Failed lookup locations in module resolution", - TypeRoots = "Type root directory" - } - const enum ConfigFileWatcherStatus { ReloadingFiles = "Reloading configured projects for files", ReloadingInferredRootFiles = "Reloading configured projects for only inferred root files", @@ -353,10 +391,18 @@ namespace ts.server { return !!(infoOrFileName as ScriptInfo).containingProjects; } + interface ScriptInfoInNodeModulesWatcher extends FileWatcher { + refCount: number; + } + function getDetailWatchInfo(watchType: WatchType, project: Project | undefined) { return `Project: ${project ? project.getProjectName() : ""} WatchType: ${watchType}`; } + function isScriptInfoWatchedFromNodeModules(info: ScriptInfo) { + return !info.isScriptOpen() && info.mTime !== undefined; + } + /*@internal*/ export function updateProjectIfDirty(project: Project) { return project.dirty && project.updateGraph(); @@ -379,7 +425,9 @@ namespace ts.server { /** * Container of all known scripts */ - private readonly filenameToScriptInfo = createMap(); + /*@internal*/ + readonly filenameToScriptInfo = createMap(); + private readonly scriptInfoInNodeModulesWatchers = createMap (); /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -420,7 +468,7 @@ namespace ts.server { */ private readonly openFilesWithNonRootedDiskPath = createMap(); - private compilerOptionsForInferredProjects: CompilerOptions; + private compilerOptionsForInferredProjects: CompilerOptions | undefined; private compilerOptionsForInferredProjectsPerProjectRoot = createMap(); /** * Project size for configured or external projects @@ -438,11 +486,11 @@ namespace ts.server { private readonly hostConfiguration: HostConfiguration; private safelist: SafeList = defaultTypeSafeList; - private legacySafelist: { [key: string]: string } = {}; + private readonly legacySafelist = createMap(); private pendingProjectUpdates = createMap(); /* @internal */ - pendingEnsureProjectForOpenFiles: boolean; + pendingEnsureProjectForOpenFiles = false; readonly currentDirectory: NormalizedPath; readonly toCanonicalFileName: (f: string) => string; @@ -461,6 +509,8 @@ namespace ts.server { public readonly globalPlugins: ReadonlyArray; public readonly pluginProbeLocations: ReadonlyArray; public readonly allowLocalPluginLoads: boolean; + private currentPluginConfigOverrides: Map | undefined; + public readonly typesMapLocation: string | undefined; public readonly syntaxOnly?: boolean; @@ -513,7 +563,7 @@ namespace ts.server { this.typingsCache = new TypingsCache(this.typingsInstaller); this.hostConfiguration = { - formatCodeOptions: getDefaultFormatCodeSettings(this.host), + formatCodeOptions: getDefaultFormatCodeSettings(this.host.newLine), preferences: emptyOptions, hostInfo: "Unknown host", extraFileExtensions: [] @@ -590,14 +640,14 @@ namespace ts.server { this.safelist = raw.typesMap; for (const key in raw.simpleMap) { if (raw.simpleMap.hasOwnProperty(key)) { - this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); } } } catch (e) { this.logger.info(`Error loading types map: ${e}`); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist.clear(); } } @@ -693,6 +743,33 @@ namespace ts.server { this.eventHandler(event); } + /* @internal */ + sendProjectLoadingStartEvent(project: ConfiguredProject, reason: string) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + const event: ProjectLoadingStartEvent = { + eventName: ProjectLoadingStartEvent, + data: { project, reason } + }; + this.eventHandler(event); + } + + /* @internal */ + sendProjectLoadingFinishEvent(project: ConfiguredProject) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + + project.sendLoadingProjectFinish = false; + const event: ProjectLoadingFinishEvent = { + eventName: ProjectLoadingFinishEvent, + data: { project } + }; + this.eventHandler(event); + } + /* @internal */ delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project: Project) { this.delayUpdateProjectGraph(project); @@ -758,9 +835,9 @@ namespace ts.server { /* @internal */ private forEachProject(cb: (project: Project) => void) { - this.inferredProjects.forEach(cb); - this.configuredProjects.forEach(cb); this.externalProjects.forEach(cb); + this.configuredProjects.forEach(cb); + this.inferredProjects.forEach(cb); } /* @internal */ @@ -790,7 +867,7 @@ namespace ts.server { private doEnsureDefaultProjectForFile(fileName: NormalizedPath): Project { this.ensureProjectStructuresUptoDate(); const scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - return scriptInfo ? scriptInfo.getDefaultProject() : Errors.ThrowNoProject(); + return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(fileName), Errors.ThrowNoProject()); } getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string) { @@ -843,14 +920,51 @@ namespace ts.server { if (!info) { this.logger.msg(`Error: got watch notification for unknown file: ${fileName}`); } - else if (eventKind === FileWatcherEventKind.Deleted) { - // File was deleted - this.handleDeletedFile(info); + else { + if (info.containingProjects) { + info.containingProjects.forEach(project => project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path)); + } + if (eventKind === FileWatcherEventKind.Deleted) { + // File was deleted + this.handleDeletedFile(info); + } + else if (!info.isScriptOpen()) { + // file has been changed which might affect the set of referenced files in projects that include + // this file and set of inferred projects + info.delayReloadNonMixedContentFile(); + this.delayUpdateProjectGraphs(info.containingProjects); + this.handleSourceMapProjects(info); + } } - else if (!info.isScriptOpen()) { - // file has been changed which might affect the set of referenced files in projects that include - // this file and set of inferred projects - info.delayReloadNonMixedContentFile(); + } + + private handleSourceMapProjects(info: ScriptInfo) { + // Change in d.ts, update source projects as well + if (info.sourceMapFilePath) { + if (isString(info.sourceMapFilePath)) { + const sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath); + this.delayUpdateSourceInfoProjects(sourceMapFileInfo && sourceMapFileInfo.sourceInfos); + } + else { + this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos); + } + } + // Change in mapInfo, update declarationProjects and source projects + this.delayUpdateSourceInfoProjects(info.sourceInfos); + if (info.declarationInfoPath) { + this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath); + } + } + + private delayUpdateSourceInfoProjects(sourceInfos: Map | undefined) { + if (sourceInfos) { + sourceInfos.forEach((_value, path) => this.delayUpdateProjectsOfScriptInfoPath(path as Path)); + } + } + + private delayUpdateProjectsOfScriptInfoPath(path: Path) { + const info = this.getScriptInfoForPath(path); + if (info) { this.delayUpdateProjectGraphs(info.containingProjects); } } @@ -868,6 +982,15 @@ namespace ts.server { // update projects to make sure that set of referenced files is correct this.delayUpdateProjectGraphs(containingProjects); + this.handleSourceMapProjects(info); + info.closeSourceMapFileWatcher(); + // need to recalculate source map from declaration file + if (info.declarationInfoPath) { + const declarationInfo = this.getScriptInfoForPath(info.declarationInfoPath); + if (declarationInfo) { + declarationInfo.sourceMapFilePath = undefined; + } + } } } @@ -882,6 +1005,7 @@ namespace ts.server { fileOrDirectory => { const fileOrDirectoryPath = this.toPath(fileOrDirectory); project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return; const configFilename = project.getConfigFilePath(); // If the the added or created file or directory is not supported file name, ignore the file @@ -898,7 +1022,7 @@ namespace ts.server { } }, flags, - WatchType.WildcardDirectories, + WatchType.WildcardDirectory, project ); } @@ -927,6 +1051,7 @@ namespace ts.server { else { this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.ReloadingInferredRootFiles); project.pendingReload = ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = "Change in config file detected"; this.delayUpdateProjectGraph(project); // As we scheduled the update on configured project graph, // we would need to schedule the project reload for only the root of inferred projects @@ -953,11 +1078,12 @@ namespace ts.server { } private removeProject(project: Project) { - this.logger.info(`remove project: ${project.getRootFiles().toString()}`); + this.logger.info("`remove Project::"); + project.print(); project.close(); if (Debug.shouldAssert(AssertionLevel.Normal)) { - this.filenameToScriptInfo.forEach(info => Debug.assert(!info.isAttached(project))); + this.filenameToScriptInfo.forEach(info => Debug.assert(!info.isAttached(project), "Found script Info still attached to project", () => `${project.projectName}: ScriptInfos still attached: ${JSON.stringify(mapDefined(arrayFrom(this.filenameToScriptInfo.values()), info => info.isAttached(project) ? info : undefined))}`)); } // Remove the project from pending project updates this.pendingProjectUpdates.delete(project.getProjectName()); @@ -1138,7 +1264,8 @@ namespace ts.server { private setConfigFileExistenceByNewConfiguredProject(project: ConfiguredProject) { const configFileExistenceInfo = this.getConfigFileExistenceInfo(project); if (configFileExistenceInfo) { - Debug.assert(configFileExistenceInfo.exists); + // The existance might not be set if the file watcher is not invoked by the time config project is created by external project + configFileExistenceInfo.exists = true; // close existing watcher if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { const configFileName = project.getConfigFilePath(); @@ -1199,7 +1326,7 @@ namespace ts.server { watches.push(WatchType.ConfigFileForInferredRoot); } if (this.configuredProjects.has(canonicalConfigFilePath)) { - watches.push(WatchType.ConfigFilePath); + watches.push(WatchType.ConfigFile); } this.logger.info(`ConfigFilePresence:: Current Watches: ${watches}:: File: ${configFileName} Currently impacted open files: RootsOfInferredProjects: ${inferredRoots} OtherOpenFiles: ${otherFiles} Status: ${status}`); } @@ -1393,19 +1520,9 @@ namespace ts.server { const writeProjectFileNames = this.logger.hasLevel(LogLevel.verbose); this.logger.startGroup(); - let counter = 0; - const printProjects = (projects: Project[], counter: number): number => { - for (const project of projects) { - this.logger.info(`Project '${project.getProjectName()}' (${ProjectKind[project.projectKind]}) ${counter}`); - this.logger.info(project.filesToString(writeProjectFileNames)); - this.logger.info("-----------------------------------------------"); - counter++; - } - return counter; - }; - counter = printProjects(this.externalProjects, counter); - counter = printProjects(arrayFrom(this.configuredProjects.values()), counter); - printProjects(this.inferredProjects, counter); + let counter = printProjectsWithCounter(this.externalProjects, 0); + counter = printProjectsWithCounter(arrayFrom(this.configuredProjects.values()), counter); + printProjectsWithCounter(this.inferredProjects, counter); this.logger.info("Open files: "); this.openFiles.forEach((projectRootPath, path) => { @@ -1447,14 +1564,14 @@ namespace ts.server { for (const f of fileNames) { const fileName = propertyReader.getFileName(f); - if (hasTypeScriptFileExtension(fileName)) { + if (hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader, hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader, hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // Keep the size as zero since it's disabled return fileName; } @@ -1464,14 +1581,14 @@ namespace ts.server { return; - function getExceedLimitMessage(context: { propertyReader: FilePropertyReader, hasTypeScriptFileExtension: (filename: string) => boolean, host: ServerHost }, totalNonTsFileSize: number) { + function getExceedLimitMessage(context: { propertyReader: FilePropertyReader, hasTSFileExtension: (filename: string) => boolean, host: ServerHost }, totalNonTsFileSize: number) { const files = getTop5LargestFiles(context); return `Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${files.map(file => `${file.name}:${file.size}`).join(", ")}`; } - function getTop5LargestFiles({ propertyReader, hasTypeScriptFileExtension, host }: { propertyReader: FilePropertyReader, hasTypeScriptFileExtension: (filename: string) => boolean, host: ServerHost }) { + function getTop5LargestFiles({ propertyReader, hasTSFileExtension, host }: { propertyReader: FilePropertyReader, hasTSFileExtension: (filename: string) => boolean, host: ServerHost }) { return fileNames.map(f => propertyReader.getFileName(f)) - .filter(name => hasTypeScriptFileExtension(name)) + .filter(name => hasTSFileExtension(name)) .map(name => ({ name, size: host.getFileSize!(name) })) // TODO: GH#18217 .sort((a, b) => b.size - a.size) .slice(0, 5); @@ -1525,7 +1642,7 @@ namespace ts.server { setProjectOptionsUsed(project); const data: ProjectInfoTelemetryEventData = { projectId: this.host.createSHA256Hash(project.projectName), - fileStats: countEachFileTypes(project.getScriptInfos()), + fileStats: countEachFileTypes(project.getScriptInfos(), /*includeSizes*/ true), compilerOptions: convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), extends: projectOptions && projectOptions.configHasExtendsProperty, @@ -1576,7 +1693,7 @@ namespace ts.server { configFileName, (_fileName, eventKind) => this.onConfigChangedForConfiguredProject(project, eventKind), PollingInterval.High, - WatchType.ConfigFilePath, + WatchType.ConfigFile, project ); this.configuredProjects.set(project.canonicalConfigFilePath, project); @@ -1585,22 +1702,23 @@ namespace ts.server { } /* @internal */ - private createConfiguredProjectWithDelayLoad(configFileName: NormalizedPath) { + private createConfiguredProjectWithDelayLoad(configFileName: NormalizedPath, reason: string) { const project = this.createConfiguredProject(configFileName); project.pendingReload = ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; return project; } /* @internal */ - private createAndLoadConfiguredProject(configFileName: NormalizedPath) { + private createAndLoadConfiguredProject(configFileName: NormalizedPath, reason: string) { const project = this.createConfiguredProject(configFileName); - this.loadConfiguredProject(project); + this.loadConfiguredProject(project, reason); return project; } /* @internal */ - private createLoadAndUpdateConfiguredProject(configFileName: NormalizedPath) { - const project = this.createAndLoadConfiguredProject(configFileName); + private createLoadAndUpdateConfiguredProject(configFileName: NormalizedPath, reason: string) { + const project = this.createAndLoadConfiguredProject(configFileName, reason); project.updateGraph(); return project; } @@ -1609,7 +1727,9 @@ namespace ts.server { * Read the config file of the project, and update the project root file names. */ /* @internal */ - private loadConfiguredProject(project: ConfiguredProject) { + private loadConfiguredProject(project: ConfiguredProject, reason: string) { + this.sendProjectLoadingStartEvent(project, reason); + // Read updated contents from disk const configFilename = normalizePath(project.getConfigFilePath()); @@ -1646,6 +1766,7 @@ namespace ts.server { }; } project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.canConfigFileJsonReportNoInputFiles = canJsonReportNoInutFiles(parsedCommandLine.raw); project.setProjectErrors(configFileErrors); project.updateReferences(parsedCommandLine.projectReferences); const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); @@ -1657,7 +1778,7 @@ namespace ts.server { project.enableLanguageService(); project.watchWildcards(createMapFromTemplate(parsedCommandLine.wildcardDirectories!)); // TODO: GH#18217 } - project.enablePluginsWithOptions(compilerOptions); + project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition!, parsedCommandLine.compileOnSave!); // TODO: GH#18217 } @@ -1738,7 +1859,7 @@ namespace ts.server { const configFileSpecs = project.configFileSpecs!; // TODO: GH#18217 const configFileName = project.getConfigFilePath(); const fileNamesResult = getFileNamesFromConfigSpecs(configFileSpecs, getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); - project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); + project.updateErrorOnNoInputFiles(fileNamesResult); this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); } @@ -1747,7 +1868,7 @@ namespace ts.server { * Read the config file of the project again by clearing the cache and update the project graph */ /* @internal */ - reloadConfiguredProject(project: ConfiguredProject) { + reloadConfiguredProject(project: ConfiguredProject, reason: string) { // At this point, there is no reason to not have configFile in the host const host = project.getCachedDirectoryStructureHost(); @@ -1757,7 +1878,7 @@ namespace ts.server { this.logger.info(`Reloading configured project ${configFileName}`); // Load project from the disk - this.loadConfiguredProject(project); + this.loadConfiguredProject(project, reason); project.updateGraph(); this.sendConfigFileDiagEvent(project, configFileName); @@ -1846,8 +1967,8 @@ namespace ts.server { } private createInferredProject(currentDirectory: string | undefined, isSingleInferredProject?: boolean, projectRootPath?: NormalizedPath): InferredProject { - const compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; - const project = new InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory); + const compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects!; // TODO: GH#18217 + const project = new InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides); if (isSingleInferredProject) { this.inferredProjects.unshift(project); } @@ -1874,10 +1995,16 @@ namespace ts.server { const path = toNormalizedPath(uncheckedFileName); const info = this.getScriptInfoForNormalizedPath(path); if (info) return info; - const configProject = this.configuredProjects.get(uncheckedFileName); + const configProject = this.configuredProjects.get(this.toPath(uncheckedFileName)); return configProject && configProject.getCompilerOptions().configFile; } + /* @internal */ + logErrorForScriptInfoNotFound(fileName: string): void { + const names = arrayFrom(this.filenameToScriptInfo.entries()).map(([path, scriptInfo]) => ({ path, fileName: scriptInfo.fileName })); + this.logger.msg(`Could not find file ${JSON.stringify(fileName)}.\nAll files are: ${JSON.stringify(names)}`, Msg.Err); + } + /** * Returns the projects that contain script info through SymLink * Note that this does not return projects in info.containingProjects @@ -1923,18 +2050,99 @@ namespace ts.server { if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - const { fileName } = info; - info.fileWatcher = this.watchFactory.watchFilePath( - this.host, - fileName, - (fileName, eventKind, path) => this.onSourceFileChanged(fileName, eventKind, path), - PollingInterval.Medium, - info.path, - WatchType.ClosedScriptInfo - ); + const indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath( + this.host, + info.fileName, + (fileName, eventKind, path) => this.onSourceFileChanged(fileName, eventKind, path), + PollingInterval.Medium, + info.path, + WatchType.ClosedScriptInfo + ); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules) as Path); + } } } + private watchClosedScriptInfoInNodeModules(dir: Path): ScriptInfoInNodeModulesWatcher { + // Watch only directory + const existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + + const watchDir = dir + "/node_modules" as Path; + const watcher = this.watchFactory.watchDirectory( + this.host, + watchDir, + (fileOrDirectory) => { + const fileOrDirectoryPath = this.toPath(fileOrDirectory); + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return; + + // Has extension + Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + this.refreshScriptInfosInDirectory(watchDir); + } + else { + const info = this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + this.refreshScriptInfo(info); + } + } + // Folder + else if (!hasExtension(fileOrDirectoryPath)) { + this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, + WatchDirectoryFlags.Recursive, + WatchType.NodeModulesForClosedScriptInfo + ); + const result: ScriptInfoInNodeModulesWatcher = { + close: () => { + if (result.refCount === 1) { + watcher.close(); + this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + } + + private getModifiedTime(info: ScriptInfo) { + return (this.host.getModifiedTime!(info.path) || missingFileModifiedTime).getTime(); + } + + private refreshScriptInfo(info: ScriptInfo) { + const mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + const eventKind = getFileWatcherEventKind(info.mTime!, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + } + + private refreshScriptInfosInDirectory(dir: Path) { + dir = dir + directorySeparator as Path; + this.filenameToScriptInfo.forEach(info => { + if (isScriptInfoWatchedFromNodeModules(info) && startsWith(info.path, dir)) { + this.refreshScriptInfo(info); + } + }); + } + private stopWatchingScriptInfo(info: ScriptInfo) { if (info.fileWatcher) { info.fileWatcher.close(); @@ -1943,7 +2151,20 @@ namespace ts.server { } private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName: NormalizedPath, currentDirectory: string, scriptKind: ScriptKind | undefined, hasMixedContent: boolean | undefined, hostToQueryFileExistsOn: DirectoryStructureHost | undefined) { - return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + if (isRootedDiskPath(fileName) || isDynamicFileName(fileName)) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + } + + // This is non rooted path with different current directory than project service current directory + // Only paths recognized are open relative file paths + const info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)); + if (info) { + return info; + } + + // This means triple slash references wont be resolved in dynamic and unsaved files + // which is intentional since we dont know what it means to be relative to non disk files + return undefined; } private getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName: NormalizedPath, currentDirectory: string, fileContent: string | undefined, scriptKind: ScriptKind | undefined, hasMixedContent: boolean | undefined) { @@ -1960,7 +2181,7 @@ namespace ts.server { let info = this.getScriptInfoForPath(path); if (!info) { const isDynamic = isDynamicFileName(fileName); - Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}\nScript info with non-dynamic relative file name can only be open script info`); + Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory`); Debug.assert(!isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names`); Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}\nDynamic files must always have current directory context since containing external project name will always match the script info name.`); // If the file is not opened by client and the file doesnot exist on the disk, return @@ -1973,7 +2194,7 @@ namespace ts.server { if (!openedByClient) { this.watchClosedScriptInfo(info); } - else if (!isRootedDiskPath(fileName) && currentDirectory !== this.currentDirectory) { + else if (!isRootedDiskPath(fileName) && !isDynamic) { // File that is opened by user but isn't rooted disk path this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); } @@ -2005,6 +2226,150 @@ namespace ts.server { return this.filenameToScriptInfo.get(fileName); } + /*@internal*/ + getDocumentPositionMapper(project: Project, generatedFileName: string, sourceFileName?: string): DocumentPositionMapper | undefined { + // Since declaration info and map file watches arent updating project's directory structure host (which can cache file structure) use host + const declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient(generatedFileName, project.currentDirectory, this.host); + if (!declarationInfo) return undefined; + + // Try to get from cache + declarationInfo.getSnapshot(); // Ensure synchronized + if (isString(declarationInfo.sourceMapFilePath)) { + // Ensure mapper is synchronized + const sourceMapFileInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); + if (sourceMapFileInfo) { + sourceMapFileInfo.getSnapshot(); + if (sourceMapFileInfo.documentPositionMapper !== undefined) { + sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos); + return sourceMapFileInfo.documentPositionMapper ? sourceMapFileInfo.documentPositionMapper : undefined; + } + } + declarationInfo.sourceMapFilePath = undefined; + } + else if (declarationInfo.sourceMapFilePath) { + declarationInfo.sourceMapFilePath.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, declarationInfo.sourceMapFilePath.sourceInfos); + return undefined; + } + else if (declarationInfo.sourceMapFilePath !== undefined) { + // Doesnt have sourceMap + return undefined; + } + + // Create the mapper + let sourceMapFileInfo: ScriptInfo | undefined; + let mapFileNameFromDeclarationInfo: string | undefined; + + let readMapFile: ReadMapFile | undefined = (mapFileName, mapFileNameFromDts) => { + const mapInfo = this.getOrCreateScriptInfoNotOpenedByClient(mapFileName, project.currentDirectory, this.host); + if (!mapInfo) { + mapFileNameFromDeclarationInfo = mapFileNameFromDts; + return undefined; + } + sourceMapFileInfo = mapInfo; + const snap = mapInfo.getSnapshot(); + if (mapInfo.documentPositionMapper !== undefined) return mapInfo.documentPositionMapper; + return snap.getText(0, snap.getLength()); + }; + const projectName = project.projectName; + const documentPositionMapper = getDocumentPositionMapper( + { getCanonicalFileName: this.toCanonicalFileName, log: s => this.logger.info(s), getSourceFileLike: f => this.getSourceFileLike(f, projectName, declarationInfo) }, + declarationInfo.fileName, + declarationInfo.getLineInfo(), + readMapFile + ); + readMapFile = undefined; // Remove ref to project + if (sourceMapFileInfo) { + declarationInfo.sourceMapFilePath = sourceMapFileInfo.path; + sourceMapFileInfo.declarationInfoPath = declarationInfo.path; + sourceMapFileInfo.documentPositionMapper = documentPositionMapper || false; + sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos); + } + else if (mapFileNameFromDeclarationInfo) { + declarationInfo.sourceMapFilePath = { + watcher: this.addMissingSourceMapFile( + project.currentDirectory === this.currentDirectory ? + mapFileNameFromDeclarationInfo : + getNormalizedAbsolutePath(mapFileNameFromDeclarationInfo, project.currentDirectory), + declarationInfo.path + ), + sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project) + }; + } + else { + declarationInfo.sourceMapFilePath = false; + } + return documentPositionMapper; + } + + private addSourceInfoToSourceMap(sourceFileName: string | undefined, project: Project, sourceInfos?: Map) { + if (sourceFileName) { + // Attach as source + const sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost)!; + (sourceInfos || (sourceInfos = createMap())).set(sourceInfo.path, true); + } + return sourceInfos; + } + + private addMissingSourceMapFile(mapFileName: string, declarationInfoPath: Path) { + const fileWatcher = this.watchFactory.watchFile( + this.host, + mapFileName, + () => { + const declarationInfo = this.getScriptInfoForPath(declarationInfoPath); + if (declarationInfo && declarationInfo.sourceMapFilePath && !isString(declarationInfo.sourceMapFilePath)) { + // Update declaration and source projects + this.delayUpdateProjectGraphs(declarationInfo.containingProjects); + this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos); + declarationInfo.closeSourceMapFileWatcher(); + } + }, + PollingInterval.High, + WatchType.MissingSourceMapFile, + ); + return fileWatcher; + } + + /*@internal*/ + getSourceFileLike(fileName: string, projectNameOrProject: string | Project, declarationInfo?: ScriptInfo) { + const project = (projectNameOrProject as Project).projectName ? projectNameOrProject as Project : this.findProject(projectNameOrProject as string); + if (project) { + const path = project.toPath(fileName); + const sourceFile = project.getSourceFile(path); + if (sourceFile && sourceFile.resolvedPath === path) return sourceFile; + } + + // Need to look for other files. + const info = this.getOrCreateScriptInfoNotOpenedByClient(fileName, (project || this).currentDirectory, project ? project.directoryStructureHost : this.host); + if (!info) return undefined; + + // Attach as source + if (declarationInfo && isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) { + const sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); + if (sourceMapInfo) { + (sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = createMap())).set(info.path, true); + } + } + + // Key doesnt matter since its only for text and lines + if (info.cacheSourceFile) return info.cacheSourceFile.sourceFile; + + // Create sourceFileLike + if (!info.sourceFileLike) { + info.sourceFileLike = { + get text() { + Debug.fail("shouldnt need text"); + return ""; + }, + getLineAndCharacterOfPosition: pos => { + const lineOffset = info.positionToLineOffset(pos); + return { line: lineOffset.line - 1, character: lineOffset.offset - 1 }; + }, + getPositionOfLineAndCharacter: (line, character, allowEdits) => info.lineOffsetToPosition(line + 1, character + 1, allowEdits) + }; + } + return info.sourceFileLike; + } + setHostConfiguration(args: protocol.ConfigureRequestArguments) { if (args.file) { const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(args.file)); @@ -2031,7 +2396,6 @@ namespace ts.server { if (project.hasExternalProjectRef() && project.pendingReload === ConfigFileProgramReloadLevel.Full && !this.pendingProjectUpdates.has(project.getProjectName())) { - this.loadConfiguredProject(project); project.updateGraph(); } }); @@ -2063,7 +2427,7 @@ namespace ts.server { // as there is no need to load contents of the files from the disk // Reload Projects - this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, returnTrue); + this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, returnTrue, "User requested reload projects"); this.ensureProjectForOpenFiles(); } @@ -2074,7 +2438,8 @@ namespace ts.server { /*delayReload*/ true, ignoreIfNotRootOfInferredProject ? isRootOfInferredProject => isRootOfInferredProject : // Reload open files if they are root of inferred project - returnTrue // Reload all the open files impacted by config file + returnTrue, // Reload all the open files impacted by config file + "Change in config file detected" ); this.delayEnsureProjectForOpenFiles(); } @@ -2086,7 +2451,7 @@ namespace ts.server { * If the there is no existing project it just opens the configured project for the config file * reloadForInfo provides a way to filter out files to reload configured project for */ - private reloadConfiguredProjectForFiles(openFiles: Map, delayReload: boolean, shouldReloadProjectFor: (openFileValue: T) => boolean) { + private reloadConfiguredProjectForFiles(openFiles: Map, delayReload: boolean, shouldReloadProjectFor: (openFileValue: T) => boolean, reason: string) { const updatedProjects = createMap(); // try to reload config file for all open files openFiles.forEach((openFileValue, path) => { @@ -2107,11 +2472,12 @@ namespace ts.server { if (!updatedProjects.has(configFileName)) { if (delayReload) { project.pendingReload = ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; this.delayUpdateProjectGraph(project); } else { // reload from the disk - this.reloadConfiguredProject(project); + this.reloadConfiguredProject(project, reason); } updatedProjects.set(configFileName, true); } @@ -2187,8 +2553,8 @@ namespace ts.server { } /*@internal*/ - getOriginalLocationEnsuringConfiguredProject(project: Project, location: sourcemaps.SourceMappableLocation): sourcemaps.SourceMappableLocation | undefined { - const originalLocation = project.getSourceMapper().tryGetOriginalLocation(location); + getOriginalLocationEnsuringConfiguredProject(project: Project, location: DocumentPosition): DocumentPosition | undefined { + const originalLocation = project.getSourceMapper().tryGetSourcePosition(location); if (!originalLocation) return undefined; const { fileName } = originalLocation; @@ -2198,7 +2564,8 @@ namespace ts.server { const configFileName = this.getConfigFileNameForFile(originalFileInfo); if (!configFileName) return undefined; - const configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createAndLoadConfiguredProject(configFileName); + const configuredProject = this.findConfiguredProjectByProjectName(configFileName) || + this.createAndLoadConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName} for location: ${location.fileName}`); updateProjectIfDirty(configuredProject); // Keep this configured project as referenced from project addOriginalConfiguredProject(configuredProject); @@ -2224,7 +2591,7 @@ namespace ts.server { /** @internal */ fileExists(fileName: NormalizedPath): boolean { - return this.filenameToScriptInfo.has(fileName) || this.host.fileExists(fileName); + return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName); } private findExternalProjectContainingOpenScriptInfo(info: ScriptInfo): ExternalProject | undefined { @@ -2248,7 +2615,7 @@ namespace ts.server { if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createLoadAndUpdateConfiguredProject(configFileName); + project = this.createLoadAndUpdateConfiguredProject(configFileName, `Creating possible configured project for ${fileName} to open`); // Send the event only if the project got created as part of this open request and info is part of the project if (info.isOrphan()) { // Since the file isnt part of configured project, do not send config file info @@ -2298,13 +2665,7 @@ namespace ts.server { // when some file/s were closed which resulted in project removal. // It was then postponed to cleanup these script infos so that they can be reused if // the file from that old project is reopened because of opening file from here. - this.filenameToScriptInfo.forEach(info => { - if (!info.isScriptOpen() && info.isOrphan()) { - // if there are not projects that include this script info - delete it - this.stopWatchingScriptInfo(info); - this.deleteScriptInfo(info); - } - }); + this.removeOrphanScriptInfos(); this.printProjects(); @@ -2326,17 +2687,14 @@ namespace ts.server { } else { // If the configured project for project reference has more than zero references, keep it alive - const resolvedProjectReferences = project.getResolvedProjectReferences(); - if (resolvedProjectReferences) { - for (const ref of resolvedProjectReferences) { - if (ref) { - const refProject = this.configuredProjects.get(ref.sourceFile.path); - if (refProject && refProject.hasOpenRef()) { - toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); - } + project.forEachResolvedProjectReference(ref => { + if (ref) { + const refProject = this.configuredProjects.get(ref.sourceFile.path); + if (refProject && refProject.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); } } - } + }); } }); @@ -2350,12 +2708,68 @@ namespace ts.server { } } + private removeOrphanScriptInfos() { + const toRemoveScriptInfos = cloneMap(this.filenameToScriptInfo); + this.filenameToScriptInfo.forEach(info => { + // If script info is open or orphan, retain it and its dependencies + if (!info.isScriptOpen() && info.isOrphan()) { + // Otherwise if there is any source info that is alive, this alive too + if (!info.sourceMapFilePath) return; + let sourceInfos: Map | undefined; + if (isString(info.sourceMapFilePath)) { + const sourceMapInfo = this.getScriptInfoForPath(info.sourceMapFilePath); + sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos; + } + else { + sourceInfos = info.sourceMapFilePath.sourceInfos; + } + if (!sourceInfos) return; + if (!forEachKey(sourceInfos, path => { + const info = this.getScriptInfoForPath(path as Path); + return !!info && (info.isScriptOpen() || !info.isOrphan()); + })) { + return; + } + } + + // Retain this script info + toRemoveScriptInfos.delete(info.path); + if (info.sourceMapFilePath) { + let sourceInfos: Map | undefined; + if (isString(info.sourceMapFilePath)) { + // And map file info and source infos + toRemoveScriptInfos.delete(info.sourceMapFilePath); + const sourceMapInfo = this.getScriptInfoForPath(info.sourceMapFilePath); + sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos; + } + else { + sourceInfos = info.sourceMapFilePath.sourceInfos; + } + if (sourceInfos) { + sourceInfos.forEach((_value, path) => toRemoveScriptInfos.delete(path)); + } + } + }); + + toRemoveScriptInfos.forEach(info => { + // if there are not projects that include this script info - delete it + this.stopWatchingScriptInfo(info); + this.deleteScriptInfo(info); + info.closeSourceMapFileWatcher(); + }); + } + private telemetryOnOpenFile(scriptInfo: ScriptInfo): void { if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { return; } - const info: OpenFileInfo = { checkJs: !!scriptInfo.getDefaultProject().getSourceFile(scriptInfo.path)!.checkJsDirective }; + const project = scriptInfo.getDefaultProject(); + if (!project.languageServiceEnabled) { + return; + } + + const info: OpenFileInfo = { checkJs: !!project.getSourceFile(scriptInfo.path)!.checkJsDirective }; this.eventHandler({ eventName: OpenFileInfoTelemetryEvent, data: { info } }); } @@ -2560,13 +2974,13 @@ namespace ts.server { if (fileExtensionIs(baseName, "js")) { const inferredTypingName = removeFileExtension(baseName); const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); - if (this.legacySafelist[cleanedTypingName]) { + const typeName = this.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { this.logger.info(`Excluded '${normalizedNames[i]}' because it matched ${cleanedTypingName} from the legacy safelist`); excludedFiles.push(normalizedNames[i]); // *exclude* it from the project... exclude = true; // ... but *include* it in the list of types to acquire - const typeName = this.legacySafelist[cleanedTypingName]; // Same best-effort dedupe as above if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); @@ -2689,8 +3103,8 @@ namespace ts.server { if (!project) { // errors are stored in the project, do not need to update the graph project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? - this.createConfiguredProjectWithDelayLoad(tsconfigFile) : - this.createLoadAndUpdateConfiguredProject(tsconfigFile); + this.createConfiguredProjectWithDelayLoad(tsconfigFile, `Creating configured project in external project: ${proj.projectFileName}`) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile, `Creating configured project in external project: ${proj.projectFileName}`); } if (project && !contains(exisingConfigFiles, tsconfigFile)) { // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project @@ -2717,6 +3131,16 @@ namespace ts.server { return false; } + + configurePlugin(args: protocol.ConfigurePluginRequestArguments) { + // For any projects that already have the plugin loaded, configure the plugin + this.forEachEnabledProject(project => project.onPluginConfigurationChanged(args.pluginName, args.configuration)); + + // Also save the current configuration to pass on to any projects that are yet to be loaded. + // If a plugin is configured twice, only the latest configuration will be remembered. + this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || createMap(); + this.currentPluginConfigOverrides.set(args.pluginName, args.configuration); + } } /* @internal */ @@ -2725,4 +3149,12 @@ namespace ts.server { export function isConfigFile(config: ScriptInfoOrConfig): config is TsConfigSourceFile { return (config as TsConfigSourceFile).kind !== undefined; } + + function printProjectsWithCounter(projects: Project[], counter: number) { + for (const project of projects) { + project.print(counter); + counter++; + } + return counter; + } } diff --git a/src/server/project.ts b/src/server/project.ts index f20530c88a9..b296668e6ae 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -10,26 +10,43 @@ namespace ts.server { export type Mutable = { -readonly [K in keyof T]: T[K]; }; /* @internal */ - export function countEachFileTypes(infos: ScriptInfo[]): FileStats { - const result: Mutable = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0, deferred: 0 }; + export function countEachFileTypes(infos: ScriptInfo[], includeSizes = false): FileStats { + const result: Mutable = { + js: 0, jsSize: 0, + jsx: 0, jsxSize: 0, + ts: 0, tsSize: 0, + tsx: 0, tsxSize: 0, + dts: 0, dtsSize: 0, + deferred: 0, deferredSize: 0, + }; for (const info of infos) { + const fileSize = includeSizes ? info.getTelemetryFileSize() : 0; switch (info.scriptKind) { case ScriptKind.JS: result.js += 1; + result.jsSize! += fileSize; break; case ScriptKind.JSX: result.jsx += 1; + result.jsxSize! += fileSize; break; case ScriptKind.TS: - fileExtensionIs(info.fileName, Extension.Dts) - ? result.dts += 1 - : result.ts += 1; + if (fileExtensionIs(info.fileName, Extension.Dts)) { + result.dts += 1; + result.dtsSize! += fileSize; + } + else { + result.ts += 1; + result.tsSize! += fileSize; + } break; case ScriptKind.TSX: result.tsx += 1; + result.tsxSize! += fileSize; break; case ScriptKind.Deferred: result.deferred += 1; + result.deferredSize! += fileSize; break; } } @@ -72,6 +89,12 @@ namespace ts.server { export interface PluginModule { create(createInfo: PluginCreateInfo): LanguageService; getExternalFiles?(proj: Project): string[]; + onConfigurationChanged?(config: any): void; + } + + export interface PluginModuleWithName { + name: string; + module: PluginModule; } export type PluginModuleFactory = (mod: { typescript: typeof ts }) => PluginModule; @@ -89,10 +112,10 @@ namespace ts.server { export abstract class Project implements LanguageServiceHost, ModuleResolutionHost { private rootFiles: ScriptInfo[] = []; private rootFilesMap: Map = createMap(); - private program: Program; - private externalFiles: SortedReadonlyArray; - private missingFilesMap: Map; - private plugins: PluginModule[] = []; + private program: Program | undefined; + private externalFiles: SortedReadonlyArray | undefined; + private missingFilesMap: Map | undefined; + private plugins: PluginModuleWithName[] = []; /*@internal*/ /** @@ -118,7 +141,7 @@ namespace ts.server { readonly realpath?: (path: string) => string; /*@internal*/ - hasInvalidatedResolution: HasInvalidatedResolution; + hasInvalidatedResolution: HasInvalidatedResolution | undefined; /*@internal*/ resolutionCache: ResolutionCache; @@ -131,7 +154,7 @@ namespace ts.server { /** * Set of files that was returned from the last call to getChangesSinceVersion. */ - private lastReportedFileNames: Map; + private lastReportedFileNames: Map | undefined; /** * Last version that was reported. */ @@ -198,7 +221,7 @@ namespace ts.server { /*@internal*/ constructor( - /*@internal*/readonly projectName: string, + readonly projectName: string, readonly projectKind: ProjectKind, readonly projectService: ProjectService, private documentRegistry: DocumentRegistry, @@ -254,6 +277,11 @@ namespace ts.server { installPackage(options: InstallPackageOptions): Promise { return this.typingsCache.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }); } + /* @internal */ + inspectValue(options: InspectValueOptions): Promise { + return this.typingsCache.inspectValue(options); + } + private get typingsCache(): TypingsCache { return this.projectService.typingsCache; } @@ -276,8 +304,8 @@ namespace ts.server { return this.projectStateVersion.toString(); } - getProjectReferences(): ReadonlyArray { - return emptyArray; + getProjectReferences(): ReadonlyArray | undefined { + return undefined; } getScriptFileNames() { @@ -352,6 +380,10 @@ namespace ts.server { return this.projectService.host.readFile(fileName); } + writeFile(fileName: string, content: string): void { + return this.projectService.host.writeFile(fileName, content); + } + fileExists(file: string): boolean { // As an optimization, don't hit the disks for files we already know don't exist // (because we're watching for their creation). @@ -359,16 +391,16 @@ namespace ts.server { return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); } - resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[] { - return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[] { + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); } getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined { return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile); } - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] { - return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[] { + return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); } directoryExists(path: string): boolean { @@ -396,7 +428,7 @@ namespace ts.server { directory, cb, flags, - WatchType.FailedLookupLocation, + WatchType.FailedLookupLocations, this ); } @@ -471,6 +503,16 @@ namespace ts.server { return this.getLanguageService().getSourceMapper(); } + /*@internal*/ + getDocumentPositionMapper(generatedFileName: string, sourceFileName?: string): DocumentPositionMapper | undefined { + return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName); + } + + /*@internal*/ + getSourceFileLike(fileName: string) { + return this.projectService.getSourceFileLike(fileName, this); + } + private shouldEmitFile(scriptInfo: ScriptInfo) { return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); } @@ -480,8 +522,8 @@ namespace ts.server { return []; } updateProjectIfDirty(this); - this.builderState = BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); - return mapDefined(BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, data => this.projectService.host.createHash!(data)), // TODO: GH#18217 + this.builderState = BuilderState.create(this.program!, this.projectService.toCanonicalFileName, this.builderState); + return mapDefined(BuilderState.getFilesAffectedBy(this.builderState, this.program!, scriptInfo.path, this.cancellationToken, data => this.projectService.host.createHash!(data)), // TODO: GH#18217 sourceFile => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)!) ? sourceFile.fileName : undefined); } @@ -539,10 +581,10 @@ namespace ts.server { } getExternalFiles(): SortedReadonlyArray { - return toSortedArray(flatMap(this.plugins, plugin => { - if (typeof plugin.getExternalFiles !== "function") return; + return sort(flatMap(this.plugins, plugin => { + if (typeof plugin.module.getExternalFiles !== "function") return; try { - return plugin.getExternalFiles(this); + return plugin.module.getExternalFiles(this); } catch (e) { this.projectService.logger.info(`A plugin threw an exception in getExternalFiles: ${e}`); @@ -562,7 +604,7 @@ namespace ts.server { /* @internal */ getSourceFileOrConfigFile(path: Path): SourceFile | undefined { - const options = this.program.getCompilerOptions(); + const options = this.program!.getCompilerOptions(); return path === options.configFilePath ? options.configFile : this.getSourceFile(path); } @@ -574,14 +616,11 @@ namespace ts.server { for (const f of this.program.getSourceFiles()) { this.detachScriptInfoIfNotRoot(f.fileName); } - const projectReferences = this.program.getProjectReferences(); - if (projectReferences) { - for (const ref of projectReferences) { - if (ref) { - this.detachScriptInfoFromProject(ref.sourceFile.fileName); - } + this.program.forEachResolvedProjectReference(ref => { + if (ref) { + this.detachScriptInfoFromProject(ref.sourceFile.fileName); } - } + }); } // Release external files forEach(this.externalFiles, externalFile => this.detachScriptInfoIfNotRoot(externalFile)); @@ -652,8 +691,8 @@ namespace ts.server { // if language service is not enabled - return just root files return this.rootFiles; } - return map(this.program.getSourceFiles(), sourceFile => { - const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + return map(this.program!.getSourceFiles(), sourceFile => { + const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); Debug.assert(!!scriptInfo, "getScriptInfo", () => `scriptInfo for a file '${sourceFile.fileName}' Path: '${sourceFile.path}' / '${sourceFile.resolvedPath}' is missing.`); return scriptInfo!; }); @@ -720,7 +759,10 @@ namespace ts.server { } containsScriptInfo(info: ScriptInfo): boolean { - return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); + if (this.isRoot(info)) return true; + if (!this.program) return false; + const file = this.program.getSourceFileByPath(info.path); + return !!file && file.resolvedPath === info.path; } containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean { @@ -783,41 +825,6 @@ namespace ts.server { } } - /* @internal */ - private extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: string[]): ReadonlyArray { - const cached = this.cachedUnresolvedImportsPerFile.get(file.path); - if (cached) { - // found cached result, return - return cached; - } - let unresolvedImports: string[] | undefined; - if (file.resolvedModules) { - file.resolvedModules.forEach((resolvedModule, name) => { - // pick unresolved non-relative names - if (!resolvedModule && !isExternalModuleNameRelative(name) && !isAmbientlyDeclaredModule(name)) { - // for non-scoped names extract part up-to the first slash - // for scoped names - extract up to the second slash - let trimmed = name.trim(); - let i = trimmed.indexOf("/"); - if (i !== -1 && trimmed.charCodeAt(0) === CharacterCodes.at) { - i = trimmed.indexOf("/", i + 1); - } - if (i !== -1) { - trimmed = trimmed.substr(0, i); - } - (unresolvedImports || (unresolvedImports = [])).push(trimmed); - } - }); - } - - this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || emptyArray); - return unresolvedImports || emptyArray; - - function isAmbientlyDeclaredModule(name: string) { - return ambientModules.some(m => m === name); - } - } - /* @internal */ onFileAddedOrRemoved() { this.hasAddedorRemovedFiles = true; @@ -851,15 +858,7 @@ namespace ts.server { // (can reuse cached imports for files that were not changed) // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch if (hasNewProgram || changedFiles.length) { - let result: string[] | undefined; - const ambientModules = this.program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName())); - for (const sourceFile of this.program.getSourceFiles()) { - const unResolved = this.extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules); - if (unResolved !== emptyArray) { - (result || (result = [])).push(...unResolved); - } - } - this.lastCachedUnresolvedImportsList = result ? toDeduplicatedSortedArray(result) : emptyArray; + this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program!, this.cachedUnresolvedImportsPerFile); } this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles); @@ -876,7 +875,7 @@ namespace ts.server { /*@internal*/ updateTypingFiles(typingFiles: SortedReadonlyArray) { - enumerateInsertsAndDeletes(typingFiles, this.typingFiles, getStringComparer(!this.useCaseSensitiveFileNames()), + enumerateInsertsAndDeletes(typingFiles, this.typingFiles, getStringComparer(!this.useCaseSensitiveFileNames()), /*inserted*/ noop, removed => this.detachScriptInfoFromProject(removed) ); @@ -886,7 +885,7 @@ namespace ts.server { } /* @internal */ - getCurrentProgram() { + getCurrentProgram(): Program | undefined { return this.program; } @@ -916,12 +915,19 @@ namespace ts.server { if (hasNewProgram) { if (oldProgram) { for (const f of oldProgram.getSourceFiles()) { - if (this.program.getSourceFileByPath(f.path)) { - continue; + const newFile = this.program.getSourceFileByPath(f.resolvedPath); + if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) { + // new program does not contain this file - detach it from the project + // - remove resolutions only if the new program doesnt contain source file by the path (not resolvedPath since path is used for resolution) + this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path)); } - // new program does not contain this file - detach it from the project - this.detachScriptInfoFromProject(f.fileName); } + + oldProgram.forEachResolvedProjectReference((resolvedProjectReference, resolvedProjectReferencePath) => { + if (resolvedProjectReference && !this.program!.getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + this.detachScriptInfoFromProject(resolvedProjectReference.sourceFile.fileName); + } + }); } // Update the missing file paths watcher @@ -940,7 +946,7 @@ namespace ts.server { const oldExternalFiles = this.externalFiles || emptyArray as SortedReadonlyArray; this.externalFiles = this.getExternalFiles(); - enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, getStringComparer(!this.useCaseSensitiveFileNames()), + enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, getStringComparer(!this.useCaseSensitiveFileNames()), // Ensure a ScriptInfo is created for new external files. This is performed indirectly // by the LSHost for files in the program when the program is retrieved above but // the program doesn't contain external files so this must be done explicitly. @@ -955,11 +961,13 @@ namespace ts.server { return hasNewProgram; } - private detachScriptInfoFromProject(uncheckedFileName: string) { + private detachScriptInfoFromProject(uncheckedFileName: string, noRemoveResolution?: boolean) { const scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); if (scriptInfoToDetach) { scriptInfoToDetach.detachFromProject(this); - this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); + if (!noRemoveResolution) { + this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); + } } } @@ -972,8 +980,8 @@ namespace ts.server { this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); } - if (eventKind === FileWatcherEventKind.Created && this.missingFilesMap.has(missingFilePath)) { - this.missingFilesMap.delete(missingFilePath); + if (eventKind === FileWatcherEventKind.Created && this.missingFilesMap!.has(missingFilePath)) { + this.missingFilesMap!.delete(missingFilePath); fileWatcher.close(); // When a missing file is created, we should update the graph. @@ -981,14 +989,14 @@ namespace ts.server { } }, PollingInterval.Medium, - WatchType.MissingFilePath, + WatchType.MissingFile, this ); return fileWatcher; } private isWatchedMissingFile(path: Path) { - return this.missingFilesMap && this.missingFilesMap.has(path); + return !!this.missingFilesMap && this.missingFilesMap.has(path); } getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined { @@ -1017,6 +1025,13 @@ namespace ts.server { return strBuilder; } + /*@internal*/ + print(counter?: number) { + this.writeLog(`Project '${this.projectName}' (${ProjectKind[this.projectKind]}) ${counter === undefined ? "" : counter}`); + this.writeLog(this.filesToString(this.projectService.logger.hasLevel(LogLevel.verbose))); + this.writeLog("-----------------------------------------------"); + } + setCompilerOptions(compilerOptions: CompilerOptions) { if (compilerOptions) { compilerOptions.allowNonTsExtensions = true; @@ -1096,7 +1111,7 @@ namespace ts.server { this.rootFilesMap.delete(info.path); } - protected enableGlobalPlugins(options: CompilerOptions) { + protected enableGlobalPlugins(options: CompilerOptions, pluginConfigOverrides: Map | undefined) { const host = this.projectService.host; if (!host.require) { @@ -1119,12 +1134,13 @@ namespace ts.server { // Provide global: true so plugins can detect why they can't find their config this.projectService.logger.info(`Loading global plugin ${globalPluginName}`); - this.enablePlugin({ name: globalPluginName, global: true } as PluginImport, searchPaths); + + this.enablePlugin({ name: globalPluginName, global: true } as PluginImport, searchPaths, pluginConfigOverrides); } } } - protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]) { + protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map | undefined) { this.projectService.logger.info(`Enabling plugin ${pluginConfigEntry.name} from candidate paths: ${searchPaths.join(",")}`); const log = (message: string) => { @@ -1134,6 +1150,14 @@ namespace ts.server { const resolvedModule = firstDefined(searchPaths, searchPath => Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log)); if (resolvedModule) { + const configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name); + if (configurationOverride) { + // Preserve the name property since it's immutable + const pluginName = pluginConfigEntry.name; + pluginConfigEntry = configurationOverride; + pluginConfigEntry.name = pluginName; + } + this.enableProxy(resolvedModule, pluginConfigEntry); } else { @@ -1141,11 +1165,6 @@ namespace ts.server { } } - /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ - refreshDiagnostics() { - this.projectService.sendProjectsUpdatedInBackgroundEvent(); - } - private enableProxy(pluginModuleFactory: PluginModuleFactory, configEntry: PluginImport) { try { if (typeof pluginModuleFactory !== "function") { @@ -1171,12 +1190,47 @@ namespace ts.server { } this.projectService.logger.info(`Plugin validation succeded`); this.languageService = newLS; - this.plugins.push(pluginModule); + this.plugins.push({ name: configEntry.name, module: pluginModule }); } catch (e) { this.projectService.logger.info(`Plugin activation failed: ${e}`); } } + + /*@internal*/ + onPluginConfigurationChanged(pluginName: string, configuration: any) { + this.plugins.filter(plugin => plugin.name === pluginName).forEach(plugin => { + if (plugin.module.onConfigurationChanged) { + plugin.module.onConfigurationChanged(configuration); + } + }); + } + + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ + refreshDiagnostics() { + this.projectService.sendProjectsUpdatedInBackgroundEvent(); + } + } + + function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile: Map>): SortedReadonlyArray { + const ambientModules = program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName())); + return sortAndDeduplicate(flatMap(program.getSourceFiles(), sourceFile => + extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile))); + } + function extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: ReadonlyArray, cachedUnresolvedImportsPerFile: Map>): ReadonlyArray { + return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => { + if (!file.resolvedModules) return emptyArray; + let unresolvedImports: string[] | undefined; + file.resolvedModules.forEach((resolvedModule, name) => { + // pick unresolved non-relative names + if ((!resolvedModule || !resolutionExtensionIsTSOrJson(resolvedModule.extension)) && + !isExternalModuleNameRelative(name) && + !ambientModules.some(m => m === name)) { + unresolvedImports = append(unresolvedImports, parsePackageName(name).packageName); + } + }); + return unresolvedImports || emptyArray; + }); } /** @@ -1204,11 +1258,10 @@ namespace ts.server { setCompilerOptions(options?: CompilerOptions) { // Avoid manipulating the given options directly - const newOptions = options ? cloneCompilerOptions(options) : this.getCompilationSettings(); - if (!newOptions) { + if (!options && !this.getCompilationSettings()) { return; } - + const newOptions = cloneCompilerOptions(options || this.getCompilationSettings()); if (this._isJsInferredProject && typeof newOptions.maxNodeModuleJsDepth !== "number") { newOptions.maxNodeModuleJsDepth = 2; } @@ -1232,7 +1285,8 @@ namespace ts.server { documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, projectRootPath: NormalizedPath | undefined, - currentDirectory: string | undefined) { + currentDirectory: string | undefined, + pluginConfigOverrides: Map | undefined) { super(InferredProject.newName(), ProjectKind.Inferred, projectService, @@ -1248,7 +1302,7 @@ namespace ts.server { if (!projectRootPath && !projectService.useSingleInferredProject) { this.canonicalCurrentDirectory = projectService.toCanonicalFileName(this.currentDirectory); } - this.enableGlobalPlugins(this.getCompilerOptions()); + this.enableGlobalPlugins(this.getCompilerOptions(), pluginConfigOverrides); } addRoot(info: ScriptInfo) { @@ -1303,18 +1357,23 @@ namespace ts.server { * Otherwise it will create an InferredProject. */ export class ConfiguredProject extends Project { - private typeAcquisition: TypeAcquisition; + private typeAcquisition!: TypeAcquisition; // TODO: GH#18217 /* @internal */ configFileWatcher: FileWatcher | undefined; private directoriesWatchedForWildcards: Map | undefined; readonly canonicalConfigFilePath: NormalizedPath; /* @internal */ - pendingReload: ConfigFileProgramReloadLevel; + pendingReload: ConfigFileProgramReloadLevel | undefined; + /* @internal */ + pendingReloadReason: string | undefined; /*@internal*/ configFileSpecs: ConfigFileSpecs | undefined; + /*@internal*/ + canConfigFileJsonReportNoInputFiles = false; + /** Ref count to the project when opened from external project */ private externalProjectRefCount = 0; @@ -1327,6 +1386,9 @@ namespace ts.server { protected isInitialLoadPending: () => boolean = returnTrue; + /*@internal*/ + sendLoadingProjectFinish = false; + /*@internal*/ constructor(configFileName: NormalizedPath, projectService: ProjectService, @@ -1359,12 +1421,15 @@ namespace ts.server { result = this.projectService.reloadFileNamesOfConfiguredProject(this); break; case ConfigFileProgramReloadLevel.Full: - this.projectService.reloadConfiguredProject(this); + const reason = Debug.assertDefined(this.pendingReloadReason); + this.pendingReloadReason = undefined; + this.projectService.reloadConfiguredProject(this, reason); result = true; break; default: result = super.updateGraph(); } + this.projectService.sendProjectLoadingFinishEvent(this); this.projectService.sendProjectTelemetry(this); this.projectService.sendSurveyReady(this); return result; @@ -1379,8 +1444,8 @@ namespace ts.server { return asNormalizedPath(this.getProjectName()); } - getProjectReferences(): ReadonlyArray { - return this.projectReferences || emptyArray; + getProjectReferences(): ReadonlyArray | undefined { + return this.projectReferences; } updateReferences(refs: ReadonlyArray | undefined) { @@ -1388,17 +1453,13 @@ namespace ts.server { } /*@internal*/ - getResolvedProjectReferences() { + forEachResolvedProjectReference(cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined): T | undefined { const program = this.getCurrentProgram(); - return program && program.getProjectReferences(); - } - - enablePlugins() { - this.enablePluginsWithOptions(this.getCompilerOptions()); + return program && program.forEachResolvedProjectReference(cb); } /*@internal*/ - enablePluginsWithOptions(options: CompilerOptions) { + enablePluginsWithOptions(options: CompilerOptions, pluginConfigOverrides: Map | undefined) { const host = this.projectService.host; if (!host.require) { @@ -1419,11 +1480,11 @@ namespace ts.server { // Enable tsconfig-specified plugins if (options.plugins) { for (const pluginConfigEntry of options.plugins) { - this.enablePlugin(pluginConfigEntry, searchPaths); + this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); } } - this.enableGlobalPlugins(options); + this.enableGlobalPlugins(options, pluginConfigOverrides); } /** @@ -1531,13 +1592,8 @@ namespace ts.server { } /*@internal*/ - updateErrorOnNoInputFiles(hasFileNames: boolean) { - if (hasFileNames) { - filterMutate(this.projectErrors!, error => !isErrorNoInputFiles(error)); // TODO: GH#18217 - } - else if (!this.configFileSpecs!.filesSpecs && !some(this.projectErrors, isErrorNoInputFiles)) { // TODO: GH#18217 - this.projectErrors!.push(getErrorForNoInputFiles(this.configFileSpecs!, this.getConfigFilePath())); - } + updateErrorOnNoInputFiles(fileNameResult: ExpandResult) { + updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs!, this.projectErrors!, this.canConfigFileJsonReportNoInputFiles); } } @@ -1547,7 +1603,7 @@ namespace ts.server { */ export class ExternalProject extends Project { excludedFiles: ReadonlyArray = []; - private typeAcquisition: TypeAcquisition; + private typeAcquisition!: TypeAcquisition; // TODO: GH#18217 /*@internal*/ constructor(public externalProjectName: string, projectService: ProjectService, diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 5c6d9bed337..11930de4d8c 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -129,6 +129,7 @@ namespace ts.server.protocol { GetEditsForFileRename = "getEditsForFileRename", /* @internal */ GetEditsForFileRenameFull = "getEditsForFileRename-full", + ConfigurePlugin = "configurePlugin" // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. } @@ -220,6 +221,11 @@ namespace ts.server.protocol { * Contains message body if success === true. */ body?: any; + + /** + * Contains extra information that plugin can include to be passed on + */ + metadata?: unknown; } /** @@ -1023,7 +1029,7 @@ namespace ts.server.protocol { /** * The file locations referencing the symbol. */ - refs: ReferencesResponseItem[]; + refs: ReadonlyArray; /** * The name of the symbol. @@ -1087,16 +1093,17 @@ namespace ts.server.protocol { /** * Information about the item to be renamed. */ - export interface RenameInfo { + export type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + export interface RenameInfoSuccess { /** * True if item can be renamed. */ - canRename: boolean; - + canRename: true; /** - * Error message if item can not be renamed. + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ - localizedErrorMessage?: string; + fileToRename?: string; /** * Display name of the item to be renamed. @@ -1117,6 +1124,16 @@ namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + export interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; } /** @@ -1126,7 +1143,12 @@ namespace ts.server.protocol { /** The file to which the spans apply */ file: string; /** The text spans in this group */ - locs: TextSpan[]; + locs: RenameTextSpan[]; + } + + export interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; } export interface RenameResponseBody { @@ -1359,6 +1381,16 @@ namespace ts.server.protocol { export interface ConfigureResponse extends Response { } + export interface ConfigurePluginRequestArguments { + pluginName: string; + configuration: any; + } + + export interface ConfigurePluginRequest extends Request { + command: CommandTypes.ConfigurePlugin; + arguments: ConfigurePluginRequestArguments; + } + /** * Information found in an "open" request. */ @@ -2374,6 +2406,7 @@ namespace ts.server.protocol { */ export interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; + event: DiagnosticEventKind; } export interface ConfigFileDiagnosticEventBody { @@ -2436,6 +2469,30 @@ namespace ts.server.protocol { openFiles: string[]; } + export type ProjectLoadingStartEventName = "projectLoadingStart"; + export interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + + export interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + + export type ProjectLoadingFinishEventName = "projectLoadingFinish"; + export interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + + export interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + export type SurveyReadyEventName = "surveyReady"; export interface SurveyReadyEvent extends Event { @@ -2469,6 +2526,10 @@ namespace ts.server.protocol { maxFileSize: number; } + /*@internal*/ + export type AnyEvent = RequestCompletedEvent | DiagnosticEvent | ConfigFileDiagnosticEvent | ProjectLanguageServiceStateEvent | TelemetryEvent | + ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | SurveyReadyEvent | LargeFileReferencedEvent; + /** * Arguments for reload request. */ @@ -2728,6 +2789,14 @@ namespace ts.server.protocol { payload: TypingsInstalledTelemetryEventPayload; } +/* __GDPR__ + "typingsinstalled" : { + "${include}": ["${TypeScriptCommonProperties}"], + "installedPackages": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, + "installSuccess": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "typingsInstallerVersion": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } + } + */ export interface TypingsInstalledTelemetryEventPayload { /** * Comma separated list of installed typing packages @@ -2836,6 +2905,8 @@ namespace ts.server.protocol { readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; readonly lazyConfiguredProjectsFromExternalProject?: boolean; + readonly providePrefixAndSuffixTextForRename?: boolean; + readonly allowRenameOfImportPath?: boolean; } export interface CompilerOptions { diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 085dd6d0eef..68c448a7e76 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -6,7 +6,6 @@ namespace ts.server { /* @internal */ export class TextStorage { - /*@internal*/ version: ScriptInfoVersion; /** @@ -26,18 +25,26 @@ namespace ts.server { */ private lineMap: number[] | undefined; + /** + * When a large file is loaded, text will artificially be set to "". + * In order to be able to report correct telemetry, we store the actual + * file size in this case. (In other cases where text === "", e.g. + * for mixed content or dynamic files, fileSize will be undefined.) + */ + private fileSize: number | undefined; + /** * True if the text is for the file thats open in the editor */ - public isOpen: boolean; + public isOpen = false; /** * True if the text present is the text from the file on the disk */ - private ownFileText: boolean; + private ownFileText = false; /** * True when reloading contents of file from the disk is pending */ - private pendingReloadFromDisk: boolean; + private pendingReloadFromDisk = false; constructor(private readonly host: ServerHost, private readonly fileName: NormalizedPath, initialVersion: ScriptInfoVersion | undefined, private readonly info: ScriptInfo) { this.version = initialVersion || { svc: 0, text: 0 }; @@ -57,10 +64,22 @@ namespace ts.server { this.switchToScriptVersionCache(); } + private resetSourceMapInfo() { + this.info.sourceFileLike = undefined; + this.info.closeSourceMapFileWatcher(); + this.info.sourceMapFilePath = undefined; + this.info.declarationInfoPath = undefined; + this.info.sourceInfos = undefined; + this.info.documentPositionMapper = undefined; + } + + /** Public for testing */ public useText(newText?: string) { this.svc = undefined; this.text = newText; this.lineMap = undefined; + this.fileSize = undefined; + this.resetSourceMapInfo(); this.version.text++; } @@ -69,13 +88,15 @@ namespace ts.server { this.ownFileText = false; this.text = undefined; this.lineMap = undefined; + this.fileSize = undefined; + this.resetSourceMapInfo(); } /** * Set the contents as newText * returns true if text changed */ - public reload(newText: string) { + public reload(newText: string): boolean { Debug.assert(newText !== undefined); // Reload always has fresh content @@ -92,6 +113,8 @@ namespace ts.server { this.ownFileText = false; return true; } + + return false; } /** @@ -99,7 +122,9 @@ namespace ts.server { * returns true if text changed */ public reloadWithFileText(tempFileName?: string) { - const reloaded = this.reload(this.getFileText(tempFileName)); + const { text: newText, fileSize } = this.getFileTextAndSize(tempFileName); + const reloaded = this.reload(newText); + this.fileSize = fileSize; // NB: after reload since reload clears it this.ownFileText = !tempFileName || tempFileName === this.fileName; return reloaded; } @@ -119,14 +144,31 @@ namespace ts.server { this.pendingReloadFromDisk = true; } + /** + * For telemetry purposes, we would like to be able to report the size of the file. + * However, we do not want telemetry to require extra file I/O so we report a size + * that may be stale (e.g. may not reflect change made on disk since the last reload). + * NB: Will read from disk if the file contents have never been loaded because + * telemetry falsely indicating size 0 would be counter-productive. + */ + public getTelemetryFileSize(): number { + return !!this.fileSize + ? this.fileSize + : !!this.text // Check text before svc because its length is cheaper + ? this.text.length // Could be wrong if this.pendingReloadFromDisk + : !!this.svc + ? this.svc.getSnapshot().getLength() // Could be wrong if this.pendingReloadFromDisk + : this.getSnapshot().getLength(); // Should be strictly correct + } + public getSnapshot(): IScriptSnapshot { return this.useScriptVersionCacheIfValidOrOpen() ? this.svc!.getSnapshot() : ScriptSnapshot.fromString(this.getOrLoadText()); } - public getLineInfo(line: number): AbsolutePositionAndLineText { - return this.switchToScriptVersionCache().getLineInfo(line); + public getAbsolutePositionAndLineText(line: number): AbsolutePositionAndLineText { + return this.switchToScriptVersionCache().getAbsolutePositionAndLineText(line); } /** * @param line 0 based index @@ -145,9 +187,9 @@ namespace ts.server { * @param line 1 based index * @param offset 1 based index */ - lineOffsetToPosition(line: number, offset: number): number { + lineOffsetToPosition(line: number, offset: number, allowEdits?: true): number { if (!this.useScriptVersionCacheIfValidOrOpen()) { - return computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); + return computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits); } // TODO: assert this offset is actually on the line @@ -162,22 +204,22 @@ namespace ts.server { return this.svc!.positionToLineOffset(position); } - private getFileText(tempFileName?: string) { + private getFileTextAndSize(tempFileName?: string): { text: string, fileSize?: number } { let text: string; const fileName = tempFileName || this.fileName; const getText = () => text === undefined ? (text = this.host.readFile(fileName) || "") : text; // Only non typescript files have size limitation - if (!hasTypeScriptFileExtension(this.fileName)) { + if (!hasTSFileExtension(this.fileName)) { const fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > maxFileSize) { Debug.assert(!!this.info.containingProjects.length); const service = this.info.containingProjects[0].projectService; service.logger.info(`Skipped loading contents of large file ${fileName} for info ${this.info.fileName}: fileSize: ${fileSize}`); this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize); - return ""; + return { text: "", fileSize }; } } - return getText(); + return { text: getText() }; } private switchToScriptVersionCache(): ScriptVersionCache { @@ -215,6 +257,17 @@ namespace ts.server { Debug.assert(!this.svc, "ScriptVersionCache should not be set"); return this.lineMap || (this.lineMap = computeLineStarts(this.getOrLoadText())); } + + getLineInfo(): LineInfo { + if (this.svc) { + return { + getLineCount: () => this.svc!.getLineCount(), + getLineText: line => this.svc!.getAbsolutePositionAndLineText(line + 1).lineText! + }; + } + const lineMap = this.getLineMap(); + return getLineInfo(this.text!, lineMap); + } } /*@internal*/ @@ -228,6 +281,12 @@ namespace ts.server { sourceFile: SourceFile; } + /*@internal*/ + export interface SourceMapFileWatcher { + watcher: FileWatcher; + sourceInfos?: Map; + } + export class ScriptInfo { /** * All projects that include this file @@ -248,7 +307,24 @@ namespace ts.server { private realpath: Path | undefined; /*@internal*/ - cacheSourceFile: DocumentRegistrySourceFileCache; + cacheSourceFile: DocumentRegistrySourceFileCache | undefined; + + /*@internal*/ + mTime?: number; + + /*@internal*/ + sourceFileLike?: SourceFileLike; + + /*@internal*/ + sourceMapFilePath?: Path | SourceMapFileWatcher | false; + + // Present on sourceMapFile info + /*@internal*/ + declarationInfoPath?: Path; + /*@internal*/ + sourceInfos?: Map; + /*@internal*/ + documentPositionMapper?: DocumentPositionMapper | false; constructor( private readonly host: ServerHost, @@ -274,6 +350,11 @@ namespace ts.server { return this.textStorage.version; } + /*@internal*/ + getTelemetryFileSize() { + return this.textStorage.getTelemetryFileSize(); + } + /*@internal*/ public isDynamicOrHasMixedContent() { return this.hasMixedContent || this.isDynamic; @@ -435,7 +516,7 @@ namespace ts.server { setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void { if (formatSettings) { if (!this.formatSettings) { - this.formatSettings = getDefaultFormatCodeSettings(this.host); + this.formatSettings = getDefaultFormatCodeSettings(this.host.newLine); assign(this.formatSettings, formatSettings); } else { @@ -482,8 +563,8 @@ namespace ts.server { } /*@internal*/ - getLineInfo(line: number): AbsolutePositionAndLineText { - return this.textStorage.getLineInfo(line); + getAbsolutePositionAndLineText(line: number): AbsolutePositionAndLineText { + return this.textStorage.getAbsolutePositionAndLineText(line); } editContent(start: number, end: number, newText: string): void { @@ -512,8 +593,12 @@ namespace ts.server { * @param line 1 based index * @param offset 1 based index */ - lineOffsetToPosition(line: number, offset: number): number { - return this.textStorage.lineOffsetToPosition(line, offset); + lineOffsetToPosition(line: number, offset: number): number; + /*@internal*/ + // tslint:disable-next-line:unified-signatures + lineOffsetToPosition(line: number, offset: number, allowEdits?: true): number; + lineOffsetToPosition(line: number, offset: number, allowEdits?: true): number { + return this.textStorage.lineOffsetToPosition(line, offset, allowEdits); } positionToLineOffset(position: number): protocol.Location { @@ -523,5 +608,18 @@ namespace ts.server { public isJavaScript() { return this.scriptKind === ScriptKind.JS || this.scriptKind === ScriptKind.JSX; } + + /*@internal*/ + getLineInfo(): LineInfo { + return this.textStorage.getLineInfo(); + } + + /*@internal*/ + closeSourceMapFileWatcher() { + if (this.sourceMapFilePath && !isString(this.sourceMapFilePath)) { + closeFileWatcherOf(this.sourceMapFilePath); + this.sourceMapFilePath = undefined; + } + } } } diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index d7ac25062d0..afd8f67ecbe 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -41,11 +41,11 @@ namespace ts.server { // path to start of range private readonly startPath: LineCollection[]; private readonly endBranch: LineCollection[] = []; - private branchNode: LineNode; + private branchNode: LineNode | undefined; // path to current node private readonly stack: LineNode[]; private state = CharRangeSection.Entire; - private lineCollectionAtBranch: LineCollection; + private lineCollectionAtBranch: LineCollection | undefined; private initialText = ""; private trailingText = ""; @@ -308,8 +308,8 @@ namespace ts.server { return this._getSnapshot().version; } - getLineInfo(line: number): AbsolutePositionAndLineText { - return this._getSnapshot().index.lineNumberToInfo(line); + getAbsolutePositionAndLineText(oneBasedLine: number): AbsolutePositionAndLineText { + return this._getSnapshot().index.lineNumberToInfo(oneBasedLine); } lineOffsetToPosition(line: number, column: number): number { @@ -348,6 +348,10 @@ namespace ts.server { } } + getLineCount() { + return this._getSnapshot().index.getLineCount(); + } + static fromString(script: string) { const svc = new ScriptVersionCache(); const snap = new LineIndexSnapshot(0, svc, new LineIndex()); @@ -382,9 +386,8 @@ namespace ts.server { } } - /* @internal */ export class LineIndex { - root: LineNode; + root!: LineNode; // set this to true to check each edit for accuracy checkEdits = false; @@ -401,8 +404,12 @@ namespace ts.server { return this.root.charOffsetToLineInfo(1, position); } + getLineCount() { + return this.root.lineCount(); + } + lineNumberToInfo(oneBasedLine: number): AbsolutePositionAndLineText { - const lineCount = this.root.lineCount(); + const lineCount = this.getLineCount(); if (oneBasedLine <= lineCount) { const { position, leaf } = this.root.lineNumberToInfo(oneBasedLine, 0); return { absolutePosition: position, lineText: leaf && leaf.text }; diff --git a/src/server/session.ts b/src/server/session.ts index 5d364abc757..2257c6740f4 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -267,7 +267,7 @@ namespace ts.server { projects: Projects, action: (project: Project, value: T) => ReadonlyArray | U | undefined, ): U[] { - const outputs = flatMap(isArray(projects) ? projects : projects.projects, project => action(project, defaultValue)); + const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, project => action(project, defaultValue)); if (!isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach((projects, path) => { const value = getValue(path as Path); @@ -289,9 +289,8 @@ namespace ts.server { function combineProjectOutputWhileOpeningReferencedProjects( projects: Projects, defaultProject: Project, - projectService: ProjectService, action: (project: Project) => ReadonlyArray, - getLocation: (t: T) => sourcemaps.SourceMappableLocation, + getLocation: (t: T) => DocumentPosition, resultsEqual: (a: T, b: T) => boolean, ): T[] { const outputs: T[] = []; @@ -299,7 +298,6 @@ namespace ts.server { projects, defaultProject, /*initialLocation*/ undefined, - projectService, ({ project }, tryAddToTodo) => { for (const output of action(project)) { if (!contains(outputs, output, resultsEqual) && !tryAddToTodo(project, getLocation(output))) { @@ -312,50 +310,78 @@ namespace ts.server { } function combineProjectOutputForRenameLocations( - projects: Projects, defaultProject: Project, initialLocation: sourcemaps.SourceMappableLocation, projectService: ProjectService, findInStrings: boolean, findInComments: boolean + projects: Projects, + defaultProject: Project, + initialLocation: DocumentPosition, + findInStrings: boolean, + findInComments: boolean, + hostPreferences: UserPreferences ): ReadonlyArray { const outputs: RenameLocation[] = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, ({ project, location }, tryAddToTodo) => { - for (const output of project.getLanguageService().findRenameLocations(location.fileName, location.position, findInStrings, findInComments) || emptyArray) { - if (!contains(outputs, output, documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { - outputs.push(output); + combineProjectOutputWorker( + projects, + defaultProject, + initialLocation, + ({ project, location }, tryAddToTodo) => { + for (const output of project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || emptyArray) { + if (!contains(outputs, output, documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { + outputs.push(output); + } } - } - }, () => getDefinitionLocation(defaultProject, initialLocation)); + }, + () => getDefinitionLocation(defaultProject, initialLocation) + ); return outputs; } - function getDefinitionLocation(defaultProject: Project, initialLocation: sourcemaps.SourceMappableLocation): sourcemaps.SourceMappableLocation | undefined { - const infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.position); + function getDefinitionLocation(defaultProject: Project, initialLocation: DocumentPosition): DocumentPosition | undefined { + const infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos); const info = infos && firstOrUndefined(infos); - return info && { fileName: info.fileName, position: info.textSpan.start }; + return info && { fileName: info.fileName, pos: info.textSpan.start }; } - function combineProjectOutputForReferences(projects: Projects, defaultProject: Project, initialLocation: sourcemaps.SourceMappableLocation, projectService: ProjectService): ReadonlyArray { + function combineProjectOutputForReferences( + projects: Projects, + defaultProject: Project, + initialLocation: DocumentPosition + ): ReadonlyArray { const outputs: ReferencedSymbol[] = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, ({ project, location }, tryAddToTodo) => { - for (const outputReferencedSymbol of project.getLanguageService().findReferences(location.fileName, location.position) || emptyArray) { - let symbolToAddTo = find(outputs, o => documentSpansEqual(o.definition, outputReferencedSymbol.definition)); - if (!symbolToAddTo) { - symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; - outputs.push(symbolToAddTo); - } + combineProjectOutputWorker( + projects, + defaultProject, + initialLocation, + ({ project, location }, getMappedLocation) => { + for (const outputReferencedSymbol of project.getLanguageService().findReferences(location.fileName, location.pos) || emptyArray) { + const mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + const definition: ReferencedSymbolDefinitionInfo = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : { + ...outputReferencedSymbol.definition, + textSpan: createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), + fileName: mappedDefinitionFile.fileName, + }; + let symbolToAddTo = find(outputs, o => documentSpansEqual(o.definition, definition)); + if (!symbolToAddTo) { + symbolToAddTo = { definition, references: [] }; + outputs.push(symbolToAddTo); + } - for (const ref of outputReferencedSymbol.references) { - if (!contains(symbolToAddTo.references, ref, documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { - symbolToAddTo.references.push(ref); + for (const ref of outputReferencedSymbol.references) { + // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. + if (!contains(symbolToAddTo.references, ref, documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { + symbolToAddTo.references.push(ref); + } } } - } - }, () => getDefinitionLocation(defaultProject, initialLocation)); + }, + () => getDefinitionLocation(defaultProject, initialLocation) + ); return outputs.filter(o => o.references.length !== 0); } - interface ProjectAndLocation { + interface ProjectAndLocation { readonly project: Project; readonly location: TLocation; } @@ -373,19 +399,24 @@ namespace ts.server { } } - function combineProjectOutputWorker( + type CombineProjectOutputCallback = ( + where: ProjectAndLocation, + getMappedLocation: (project: Project, location: DocumentPosition) => DocumentPosition | undefined, + ) => void; + + function combineProjectOutputWorker( projects: Projects, defaultProject: Project, initialLocation: TLocation, - projectService: ProjectService, - cb: (where: ProjectAndLocation, getMappedLocation: (project: Project, location: sourcemaps.SourceMappableLocation) => boolean) => void, - getDefinition: (() => sourcemaps.SourceMappableLocation | undefined) | undefined, + cb: CombineProjectOutputCallback, + getDefinition: (() => DocumentPosition | undefined) | undefined, ): void { + const projectService = defaultProject.projectService; let toDo: ProjectAndLocation[] | undefined; const seenProjects = createMap(); forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, (project, path) => { - // TLocation shoud be either `sourcemaps.SourceMappableLocation` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. - const location = (initialLocation ? { fileName: path, position: initialLocation.position } : undefined) as TLocation; + // TLocation shoud be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. + const location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined) as TLocation; toDo = callbackProjectAndLocation({ project, location }, projectService, toDo, seenProjects, cb); }); @@ -406,24 +437,24 @@ namespace ts.server { } } - function getDefinitionInProject(definition: sourcemaps.SourceMappableLocation | undefined, definingProject: Project, project: Project): sourcemaps.SourceMappableLocation | undefined { + function getDefinitionInProject(definition: DocumentPosition | undefined, definingProject: Project, project: Project): DocumentPosition | undefined { if (!definition || project.containsFile(toNormalizedPath(definition.fileName))) return definition; - const mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedLocation(definition); + const mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(definition); return mappedDefinition && project.containsFile(toNormalizedPath(mappedDefinition.fileName)) ? mappedDefinition : undefined; } - function callbackProjectAndLocation( + function callbackProjectAndLocation( projectAndLocation: ProjectAndLocation, projectService: ProjectService, toDo: ProjectAndLocation[] | undefined, seenProjects: Map, - cb: (where: ProjectAndLocation, getMappedLocation: (project: Project, location: sourcemaps.SourceMappableLocation) => boolean) => void, + cb: CombineProjectOutputCallback, ): ProjectAndLocation[] | undefined { if (projectAndLocation.project.getCancellationToken().isCancellationRequested()) return undefined; // Skip rest of toDo if cancelled cb(projectAndLocation, (project, location) => { seenProjects.set(projectAndLocation.project.projectName, true); const originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); - if (!originalLocation) return false; + if (!originalLocation) return undefined; const originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName)!; toDo = toDo || []; @@ -437,21 +468,21 @@ namespace ts.server { for (const symlinkedProject of symlinkedProjects) addToTodo({ project: symlinkedProject, location: originalLocation as TLocation }, toDo!, seenProjects); }); } - return true; + return originalLocation; }); return toDo; } - function addToTodo(projectAndLocation: ProjectAndLocation, toDo: Push>, seenProjects: Map): void { + function addToTodo(projectAndLocation: ProjectAndLocation, toDo: Push>, seenProjects: Map): void { if (addToSeen(seenProjects, projectAndLocation.project.projectName)) toDo.push(projectAndLocation); } - function documentSpanLocation({ fileName, textSpan }: DocumentSpan): sourcemaps.SourceMappableLocation { - return { fileName, position: textSpan.start }; + function documentSpanLocation({ fileName, textSpan }: DocumentSpan): DocumentPosition { + return { fileName, pos: textSpan.start }; } - function getMappedLocation(location: sourcemaps.SourceMappableLocation, projectService: ProjectService, project: Project): sourcemaps.SourceMappableLocation | undefined { - const mapsTo = project.getSourceMapper().tryGetOriginalLocation(location); + function getMappedLocation(location: DocumentPosition, projectService: ProjectService, project: Project): DocumentPosition | undefined { + const mapsTo = project.getSourceMapper().tryGetSourcePosition(location); return mapsTo && projectService.fileExists(toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined; } @@ -478,6 +509,7 @@ namespace ts.server { globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; + typesMapLocation?: string; } export class Session implements EventSender { @@ -485,7 +517,7 @@ namespace ts.server { protected projectService: ProjectService; private changeSeq = 0; - private currentRequestId: number; + private currentRequestId!: number; private errorCheck: MultistepOperation; protected host: ServerHost; @@ -538,6 +570,7 @@ namespace ts.server { globalPlugins: opts.globalPlugins, pluginProbeLocations: opts.pluginProbeLocations, allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, syntaxOnly: opts.syntaxOnly, }; this.projectService = new ProjectService(settings); @@ -554,9 +587,19 @@ namespace ts.server { const { openFiles } = event.data; this.projectsUpdatedInBackgroundEvent(openFiles); break; + case ProjectLoadingStartEvent: + const { project, reason } = event.data; + this.event( + { projectName: project.getProjectName(), reason }, + ProjectLoadingStartEvent); + break; + case ProjectLoadingFinishEvent: + const { project: finishProject } = event.data; + this.event({ projectName: finishProject.getProjectName() }, ProjectLoadingFinishEvent); + break; case LargeFileReferencedEvent: const { file, fileSize, maxFileSize } = event.data; - this.event({ file, fileSize, maxFileSize }, "largeFileReferenced"); + this.event({ file, fileSize, maxFileSize }, LargeFileReferencedEvent); break; case ConfigFileDiagEvent: const { triggerFile, configFileName: configFile, diagnostics } = event.data; @@ -565,14 +608,14 @@ namespace ts.server { triggerFile, configFile, diagnostics: bakedDiags - }, "configFileDiag"); + }, ConfigFileDiagEvent); break; case SurveyReady: const { surveyId } = event.data; - this.event({ surveyId }, "surveyReady"); + this.event({ surveyId }, SurveyReady); break; case ProjectLanguageServiceStateEvent: { - const eventName: protocol.ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + const eventName: protocol.ProjectLanguageServiceStateEventName = ProjectLanguageServiceStateEvent; this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled @@ -603,11 +646,15 @@ namespace ts.server { // Send project changed event this.event({ openFiles - }, "projectsUpdatedInBackground"); + }, ProjectsUpdatedInBackgroundEvent); } } - public logError(err: Error, cmd: string) { + public logError(err: Error, cmd: string): void { + this.logErrorWorker(err, cmd); + } + + private logErrorWorker(err: Error, cmd: string, fileRequest?: protocol.FileRequestArgs): void { let msg = "Exception on executing command " + cmd; if (err.message) { msg += ":\n" + indent(err.message); @@ -615,6 +662,19 @@ namespace ts.server { msg += "\n" + indent((err).stack!); } } + + if (fileRequest && this.logger.hasLevel(LogLevel.verbose)) { + try { + const { file, project } = this.getFileAndProject(fileRequest); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + const text = getSnapshotText(scriptInfo.getSnapshot()); + msg += `\n\nFile text of ${fileRequest.file}:${indent(text)}\n`; + } + } + catch {} // tslint:disable-line no-empty + } + this.logger.msg(msg, Msg.Err); } @@ -647,7 +707,26 @@ namespace ts.server { success, }; if (success) { - res.body = info; + let metadata: unknown; + if (isArray(info)) { + res.body = info; + metadata = (info as WithMetadata>).metadata; + delete (info as WithMetadata>).metadata; + } + else if (typeof info === "object") { + if ((info as WithMetadata<{}>).metadata) { + const { metadata: infoMetadata, ...body } = (info as WithMetadata<{}>); + res.body = body; + metadata = infoMetadata; + } + else { + res.body = info; + } + } + else { + res.body = info; + } + if (metadata) res.metadata = metadata; } else { Debug.assert(info === undefined); @@ -863,7 +942,7 @@ namespace ts.server { kind: info.kind, name: info.name, textSpan: { - start: newLoc.position, + start: newLoc.pos, length: info.textSpan.length }, originalFileName: info.fileName, @@ -960,7 +1039,7 @@ namespace ts.server { kind: info.kind, displayParts: info.displayParts, textSpan: { - start: newLoc.position, + start: newLoc.pos, length: info.textSpan.length }, originalFileName: info.fileName, @@ -1096,10 +1175,11 @@ namespace ts.server { return projectInfo; } - private getRenameInfo(args: protocol.FileLocationRequestArgs) { + private getRenameInfo(args: protocol.FileLocationRequestArgs): RenameInfo { const { file, project } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); - return project.getLanguageService().getRenameInfo(file, position); + const preferences = this.getHostPreferences(); + return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: preferences.allowRenameOfImportPath }); } private getProjects(args: protocol.FileRequestArgs, getScriptInfoEnsuringProjectsUptoDate?: boolean, ignoreNoProjectError?: boolean): Projects { @@ -1116,7 +1196,9 @@ namespace ts.server { this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : this.projectService.getScriptInfo(args.file); if (!scriptInfo) { - return ignoreNoProjectError ? emptyArray : Errors.ThrowNoProject(); + if (ignoreNoProjectError) return emptyArray; + this.projectService.logErrorForScriptInfoNotFound(args.file); + return Errors.ThrowNoProject(); } projects = scriptInfo.containingProjects; symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); @@ -1124,6 +1206,7 @@ namespace ts.server { // filter handles case when 'projects' is undefined projects = filter(projects, p => p.languageServiceEnabled && !p.isOrphan()); if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { + this.projectService.logErrorForScriptInfoNotFound(args.file); return Errors.ThrowNoProject(); } return symLinkedProjects ? { projects: projects!, symLinkedProjects } : projects!; // TODO: GH#18217 @@ -1145,25 +1228,39 @@ namespace ts.server { const position = this.getPositionInFile(args, file); const projects = this.getProjects(args); - const locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, position }, this.projectService, !!args.findInStrings, !!args.findInComments); + const locations = combineProjectOutputForRenameLocations( + projects, + this.getDefaultProject(args), + { fileName: args.file, pos: position }, + !!args.findInStrings, + !!args.findInComments, + this.getHostPreferences() + ); if (!simplifiedResult) return locations; const defaultProject = this.getDefaultProject(args); - const renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + const renameInfo: protocol.RenameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getHostPreferences().allowRenameOfImportPath }), Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; } - // strips 'triggerSpan' - private static mapRenameInfo({ canRename, localizedErrorMessage, displayName, fullDisplayName, kind, kindModifiers }: RenameInfo): protocol.RenameInfo { - return { canRename, localizedErrorMessage, displayName, fullDisplayName, kind, kindModifiers }; + private mapRenameInfo(info: RenameInfo, scriptInfo: ScriptInfo): protocol.RenameInfo { + if (info.canRename) { + const { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan } = info; + return identity( + { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }); + } + else { + return info; + } } private toSpanGroups(locations: ReadonlyArray): ReadonlyArray { const map = createMap(); - for (const { fileName, textSpan } of locations) { + for (const { fileName, textSpan, originalTextSpan: _, originalFileName: _1, ...prefixSuffixText } of locations) { let group = map.get(fileName); if (!group) map.set(fileName, group = { file: fileName, locs: [] }); - group.locs.push(this.toLocationTextSpan(textSpan, Debug.assertDefined(this.projectService.getScriptInfo(fileName)))); + const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(fileName)); + group.locs.push({ ...this.toLocationTextSpan(textSpan, scriptInfo), ...prefixSuffixText }); } return arrayFrom(map.values()); } @@ -1172,7 +1269,11 @@ namespace ts.server { const file = toNormalizedPath(args.file); const projects = this.getProjects(args); const position = this.getPositionInFile(args, file); - const references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, position }, this.projectService); + const references = combineProjectOutputForReferences( + projects, + this.getDefaultProject(args), + { fileName: args.file, pos: position }, + ); if (simplifiedResult) { const defaultProject = this.getDefaultProject(args); @@ -1182,7 +1283,7 @@ namespace ts.server { const nameSpan = nameInfo && nameInfo.textSpan; const symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; const symbolName = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, textSpanEnd(nameSpan)) : ""; - const refs: protocol.ReferencesResponseItem[] = flatMap(references, referencedSymbol => + const refs: ReadonlyArray = flatMap(references, referencedSymbol => referencedSymbol.references.map(({ fileName, textSpan, isWriteAccess, isDefinition }): protocol.ReferencesResponseItem => { const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(fileName)); const start = scriptInfo.positionToLineOffset(textSpan.start); @@ -1376,7 +1477,7 @@ namespace ts.server { // only to the previous line. If all this is true, then // add edits necessary to properly indent the current line. if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - const { lineText, absolutePosition } = scriptInfo.getLineInfo(args.line); + const { lineText, absolutePosition } = scriptInfo.getAbsolutePositionAndLineText(args.line); if (lineText && lineText.search("\\S") < 0) { const preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions); let hasIndent = 0; @@ -1416,7 +1517,7 @@ namespace ts.server { }); } - private getCompletions(args: protocol.CompletionsRequestArgs, kind: protocol.CommandTypes.CompletionInfo | protocol.CommandTypes.Completions | protocol.CommandTypes.CompletionsFull): ReadonlyArray | protocol.CompletionInfo | CompletionInfo | undefined { + private getCompletions(args: protocol.CompletionsRequestArgs, kind: protocol.CommandTypes.CompletionInfo | protocol.CommandTypes.Completions | protocol.CommandTypes.CompletionsFull): WithMetadata> | protocol.CompletionInfo | CompletionInfo | undefined { const { file, project } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file)!; const position = this.getPosition(args, scriptInfo); @@ -1441,7 +1542,10 @@ namespace ts.server { } }).sort((a, b) => compareStringsCaseSensitiveUI(a.name, b.name)); - if (kind === protocol.CommandTypes.Completions) return entries; + if (kind === protocol.CommandTypes.Completions) { + if (completions.metadata) (entries as WithMetadata>).metadata = completions.metadata; + return entries; + } const res: protocol.CompletionInfo = { ...completions, @@ -1676,7 +1780,6 @@ namespace ts.server { return combineProjectOutputWhileOpeningReferencedProjects( this.getProjects(args), this.getDefaultProject(args), - this.projectService, project => project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject()), documentSpanLocation, @@ -1711,7 +1814,7 @@ namespace ts.server { return (locationOrSpan).line !== undefined; } - private extractPositionAndRange(args: protocol.FileLocationOrRangeRequestArgs, scriptInfo: ScriptInfo): { position: number, textRange: TextRange } { + private extractPositionOrRange(args: protocol.FileLocationOrRangeRequestArgs, scriptInfo: ScriptInfo): number | TextRange { let position: number | undefined; let textRange: TextRange | undefined; if (this.isLocation(args)) { @@ -1721,7 +1824,7 @@ namespace ts.server { const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); textRange = { pos: startPosition, end: endPosition }; } - return { position: position!, textRange: textRange! }; // TODO: GH#18217 + return Debug.assertDefined(position === undefined ? textRange : position); function getPosition(loc: protocol.FileLocationRequestArgs) { return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); @@ -1731,19 +1834,16 @@ namespace ts.server { private getApplicableRefactors(args: protocol.GetApplicableRefactorsRequestArgs): protocol.ApplicableRefactorInfo[] { const { file, project } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file)!; - const { position, textRange } = this.extractPositionAndRange(args, scriptInfo); - return project.getLanguageService().getApplicableRefactors(file, position || textRange, this.getPreferences(file)); + return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); } private getEditsForRefactor(args: protocol.GetEditsForRefactorRequestArgs, simplifiedResult: boolean): RefactorEditInfo | protocol.RefactorEditInfo { const { file, project } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file)!; - const { position, textRange } = this.extractPositionAndRange(args, scriptInfo); - const result = project.getLanguageService().getEditsForRefactor( file, this.getFormatOptions(file), - position || textRange, + this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, this.getPreferences(file), @@ -1818,8 +1918,8 @@ namespace ts.server { private applyCodeActionCommand(args: protocol.ApplyCodeActionCommandRequestArgs): {} { const commands = args.command as CodeActionCommand | CodeActionCommand[]; // They should be sending back the command we sent them. for (const command of toArray(commands)) { - const { project } = this.getFileAndProject(command); - project.getLanguageService().applyCodeActionCommand(command).then( + const { file, project } = this.getFileAndProject(command); + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then( _result => { /* TODO: GH#20447 report success message? */ }, _error => { /* TODO: GH#20447 report errors */ }); } @@ -1860,8 +1960,17 @@ namespace ts.server { return textChanges.map(change => this.mapTextChangeToCodeEdit(change)); } - private mapTextChangeToCodeEdit(change: FileTextChanges): protocol.FileCodeEdits { - return mapTextChangesToCodeEdits(change, this.projectService.getScriptInfoOrConfig(change.fileName)); + private mapTextChangeToCodeEdit(textChanges: FileTextChanges): protocol.FileCodeEdits { + const scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges.fileName); + if (!!textChanges.isNewFile === !!scriptInfo) { + if (!scriptInfo) { // and !isNewFile + this.projectService.logErrorForScriptInfoNotFound(textChanges.fileName); + } + Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo })); + } + return scriptInfo + ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(textChange => convertTextChangeToCodeEdit(textChange, scriptInfo)) } + : convertNewFileTextChangeToCodeEdit(textChanges); } private convertTextChangeToCodeEdit(change: TextChange, scriptInfo: ScriptInfo): protocol.CodeEdit { @@ -1935,6 +2044,10 @@ namespace ts.server { this.updateErrorCheck(next, checkList, delay, /*requireOpen*/ false); } + private configurePlugin(args: protocol.ConfigurePluginRequestArguments) { + this.projectService.configurePlugin(args); + } + getCanonicalFileName(fileName: string) { const name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); return normalizePath(name); @@ -2256,6 +2369,10 @@ namespace ts.server { [CommandNames.GetEditsForFileRenameFull]: (request: protocol.GetEditsForFileRenameRequest) => { return this.requiredResponse(this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ false)); }, + [CommandNames.ConfigurePlugin]: (request: protocol.ConfigurePluginRequest) => { + this.configurePlugin(request.arguments); + return this.notRequired(); + } }); public addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse) { @@ -2310,8 +2427,10 @@ namespace ts.server { } let request: protocol.Request | undefined; + let relevantFile: protocol.FileRequestArgs | undefined; try { request = JSON.parse(message); + relevantFile = request.arguments && (request as protocol.FileRequest).arguments.file ? (request as protocol.FileRequest).arguments : undefined; const { response, responseRequired } = this.executeCommand(request); if (this.logger.hasLevel(LogLevel.requestTime)) { @@ -2337,7 +2456,7 @@ namespace ts.server { this.doOutput({ canceled: true }, request!.command, request!.seq, /*success*/ true); return; } - this.logError(err, message); + this.logErrorWorker(err, message, relevantFile); this.doOutput( /*info*/ undefined, request ? request.command : CommandNames.Unknown, @@ -2373,13 +2492,6 @@ namespace ts.server { return { file: fileName, start: scriptInfo.positionToLineOffset(textSpan.start), end: scriptInfo.positionToLineOffset(textSpanEnd(textSpan)) }; } - function mapTextChangesToCodeEdits(textChanges: FileTextChanges, scriptInfo: ScriptInfoOrConfig | undefined): protocol.FileCodeEdits { - Debug.assert(!!textChanges.isNewFile === !scriptInfo, "Expected isNewFile for (only) new files", () => JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo })); - return scriptInfo - ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(textChange => convertTextChangeToCodeEdit(textChange, scriptInfo)) } - : convertNewFileTextChangeToCodeEdit(textChanges); - } - function convertTextChangeToCodeEdit(change: TextChange, scriptInfo: ScriptInfoOrConfig): protocol.CodeEdit { return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, textSpanEnd(change.span)), newText: change.newText }; } diff --git a/src/server/typingsCache.ts b/src/server/typingsCache.ts index 12b2303cfd3..d3b6e21a21c 100644 --- a/src/server/typingsCache.ts +++ b/src/server/typingsCache.ts @@ -8,6 +8,8 @@ namespace ts.server { export interface ITypingsInstaller { isKnownTypesPackageName(name: string): boolean; installPackage(options: InstallPackageOptionsWithProject): Promise; + /* @internal */ + inspectValue(options: InspectValueOptions): Promise; enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray | undefined): void; attach(projectService: ProjectService): void; onProjectClosed(p: Project): void; @@ -18,6 +20,7 @@ namespace ts.server { isKnownTypesPackageName: returnFalse, // Should never be called because we never provide a types registry. installPackage: notImplemented, + inspectValue: notImplemented, enqueueInstallTypingsRequest: noop, attach: noop, onProjectClosed: noop, @@ -95,6 +98,10 @@ namespace ts.server { return this.installer.installPackage(options); } + inspectValue(options: InspectValueOptions): Promise { + return this.installer.inspectValue(options); + } + enqueueInstallTypingsForProject(project: Project, unresolvedImports: SortedReadonlyArray | undefined, forceRefresh: boolean) { const typeAcquisition = project.getTypeAcquisition(); @@ -123,7 +130,7 @@ namespace ts.server { } updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, newTypings: string[]) { - const typings = toSortedArray(newTypings); + const typings = sort(newTypings); this.perProjectCache.set(projectName, { compilerOptions, typeAcquisition, diff --git a/src/server/utilities.ts b/src/server/utilities.ts index 615361cdcd8..04ce9f4e420 100644 --- a/src/server/utilities.ts +++ b/src/server/utilities.ts @@ -56,30 +56,6 @@ namespace ts.server { } } - export function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings { - return { - indentSize: 4, - tabSize: 4, - newLineCharacter: host.newLine || "\n", - convertTabsToSpaces: true, - indentStyle: IndentStyle.Smart, - insertSpaceAfterConstructor: false, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceBeforeFunctionParenthesis: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - }; - } - export type NormalizedPath = string & { __normalizedPathTag: any }; export function toNormalizedPath(fileName: string): NormalizedPath { @@ -230,30 +206,25 @@ namespace ts.server { } } - export function toSortedArray(arr: string[]): SortedArray; - export function toSortedArray(arr: T[], comparer: Comparer): SortedArray; - export function toSortedArray(arr: T[], comparer?: Comparer): SortedArray { - arr.sort(comparer); - return arr as SortedArray; - } + const indentStr = "\n "; - export function toDeduplicatedSortedArray(arr: string[]): SortedArray { - arr.sort(); - filterMutate(arr, isNonDuplicateInSortedArray); - return arr as SortedArray; - } - function isNonDuplicateInSortedArray(value: T, index: number, array: T[]) { - return index === 0 || value !== array[index - 1]; - } - - /* @internal */ export function indent(str: string): string { - return "\n " + str; + return indentStr + str.replace(/\n/g, indentStr); } /** Put stringified JSON on the next line, indented. */ - /* @internal */ export function stringifyIndented(json: {}): string { - return "\n " + JSON.stringify(json); + return indentStr + JSON.stringify(json); + } +} + +/* @internal */ +namespace ts { + // Additional tsserver specific watch information + export const enum WatchType { + ClosedScriptInfo = "Closed Script info", + ConfigFileForInferredRoot = "Config file for the inferred project root", + NodeModulesForClosedScriptInfo = "node_modules for closed script infos in them", + MissingSourceMapFile = "Missing source map file", } } diff --git a/src/services/classifier.ts b/src/services/classifier.ts index 5c18eae4aa1..f85a69681de 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -182,6 +182,7 @@ namespace ts { SyntaxKind.Identifier, SyntaxKind.StringLiteral, SyntaxKind.NumericLiteral, + SyntaxKind.BigIntLiteral, SyntaxKind.RegularExpressionLiteral, SyntaxKind.ThisKeyword, SyntaxKind.PlusPlusToken, @@ -286,6 +287,7 @@ namespace ts { case ClassificationType.comment: return TokenClass.Comment; case ClassificationType.keyword: return TokenClass.Keyword; case ClassificationType.numericLiteral: return TokenClass.NumberLiteral; + case ClassificationType.bigintLiteral: return TokenClass.BigIntLiteral; case ClassificationType.operator: return TokenClass.Operator; case ClassificationType.stringLiteral: return TokenClass.StringLiteral; case ClassificationType.whiteSpace: return TokenClass.Whitespace; @@ -422,6 +424,8 @@ namespace ts { switch (token) { case SyntaxKind.NumericLiteral: return ClassificationType.numericLiteral; + case SyntaxKind.BigIntLiteral: + return ClassificationType.bigintLiteral; case SyntaxKind.StringLiteral: return ClassificationType.stringLiteral; case SyntaxKind.RegularExpressionLiteral: @@ -542,6 +546,7 @@ namespace ts { case ClassificationType.identifier: return ClassificationTypeNames.identifier; case ClassificationType.keyword: return ClassificationTypeNames.keyword; case ClassificationType.numericLiteral: return ClassificationTypeNames.numericLiteral; + case ClassificationType.bigintLiteral: return ClassificationTypeNames.bigintLiteral; case ClassificationType.operator: return ClassificationTypeNames.operator; case ClassificationType.stringLiteral: return ClassificationTypeNames.stringLiteral; case ClassificationType.whiteSpace: return ClassificationTypeNames.whiteSpace; @@ -698,7 +703,7 @@ namespace ts { pushCommentRange(pos, tag.pos - pos); } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, ClassificationType.punctuation); // "@" + pushClassification(tag.pos, 1, ClassificationType.punctuation); // "@" pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, ClassificationType.docCommentTagName); // e.g. "param" pos = tag.tagName.end; @@ -886,6 +891,9 @@ namespace ts { else if (tokenKind === SyntaxKind.NumericLiteral) { return ClassificationType.numericLiteral; } + else if (tokenKind === SyntaxKind.BigIntLiteral) { + return ClassificationType.bigintLiteral; + } else if (tokenKind === SyntaxKind.StringLiteral) { // TODO: GH#18217 return token!.parent.kind === SyntaxKind.JsxAttribute ? ClassificationType.jsxAttributeStringLiteralValue : ClassificationType.stringLiteral; diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index ad4e37974b3..8d42fdcc6c2 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -62,7 +62,7 @@ namespace ts { return arrayFrom(errorCodeToFixes.keys()); } - export function getFixes(context: CodeFixContext): CodeFixAction[] { + export function getFixes(context: CodeFixContext): ReadonlyArray { return flatMap(errorCodeToFixes.get(String(context.errorCode)) || emptyArray, f => f.getCodeActions(context)); } diff --git a/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts b/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts new file mode 100644 index 00000000000..e6e8d759c60 --- /dev/null +++ b/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts @@ -0,0 +1,23 @@ +/* @internal */ +namespace ts.codefix { + const fixId = "addConvertToUnknownForNonOverlappingTypes"; + const errorCodes = [Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; + registerCodeFix({ + errorCodes, + getCodeActions: (context) => { + const changes = textChanges.ChangeTracker.with(context, t => makeChange(t, context.sourceFile, context.span.start)); + return [createCodeFixAction(fixId, changes, Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; + }, + fixIds: [fixId], + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => makeChange(changes, diag.file, diag.start)), + }); + + function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) { + const token = getTokenAtPosition(sourceFile, pos); + const assertion = Debug.assertDefined(findAncestor(token, (n): n is AsExpression | TypeAssertion => isAsExpression(n) || isTypeAssertion(n))); + const replacement = isAsExpression(assertion) + ? createAsExpression(assertion.expression, createKeywordTypeNode(SyntaxKind.UnknownKeyword)) + : createTypeAssertion(createKeywordTypeNode(SyntaxKind.UnknownKeyword), assertion.expression); + changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + } +} diff --git a/src/services/codefixes/addNameToNamelessParameter.ts b/src/services/codefixes/addNameToNamelessParameter.ts new file mode 100644 index 00000000000..f87816ab228 --- /dev/null +++ b/src/services/codefixes/addNameToNamelessParameter.ts @@ -0,0 +1,37 @@ +/* @internal */ +namespace ts.codefix { + const fixId = "addNameToNamelessParameter"; + const errorCodes = [Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; + registerCodeFix({ + errorCodes, + getCodeActions: (context) => { + const changes = textChanges.ChangeTracker.with(context, t => makeChange(t, context.sourceFile, context.span.start)); + return [createCodeFixAction(fixId, changes, Diagnostics.Add_parameter_name, fixId, Diagnostics.Add_names_to_all_parameters_without_names)]; + }, + fixIds: [fixId], + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => makeChange(changes, diag.file, diag.start)), + }); + + function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) { + const token = getTokenAtPosition(sourceFile, pos); + if (!isIdentifier(token)) { + return Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + formatSyntaxKind(token.kind)); + } + const param = token.parent; + if (!isParameter(param)) { + return Debug.fail("Tried to add a parameter name to a non-parameter: " + formatSyntaxKind(token.kind)); + } + const i = param.parent.parameters.indexOf(param); + Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); + Debug.assert(i > -1, "Parameter not found in parent parameter list."); + const replacement = createParameter( + /*decorators*/ undefined, + param.modifiers, + param.dotDotDotToken, + "arg" + i, + param.questionToken, + createTypeReferenceNode(token, /*typeArguments*/ undefined), + param.initializer); + changeTracker.replaceNode(sourceFile, token, replacement); + } +} diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index c2041179888..78e10ce2044 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -138,7 +138,7 @@ namespace ts.codefix { default: { // Don't try to declare members in JavaScript files - if (isSourceFileJavaScript(sourceFile)) { + if (isSourceFileJS(sourceFile)) { return; } const prop = createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 76cdf471466..aae1d205de3 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -2,42 +2,37 @@ namespace ts.codefix { const fixId = "convertToAsyncFunction"; const errorCodes = [Diagnostics.This_may_be_converted_to_an_async_function.code]; + let codeActionSucceeded = true; registerCodeFix({ errorCodes, getCodeActions(context: CodeFixContext) { + codeActionSucceeded = true; const changes = textChanges.ChangeTracker.with(context, (t) => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context)); - return [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_async_function, fixId, Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_async_function, fixId, Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context)), }); - - /* - custom type to encapsulate information for variable declarations synthesized in the refactor - numberOfUsesOriginal - number of times the variable should be assigned in the refactor - numberOfUsesSynthesized - count of how many times the variable has been assigned so far - At the end of the refactor, numberOfUsesOriginal should === numberOfUsesSynthesized - */ interface SynthIdentifier { - identifier: Identifier; - types: Type[]; - numberOfAssignmentsOriginal: number; + readonly identifier: Identifier; + readonly types: Type[]; + numberOfAssignmentsOriginal: number; // number of times the variable should be assigned in the refactor } interface SymbolAndIdentifier { - identifier: Identifier; - symbol: Symbol; + readonly identifier: Identifier; + readonly symbol: Symbol; } interface Transformer { - checker: TypeChecker; - synthNamesMap: Map; // keys are the symbol id of the identifier - allVarNames: SymbolAndIdentifier[]; - setOfExpressionsToReturn: Map; // keys are the node ids of the expressions - constIdentifiers: Identifier[]; - originalTypeMap: Map; // keys are the node id of the identifier - isInJSFile: boolean; + readonly checker: TypeChecker; + readonly synthNamesMap: Map; // keys are the symbol id of the identifier + readonly allVarNames: ReadonlyArray; + readonly setOfExpressionsToReturn: ReadonlyMap; // keys are the node ids of the expressions + readonly constIdentifiers: Identifier[]; + readonly originalTypeMap: ReadonlyMap; // keys are the node id of the identifier + readonly isInJSFile: boolean; } function convertToAsyncFunction(changes: textChanges.ChangeTracker, sourceFile: SourceFile, position: number, checker: TypeChecker, context: CodeFixContextBase): void { @@ -61,19 +56,19 @@ namespace ts.codefix { const synthNamesMap: Map = createMap(); const originalTypeMap: Map = createMap(); const allVarNames: SymbolAndIdentifier[] = []; - const isInJSFile = isInJavaScriptFile(functionToConvert); + const isInJavascript = isInJSFile(functionToConvert); const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); - const functionToConvertRenamed: FunctionLikeDeclaration = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); + const functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); const constIdentifiers = getConstIdentifiers(synthNamesMap); - const returnStatements = getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - const transformer = { checker, synthNamesMap, allVarNames, setOfExpressionsToReturn, constIdentifiers, originalTypeMap, isInJSFile }; + const returnStatements = functionToConvertRenamed.body && isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : emptyArray; + const transformer: Transformer = { checker, synthNamesMap, allVarNames, setOfExpressionsToReturn, constIdentifiers, originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, SyntaxKind.AsyncKeyword, functionToConvert); + changes.insertLastModifierBefore(sourceFile, SyntaxKind.AsyncKeyword, functionToConvert); function startTransformation(node: CallExpression, nodeToReplace: Node) { const newNodes = transformExpression(node, transformer, node); @@ -81,24 +76,27 @@ namespace ts.codefix { } for (const statement of returnStatements) { - if (isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - forEachChild(statement, function visit(node: Node) { - if (isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!isFunctionLike(node)) { - forEachChild(node, visit); - } - }); - } + forEachChild(statement, function visit(node) { + if (isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!isFunctionLike(node)) { + forEachChild(node, visit); + } + }); } } + function getReturnStatementsWithPromiseHandlers(body: Block): ReadonlyArray { + const res: ReturnStatement[] = []; + forEachReturnStatement(body, ret => { + if (isReturnStatementWithFixablePromiseHandler(ret)) res.push(ret); + }); + return res; + } + // Returns the identifiers that are never reassigned in the refactor - function getConstIdentifiers(synthNamesMap: Map): Identifier[] { + function getConstIdentifiers(synthNamesMap: ReadonlyMap): Identifier[] { const constIdentifiers: Identifier[] = []; synthNamesMap.forEach((val) => { if (val.numberOfAssignmentsOriginal === 0) { @@ -165,6 +163,7 @@ namespace ts.codefix { function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker: TypeChecker, synthNamesMap: Map, context: CodeFixContextBase, setOfAllExpressionsToReturn: Map, originalType: Map, allVarNames: SymbolAndIdentifier[]): FunctionLikeDeclaration { const identsToRenameMap: Map = createMap(); // key is the symbol id + const collidingSymbolMap: Map = createMap(); forEachChild(nodeToRename, function visit(node: Node) { if (!isIdentifier(node)) { forEachChild(node, visit); @@ -181,20 +180,26 @@ namespace ts.codefix { // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - const synthName = getNewNameIfConflict(createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + const firstParameter = firstOrUndefined(lastCallSignature.parameters); + const ident = firstParameter && isParameter(firstParameter.valueDeclaration) && tryCast(firstParameter.valueDeclaration.name, isIdentifier) || createOptimisticUniqueName("result"); + const synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent))) { + const originalName = node.text; + const collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(ident => ident.identifier.text === node.text && ident.symbol !== symbol)) { - const newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(prevSymbol => prevSymbol !== symbol)) { + const newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { const identifier = getSynthesizedDeepClone(node); @@ -202,6 +207,7 @@ namespace ts.codefix { synthNamesMap.set(symbolIdString, { identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(elem => elem.identifier.text === node.text).length/*, numberOfAssignmentsSynthesized: 0*/ }); if ((isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || isVariableDeclaration(node.parent)) { allVarNames.push({ identifier, symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -229,9 +235,7 @@ namespace ts.codefix { if (renameInfo) { const type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(getNodeId(clone).toString(), type); - } + originalType.set(getNodeId(clone).toString(), type); } } @@ -244,17 +248,27 @@ namespace ts.codefix { } - function getNewNameIfConflict(name: Identifier, allVarNames: SymbolAndIdentifier[]): SynthIdentifier { - const numVarsSameName = allVarNames.filter(elem => elem.identifier.text === name.text).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap: Map, originalName: string, symbol: Symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName)!.push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + + function getNewNameIfConflict(name: Identifier, originalNames: ReadonlyMap): SynthIdentifier { + const numVarsSameName = (originalNames.get(name.text) || emptyArray).length; const numberOfAssignmentsOriginal = 0; const identifier = numVarsSameName === 0 ? name : createIdentifier(name.text + "_" + numVarsSameName); return { identifier, types: [], numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring - function transformExpression(node: Expression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): Statement[] { + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts + function transformExpression(node: Expression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): ReadonlyArray { if (!node) { - return []; + return emptyArray; } const originalType = isIdentifier(node) && transformer.originalTypeMap.get(getNodeId(node).toString()); @@ -273,10 +287,11 @@ namespace ts.codefix { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return emptyArray; } - function transformCatch(node: CallExpression, transformer: Transformer, prevArgName?: SynthIdentifier): Statement[] { + function transformCatch(node: CallExpression, transformer: Transformer, prevArgName?: SynthIdentifier): ReadonlyArray { const func = node.arguments[0]; const argName = getArgName(func, transformer); const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(node).toString()); @@ -290,20 +305,21 @@ namespace ts.codefix { prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach((val, key) => { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + const newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(elem => elem.text === prevArgName.identifier.text)) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } const tryBlock = createBlock(transformExpression(node.expression, transformer, node, prevArgName)); const transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - const catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + const catchArg = argName ? argName.identifier.text : "e"; const catchClause = createCatchClause(catchArg, createBlock(transformationBody)); /* @@ -322,7 +338,13 @@ namespace ts.codefix { return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } - function transformThen(node: CallExpression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): Statement[] { + function createUniqueSynthName(prevArgName: SynthIdentifier) { + const renamedPrevArg = createOptimisticUniqueName(prevArgName.identifier.text); + const newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } + + function transformThen(node: CallExpression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): ReadonlyArray { const [res, rej] = node.arguments; if (!res) { @@ -339,80 +361,96 @@ namespace ts.codefix { const transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - const catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + const catchArg = argNameRej ? argNameRej.identifier.text : "e"; const catchClause = createCatchClause(catchArg, createBlock(transformationBody2)); - return [createTry(tryBlock, catchClause, /* finallyBlock */ undefined) as Statement]; - } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + return [createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } - function getFlagOfIdentifier(node: Identifier, constIdentifiers: Identifier[]): NodeFlags { + function getFlagOfIdentifier(node: Identifier, constIdentifiers: ReadonlyArray): NodeFlags { const inArr: boolean = constIdentifiers.some(elem => elem.text === node.text); return inArr ? NodeFlags.Const : NodeFlags.Let; } - function transformPromiseCall(node: Expression, transformer: Transformer, prevArgName?: SynthIdentifier): Statement[] { + function transformPromiseCall(node: Expression, transformer: Transformer, prevArgName?: SynthIdentifier): ReadonlyArray { const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - const hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; const originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName!, createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || isPropertyAccessExpression(originalNodeParent))) { return [createStatement(createAwait(node))]; } return [createReturn(getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName: SynthIdentifier, rightHandSide: Expression, transformer: Transformer): NodeArray { - - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return createNodeArray([createStatement(createAssignment(getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName: SynthIdentifier | undefined, rightHandSide: Expression, transformer: Transformer): ReadonlyArray { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [createStatement(rightHandSide)]; } - return createNodeArray([createVariableStatement(/*modifiers*/ undefined, - (createVariableDeclarationList([createVariableDeclaration(getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [createStatement(createAssignment(getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + + return [createVariableStatement(/*modifiers*/ undefined, + (createVariableDeclarationList([createVariableDeclaration(getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } - function getTransformationBody(func: Node, prevArgName: SynthIdentifier | undefined, argName: SynthIdentifier, parent: CallExpression, transformer: Transformer): NodeArray { + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts + function getTransformationBody(func: Expression, prevArgName: SynthIdentifier | undefined, argName: SynthIdentifier | undefined, parent: CallExpression, transformer: Transformer): ReadonlyArray { - const hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - const hasArgName = argName && argName.identifier.text.length > 0; const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(parent).toString()); switch (func.kind) { - case SyntaxKind.Identifier: - if (!hasArgName) break; - - const synthCall = createCall(getSynthesizedDeepClone(func) as Identifier, /*typeArguments*/ undefined, [argName.identifier]); - if (shouldReturn) { - return createNodeArray([createReturn(synthCall)]); + case SyntaxKind.NullKeyword: + // do not produce a transformed statement for a null argument + break; + case SyntaxKind.Identifier: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler + break; } - if (!hasPrevArgName) break; + const synthCall = createCall(getSynthesizedDeepClone(func as Identifier), /*typeArguments*/ undefined, [argName.identifier]); + if (shouldReturn) { + return [createReturn(synthCall)]; + } - const type = transformer.originalTypeMap.get(getNodeId(func).toString()); - const callSignatures = type && transformer.checker.getSignaturesOfType(type, SignatureKind.Call); - const returnType = callSignatures && callSignatures[0].getReturnType(); - const varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName!, createAwait(synthCall), transformer); - prevArgName!.types.push(returnType!); + const type = transformer.originalTypeMap.get(getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + const callSignatures = transformer.checker.getSignaturesOfType(type, SignatureKind.Call); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; + break; + } + const returnType = callSignatures[0].getReturnType(); + const varDeclOrAssignment = createTransformedStatement(prevArgName, createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: + case SyntaxKind.ArrowFunction: { + const funcBody = (func as FunctionExpression | ArrowFunction).body; // Arrow functions with block bodies { } will enter this control flow - if (isFunctionLikeDeclaration(func) && func.body && isBlock(func.body) && func.body.statements) { + if (isBlock(funcBody)) { let refactoredStmts: Statement[] = []; + let seenReturnStatement = false; - for (const statement of func.body.statements) { - if (getReturnStatementsWithPromiseHandlers(statement).length) { + for (const statement of funcBody.statements) { + if (isReturnStatement(statement)) { + seenReturnStatement = true; + } + + if (isReturnStatementWithFixablePromiseHandler(statement)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { @@ -420,47 +458,64 @@ namespace ts.codefix { } } - return shouldReturn ? getSynthesizedDeepClones(createNodeArray(refactoredStmts)) : - removeReturns(createNodeArray(refactoredStmts), prevArgName!.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(s => getSynthesizedDeepClone(s)) : + removeReturns( + refactoredStmts, + prevArgName === undefined ? undefined : prevArgName.identifier, + transformer, + seenReturnStatement); } else { - const funcBody = (func).body; - const innerRetStmts = getReturnStatementsWithPromiseHandlers(createReturn(funcBody as Expression)); + const innerRetStmts = isFixablePromiseHandler(funcBody) ? [createReturn(funcBody)] : emptyArray; const innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - const type = transformer.checker.getTypeAtLocation(func); - const returnType = getLastCallSignature(type, transformer.checker).getReturnType(); - const varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName!, getSynthesizedDeepClone(funcBody) as Expression, transformer); - prevArgName!.types.push(returnType); - return varDeclOrAssignment; + const type = transformer.checker.getTypeAtLocation(func); + const returnType = getLastCallSignature(type, transformer.checker)!.getReturnType(); + const rightHandSide = getSynthesizedDeepClone(funcBody); + const possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType) ? createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + const transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } + return transformedStatement; } else { - return createNodeArray([createReturn(getSynthesizedDeepClone(funcBody) as Expression)]); + return [createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return createNodeArray([]); + return emptyArray; } - function getLastCallSignature(type: Type, checker: TypeChecker): Signature { - const callSignatures = type && checker.getSignaturesOfType(type, SignatureKind.Call); - return callSignatures && callSignatures[callSignatures.length - 1]; + function getLastCallSignature(type: Type, checker: TypeChecker): Signature | undefined { + const callSignatures = checker.getSignaturesOfType(type, SignatureKind.Call); + return lastOrUndefined(callSignatures); } - function removeReturns(stmts: NodeArray, prevArgName: Identifier, constIdentifiers: Identifier[]): NodeArray { + function removeReturns(stmts: ReadonlyArray, prevArgName: Identifier | undefined, transformer: Transformer, seenReturnStatement: boolean): ReadonlyArray { const ret: Statement[] = []; for (const stmt of stmts) { if (isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(createVariableStatement(/*modifiers*/ undefined, - (createVariableDeclarationList([createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + const possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(createVariableStatement(/*modifiers*/ undefined, + (createVariableDeclarationList([createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { @@ -468,15 +523,21 @@ namespace ts.codefix { } } - return createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(createVariableStatement(/*modifiers*/ undefined, + (createVariableDeclarationList([createVariableDeclaration(prevArgName, /*type*/ undefined, createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + + return ret; } - function getInnerTransformationBody(transformer: Transformer, innerRetStmts: Node[], prevArgName?: SynthIdentifier) { + function getInnerTransformationBody(transformer: Transformer, innerRetStmts: ReadonlyArray, prevArgName?: SynthIdentifier) { let innerCbBody: Statement[] = []; for (const stmt of innerRetStmts) { - forEachChild(stmt, function visit(node: Node) { + forEachChild(stmt, function visit(node) { if (isCallExpression(node)) { const temp = transformExpression(node, transformer, node, prevArgName); innerCbBody = innerCbBody.concat(temp); @@ -492,15 +553,7 @@ namespace ts.codefix { return innerCbBody; } - function hasPropertyAccessExpressionWithName(node: CallExpression, funcName: string): boolean { - if (!isPropertyAccessExpression(node.expression)) { - return false; - } - - return node.expression.name.text === funcName; - } - - function getArgName(funcNode: Node, transformer: Transformer): SynthIdentifier { + function getArgName(funcNode: Expression, transformer: Transformer): SynthIdentifier | undefined { const numberOfAssignmentsOriginal = 0; const types: Type[] = []; @@ -510,23 +563,21 @@ namespace ts.codefix { if (isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { const param = funcNode.parameters[0].name as Identifier; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (isCallExpression(funcNode) && funcNode.arguments.length > 0 && isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0] as Identifier, types, numberOfAssignmentsOriginal }; - } else if (isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: createIdentifier(""), types, numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier: Identifier): SynthIdentifier { + function getMapEntryOrDefault(identifier: Identifier): SynthIdentifier { const originalNode = getOriginalNode(identifier); const symbol = getSymbol(originalNode); @@ -546,4 +597,4 @@ namespace ts.codefix { return node.original ? node.original : node; } } -} \ No newline at end of file +} diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index c81446152dd..4cdd7eb42d2 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -12,7 +12,7 @@ namespace ts.codefix { getCodeActions(context) { const { sourceFile, program, span, host, formatContext } = context; - if (!isInJavaScriptFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index a23cb621608..98ddee61f8e 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -4,6 +4,9 @@ namespace ts.codefix { const errorCodes = [ Diagnostics.Property_0_does_not_exist_on_type_1.code, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, + Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, + Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code ]; const fixId = "addMissingMember"; registerCodeFix({ @@ -20,7 +23,7 @@ namespace ts.codefix { const { parentDeclaration, declSourceFile, inJs, makeStatic, token, call } = info; const methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); const addMember = inJs && !isInterfaceDeclaration(parentDeclaration) ? - singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return concatenate(singleElementArray(methodCodeAction), addMember); }, @@ -131,7 +134,7 @@ namespace ts.codefix { if (classOrInterface) { const makeStatic = ((leftExpressionType as TypeReference).target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); const declSourceFile = classOrInterface.getSourceFile(); - const inJs = isSourceFileJavaScript(declSourceFile); + const inJs = isSourceFileJS(declSourceFile); const call = tryCast(parent.parent, isCallExpression); return { kind: InfoKind.ClassOrInterface, token, parentDeclaration: classOrInterface, makeStatic, declSourceFile, inJs, call }; } @@ -142,7 +145,7 @@ namespace ts.codefix { return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): CodeFixAction | undefined { + function getActionsForAddMissingMemberInJavascriptFile(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): CodeFixAction | undefined { const changes = textChanges.ChangeTracker.with(context, t => addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic)); return changes.length === 0 ? undefined : createCodeFixAction(fixName, changes, [makeStatic ? Diagnostics.Initialize_static_property_0 : Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, Diagnostics.Add_all_missing_members); @@ -185,6 +188,10 @@ namespace ts.codefix { const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } + else { + const contextualType = checker.getContextualType(token.parent as Expression); + typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + } return typeNode || createKeywordTypeNode(SyntaxKind.AnyKeyword); } @@ -268,7 +275,7 @@ namespace ts.codefix { inJs: boolean, preferences: UserPreferences, ): void { - const methodDeclaration = createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !isInterfaceDeclaration(typeDecl)); + const methodDeclaration = createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl); const containingMethodDeclaration = getAncestor(callExpression, SyntaxKind.MethodDeclaration); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { diff --git a/src/services/codefixes/fixAddMissingNewOperator.ts b/src/services/codefixes/fixAddMissingNewOperator.ts new file mode 100644 index 00000000000..5acaf6eb82e --- /dev/null +++ b/src/services/codefixes/fixAddMissingNewOperator.ts @@ -0,0 +1,32 @@ +/* @internal */ +namespace ts.codefix { + const fixId = "addMissingNewOperator"; + const errorCodes = [Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code]; + registerCodeFix({ + errorCodes, + getCodeActions(context) { + const { sourceFile, span } = context; + const changes = textChanges.ChangeTracker.with(context, t => addMissingNewOperator(t, sourceFile, span)); + return [createCodeFixAction(fixId, changes, Diagnostics.Add_missing_new_operator_to_call, fixId, Diagnostics.Add_missing_new_operator_to_all_calls)]; + }, + fixIds: [fixId], + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => + addMissingNewOperator(changes, context.sourceFile, diag)), + }); + + function addMissingNewOperator(changes: textChanges.ChangeTracker, sourceFile: SourceFile, span: TextSpan): void { + const call = cast(findAncestorMatchingSpan(sourceFile, span), isCallExpression); + const newExpression = createNew(call.expression, call.typeArguments, call.arguments); + + changes.replaceNode(sourceFile, call, newExpression); + } + + function findAncestorMatchingSpan(sourceFile: SourceFile, span: TextSpan): Node { + let token = getTokenAtPosition(sourceFile, span.start); + const end = textSpanEnd(span); + while (token.end < end) { + token = token.parent; + } + return token; + } +} diff --git a/src/services/codefixes/fixCannotFindModule.ts b/src/services/codefixes/fixCannotFindModule.ts index 68fa3a5c030..1baaa9714f2 100644 --- a/src/services/codefixes/fixCannotFindModule.ts +++ b/src/services/codefixes/fixCannotFindModule.ts @@ -1,6 +1,9 @@ /* @internal */ namespace ts.codefix { - const fixId = "fixCannotFindModule"; + const fixName = "fixCannotFindModule"; + const fixIdInstallTypesPackage = "installTypesPackage"; + const fixIdGenerateTypes = "generateTypes"; + const errorCodeCannotFindModule = Diagnostics.Cannot_find_module_0.code; const errorCodes = [ errorCodeCannotFindModule, @@ -10,26 +13,133 @@ namespace ts.codefix { errorCodes, getCodeActions: context => { const { host, sourceFile, span: { start } } = context; - const packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [createCodeFixAction(fixId, /*changes*/ [], [Diagnostics.Install_0, packageName], fixId, Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + const packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) return undefined; + const typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [createCodeFixAction(fixName, /*changes*/ [], [Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: context => { + let savedTypesDir: string | null | undefined = null; // tslint:disable-line no-null-keyword + return codeFixAll(context, errorCodes, (changes, diag, commands) => { + const packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + const pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + const typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + const command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) commands.push(command); + break; + } + default: + Debug.fail(`Bad fixId: ${context.fixId}`); + } + }); }, - fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (_, diag, commands) => { - const pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }), }); - function getCommand(fileName: string, packageName: string): InstallPackageAction { + function tryGetGenerateTypesAction(context: CodeFixContextBase, packageName: string): CodeFixAction | undefined { + let command: GenerateTypesAction | undefined; + const changes = textChanges.ChangeTracker.with(context, t => { + const typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && createCodeFixAction(fixName, changes, [Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, Diagnostics.Generate_types_for_all_packages_without_types, command); + } + + function tryGenerateTypes(typesDir: string, packageName: string, context: CodeFixContextBase): GenerateTypesAction | undefined { + const file = context.sourceFile.fileName; + const fileToGenerateTypesFor = tryResolveJSModule(packageName, getDirectoryPath(file), context.host as ModuleResolutionHost); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) return undefined; + + const outputFileName = resolvePath(getDirectoryPath(context.program.getCompilerOptions().configFile!.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists!(outputFileName)) return undefined; + return { type: "generate types", file, fileToGenerateTypesFor, outputFileName }; + } + + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes: textChanges.ChangeTracker, context: CodeFixContextBase): string | undefined { + const { configFile } = context.program.getCompilerOptions(); + if (!configFile) return undefined; + + const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) return undefined; + + const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + const newCompilerOptions = createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + + const compilerOptions = compilerOptionsProperty.initializer; + if (!isObjectLiteralExpression(compilerOptions)) return defaultTypesDirectoryName; + + const baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + const typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + + const defaultBaseUrl = "."; + function makeDefaultBaseUrl(): PropertyAssignment { + return createJsonPropertyAssignment("baseUrl", createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes: textChanges.ChangeTracker, tsconfig: TsConfigSourceFile, compilerOptions: ObjectLiteralExpression): string { + const baseUrlProp = findJsonProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + + const defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping(): PropertyAssignment { + return createJsonPropertyAssignment("*", createArrayLiteral([createStringLiteral(`${defaultTypesDirectoryName}/*`)])); + } + function makeDefaultPaths(): PropertyAssignment { + return createJsonPropertyAssignment("paths", createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes: textChanges.ChangeTracker, tsconfig: TsConfigSourceFile, compilerOptions: ObjectLiteralExpression) { + const paths = findJsonProperty(compilerOptions, "paths"); + if (!paths || !isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + const existing = firstDefined(paths.initializer.properties, prop => + isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "*" && isArrayLiteralExpression(prop.initializer) + ? firstDefined(prop.initializer.elements, value => isStringLiteral(value) ? tryRemoveSuffix(value.text, "/*") : undefined) + : undefined); + if (existing) return existing; + + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + + function getInstallCommand(fileName: string, packageName: string): InstallPackageAction { return { type: "install package", file: fileName, packageName }; } - function getTypesPackageNameToInstall(host: LanguageServiceHost, sourceFile: SourceFile, pos: number, diagCode: number): string | undefined { + function tryGetImportedPackageName(sourceFile: SourceFile, pos: number): string | undefined { const moduleName = cast(getTokenAtPosition(sourceFile, pos), isStringLiteral).text; - const { packageName } = getPackageName(moduleName); + const { packageName } = parsePackageName(moduleName); + return isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + + function getTypesPackageNameToInstall(packageName: string, host: LanguageServiceHost, diagCode: number): string | undefined { return diagCode === errorCodeCannotFindModule ? (JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName!(packageName) ? getTypesPackageName(packageName) : undefined); // TODO: GH#18217 diff --git a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts index 9d9972c03e8..d18bc50639a 100644 --- a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts +++ b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts @@ -8,9 +8,9 @@ namespace ts.codefix { registerCodeFix({ errorCodes, getCodeActions(context) { - const { program, sourceFile, span } = context; + const { sourceFile, span } = context; const changes = textChanges.ChangeTracker.with(context, t => - addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences)); + addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences)); return changes.length === 0 ? undefined : [createCodeFixAction(fixId, changes, Diagnostics.Implement_inherited_abstract_class, fixId, Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], @@ -19,7 +19,7 @@ namespace ts.codefix { return codeFixAll(context, errorCodes, (changes, diag) => { const classDeclaration = getClass(diag.file, diag.start); if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) { - addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences); } }); }, @@ -32,15 +32,16 @@ namespace ts.codefix { return cast(token.parent, isClassLike); } - function addMissingMembers(classDeclaration: ClassLikeDeclaration, sourceFile: SourceFile, checker: TypeChecker, changeTracker: textChanges.ChangeTracker, preferences: UserPreferences): void { + function addMissingMembers(classDeclaration: ClassLikeDeclaration, sourceFile: SourceFile, context: TypeConstructionContext, changeTracker: textChanges.ChangeTracker, preferences: UserPreferences): void { const extendsNode = getEffectiveBaseTypeNode(classDeclaration)!; + const checker = context.program.getTypeChecker(); const instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member)); + createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member)); } function symbolPointsToNonPrivateAndAbstractMember(symbol: Symbol): boolean { diff --git a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts index 4401625000a..59385f2e2e9 100644 --- a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts +++ b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts @@ -6,11 +6,10 @@ namespace ts.codefix { registerCodeFix({ errorCodes, getCodeActions(context) { - const { program, sourceFile, span } = context; + const { sourceFile, span } = context; const classDeclaration = getClass(sourceFile, span.start); - const checker = program.getTypeChecker(); return mapDefined(getClassImplementsHeritageClauseElements(classDeclaration), implementedTypeNode => { - const changes = textChanges.ChangeTracker.with(context, t => addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences)); + const changes = textChanges.ChangeTracker.with(context, t => addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences)); return changes.length === 0 ? undefined : createCodeFixAction(fixId, changes, [Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, Diagnostics.Implement_all_unimplemented_interfaces); }); }, @@ -21,7 +20,7 @@ namespace ts.codefix { const classDeclaration = getClass(diag.file, diag.start); if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) { for (const implementedTypeNode of getClassImplementsHeritageClauseElements(classDeclaration)!) { - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); + addMissingDeclarations(context, implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); @@ -37,13 +36,14 @@ namespace ts.codefix { } function addMissingDeclarations( - checker: TypeChecker, + context: TypeConstructionContext, implementedTypeNode: ExpressionWithTypeArguments, sourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, changeTracker: textChanges.ChangeTracker, preferences: UserPreferences, ): void { + const checker = context.program.getTypeChecker(); const maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. @@ -60,12 +60,12 @@ namespace ts.codefix { createMissingIndexSignatureDeclaration(implementedType, IndexKind.String); } - createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member)); + createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member)); function createMissingIndexSignatureDeclaration(type: InterfaceType, kind: IndexKind): void { const indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { - changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)!); + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context))!); } } } diff --git a/src/services/codefixes/fixEnableExperimentalDecorators.ts b/src/services/codefixes/fixEnableExperimentalDecorators.ts new file mode 100644 index 00000000000..8aeefe48a47 --- /dev/null +++ b/src/services/codefixes/fixEnableExperimentalDecorators.ts @@ -0,0 +1,24 @@ +/* @internal */ +namespace ts.codefix { + const fixId = "enableExperimentalDecorators"; + const errorCodes = [ + 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.code + ]; + registerCodeFix({ + errorCodes, + getCodeActions: (context) => { + const { configFile } = context.program.getCompilerOptions(); + if (configFile === undefined) { + return undefined; + } + + const changes = textChanges.ChangeTracker.with(context, changeTracker => makeChange(changeTracker, configFile)); + return [createCodeFixActionNoFixId(fixId, changes, Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)]; + }, + fixIds: [fixId], + }); + + function makeChange(changeTracker: textChanges.ChangeTracker, configFile: TsConfigSourceFile) { + setJsonCompilerOptionValue(changeTracker, configFile, "experimentalDecorators", createTrue()); + } +} diff --git a/src/services/codefixes/fixStrictClassInitialization.ts b/src/services/codefixes/fixStrictClassInitialization.ts index 0647a64c368..15c57c604dd 100644 --- a/src/services/codefixes/fixStrictClassInitialization.ts +++ b/src/services/codefixes/fixStrictClassInitialization.ts @@ -110,7 +110,7 @@ namespace ts.codefix { function getDefaultValueFromType (checker: TypeChecker, type: Type): Expression | undefined { if (type.flags & TypeFlags.BooleanLiteral) { - return type === checker.getFalseType() ? createFalse() : createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? createFalse() : createTrue(); } else if (type.isLiteral()) { return createLiteral(type.value); diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index 2905f0b131b..de071ded24c 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -181,8 +181,8 @@ namespace ts.codefix { function deleteAssignments(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Identifier, checker: TypeChecker) { FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, (ref: Node) => { - if (ref.parent.kind === SyntaxKind.PropertyAccessExpression) ref = ref.parent; - if (ref.parent.kind === SyntaxKind.BinaryExpression && ref.parent.parent.kind === SyntaxKind.ExpressionStatement) { + if (isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent; + if (isBinaryExpression(ref.parent) && isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) { changes.delete(sourceFile, ref.parent.parent); } }); @@ -200,8 +200,16 @@ namespace ts.codefix { function tryDeleteParameter(changes: textChanges.ChangeTracker, sourceFile: SourceFile, p: ParameterDeclaration, checker: TypeChecker, sourceFiles: ReadonlyArray, isFixAll: boolean): void { if (mayDeleteParameter(p, checker, isFixAll)) { - changes.delete(sourceFile, p); - deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + if (p.modifiers && p.modifiers.length > 0 + && (!isIdentifier(p.name) || FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + p.modifiers.forEach(modifier => { + changes.deleteModifier(sourceFile, modifier); + }); + } + else { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + } } } diff --git a/src/services/codefixes/generateTypes.ts b/src/services/codefixes/generateTypes.ts new file mode 100644 index 00000000000..040d58c8e11 --- /dev/null +++ b/src/services/codefixes/generateTypes.ts @@ -0,0 +1,251 @@ +namespace ts { + export function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string { + return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, OutputKind.ExportEquals); + } + + export function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string { + return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, OutputKind.Global); + } + + function generateTypesForModuleOrGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings, outputKind: OutputKind.ExportEquals | OutputKind.Global): string { + return valueInfoToDeclarationFileText(inspectValue(name, globalValue), formatSettings, outputKind); + } + + /* @internal */ + export function valueInfoToDeclarationFileText(valueInfo: ValueInfo, formatSettings: FormatCodeSettings, outputKind: OutputKind.ExportEquals | OutputKind.Global = OutputKind.ExportEquals): string { + return textChanges.getNewFileText(toStatements(valueInfo, outputKind), ScriptKind.TS, formatSettings.newLineCharacter || "\n", formatting.getFormatContext(formatSettings)); + } + + const enum OutputKind { ExportEquals, NamedExport, NamespaceMember, Global } + function toNamespaceMemberStatements(info: ValueInfo): ReadonlyArray { + return toStatements(info, OutputKind.NamespaceMember); + } + function toStatements(info: ValueInfo, kind: OutputKind): ReadonlyArray { + const isDefault = info.name === InternalSymbolName.Default; + const name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== OutputKind.NamedExport) return emptyArray; + + const modifiers = isDefault && info.kind === ValueKind.FunctionOrClass ? [createModifier(SyntaxKind.ExportKeyword), createModifier(SyntaxKind.DefaultKeyword)] + : kind === OutputKind.Global || kind === OutputKind.ExportEquals ? [createModifier(SyntaxKind.DeclareKeyword)] + : kind === OutputKind.NamedExport ? [createModifier(SyntaxKind.ExportKeyword)] + : undefined; + const exportEquals = () => kind === OutputKind.ExportEquals ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : emptyArray; + const exportDefault = () => isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : emptyArray; + + switch (info.kind) { + case ValueKind.FunctionOrClass: + return [...exportEquals(), ...functionOrClassToStatements(modifiers, name, info)]; + case ValueKind.Object: + const { members, hasNontrivialPrototype } = info; + if (!hasNontrivialPrototype) { + if (kind === OutputKind.ExportEquals) { + return flatMap(members, v => toStatements(v, OutputKind.NamedExport)); + } + if (members.some(m => m.kind === ValueKind.FunctionOrClass)) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return [...exportDefault(), createNamespace(modifiers, name, flatMap(members, toNamespaceMemberStatements))]; + } + } + // falls through + case ValueKind.Const: + case ValueKind.Array: { + const comment = info.kind === ValueKind.Const ? info.comment : undefined; + const constVar = createVariableStatement(modifiers, createVariableDeclarationList([createVariableDeclaration(name, toType(info))], NodeFlags.Const)); + return [...exportEquals(), ...exportDefault(), addComment(constVar, comment)]; + } + default: + return Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name: string, isExportEquals: boolean): ExportAssignment { + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, createIdentifier(name)); + } + + function functionOrClassToStatements(modifiers: Modifiers, name: string, { source, prototypeMembers, namespaceMembers }: ValueInfoFunctionOrClass): ReadonlyArray { + const fnAst = parseClassOrFunctionBody(source); + const { parameters, returnType } = fnAst === undefined ? { parameters: emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst); + const protoOrInstanceMembers = createMap(); + if (typeof fnAst === "object") getConstructorFunctionInstanceProperties(fnAst, protoOrInstanceMembers); + for (const p of prototypeMembers) { + // ignore non-functions on the prototype + if (p.kind === ValueKind.FunctionOrClass) { + const m = tryGetMethod(p); + if (m) { + protoOrInstanceMembers.set(p.name, m); + } + } + } + + const classStaticMembers: ClassElement[] | undefined = + protoOrInstanceMembers.size !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === SyntaxKind.Constructor ? [] : undefined; + + const namespaceStatements = flatMap(namespaceMembers, info => { + if (!isValidIdentifier(info.name)) return undefined; + if (classStaticMembers) { + switch (info.kind) { + case ValueKind.Object: + if (info.members.some(m => m.kind === ValueKind.FunctionOrClass)) { + break; + } + // falls through + case ValueKind.Array: + case ValueKind.Const: + classStaticMembers.push( + addComment( + createProperty(/*decorators*/ undefined, [createModifier(SyntaxKind.StaticKeyword)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), + info.kind === ValueKind.Const ? info.comment : undefined)); + return undefined; + case ValueKind.FunctionOrClass: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + const sig = tryGetMethod(info, [createModifier(SyntaxKind.StaticKeyword)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + break; + default: + Debug.assertNever(info); + } + } + return toStatements(info, OutputKind.NamespaceMember); + }); + + const decl = classStaticMembers + ? createClassDeclaration( + /*decorators*/ undefined, + modifiers, + name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, + [ + ...classStaticMembers, + ...(parameters.length ? [createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : emptyArray), + ...arrayFrom(protoOrInstanceMembers.values()), + ]) + : createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl, ...(namespaceStatements.length === 0 ? emptyArray : [createNamespace(modifiers && modifiers.map(m => getSynthesizedDeepClone(m)), name, namespaceStatements)])]; + } + + function tryGetMethod({ name, source }: ValueInfoFunctionOrClass, modifiers?: Modifiers): MethodDeclaration | undefined { + if (!isValidIdentifier(name)) return undefined; + const fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === SyntaxKind.Constructor)) return undefined; + const sig = getParametersAndReturnType(fnAst); + return sig && createMethod( + /*decorators*/ undefined, + modifiers, + /*asteriskToken*/ undefined, + name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, + sig.parameters, + sig.returnType, + /*body*/ undefined); + } + + function toType(info: ValueInfo): TypeNode { + switch (info.kind) { + case ValueKind.Const: + return createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case ValueKind.Array: + return createArrayTypeNode(toType(info.inner)); + case ValueKind.FunctionOrClass: + return createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case ValueKind.Object: + return createTypeLiteralNode(info.members.map(m => createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined))); + default: + return Debug.assertNever(info); + } + } + function toPropertyName(name: string): Identifier | StringLiteral { + return isIdentifierText(name, ScriptTarget.ESNext) ? createIdentifier(name) : createStringLiteral(name); + } + + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst: FunctionOrConstructorNode, members: Map): void { + forEachOwnNodeOfFunction(fnAst, node => { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + isPropertyAccessExpression(node.left) && node.left.expression.kind === SyntaxKind.ThisKeyword) { + const name = node.left.name.text; + if (!isJsPrivate(name)) { + getOrUpdate(members, name, () => createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + } + }); + } + + interface ParametersAndReturnType { readonly parameters: ReadonlyArray; readonly returnType: TypeNode; } + function getParametersAndReturnType(fnAst: FunctionOrConstructor): ParametersAndReturnType { + if (typeof fnAst === "number") { + return { parameters: fill(fnAst, i => makeParameter(`p${i}`, anyType())), returnType: anyType() }; + } + let usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, node => { + usedArguments = usedArguments || isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || isReturnStatement(node) && !!node.expression && node.expression.kind !== SyntaxKind.VoidExpression; + }); + const parameters = [ + ...fnAst.parameters.map(p => makeParameter(`${p.name.getText()}`, inferParameterType(fnAst, p))), + ...(usedArguments ? [makeRestParameter()] : emptyArray), + ]; + return { parameters, returnType: hasReturn ? anyType() : createKeywordTypeNode(SyntaxKind.VoidKeyword) }; + } + function makeParameter(name: string, type: TypeNode): ParameterDeclaration { + return createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter(): ParameterDeclaration { + return createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, createToken(SyntaxKind.DotDotDotToken), "args", /*questionToken*/ undefined, createArrayTypeNode(anyType())); + } + + type FunctionOrConstructorNode = FunctionExpression | ArrowFunction | ConstructorDeclaration | MethodDeclaration; + type FunctionOrConstructor = FunctionOrConstructorNode | number; // number is for native function + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source: string | number): FunctionOrConstructor | undefined { + if (typeof source === "number") return source; + const classOrFunction = tryCast(parseExpression(source), (node): node is FunctionExpression | ArrowFunction | ClassExpression => isFunctionExpression(node) || isArrowFunction(node) || isClassExpression(node)); + return classOrFunction + ? isClassExpression(classOrFunction) ? find(classOrFunction.members, isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : cast(first(cast(parseExpression(`{ ${source} }`), isObjectLiteralExpression).properties), isMethodDeclaration); + } + + function parseExpression(expr: string): Expression { + const text = `const _ = ${expr}`; + const srcFile = createSourceFile("test.ts", text, ScriptTarget.Latest, /*setParentNodes*/ true); + return first(cast(first(srcFile.statements), isVariableStatement).declarationList.declarations).initializer!; + } + + function inferParameterType(_fn: FunctionOrConstructor, _param: ParameterDeclaration): TypeNode { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst: FunctionOrConstructorNode, cb: (node: Node) => void) { + fnAst.body!.forEachChild(function recur(node) { + cb(node); + if (!isFunctionLike(node)) node.forEachChild(recur); + }); + } + + function isValidIdentifier(name: string): boolean { + const keyword = stringToToken(name); + return !(keyword && isNonContextualKeyword(keyword)) && isIdentifierText(name, ScriptTarget.ESNext); + } + + type Modifiers = ReadonlyArray | undefined; + + function addComment(node: T, comment: string | undefined): T { + if (comment !== undefined) addSyntheticLeadingComment(node, SyntaxKind.SingleLineCommentTrivia, comment); + return node; + } + + function anyType(): KeywordTypeNode { + return createKeywordTypeNode(SyntaxKind.AnyKeyword); + } + + function createNamespace(modifiers: Modifiers, name: string, statements: ReadonlyArray): NamespaceDeclaration { + return createModuleDeclaration(/*decorators*/ undefined, modifiers, createIdentifier(name), createModuleBlock(statements), NodeFlags.Namespace) as NamespaceDeclaration; + } +} diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index eec693bbb69..4309e6ec35d 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -6,23 +6,48 @@ namespace ts.codefix { * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: ReadonlyArray, checker: TypeChecker, preferences: UserPreferences, out: (node: ClassElement) => void): void { + export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: ReadonlyArray, context: TypeConstructionContext, preferences: UserPreferences, out: (node: ClassElement) => void): void { const classMembers = classDeclaration.symbol.members!; for (const symbol of possiblyMissingSymbols) { if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, out); } } } + function getModuleSpecifierResolverHost(context: TypeConstructionContext): SymbolTracker["moduleResolverHost"] { + return { + directoryExists: context.host.directoryExists ? d => context.host.directoryExists!(d) : undefined, + fileExists: context.host.fileExists ? f => context.host.fileExists!(f) : undefined, + getCurrentDirectory: context.host.getCurrentDirectory ? () => context.host.getCurrentDirectory!() : undefined, + readFile: context.host.readFile ? f => context.host.readFile!(f) : undefined, + useCaseSensitiveFileNames: context.host.useCaseSensitiveFileNames ? () => context.host.useCaseSensitiveFileNames!() : undefined, + getSourceFiles: () => context.program.getSourceFiles(), + getCommonSourceDirectory: () => context.program.getCommonSourceDirectory(), + }; + } + + export function getNoopSymbolTrackerWithResolver(context: TypeConstructionContext): SymbolTracker { + return { + trackSymbol: noop, + moduleResolverHost: getModuleSpecifierResolverHost(context), + }; + } + + export interface TypeConstructionContext { + program: Program; + host: ModuleSpecifierResolutionHost; + } + /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol: Symbol, enclosingDeclaration: ClassLikeDeclaration, checker: TypeChecker, preferences: UserPreferences, out: (node: Node) => void): void { + function addNewNodeForMemberSymbol(symbol: Symbol, enclosingDeclaration: ClassLikeDeclaration, context: TypeConstructionContext, preferences: UserPreferences, out: (node: Node) => void): void { const declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } + const checker = context.program.getTypeChecker(); const declaration = declarations[0]; const name = getSynthesizedDeepClone(getNameOfDeclaration(declaration), /*includeTrivia*/ false) as PropertyName; @@ -36,7 +61,7 @@ namespace ts.codefix { case SyntaxKind.SetAccessor: case SyntaxKind.PropertySignature: case SyntaxKind.PropertyDeclaration: - const typeNode = checker.typeToTypeNode(type, enclosingDeclaration); + const typeNode = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); out(createProperty( /*decorators*/undefined, modifiers, @@ -83,13 +108,13 @@ namespace ts.codefix { } function outputMethod(signature: Signature, modifiers: NodeArray | undefined, name: PropertyName, body?: Block): void { - const method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + const method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body); if (method) out(method); } } function signatureToMethodDeclaration( - checker: TypeChecker, + context: TypeConstructionContext, signature: Signature, enclosingDeclaration: ClassLikeDeclaration, modifiers: NodeArray | undefined, @@ -97,7 +122,8 @@ namespace ts.codefix { optional: boolean, body: Block | undefined, ): MethodDeclaration | undefined { - const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.SuppressAnyReturnType); + const program = context.program; + const signatureDeclaration = program.getTypeChecker().signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.NoTruncation | NodeBuilderFlags.SuppressAnyReturnType, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return undefined; } @@ -117,18 +143,20 @@ namespace ts.codefix { inJs: boolean, makeStatic: boolean, preferences: UserPreferences, - body: boolean, + contextNode: Node, ): MethodDeclaration { + const body = !isInterfaceDeclaration(contextNode); const { typeArguments, arguments: args, parent } = call; const checker = context.program.getTypeChecker(); + const tracker = getNoopSymbolTrackerWithResolver(context); const types = map(args, arg => // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)))); + checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker)); const names = map(args, arg => isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) ? arg.name.text : undefined); const contextualType = checker.getContextualType(call); - const returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || createKeywordTypeNode(SyntaxKind.AnyKeyword); + const returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || createKeywordTypeNode(SyntaxKind.AnyKeyword); return createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [createToken(SyntaxKind.StaticKeyword)] : undefined, @@ -249,4 +277,46 @@ namespace ts.codefix { } return undefined; } + + export function setJsonCompilerOptionValue( + changeTracker: textChanges.ChangeTracker, + configFile: TsConfigSourceFile, + optionName: string, + optionValue: Expression, + ) { + const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) return undefined; + + const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); + if (compilerOptionsProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment( + "compilerOptions", + createObjectLiteral([ + createJsonPropertyAssignment(optionName, optionValue), + ]))); + return; + } + + const compilerOptions = compilerOptionsProperty.initializer; + if (!isObjectLiteralExpression(compilerOptions)) { + return; + } + + const optionProperty = findJsonProperty(compilerOptions, optionName); + + if (optionProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); + } + else { + changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + } + } + + export function createJsonPropertyAssignment(name: string, initializer: Expression) { + return createPropertyAssignment(createStringLiteral(name), initializer); + } + + export function findJsonProperty(obj: ObjectLiteralExpression, name: string): PropertyAssignment | undefined { + return find(obj.properties, (p): p is PropertyAssignment => isPropertyAssignment(p) && !!p.name && isStringLiteral(p.name) && p.name.text === name); + } } diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 963d1cd64f2..8006d1a0cfd 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -185,20 +185,20 @@ namespace ts.codefix { const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && defaultInfo.name === symbolName && skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { - result.push({ moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol) }); + result.push({ moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); } for (const exported of checker.getExportsOfModule(moduleSymbol)) { if (exported.name === symbolName && skipAlias(exported, checker) === exportedSymbol) { - result.push({ moduleSymbol, importKind: ImportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + result.push({ moduleSymbol, importKind: ImportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s: Symbol): boolean { - return !(s.flags & SymbolFlags.Value); + function isTypeOnlySymbol(s: Symbol, checker: TypeChecker): boolean { + return !(skipAlias(s, checker).flags & SymbolFlags.Value); } function getFixForImport( @@ -267,7 +267,7 @@ namespace ts.codefix { function getExistingImportDeclarations({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }: SymbolExportInfo, checker: TypeChecker, sourceFile: SourceFile): ReadonlyArray { // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && isSourceFileJavaScript(sourceFile) ? emptyArray : mapDefined(sourceFile.imports, moduleSpecifier => { + return exportedSymbolIsTypeOnly && isSourceFileJS(sourceFile) ? emptyArray : mapDefined(sourceFile.imports, moduleSpecifier => { const i = importFromModuleSpecifier(moduleSpecifier); return (i.kind === SyntaxKind.ImportDeclaration || i.kind === SyntaxKind.ImportEqualsDeclaration) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind } : undefined; @@ -282,14 +282,14 @@ namespace ts.codefix { host: LanguageServiceHost, preferences: UserPreferences, ): ReadonlyArray { - const isJs = isSourceFileJavaScript(sourceFile); + const isJs = isSourceFileJS(sourceFile); const choicesForEachExportingModule = flatMap(moduleSymbols, ({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }) => moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) .map((moduleSpecifier): FixAddNewImport | FixUseImportType => // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. exportedSymbolIsTypeOnly && isJs ? { kind: ImportFixKind.ImportType, moduleSpecifier, position: Debug.assertDefined(position) } : { kind: ImportFixKind.AddNew, moduleSpecifier, importKind })); // Sort to keep the shortest paths first - return choicesForEachExportingModule.sort((a, b) => a.moduleSpecifier.length - b.moduleSpecifier.length); + return sort(choicesForEachExportingModule, (a, b) => a.moduleSpecifier.length - b.moduleSpecifier.length); } function getFixesForAddImport( @@ -375,7 +375,7 @@ namespace ts.codefix { const symbolName = isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken && (isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, SymbolFlags.All, /*excludeGlobals*/ false)) - ? checker.getJsxNamespace() + ? checker.getJsxNamespace(sourceFile) : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here Debug.assert(symbolName !== InternalSymbolName.Default); @@ -398,7 +398,7 @@ namespace ts.codefix { // Maps symbol id to info for modules providing that symbol (original export + re-exports). const originalSymbolToExportInfos = createMultiMap(); function addSymbol(moduleSymbol: Symbol, exportedSymbol: Symbol, importKind: ImportKind): void { - originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol, importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol, importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), moduleSymbol => { cancellationToken.throwIfCancellationRequested(); @@ -424,7 +424,7 @@ namespace ts.codefix { if (!exported) return undefined; const { symbol, kind } = exported; const info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); - return info && { symbol, symbolForMeaning: info.symbolForMeaning, name: info.name, kind }; + return info && { symbol, kind, ...info }; } function getDefaultLikeExportWorker(moduleSymbol: Symbol, checker: TypeChecker): { readonly symbol: Symbol, readonly kind: ImportKind.Default | ImportKind.Equals } | undefined { diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 17b3469f0bf..8e5b962116d 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -21,28 +21,46 @@ namespace ts.codefix { // Property declarations Diagnostics.Member_0_implicitly_has_an_1_type.code, + + //// Suggestions + // Variable declarations + Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + + // Variable uses + Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + + // Parameter declarations + Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + + // Get Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + + // Set Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + + // Property declarations + Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, ]; registerCodeFix({ errorCodes, getCodeActions(context) { - const { sourceFile, program, span: { start }, errorCode, cancellationToken } = context; - if (isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } + const { sourceFile, program, span: { start }, errorCode, cancellationToken, host } = context; const token = getTokenAtPosition(sourceFile, start); let declaration!: Declaration | undefined; - const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ returnTrue); }); + const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host); }); const name = declaration && getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions(context) { - const { sourceFile, program, cancellationToken } = context; + const { sourceFile, program, cancellationToken, host } = context; const markSeen = nodeSeenTracker(); return codeFixAll(context, errorCodes, (changes, err) => { - doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); @@ -50,26 +68,62 @@ namespace ts.codefix { function getDiagnostic(errorCode: number, token: Node): DiagnosticMessage { switch (errorCode) { case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return isSetAccessor(getContainingFunction(token)!) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return isSetAccessorDeclaration(getContainingFunction(token)!) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: return Diagnostics.Infer_parameter_types_from_usage; default: return Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker): Declaration | undefined { - if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken) { + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode: number) { + switch (errorCode) { + case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost): Declaration | undefined { + if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken && token.kind !== SyntaxKind.ThisKeyword) { return undefined; } const { parent } = token; + errorCode = mapSuggestionDiagnostic(errorCode); switch (errorCode) { // Variable and Property declarations case Diagnostics.Member_0_implicitly_has_an_1_type.code: case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((isVariableDeclaration(parent) && markSeen(parent)) || isPropertyDeclaration(parent) || isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (isPropertyAccessExpression(parent)) { + const type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + const typeNode = getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags + const typeTag = createJSDocTypeTag(createJSDocTypeExpression(typeNode), /*comment*/ ""); + addJSDocTags(changes, sourceFile, cast(parent.parent.parent, isExpressionStatement), [typeTag]); + } return parent; } return undefined; @@ -77,7 +131,7 @@ namespace ts.codefix { case Diagnostics.Variable_0_implicitly_has_an_1_type.code: { const symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -92,15 +146,15 @@ namespace ts.codefix { switch (errorCode) { // Parameter declarations case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { const param = cast(parent, isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); return param; } return undefined; @@ -108,16 +162,16 @@ namespace ts.codefix { // Get Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (isGetAccessor(containingFunction) && isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + if (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; // Set Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -127,58 +181,121 @@ namespace ts.codefix { } } - function annotateVariableDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, program: Program, cancellationToken: CancellationToken): void { + function annotateVariableDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { if (isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } - function isApplicableFunctionForInference(declaration: FunctionLike): declaration is MethodDeclaration | FunctionDeclaration | ConstructorDeclaration { - switch (declaration.kind) { - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.Constructor: - return true; - case SyntaxKind.FunctionExpression: - return !!declaration.name; - } - return false; - } - - function annotateParameters(changes: textChanges.ChangeTracker, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): void { - if (!isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + function annotateParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { + if (!isIdentifier(parameterDeclaration.name)) { return; } + const parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(p => ({ + declaration: p, + type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + })); + Debug.assert(containingFunction.parameters.length === parameterInferences.length); - const types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(p => isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; + if (isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } - - zipWith(containingFunction.parameters, types, (parameter, type) => { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + else { + const needParens = isArrowFunction(containingFunction) && !findChildOfKind(containingFunction, SyntaxKind.OpenParenToken, sourceFile); + if (needParens) changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), createToken(SyntaxKind.OpenParenToken)); + for (const { declaration, type } of parameterInferences) { + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + if (needParens) changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), createToken(SyntaxKind.CloseParenToken)); + } } - function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, cancellationToken: CancellationToken): void { + function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { const param = firstOrUndefined(setAccessorDeclaration.parameters); if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { - const type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || - inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + let type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } + if (isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } - function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type | undefined, program: Program): void { - const typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type, program: Program, host: LanguageServiceHost): void { + const typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (isInJSFile(sourceFile) && declaration.kind !== SyntaxKind.PropertySignature) { + const parent = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : declaration; + if (!parent) { + return; + } + const typeExpression = createJSDocTypeExpression(typeNode); + const typeTag = isGetAccessorDeclaration(declaration) ? createJSDocReturnTag(typeExpression, "") : createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, checker: TypeChecker): TypeNode | undefined { + function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterInferences: ReadonlyArray, program: Program, host: LanguageServiceHost): void { + const signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + const paramTags = mapDefined(parameterInferences, inference => { + const param = inference.declaration; + // only infer parameters that have (1) no type and (2) an accessible inferred type + if (param.initializer || getJSDocType(param) || !isIdentifier(param.name)) return; + + const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + const name = getSynthesizedClone(param.name); + setEmitFlags(name, EmitFlags.NoComments | EmitFlags.NoNestedComments); + return typeNode && createJSDocParamTag(name, !!inference.isOptional, createJSDocTypeExpression(typeNode), ""); + }); + addJSDocTags(changes, sourceFile, signature, paramTags); + } + + function addJSDocTags(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parent: HasJSDoc, newTags: ReadonlyArray): void { + const comments = mapDefined(parent.jsDoc, j => j.comment); + const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags); + const unmergedNewTags = newTags.filter(newTag => !oldTags || !oldTags.some((tag, i) => { + const merged = tryMergeJsdocTags(tag, newTag); + if (merged) oldTags[i] = merged; + return !!merged; + })); + const tag = createJSDocComment(comments.join("\n"), createNodeArray([...(oldTags || emptyArray), ...unmergedNewTags])); + changes.insertJsdocCommentBefore(sourceFile, parent, tag); + } + + function tryMergeJsdocTags(oldTag: JSDocTag, newTag: JSDocTag): JSDocTag | undefined { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case SyntaxKind.JSDocParameterTag: { + const oldParam = oldTag as JSDocParameterTag; + const newParam = newTag as JSDocParameterTag; + return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + : undefined; + } + case SyntaxKind.JSDocReturnTag: + return createJSDocReturnTag((newTag as JSDocReturnTag).typeExpression, oldTag.comment); + } + } + + function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined { + const checker = program.getTypeChecker(); let typeIsAccessible = true; const notAccessible = () => { typeIsAccessible = false; }; const res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -189,6 +306,14 @@ namespace ts.codefix { reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } @@ -196,27 +321,43 @@ namespace ts.codefix { function getReferences(token: PropertyName | Token, program: Program, cancellationToken: CancellationToken): ReadonlyArray { // Position shouldn't matter since token is not a SourceFile. return mapDefined(FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), entry => - entry.type === "node" ? tryCast(entry.node, isIdentifier) : undefined); + entry.kind !== FindAllReferences.EntryKind.Span ? tryCast(entry.node, isIdentifier) : undefined); } - function inferTypeForVariableFromUsage(token: Identifier, program: Program, cancellationToken: CancellationToken): Type | undefined { - return InferFromReference.inferTypeFromReferences(getReferences(token, program, cancellationToken), program.getTypeChecker(), cancellationToken); + function inferTypeForVariableFromUsage(token: Identifier, program: Program, cancellationToken: CancellationToken): Type { + const references = getReferences(token, program, cancellationToken); + const checker = program.getTypeChecker(); + const types = InferFromReference.inferTypesFromReferences(references, checker, cancellationToken); + return InferFromReference.unifyFromContext(types, checker); } - function inferTypeForParametersFromUsage(containingFunction: FunctionLikeDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): (Type | undefined)[] | undefined { + function inferTypeForParametersFromUsage(containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { + let searchToken; switch (containingFunction.kind) { case SyntaxKind.Constructor: + searchToken = findChildOfKind>(containingFunction, SyntaxKind.ConstructorKeyword, sourceFile); + break; + case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionExpression: + const parent = containingFunction.parent; + searchToken = isVariableDeclaration(parent) && isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: - const isConstructor = containingFunction.kind === SyntaxKind.Constructor; - const searchToken = isConstructor ? - findChildOfKind>(containingFunction, SyntaxKind.ConstructorKeyword, sourceFile) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); - } + searchToken = containingFunction.name; + break; } + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); + } + } + + interface ParameterInference { + readonly declaration: ParameterDeclaration; + readonly type: Type; + readonly isOptional?: boolean; } namespace InferFromReference { @@ -228,7 +369,9 @@ namespace ts.codefix { interface UsageContext { isNumber?: boolean; isString?: boolean; + /** Used ambiguously, eg x + ___ or object[___]; results in string | number if no other evidence exists */ isNumberOrString?: boolean; + candidateTypes?: Type[]; properties?: UnderscoreEscapedMap; callContexts?: CallContext[]; @@ -237,20 +380,20 @@ namespace ts.codefix { stringIndexContext?: UsageContext; } - export function inferTypeFromReferences(references: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken): Type | undefined { + export function inferTypesFromReferences(references: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken): Type[] { const usageContext: UsageContext = {}; for (const reference of references) { cancellationToken.throwIfCancellationRequested(); inferTypeFromContext(reference, checker, usageContext); } - return getTypeFromUsageContext(usageContext, checker); + return inferFromContext(usageContext, checker); } - export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLikeDeclaration, checker: TypeChecker, cancellationToken: CancellationToken): (Type | undefined)[] | undefined { + export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLike, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { + const checker = program.getTypeChecker(); if (references.length === 0) { return undefined; } - if (!declaration.parameters) { return undefined; } @@ -260,17 +403,17 @@ namespace ts.codefix { cancellationToken.throwIfCancellationRequested(); inferTypeFromContext(reference, checker, usageContext); } - const isConstructor = declaration.kind === SyntaxKind.Constructor; - const callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; - return callContexts && declaration.parameters.map((parameter, parameterIndex) => { - const types: Type[] = []; + const callContexts = [...usageContext.constructContexts || [], ...usageContext.callContexts || []]; + return declaration.parameters.map((parameter, parameterIndex): ParameterInference => { + const types = []; const isRest = isRestParameter(parameter); + let isOptional = false; for (const callContext of callContexts) { if (callContext.argumentTypes.length <= parameterIndex) { - continue; + isOptional = isInJSFile(declaration); + types.push(checker.getUndefinedType()); } - - if (isRest) { + else if (isRest) { for (let i = parameterIndex; i < callContext.argumentTypes.length; i++) { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); } @@ -279,11 +422,16 @@ namespace ts.codefix { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); } } - if (!types.length) { - return undefined; + if (isIdentifier(parameter.name)) { + const inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken); + types.push(...(isRest ? mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); } - const type = checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype)); - return isRest ? checker.createArrayType(type) : type; + const type = unifyFromContext(types, checker); + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } @@ -513,29 +661,120 @@ namespace ts.codefix { } } - function getTypeFromUsageContext(usageContext: UsageContext, checker: TypeChecker): Type | undefined { - if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { - return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); + interface Priority { + high: (t: Type) => boolean; + low: (t: Type) => boolean; + } + + function removeLowPriorityInferences(inferences: ReadonlyArray, priorities: Priority[]): Type[] { + const toRemove: ((t: Type) => boolean)[] = []; + for (const i of inferences) { + for (const { high, low } of priorities) { + if (high(i)) { + Debug.assert(!low(i)); + toRemove.push(low); + } + } } - else if (usageContext.isNumber) { - return checker.getNumberType(); + return inferences.filter(i => toRemove.every(f => !f(i))); + } + + export function unifyFromContext(inferences: ReadonlyArray, checker: TypeChecker, fallback = checker.getAnyType()): Type { + if (!inferences.length) return fallback; + + // 1. string or number individually override string | number + // 2. non-any, non-void overrides any or void + // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types + const stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); + const priorities: Priority[] = [ + { + high: t => t === checker.getStringType() || t === checker.getNumberType(), + low: t => t === stringNumber + }, + { + high: t => !(t.flags & (TypeFlags.Any | TypeFlags.Void)), + low: t => !!(t.flags & (TypeFlags.Any | TypeFlags.Void)) + }, + { + high: t => !(t.flags & (TypeFlags.Nullable | TypeFlags.Any | TypeFlags.Void)) && !(checker.getObjectFlags(t) & ObjectFlags.Anonymous), + low: t => !!(checker.getObjectFlags(t) & ObjectFlags.Anonymous) + }]; + let good = removeLowPriorityInferences(inferences, priorities); + const anons = good.filter(i => checker.getObjectFlags(i) & ObjectFlags.Anonymous) as AnonymousType[]; + if (anons.length) { + good = good.filter(i => !(checker.getObjectFlags(i) & ObjectFlags.Anonymous)); + good.push(unifyAnonymousTypes(anons, checker)); } - else if (usageContext.isString) { - return checker.getStringType(); + return checker.getWidenedType(checker.getUnionType(good)); + } + + function unifyAnonymousTypes(anons: AnonymousType[], checker: TypeChecker) { + if (anons.length === 1) { + return anons[0]; } - else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(t => checker.getBaseTypeOfLiteralType(t)), UnionReduction.Subtype)); + const calls = []; + const constructs = []; + const stringIndices = []; + const numberIndices = []; + let stringIndexReadonly = false; + let numberIndexReadonly = false; + const props = createMultiMap(); + for (const anon of anons) { + for (const p of checker.getPropertiesOfType(anon)) { + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push(...checker.getSignaturesOfType(anon, SignatureKind.Call)); + constructs.push(...checker.getSignaturesOfType(anon, SignatureKind.Construct)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } } - else if (usageContext.properties && hasCallContext(usageContext.properties.get("then" as __String))) { + const members = mapEntries(props, (name, types) => { + const isOptional = types.length < anons.length ? SymbolFlags.Optional : 0; + const s = checker.createSymbol(SymbolFlags.Property | isOptional, name as __String); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType( + anons[0].symbol, + members as UnderscoreEscapedMap, + calls, + constructs, + stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, + numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + + function inferFromContext(usageContext: UsageContext, checker: TypeChecker) { + const types = []; + + if (usageContext.isNumber) { + types.push(checker.getNumberType()); + } + if (usageContext.isString) { + types.push(checker.getStringType()); + } + if (usageContext.isNumberOrString) { + types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); + } + + types.push(...(usageContext.candidateTypes || []).map(t => checker.getBaseTypeOfLiteralType(t))); + + if (usageContext.properties && hasCallContext(usageContext.properties.get("then" as __String))) { const paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then" as __String)!.callContexts!, /*isRestParameter*/ false, checker)!; // TODO: GH#18217 const types = paramType.getCallSignatures().map(c => c.getReturnType()); - return checker.createPromiseType(types.length ? checker.getUnionType(types, UnionReduction.Subtype) : checker.getAnyType()); + types.push(checker.createPromiseType(types.length ? checker.getUnionType(types, UnionReduction.Subtype) : checker.getAnyType())); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("push" as __String))) { - return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push" as __String)!.callContexts!, /*isRestParameter*/ false, checker)!); + types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push" as __String)!.callContexts!, /*isRestParameter*/ false, checker)!)); } - else if (usageContext.numberIndexContext) { - return checker.createArrayType(recur(usageContext.numberIndexContext)); + + if (usageContext.numberIndexContext) { + types.push(checker.createArrayType(recur(usageContext.numberIndexContext))); } else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { const members = createUnderscoreEscapedMap(); @@ -567,14 +806,12 @@ namespace ts.codefix { stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined!, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 - } - else { - return undefined; + types.push(checker.createAnonymousType(/*symbol*/ undefined!, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 } + return types; function recur(innerContext: UsageContext): Type { - return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + return unifyFromContext(inferFromContext(innerContext, checker), checker); } } @@ -607,7 +844,7 @@ namespace ts.codefix { symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); parameters.push(symbol); } - const returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + const returnType = unifyFromContext(inferFromContext(callContext.returnType, checker), checker, checker.getVoidType()); // TODO: GH#18217 return checker.createSignature(/*declaration*/ undefined!, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); } diff --git a/src/services/completions.ts b/src/services/completions.ts index 3edc1cc4f56..f17ee862cca 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -37,18 +37,13 @@ namespace ts.Completions { export function getCompletionsAtPosition(host: LanguageServiceHost, program: Program, log: Log, sourceFile: SourceFile, position: number, preferences: UserPreferences, triggerCharacter: CompletionsTriggerCharacter | undefined): CompletionInfo | undefined { const typeChecker = program.getTypeChecker(); const compilerOptions = program.getCompilerOptions(); - if (isInReferenceComment(sourceFile, position)) { - const entries = PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries && convertPathCompletions(entries); - } const contextToken = findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) return undefined; + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; - if (isInString(sourceFile, position, contextToken)) { - return !contextToken || !isStringLiteralLike(contextToken) - ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); + const stringCompletions = StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); + if (stringCompletions) { + return stringCompletions; } if (contextToken && isBreakOrContinueStatement(contextToken.parent) @@ -77,34 +72,6 @@ namespace ts.Completions { } } - function convertStringLiteralCompletions(completion: StringLiteralCompletion | undefined, sourceFile: SourceFile, checker: TypeChecker, log: Log, preferences: UserPreferences): CompletionInfo | undefined { - if (completion === undefined) { - return undefined; - } - switch (completion.kind) { - case StringLiteralCompletionKind.Paths: - return convertPathCompletions(completion.paths); - case StringLiteralCompletionKind.Properties: { - const entries: CompletionEntry[] = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, ScriptTarget.ESNext, log, CompletionKind.String, preferences); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries }; - } - case StringLiteralCompletionKind.Types: { - const entries = completion.types.map(type => ({ name: type.value, kindModifiers: ScriptElementKindModifier.none, kind: ScriptElementKind.string, sortText: "0" })); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries }; - } - default: - return Debug.assertNever(completion); - } - } - - function convertPathCompletions(pathCompletions: ReadonlyArray): CompletionInfo { - const isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. - const isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. - const entries = pathCompletions.map(({ name, kind, span }) => ({ name, kind, kindModifiers: ScriptElementKindModifier.none, sortText: "0", replacementSpan: span })); - return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries }; - } - function jsdocCompletionInfo(entries: CompletionEntry[]): CompletionInfo { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; } @@ -134,17 +101,24 @@ namespace ts.Completions { if (isUncheckedFile(sourceFile, compilerOptions)) { const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target!, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217 } else { - if ((!symbols || symbols.length === 0) && keywordFilters === KeywordCompletionFilters.None) { + if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === KeywordCompletionFilters.None) { return undefined; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target!, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== KeywordCompletionFilters.None) { + const entryNames = arrayToSet(entries, e => e.name); + for (const keywordEntry of getKeywordCompletions(keywordFilters)) { + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } + } for (const literal of literals) { entries.push(createCompletionEntryForLiteral(literal)); @@ -154,7 +128,7 @@ namespace ts.Completions { } function isUncheckedFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean { - return isSourceFileJavaScript(sourceFile) && !isCheckJsEnabledForFile(sourceFile, compilerOptions); + return isSourceFileJS(sourceFile) && !isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind: CompletionKind): boolean { @@ -168,7 +142,7 @@ namespace ts.Completions { } } - function getJavaScriptCompletionEntries( + function getJSCompletionEntries( sourceFile: SourceFile, position: number, uniqueNames: Map, @@ -180,7 +154,7 @@ namespace ts.Completions { return; } const realName = unescapeLeadingUnderscores(name); - if (addToSeen(uniqueNames, realName) && isIdentifierText(realName, target) && !isStringANonContextualKeyword(realName)) { + if (addToSeen(uniqueNames, realName) && isIdentifierText(realName, target)) { entries.push({ name: realName, kind: ScriptElementKind.warning, @@ -191,8 +165,9 @@ namespace ts.Completions { }); } - const completionNameForLiteral = JSON.stringify; - function createCompletionEntryForLiteral(literal: string | number): CompletionEntry { + const completionNameForLiteral = (literal: string | number | PseudoBigInt) => + typeof literal === "object" ? pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); + function createCompletionEntryForLiteral(literal: string | number | PseudoBigInt): CompletionEntry { return { name: completionNameForLiteral(literal), kind: ScriptElementKind.string, kindModifiers: ScriptElementKindModifier.none, sortText: "0" }; } @@ -263,22 +238,6 @@ namespace ts.Completions { }; } - function quote(text: string, preferences: UserPreferences): string { - if (/^\d+$/.test(text)) { - return text; - } - const quoted = JSON.stringify(text); - switch (preferences.quotePreference) { - case undefined: - case "double": - return quoted; - case "single": - return `'${stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"')}'`; - default: - return Debug.assertNever(preferences.quotePreference); - } - } - function isRecommendedCompletionMatch(localSymbol: Symbol, recommendedCompletion: Symbol | undefined, checker: TypeChecker): boolean { return localSymbol === recommendedCompletion || !!(localSymbol.flags & SymbolFlags.ExportValue) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; @@ -292,7 +251,7 @@ namespace ts.Completions { return origin && originIsExport(origin) ? stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols( + export function getCompletionEntriesFromSymbols( symbols: ReadonlyArray, entries: Push, location: Node | undefined, @@ -370,135 +329,6 @@ namespace ts.Completions { return entries; } - const enum StringLiteralCompletionKind { Paths, Properties, Types } - interface StringLiteralCompletionsFromProperties { - readonly kind: StringLiteralCompletionKind.Properties; - readonly symbols: ReadonlyArray; - readonly hasIndexSignature: boolean; - } - interface StringLiteralCompletionsFromTypes { - readonly kind: StringLiteralCompletionKind.Types; - readonly types: ReadonlyArray; - readonly isNewIdentifier: boolean; - } - type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: ReadonlyArray } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; - function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost): StringLiteralCompletion | undefined { - switch (node.parent.kind) { - case SyntaxKind.LiteralType: - switch (node.parent.parent.kind) { - case SyntaxKind.TypeReference: - return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent as LiteralTypeNode)), isNewIdentifier: false }; - case SyntaxKind.IndexedAccessType: - // Get all apparent property names - // i.e. interface Foo { - // foo: string; - // bar: string; - // } - // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((node.parent.parent as IndexedAccessTypeNode).objectType)); - case SyntaxKind.ImportType: - return { kind: StringLiteralCompletionKind.Paths, paths: PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case SyntaxKind.UnionType: - return isTypeReferenceNode(node.parent.parent.parent) ? { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent as UnionTypeNode)), isNewIdentifier: false } : undefined; - default: - return undefined; - } - - case SyntaxKind.PropertyAssignment: - if (isObjectLiteralExpression(node.parent.parent) && (node.parent).name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); - } - return fromContextualType(); - - case SyntaxKind.ElementAccessExpression: { - const { expression, argumentExpression } = node.parent as ElementAccessExpression; - if (node === argumentExpression) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); - } - return undefined; - } - - case SyntaxKind.CallExpression: - case SyntaxKind.NewExpression: - if (!isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(node.parent)) { - const argumentInfo = SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); - } - // falls through (is `require("")` or `import("")`) - - case SyntaxKind.ImportDeclaration: - case SyntaxKind.ExportDeclaration: - case SyntaxKind.ExternalModuleReference: - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - return { kind: StringLiteralCompletionKind.Paths, paths: PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - - default: - return fromContextualType(); - } - - function fromContextualType(): StringLiteralCompletion { - // Get completion for string literal from string literal type - // i.e. var x: "hi" | "hello" = "/*completion position*/" - return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; - } - } - - function getStringLiteralCompletionsFromSignature(argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker): StringLiteralCompletionsFromTypes { - let isNewIdentifier = false; - - const uniques = createMap(); - const candidates: Signature[] = []; - checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); - const types = flatMap(candidates, candidate => { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) return; - const type = checker.getParameterType(candidate, argumentInfo.argumentIndex); - isNewIdentifier = isNewIdentifier || !!(type.flags & TypeFlags.String); - return getStringLiteralTypes(type, uniques); - }); - - return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier }; - } - - function stringLiteralCompletionsFromProperties(type: Type | undefined): StringLiteralCompletionsFromProperties | undefined { - return type && { kind: StringLiteralCompletionKind.Properties, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; - } - - function getStringLiteralTypes(type: Type | undefined, uniques = createMap()): ReadonlyArray { - if (!type) return emptyArray; - type = skipConstraint(type); - return type.isUnion() - ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) - : type.isStringLiteral() && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, type.value) - ? [type] - : emptyArray; - } - interface SymbolCompletion { type: "symbol"; symbol: Symbol; @@ -508,7 +338,7 @@ namespace ts.Completions { readonly isJsxInitializer: IsJsxInitializer; } function getSymbolCompletionFromEntryId(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier, - ): SymbolCompletion | { type: "request", request: Request } | { type: "literal", literal: string | number } | { type: "none" } { + ): SymbolCompletion | { type: "request", request: Request } | { type: "literal", literal: string | number | PseudoBigInt } | { type: "none" } { const compilerOptions = program.getCompilerOptions(); const completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); if (!completionData) { @@ -537,7 +367,9 @@ namespace ts.Completions { } function getSymbolName(symbol: Symbol, origin: SymbolOriginInfo | undefined, target: ScriptTarget): string { - return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === InternalSymbolName.Default + return origin && originIsExport(origin) && ( + (origin.isDefaultExport && symbol.escapedName === InternalSymbolName.Default) || + (symbol.escapedName === InternalSymbolName.ExportEquals)) // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? firstDefined(symbol.declarations, d => isExportAssignment(d) && isIdentifier(d.expression) ? d.expression.text : undefined) || codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -566,10 +398,7 @@ namespace ts.Completions { const contextToken = findPrecedingToken(position, sourceFile); if (isInString(sourceFile, position, contextToken)) { - const stringLiteralCompletions = !contextToken || !isStringLiteralLike(contextToken) - ? undefined - : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); - return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken!, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 + return StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); } // Compute all the completion symbols again. @@ -609,7 +438,7 @@ namespace ts.Completions { return createCompletionDetails(name, ScriptElementKindModifier.none, kind, [displayPart(name, kind2)]); } - function createCompletionDetailsForSymbol(symbol: Symbol, checker: TypeChecker, sourceFile: SourceFile, location: Node, cancellationToken: CancellationToken, codeActions?: CodeAction[], sourceDisplay?: SymbolDisplayPart[]): CompletionEntryDetails { + export function createCompletionDetailsForSymbol(symbol: Symbol, checker: TypeChecker, sourceFile: SourceFile, location: Node, cancellationToken: CancellationToken, codeActions?: CodeAction[], sourceDisplay?: SymbolDisplayPart[]): CompletionEntryDetails { const { displayParts, documentation, symbolKind, tags } = checker.runWithCancellationToken(cancellationToken, checker => SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, SemanticMeaning.All) @@ -617,24 +446,7 @@ namespace ts.Completions { return createCompletionDetails(symbol.name, SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } - function stringLiteralCompletionDetails(name: string, location: Node, completion: StringLiteralCompletion, sourceFile: SourceFile, checker: TypeChecker, cancellationToken: CancellationToken): CompletionEntryDetails | undefined { - switch (completion.kind) { - case StringLiteralCompletionKind.Paths: { - const match = find(completion.paths, p => p.name === name); - return match && createCompletionDetails(name, ScriptElementKindModifier.none, match.kind, [textPart(name)]); - } - case StringLiteralCompletionKind.Properties: { - const match = find(completion.symbols, s => s.name === name); - return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); - } - case StringLiteralCompletionKind.Types: - return find(completion.types, t => t.value === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.typeElement, [textPart(name)]) : undefined; - default: - return Debug.assertNever(completion); - } - } - - function createCompletionDetails(name: string, kindModifiers: string, kind: ScriptElementKind, displayParts: SymbolDisplayPart[], documentation?: SymbolDisplayPart[], tags?: JSDocTagInfo[], codeActions?: CodeAction[], source?: SymbolDisplayPart[]): CompletionEntryDetails { + export function createCompletionDetails(name: string, kindModifiers: string, kind: ScriptElementKind, displayParts: SymbolDisplayPart[], documentation?: SymbolDisplayPart[], tags?: JSDocTagInfo[], codeActions?: CodeAction[], source?: SymbolDisplayPart[]): CompletionEntryDetails { return { name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source }; } @@ -693,7 +505,7 @@ namespace ts.Completions { readonly isNewIdentifierLocation: boolean; readonly location: Node | undefined; readonly keywordFilters: KeywordCompletionFilters; - readonly literals: ReadonlyArray; + readonly literals: ReadonlyArray; readonly symbolToOriginInfoMap: SymbolOriginInfoMap; readonly recommendedCompletion: Symbol | undefined; readonly previousToken: Node | undefined; @@ -701,7 +513,7 @@ namespace ts.Completions { } type Request = { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag }; - const enum CompletionKind { + export const enum CompletionKind { ObjectPropertyDeclaration, Global, PropertyAccess, @@ -755,28 +567,6 @@ namespace ts.Completions { } } - function getContextualTypeFromParent(node: Expression, checker: TypeChecker): Type | undefined { - const { parent } = node; - switch (parent.kind) { - case SyntaxKind.NewExpression: - return checker.getContextualType(parent as NewExpression); - case SyntaxKind.BinaryExpression: { - const { left, operatorToken, right } = parent as BinaryExpression; - return isEqualityOperatorKind(operatorToken.kind) - ? checker.getTypeAtLocation(node === right ? left : right) - : checker.getContextualType(node); - } - case SyntaxKind.CaseClause: - return (parent as CaseClause).expression === node ? getSwitchedType(parent as CaseClause, checker) : undefined; - default: - return checker.getContextualType(node); - } - } - - function getSwitchedType(caseClause: CaseClause, checker: TypeChecker): Type | undefined { - return checker.getTypeAtLocation(caseClause.parent.parent.expression); - } - function getFirstSymbolInChain(symbol: Symbol, enclosingDeclaration: Node, checker: TypeChecker): Symbol | undefined { const chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ SymbolFlags.All, /*useOnlyExternalAliasing*/ false); if (chain) return first(chain); @@ -1125,7 +915,7 @@ namespace ts.Completions { } else { for (const symbol of type.getApparentProperties()) { - if (typeChecker.isValidPropertyAccessForCompletions(node.kind === SyntaxKind.ImportType ? node : node.parent, type, symbol)) { + if (typeChecker.isValidPropertyAccessForCompletions(node.kind === SyntaxKind.ImportType ? node : node.parent, type, symbol)) { addPropertySymbol(symbol); } } @@ -1183,9 +973,9 @@ namespace ts.Completions { function tryGetJsxCompletionSymbols(): GlobalsSearch { const jsxContainer = tryGetContainingJsxElement(contextToken); // Cursor is inside a JSX self-closing element or opening element - const attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + const attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); if (!attrsType) return GlobalsSearch.Continue; - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer!.attributes.properties); + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer!.attributes, typeChecker), jsxContainer!.attributes.properties); completionKind = CompletionKind.MemberLike; isNewIdentifierLocation = false; return GlobalsSearch.Success; @@ -1233,7 +1023,8 @@ namespace ts.Completions { const scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - const symbolMeanings = SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace | SymbolFlags.Alias; + const isTypeOnly = isTypeOnlyCompletion(); + const symbolMeanings = (isTypeOnly ? SymbolFlags.None : SymbolFlags.Value) | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias; symbols = Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); @@ -1261,12 +1052,10 @@ namespace ts.Completions { if (sourceFile.externalModuleIndicator) return true; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (programContainsEs6Modules(program)) return true; - // For JS, stay on the safe side. - if (isUncheckedFile) return false; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. - return compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); + if (compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) return true; + // If some file is using ES6 modules, assume that it's OK to add more. + return programContainsEs6Modules(program); } function isSnippetScope(scopeNode: Node): boolean { @@ -1282,9 +1071,9 @@ namespace ts.Completions { } function filterGlobalCompletion(symbols: Symbol[]): void { - const isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - const allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); - if (isTypeOnlyCompletion) keywordFilters = KeywordCompletionFilters.TypeKeywords; + const isTypeOnly = isTypeOnlyCompletion(); + const allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); + if (isTypeOnly) keywordFilters = KeywordCompletionFilters.TypeKeywords; filterMutate(symbols, symbol => { if (!isSourceFile(location)) { @@ -1303,7 +1092,7 @@ namespace ts.Completions { if (allowTypes) { // Its a type, but you can reach it by namespace.type as well const symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); - if (symbolAllowedAsType || isTypeOnlyCompletion) { + if (symbolAllowedAsType || isTypeOnly) { return symbolAllowedAsType; } } @@ -1314,6 +1103,10 @@ namespace ts.Completions { }); } + function isTypeOnlyCompletion(): boolean { + return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + } + function isContextTokenValueLocation(contextToken: Node) { return contextToken && contextToken.kind === SyntaxKind.TypeOfKeyword && @@ -1341,23 +1134,13 @@ namespace ts.Completions { return false; } - function symbolCanBeReferencedAtTypeLocation(symbol: Symbol): boolean { - symbol = symbol.exportSymbol || symbol; - - // This is an alias, follow what it aliases - symbol = skipAlias(symbol, typeChecker); - - if (symbol.flags & SymbolFlags.Type) { - return true; - } - - if (symbol.flags & SymbolFlags.Module) { - const exportedSymbols = typeChecker.getExportsOfModule(symbol); - // If the exported symbols contains type, - // symbol can be referenced at locations where type is allowed - return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); - } - return false; + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol: Symbol, seenModules = createMap()): boolean { + const sym = skipAlias(symbol.exportSymbol || symbol, typeChecker); + return !!(sym.flags & SymbolFlags.Type) || + !!(sym.flags & SymbolFlags.Module) && + addToSeen(seenModules, getSymbolId(sym)) && + typeChecker.getExportsOfModule(sym).some(e => symbolCanBeReferencedAtTypeLocation(e, seenModules)); } function getSymbolsFromOtherSourceFileExports(symbols: Symbol[], tokenText: string, target: ScriptTarget): void { @@ -1380,7 +1163,7 @@ namespace ts.Completions { if (resolvedModuleSymbol !== moduleSymbol && // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - resolvedModuleSymbol.declarations.some(d => !!d.getSourceFile().externalModuleIndicator)) { + some(resolvedModuleSymbol.declarations, d => !!d.getSourceFile().externalModuleIndicator)) { symbols.push(resolvedModuleSymbol); symbolToOriginInfoMap[getSymbolId(resolvedModuleSymbol)] = { kind: SymbolOriginInfoKind.Export, moduleSymbol, isDefaultExport: false }; } @@ -1390,14 +1173,16 @@ namespace ts.Completions { // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details. // This is just to avoid adding duplicate completion entries. // - // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. - // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + // If `symbol.parent !== ...`, this is an `export * from "foo"` re-export. Those don't create new symbols. if (typeChecker.getMergedSymbol(symbol.parent!) !== resolvedModuleSymbol - || some(symbol.declarations, d => isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier)) { + || some(symbol.declarations, d => + // If `!!d.name.originalKeywordKind`, this is `export { _break as break };` -- skip this and prefer the keyword completion. + // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + isExportSpecifier(d) && (d.propertyName ? isIdentifierANonContextualKeyword(d.name) : !!d.parent.parent.moduleSpecifier))) { continue; } - const isDefaultExport = symbol.name === InternalSymbolName.Default; + const isDefaultExport = symbol.escapedName === InternalSymbolName.Default; if (isDefaultExport) { symbol = getLocalSymbolForExportDefault(symbol) || symbol; } @@ -1696,6 +1481,9 @@ namespace ts.Completions { break; case SyntaxKind.AsteriskToken: return isMethodDeclaration(parent) ? tryCast(parent.parent, isObjectLiteralExpression) : undefined; + case SyntaxKind.Identifier: + return (contextToken as Identifier).text === "async" && isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } @@ -1749,6 +1537,7 @@ namespace ts.Completions { if (contextToken) { const parent = contextToken.parent; switch (contextToken.kind) { + case SyntaxKind.GreaterThanToken: // End of a type argument list case SyntaxKind.LessThanSlashToken: case SyntaxKind.SlashToken: case SyntaxKind.Identifier: @@ -1757,6 +1546,10 @@ namespace ts.Completions { case SyntaxKind.JsxAttribute: case SyntaxKind.JsxSpreadAttribute: if (parent && (parent.kind === SyntaxKind.JsxSelfClosingElement || parent.kind === SyntaxKind.JsxOpeningElement)) { + if (contextToken.kind === SyntaxKind.GreaterThanToken) { + const precedingToken = findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); + if (!(parent as JsxOpeningLikeElement).typeArguments || (precedingToken && precedingToken.kind === SyntaxKind.SlashToken)) break; + } return parent; } else if (parent.kind === SyntaxKind.JsxAttribute) { @@ -1911,7 +1704,6 @@ namespace ts.Completions { // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { case SyntaxKind.AbstractKeyword: - case SyntaxKind.AsyncKeyword: case SyntaxKind.ClassKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DeclareKeyword: @@ -1926,6 +1718,8 @@ namespace ts.Completions { case SyntaxKind.VarKeyword: case SyntaxKind.YieldKeyword: return true; + case SyntaxKind.AsyncKeyword: + return isPropertyDeclaration(contextToken.parent); } return isDeclarationName(contextToken) @@ -2129,7 +1923,7 @@ namespace ts.Completions { case KeywordCompletionFilters.None: return false; case KeywordCompletionFilters.All: - return kind === SyntaxKind.AsyncKeyword || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === SyntaxKind.DeclareKeyword || kind === SyntaxKind.ModuleKeyword + return kind === SyntaxKind.AsyncKeyword || SyntaxKind.AwaitKeyword || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === SyntaxKind.DeclareKeyword || kind === SyntaxKind.ModuleKeyword || isTypeKeyword(kind) && kind !== SyntaxKind.UndefinedKeyword; case KeywordCompletionFilters.ClassElementKeywords: return isClassMemberCompletionKeyword(kind); @@ -2165,32 +1959,20 @@ namespace ts.Completions { } function isFunctionLikeBodyKeyword(kind: SyntaxKind) { - return kind === SyntaxKind.AsyncKeyword || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + return kind === SyntaxKind.AsyncKeyword || kind === SyntaxKind.AwaitKeyword || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node: Node): SyntaxKind { return isIdentifier(node) ? node.originalKeywordKind || SyntaxKind.Unknown : node.kind; } - function isEqualityOperatorKind(kind: SyntaxKind): kind is EqualityOperator { - switch (kind) { - case SyntaxKind.EqualsEqualsEqualsToken: - case SyntaxKind.EqualsEqualsToken: - case SyntaxKind.ExclamationEqualsEqualsToken: - case SyntaxKind.ExclamationEqualsToken: - return true; - default: - return false; - } - } - /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node: Node, position: number): JSDocTag | undefined { const jsdoc = findAncestor(node, isJSDoc); return jsdoc && jsdoc.tags && (rangeContainsPosition(jsdoc, position) ? findLast(jsdoc.tags, tag => tag.pos < position) : undefined); } - function getPropertiesForObjectExpression(contextualType: Type, obj: ObjectLiteralExpression, checker: TypeChecker): Symbol[] { + function getPropertiesForObjectExpression(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes, checker: TypeChecker): Symbol[] { return contextualType.isUnion() ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(memberType => // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. @@ -2251,11 +2033,7 @@ namespace ts.Completions { return node.parent && isClassOrTypeElement(node.parent) && isObjectTypeDeclaration(node.parent.parent); } - function hasIndexSignature(type: Type): boolean { - return !!type.getStringIndexType() || !!type.getNumberIndexType(); - } - - function isValidTrigger(sourceFile: SourceFile, triggerCharacter: CompletionsTriggerCharacter, contextToken: Node, position: number): boolean { + function isValidTrigger(sourceFile: SourceFile, triggerCharacter: CompletionsTriggerCharacter, contextToken: Node | undefined, position: number): boolean { switch (triggerCharacter) { case ".": case "@": @@ -2264,14 +2042,14 @@ namespace ts.Completions { case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === SyntaxKind.LessThanToken && (!isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === SyntaxKind.LessThanToken && (!isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return isStringLiteralLike(contextToken) + return !!contextToken && (isStringLiteralLike(contextToken) ? !!tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === SyntaxKind.SlashToken && isJsxClosingElement(contextToken.parent); + : contextToken.kind === SyntaxKind.SlashToken && isJsxClosingElement(contextToken.parent)); default: return Debug.assertNever(triggerCharacter); } @@ -2280,16 +2058,4 @@ namespace ts.Completions { function binaryExpressionMayBeOpenTag({ left }: BinaryExpression): boolean { return nodeIsMissing(left); } - - function isStringLiteralOrTemplate(node: Node): node is StringLiteralLike | TemplateExpression | TaggedTemplateExpression { - switch (node.kind) { - case SyntaxKind.StringLiteral: - case SyntaxKind.NoSubstitutionTemplateLiteral: - case SyntaxKind.TemplateExpression: - case SyntaxKind.TaggedTemplateExpression: - return true; - default: - return false; - } - } } diff --git a/src/services/documentRegistry.ts b/src/services/documentRegistry.ts index 7a21cebb4f3..4744f25ac7b 100644 --- a/src/services/documentRegistry.ts +++ b/src/services/documentRegistry.ts @@ -121,18 +121,6 @@ namespace ts { const buckets = createMap>(); const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey { - return `_${settings.target}|${settings.module}|${settings.noResolve}|${settings.jsx}|${settings.allowJs}|${settings.baseUrl}|${JSON.stringify(settings.typeRoots)}|${JSON.stringify(settings.rootDirs)}|${JSON.stringify(settings.paths)}`; - } - - function getBucketForCompilationSettings(key: DocumentRegistryBucketKey, createIfMissing: boolean): Map { - let bucket = buckets.get(key); - if (!bucket && createIfMissing) { - buckets.set(key, bucket = createMap()); - } - return bucket!; // TODO: GH#18217 - } - function reportStats() { const bucketInfoArray = arrayFrom(buckets.keys()).filter(name => name && name.charAt(0) === "_").map(name => { const entries = buckets.get(name)!; @@ -182,7 +170,7 @@ namespace ts { acquiring: boolean, scriptKind?: ScriptKind): SourceFile { - const bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); + const bucket = getOrUpdate>(buckets, key, createMap); let entry = bucket.get(path); const scriptTarget = scriptKind === ScriptKind.JSON ? ScriptTarget.JSON : compilationSettings.target || ScriptTarget.ES5; if (!entry && externalCache) { @@ -242,9 +230,7 @@ namespace ts { } function releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void { - const bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); - Debug.assert(bucket !== undefined); - + const bucket = Debug.assertDefined(buckets.get(key)); const entry = bucket.get(path)!; entry.languageServiceRefCount--; @@ -273,4 +259,8 @@ namespace ts { getKeyForCompilationSettings }; } + + function getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey { + return sourceFileAffectingCompilerOptions.map(option => getCompilerOptionValue(settings, option)).join("|") as DocumentRegistryBucketKey; + } } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index b857a05dffb..54202322260 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -1,8 +1,8 @@ /* @internal */ namespace ts.FindAllReferences { export interface SymbolAndEntries { - definition: Definition | undefined; - references: Entry[]; + readonly definition: Definition | undefined; + readonly references: ReadonlyArray; } export const enum DefinitionKind { Symbol, Label, Keyword, This, String } @@ -13,19 +13,20 @@ namespace ts.FindAllReferences { | { readonly type: DefinitionKind.This; readonly node: Node } | { readonly type: DefinitionKind.String; readonly node: StringLiteral }; + export const enum EntryKind { Span, Node, StringLiteral, SearchedLocalFoundProperty, SearchedPropertyFoundLocal } + export type NodeEntryKind = EntryKind.Node | EntryKind.StringLiteral | EntryKind.SearchedLocalFoundProperty | EntryKind.SearchedPropertyFoundLocal; export type Entry = NodeEntry | SpanEntry; export interface NodeEntry { - type: "node"; - node: Node; - isInString?: true; + readonly kind: NodeEntryKind; + readonly node: Node; } export interface SpanEntry { - type: "span"; - fileName: string; - textSpan: TextSpan; + readonly kind: EntryKind.Span; + readonly fileName: string; + readonly textSpan: TextSpan; } - export function nodeEntry(node: Node, isInString?: true): NodeEntry { - return { type: "node", node: (node as NamedDeclaration).name || node, isInString }; + export function nodeEntry(node: Node, kind: NodeEntryKind = EntryKind.Node): NodeEntry { + return { kind, node: (node as NamedDeclaration).name || node }; } export interface Options { @@ -33,11 +34,16 @@ namespace ts.FindAllReferences { readonly findInComments?: boolean; /** * True if we are renaming the symbol. - * If so, we will find fewer references -- if it is referenced by several different names, we sill only find references for the original name. + * If so, we will find fewer references -- if it is referenced by several different names, we still only find references for the original name. */ readonly isForRename?: boolean; /** True if we are searching for implementations. We will have a different method of adding references if so. */ readonly implementations?: boolean; + /** + * True to opt in for enhanced renaming of shorthand properties and import/export specifiers. + * Default is false for backwards compatibility. + */ + readonly providePrefixAndSuffixTextForRename?: boolean; } export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined { @@ -59,7 +65,7 @@ namespace ts.FindAllReferences { return map(referenceEntries, entry => toImplementationLocation(entry, checker)); } - function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number): Entry[] | undefined { + function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number): ReadonlyArray | undefined { if (node.kind === SyntaxKind.SourceFile) { return undefined; } @@ -84,15 +90,28 @@ namespace ts.FindAllReferences { } } - export function findReferencedEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number, options: Options | undefined): ReferenceEntry[] | undefined { - return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + export function findReferenceOrRenameEntries( + program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number, options: Options | undefined, + convertEntry: ToReferenceOrRenameEntry, + ): T[] | undefined { + return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), entry => convertEntry(entry, node, program.getTypeChecker())); } - export function getReferenceEntriesForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlyMap = arrayToSet(sourceFiles, f => f.fileName)): Entry[] | undefined { + export type ToReferenceOrRenameEntry = (entry: Entry, originalNode: Node, checker: TypeChecker) => T; + + export function getReferenceEntriesForNode( + position: number, + node: Node, + program: Program, + sourceFiles: ReadonlyArray, + cancellationToken: CancellationToken, + options: Options = {}, + sourceFilesSet: ReadonlyMap = arrayToSet(sourceFiles, f => f.fileName), + ): ReadonlyArray | undefined { return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); } - function flattenEntries(referenceSymbols: SymbolAndEntries[] | undefined): Entry[] | undefined { + function flattenEntries(referenceSymbols: SymbolAndEntries[] | undefined): ReadonlyArray | undefined { return referenceSymbols && flatMap(referenceSymbols, r => r.references); } @@ -137,32 +156,73 @@ namespace ts.FindAllReferences { function getDefinitionKindAndDisplayParts(symbol: Symbol, checker: TypeChecker, node: Node): { displayParts: SymbolDisplayPart[], kind: ScriptElementKind } { const meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol); - const enclosingDeclaration = firstOrUndefined(symbol.declarations) || node; + const enclosingDeclaration = symbol.declarations && firstOrUndefined(symbol.declarations) || node; const { displayParts, symbolKind } = SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); return { displayParts, kind: symbolKind }; } - function toReferenceEntry(entry: Entry): ReferenceEntry { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; - } + export function toRenameLocation(entry: Entry, originalNode: Node, checker: TypeChecker, providePrefixAndSuffixText: boolean): RenameLocation { + return { ...entryToDocumentSpan(entry), ...(providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker)) }; + } - const { node, isInString } = entry; - const sourceFile = node.getSourceFile(); + export function toReferenceEntry(entry: Entry): ReferenceEntry { + const { textSpan, fileName } = entryToDocumentSpan(entry); + if (entry.kind === EntryKind.Span) { + return { textSpan, fileName, isWriteAccess: false, isDefinition: false }; + } + const { kind, node } = entry; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan, + fileName, isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === SyntaxKind.DefaultKeyword || !!getDeclarationFromName(node) || isLiteralComputedPropertyDeclarationName(node), - isInString, + isInString: kind === EntryKind.StringLiteral ? true : undefined, }; } + function entryToDocumentSpan(entry: Entry): DocumentSpan { + if (entry.kind === EntryKind.Span) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + const sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + + interface PrefixAndSuffix { readonly prefixText?: string; readonly suffixText?: string; } + function getPrefixAndSuffixText(entry: Entry, originalNode: Node, checker: TypeChecker): PrefixAndSuffix { + if (entry.kind !== EntryKind.Span && isIdentifier(originalNode)) { + const { node, kind } = entry; + const name = originalNode.text; + const isShorthandAssignment = isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || isObjectBindingElementWithoutPropertyName(node.parent)) { + const prefixColon: PrefixAndSuffix = { prefixText: name + ": " }; + const suffixColon: PrefixAndSuffix = { suffixText: ": " + name }; + return kind === EntryKind.SearchedLocalFoundProperty ? prefixColon + : kind === EntryKind.SearchedPropertyFoundLocal ? suffixColon + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : isShorthandAssignment ? suffixColon : prefixColon; + } + else if (isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + // If the original symbol was using this alias, just rename the alias. + const originalSymbol = isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); + return contains(originalSymbol!.declarations, entry.node.parent) ? { prefixText: name + " as " } : emptyOptions; + } + else if (isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) { + return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name }; + } + } + + return emptyOptions; + } + function toImplementationLocation(entry: Entry, checker: TypeChecker): ImplementationLocation { - if (entry.type === "node") { + if (entry.kind !== EntryKind.Span) { const { node } = entry; const sourceFile = node.getSourceFile(); return { textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName, ...implementationKindDisplayParts(node, checker) }; @@ -196,18 +256,18 @@ namespace ts.FindAllReferences { } export function toHighlightSpan(entry: Entry): { fileName: string, span: HighlightSpan } { - if (entry.type === "span") { + if (entry.kind === EntryKind.Span) { const { fileName, textSpan } = entry; return { fileName, span: { textSpan, kind: HighlightSpanKind.reference } }; } - const { node, isInString } = entry; + const { node, kind } = entry; const sourceFile = node.getSourceFile(); const writeAccess = isWriteAccessForReference(node); const span: HighlightSpan = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference, - isInString + isInString: kind === EntryKind.StringLiteral ? true : undefined, }; return { fileName: sourceFile.fileName, span }; } @@ -316,6 +376,10 @@ namespace ts.FindAllReferences.Core { return !options.implementations && isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } + if (symbol.escapedName === InternalSymbolName.ExportEquals) { + return getReferencedSymbolsForModule(program, symbol.parent!, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } + let moduleReferences: SymbolAndEntries[] = emptyArray; const moduleSourceFile = isModuleSymbol(symbol); let referencedNode: Node | undefined = node; @@ -348,11 +412,11 @@ namespace ts.FindAllReferences.Core { } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return nodeEntry(reference.literal); } else { return { - type: "span", + kind: EntryKind.Span, fileName: reference.referencingFile.fileName, textSpan: createTextSpanFromRange(reference.ref), }; @@ -366,7 +430,7 @@ namespace ts.FindAllReferences.Core { break; case SyntaxKind.ModuleDeclaration: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: (decl as ModuleDeclaration).name }); + references.push(nodeEntry((decl as ModuleDeclaration).name)); } break; default: @@ -375,6 +439,22 @@ namespace ts.FindAllReferences.Core { } } + const exported = symbol.exports!.get(InternalSymbolName.ExportEquals); + if (exported) { + for (const decl of exported.declarations) { + const sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + // At `module.exports = ...`, reference node is `module` + const node = isBinaryExpression(decl) && isPropertyAccessExpression(decl.left) + ? decl.left.expression + : isExportAssignment(decl) + ? Debug.assertDefined(findChildOfKind(decl, SyntaxKind.ExportKeyword, sourceFile)) + : getNameOfDeclaration(decl) || decl; + references.push(nodeEntry(node)); + } + } + } + return references.length ? [{ definition: { type: DefinitionKind.Symbol, symbol }, references }] : emptyArray; } @@ -408,8 +488,8 @@ namespace ts.FindAllReferences.Core { } /** Core find-all-references algorithm for a normal symbol. */ - function getReferencedSymbolsForSymbol(symbol: Symbol, node: Node | undefined, sourceFiles: ReadonlyArray, sourceFilesSet: ReadonlyMap, checker: TypeChecker, cancellationToken: CancellationToken, options: Options): SymbolAndEntries[] { - symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + function getReferencedSymbolsForSymbol(originalSymbol: Symbol, node: Node | undefined, sourceFiles: ReadonlyArray, sourceFilesSet: ReadonlyMap, checker: TypeChecker, cancellationToken: CancellationToken, options: Options): SymbolAndEntries[] { + const symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; // Compute the meaning from the location and the symbol it references const searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : SemanticMeaning.All; @@ -417,12 +497,17 @@ namespace ts.FindAllReferences.Core { const result: SymbolAndEntries[] = []; const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : SpecialSearchKind.None, checker, cancellationToken, searchMeaning, options, result); - if (node && node.kind === SyntaxKind.DefaultKeyword) { + const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : find(symbol.declarations, isExportSpecifier); + if (exportSpecifier) { + // When renaming at an export specifier, rename the export and not the thing being exported. + getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); + } + else if (node && node.kind === SyntaxKind.DefaultKeyword) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: ExportKind.Default }, state); } else { - const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). @@ -458,16 +543,11 @@ namespace ts.FindAllReferences.Core { } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifierOrUnion(symbol: Symbol, node: Node, checker: TypeChecker): Symbol | undefined { + function skipPastExportOrImportSpecifierOrUnion(symbol: Symbol, node: Node, checker: TypeChecker, useLocalSymbolForExportSpecifier: boolean): Symbol | undefined { const { parent } = node; - if (isExportSpecifier(parent)) { + if (isExportSpecifier(parent) && useLocalSymbolForExportSpecifier) { return getLocalSymbolForExportSpecifier(node as Identifier, symbol, parent, checker); } - if (isImportSpecifier(parent) && parent.propertyName === node) { - // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. - return checker.getImmediateAliasedSymbol(symbol)!; - } - // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. return firstDefined(symbol.declarations, decl => { if (!decl.parent) { @@ -581,21 +661,21 @@ namespace ts.FindAllReferences.Core { * Callback to add references for a particular searched symbol. * This initializes a reference group, so only call this if you will add at least one reference. */ - referenceAdder(searchSymbol: Symbol): (node: Node) => void { + referenceAdder(searchSymbol: Symbol): (node: Node, kind?: NodeEntryKind) => void { const symbolId = getSymbolId(searchSymbol); let references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; this.result.push({ definition: { type: DefinitionKind.Symbol, symbol: searchSymbol }, references }); } - return node => references.push(nodeEntry(node)); + return (node, kind) => references.push(nodeEntry(node, kind)); } /** Add a reference with no associated definition. */ addStringOrCommentReference(fileName: string, textSpan: TextSpan): void { this.result.push({ definition: undefined, - references: [{ type: "span", fileName, textSpan }] + references: [{ kind: EntryKind.Span, fileName, textSpan }] }); } @@ -669,7 +749,8 @@ namespace ts.FindAllReferences.Core { } for (const indirectUser of indirectUsers) { for (const node of getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName)) { - if (isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) { + // Import specifiers should be handled by importSearches + if (isIdentifier(node) && !isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { cb(node); } } @@ -682,7 +763,7 @@ namespace ts.FindAllReferences.Core { // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` if (!isIdentifier(singleRef)) return false; // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - return !((isExportSpecifier(singleRef.parent) || isImportSpecifier(singleRef.parent)) && singleRef.escapedText === InternalSymbolName.Default); + return !(isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === InternalSymbolName.Default); } // Go to the symbol we imported from and find references for it. @@ -707,21 +788,6 @@ namespace ts.FindAllReferences.Core { : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol: Symbol): BindingElement & { name: Identifier } | undefined { - const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); - if (bindingElement && - bindingElement.parent.kind === SyntaxKind.ObjectBindingPattern && - isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement as BindingElement & { name: Identifier }; - } - } - - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol, checker: TypeChecker): Symbol | undefined { - const bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && getPropertySymbolFromBindingElement(checker, bindingElement); - } - /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -754,7 +820,7 @@ namespace ts.FindAllReferences.Core { // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(isObjectBindingElementWithoutPropertyName)) { return undefined; } @@ -802,7 +868,9 @@ namespace ts.FindAllReferences.Core { } export function eachSymbolReferenceInFile(definition: Identifier, checker: TypeChecker, sourceFile: SourceFile, cb: (token: Identifier) => T): T | undefined { - const symbol = checker.getSymbolAtLocation(definition); + const symbol = isParameterPropertyDeclaration(definition.parent) + ? first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) + : checker.getSymbolAtLocation(definition); if (!symbol) return undefined; for (const token of getPossibleSymbolReferenceNodes(sourceFile, symbol.name)) { if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue; @@ -891,7 +959,7 @@ namespace ts.FindAllReferences.Core { case SyntaxKind.StringLiteral: { const str = node as StringLiteral; - return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || (isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && str.text.length === searchSymbolName.length; } @@ -999,17 +1067,27 @@ namespace ts.FindAllReferences.Core { getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation: Identifier, referenceSymbol: Symbol, exportSpecifier: ExportSpecifier, search: Search, state: State, addReferencesHere: boolean): void { + function getReferencesAtExportSpecifier( + referenceLocation: Identifier, + referenceSymbol: Symbol, + exportSpecifier: ExportSpecifier, + search: Search, + state: State, + addReferencesHere: boolean, + alwaysGetReferences?: boolean, + ): void { + Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled"); + const { parent, propertyName, name } = exportSpecifier; const exportDeclaration = parent.parent; const localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); - if (!search.includes(localSymbol)) { + if (!alwaysGetReferences && !search.includes(localSymbol)) { return; } if (!propertyName) { // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) - if (!(state.options.isForRename && name.escapedText === InternalSymbolName.Default)) { + if (!(state.options.isForRename && (name.escapedText === InternalSymbolName.Default))) { addRef(); } } @@ -1021,7 +1099,7 @@ namespace ts.FindAllReferences.Core { } if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { - addReference(name, referenceSymbol, state); + addReference(name, Debug.assertDefined(exportSpecifier.symbol), state); } } else { @@ -1031,15 +1109,15 @@ namespace ts.FindAllReferences.Core { } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!(referenceLocation === propertyName && state.options.isForRename)) { + if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) { const exportKind = referenceLocation.originalKeywordKind === SyntaxKind.DefaultKeyword ? ExportKind.Default : ExportKind.Named; - const exportInfo = getExportInfo(referenceSymbol, exportKind, state.checker); - if (!exportInfo) return Debug.fail(); - searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); + const exportSymbol = Debug.assertDefined(exportSpecifier.symbol); + const exportInfo = Debug.assertDefined(getExportInfo(exportSymbol, exportKind, state.checker)); + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. - if (search.comingFrom !== ImportExport.Export && exportDeclaration.moduleSpecifier && !propertyName) { + if (search.comingFrom !== ImportExport.Export && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { const imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (imported) searchForImportedSymbol(imported, state); } @@ -1074,12 +1152,11 @@ namespace ts.FindAllReferences.Core { const { symbol } = importOrExport; if (importOrExport.kind === ImportExport.Import) { - if (!state.options.isForRename || importOrExport.isNamedImport) { + if (!(isForRenameWithPrefixAndSuffixText(state.options))) { searchForImportedSymbol(symbol, state); } } else { - // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching. searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); } } @@ -1099,13 +1176,14 @@ namespace ts.FindAllReferences.Core { } } - function addReference(referenceLocation: Node, relatedSymbol: Symbol, state: State): void { - const addRef = state.referenceAdder(relatedSymbol); + function addReference(referenceLocation: Node, relatedSymbol: Symbol | RelatedSymbol, state: State): void { + const { kind, symbol } = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }; + const addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } @@ -1357,6 +1435,10 @@ namespace ts.FindAllReferences.Core { return [{ definition: { type: DefinitionKind.Symbol, symbol: searchSpaceNode.symbol }, references }]; } + function isParameterName(node: Node) { + return node.kind === SyntaxKind.Identifier && node.parent.kind === SyntaxKind.Parameter && (node.parent).name === node; + } + function getReferencesForThisKeyword(thisOrSuperKeyword: Node, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken): SymbolAndEntries[] | undefined { let searchSpaceNode = getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -1379,7 +1461,7 @@ namespace ts.FindAllReferences.Core { searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; case SyntaxKind.SourceFile: - if (isExternalModule(searchSpaceNode)) { + if (isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } // falls through @@ -1412,7 +1494,7 @@ namespace ts.FindAllReferences.Core { // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (getModifierFlags(container) & ModifierFlags.Static) === staticFlag; case SyntaxKind.SourceFile: - return container.kind === SyntaxKind.SourceFile && !isExternalModule(container); + return container.kind === SyntaxKind.SourceFile && !isExternalModule(container) && !isParameterName(node); } }); }).map(n => nodeEntry(n)); @@ -1428,7 +1510,7 @@ namespace ts.FindAllReferences.Core { const references = flatMap(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), ref => - isStringLiteral(ref) && ref.text === node.text ? nodeEntry(ref, /*isInString*/ true) : undefined); + isStringLiteral(ref) && ref.text === node.text ? nodeEntry(ref, EntryKind.StringLiteral) : undefined); }); return [{ @@ -1439,35 +1521,21 @@ namespace ts.FindAllReferences.Core { // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol: Symbol, location: Node, checker: TypeChecker, implementations: boolean): Symbol[] { + function populateSearchSymbolSet(symbol: Symbol, location: Node, checker: TypeChecker, isForRename: boolean, providePrefixAndSuffixText: boolean, implementations: boolean): Symbol[] { const result: Symbol[] = []; - forEachRelatedSymbol(symbol, location, checker, + forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), (sym, root, base) => { result.push(base || root || sym); }, /*allowBaseTypes*/ () => !implementations); return result; } function forEachRelatedSymbol( - symbol: Symbol, location: Node, checker: TypeChecker, - cbSymbol: (symbol: Symbol, rootSymbol?: Symbol, baseSymbol?: Symbol) => T | undefined, + symbol: Symbol, location: Node, checker: TypeChecker, isForRenamePopulateSearchSymbolSet: boolean, onlyIncludeBindingElementAtReferenceLocation: boolean, + cbSymbol: (symbol: Symbol, rootSymbol?: Symbol, baseSymbol?: Symbol, kind?: NodeEntryKind) => T | undefined, allowBaseTypes: (rootSymbol: Symbol) => boolean, ): T | undefined { const containingObjectLiteralElement = getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // 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 - const contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - const res = contextualType && firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res) return res; - - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - const propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - const res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) return res1; - /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -1479,8 +1547,29 @@ namespace ts.FindAllReferences.Core { * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - const shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - const res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + const shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, EntryKind.SearchedLocalFoundProperty); + } + + // 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 + const contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + const res = contextualType && firstDefined( + getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), + sym => fromRoot(sym, EntryKind.SearchedPropertyFoundLocal)); + if (res) return res; + + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + const propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + const res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, EntryKind.SearchedPropertyFoundLocal); + if (res1) return res1; + + const res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, EntryKind.SearchedLocalFoundProperty); if (res2) return res2; } @@ -1494,12 +1583,30 @@ namespace ts.FindAllReferences.Core { return fromRoot(symbol.flags & SymbolFlags.FunctionScopedVariable ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename when prefix and suffix text will be provided -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + let bindingElementPropertySymbol: Symbol | undefined; + if (onlyIncludeBindingElementAtReferenceLocation) { + bindingElementPropertySymbol = isObjectBindingElementWithoutPropertyName(location.parent) ? getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + } + else { + bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); + } + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, EntryKind.SearchedPropertyFoundLocal); + } - function fromRoot(sym: Symbol): T | undefined { + Debug.assert(isForRenamePopulateSearchSymbolSet); + // due to the above assert and the arguments at the uses of this function, + // (onlyIncludeBindingElementAtReferenceLocation <=> !providePrefixAndSuffixTextForRename) holds + const includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation; + + if (includeOriginalSymbolOfBindingElement) { + const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, EntryKind.SearchedPropertyFoundLocal); + } + + function fromRoot(sym: Symbol, kind?: NodeEntryKind): T | undefined { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -1507,20 +1614,32 @@ namespace ts.FindAllReferences.Core { // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return firstDefined(checker.getRootSymbols(sym), rootSymbol => - cbSymbol(sym, rootSymbol) + cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface) && allowBaseTypes(rootSymbol) - ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, base => cbSymbol(sym, rootSymbol, base)) + ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, base => cbSymbol(sym, rootSymbol, base, kind)) : undefined)); } + + function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol, checker: TypeChecker): Symbol | undefined { + const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); + if (bindingElement && isObjectBindingElementWithoutPropertyName(bindingElement)) { + return getPropertySymbolFromBindingElement(checker, bindingElement); + } + } } - function getRelatedSymbol(search: Search, referenceSymbol: Symbol, referenceLocation: Node, state: State): Symbol | undefined { + interface RelatedSymbol { + readonly symbol: Symbol; + readonly kind: NodeEntryKind | undefined; + } + function getRelatedSymbol(search: Search, referenceSymbol: Symbol, referenceLocation: Node, state: State): RelatedSymbol | undefined { const { checker } = state; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, - (sym, rootSymbol, baseSymbol) => search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, + /*onlyIncludeBindingElementAtReferenceLocation*/ !state.options.isForRename || !!state.options.providePrefixAndSuffixTextForRename, + (sym, rootSymbol, baseSymbol, kind): RelatedSymbol | undefined => search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(getCheckFlags(sym) & CheckFlags.Synthetic) ? rootSymbol : sym + ? { symbol: rootSymbol && !(getCheckFlags(sym) & CheckFlags.Synthetic) ? rootSymbol : sym, kind } : undefined, /*allowBaseTypes*/ rootSymbol => !(search.parents && !search.parents.some(parent => explicitlyInheritsFrom(rootSymbol.parent!, parent, state.inheritsFromCache, checker)))); @@ -1563,7 +1682,8 @@ namespace ts.FindAllReferences.Core { function isImplementation(node: Node): boolean { return !!(node.flags & NodeFlags.Ambient) - || (isVariableLike(node) ? hasInitializer(node) + ? !(isInterfaceDeclaration(node) || isTypeAliasDeclaration(node)) + : (isVariableLike(node) ? hasInitializer(node) : isFunctionLikeDeclaration(node) ? !!node.body : isClassLike(node) || isModuleOrEnumDeclaration(node)); } @@ -1608,4 +1728,8 @@ namespace ts.FindAllReferences.Core { t.symbol && t.symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? t.symbol : undefined); return res.length === 0 ? undefined : res; } + + function isForRenameWithPrefixAndSuffixText(options: Options) { + return options.isForRename && options.providePrefixAndSuffixTextForRename; + } } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index c1de1574e88..01c09a4989c 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -34,7 +34,7 @@ namespace ts.formatting { * the first token in line so it should be indented */ interface DynamicIndentation { - getIndentationForToken(tokenLine: number, tokenKind: SyntaxKind, container: Node): number; + getIndentationForToken(tokenLine: number, tokenKind: SyntaxKind, container: Node, suppressDelta: boolean): number; getIndentationForComment(owningToken: SyntaxKind, tokenIndentation: number, container: Node): number; /** * Indentation for open and close tokens of the node if it is block or another node that needs special indentation @@ -334,7 +334,6 @@ namespace ts.formatting { return 0; } - /* @internal */ export function formatNodeGivenIndentation(node: Node, sourceFileLike: SourceFileLike, languageVariant: LanguageVariant, initialIndentation: number, delta: number, formatContext: FormatContext): TextChange[] { const range = { pos: 0, end: sourceFileLike.text.length }; return getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, scanner => formatSpanWorker( @@ -365,16 +364,21 @@ namespace ts.formatting { function formatSpan(originalRange: TextRange, sourceFile: SourceFile, formatContext: FormatContext, requestKind: FormattingRequestKind): TextChange[] { // find the smallest node that fully wraps the range and compute the initial indentation for the node const enclosingNode = findEnclosingNode(originalRange, sourceFile); - return getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, scanner => formatSpanWorker( - originalRange, - enclosingNode, - SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), - getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), - scanner, - formatContext, - requestKind, - prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), - sourceFile)); + return getFormattingScanner( + sourceFile.text, + sourceFile.languageVariant, + getScanStartPosition(enclosingNode, originalRange, sourceFile), + originalRange.end, + scanner => formatSpanWorker( + originalRange, + enclosingNode, + SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), + getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), + scanner, + formatContext, + requestKind, + prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), + sourceFile)); } function formatSpanWorker(originalRange: TextRange, @@ -394,7 +398,7 @@ namespace ts.formatting { let previousRangeStartLine: number; let lastIndentedLine: number; - let indentationOnLastIndentedLine: number; + let indentationOnLastIndentedLine = Constants.Unknown; const edits: TextChange[] = []; @@ -413,7 +417,8 @@ namespace ts.formatting { if (!formattingScanner.isOnToken()) { const leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined!); // TODO: GH#18217 + indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, + item => processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined!)); trimTrailingWhitespacesForRemainingRange(); } } @@ -534,8 +539,18 @@ namespace ts.formatting { } return tokenIndentation !== Constants.Unknown ? tokenIndentation : indentation; }, - getIndentationForToken: (line, kind, container) => - shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation, + // if list end token is LessThanToken '>' then its delta should be explicitly suppressed + // so that LessThanToken as a binary operator can still be indented. + // foo.then + // < + // number, + // string, + // >(); + // vs + // var a = xValue + // > yValue; + getIndentationForToken: (line, kind, container, suppressDelta) => + !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation, getIndentation: () => indentation, getDelta, recomputeIndentation: lineAdded => { @@ -551,7 +566,6 @@ namespace ts.formatting { // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent case SyntaxKind.OpenBraceToken: case SyntaxKind.CloseBraceToken: - case SyntaxKind.OpenParenToken: case SyntaxKind.CloseParenToken: case SyntaxKind.ElseKeyword: case SyntaxKind.WhileKeyword: @@ -732,11 +746,23 @@ namespace ts.formatting { else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - const indentation = - computeIndentation(tokenInfo.token, startLine, Constants.Unknown, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation.indentation, indentation.delta); - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); + + let indentationOnListStartToken: number; + if (indentationOnLastIndentedLine !== Constants.Unknown) { + // scanner just processed list start token so consider last indentation as list indentation + // function foo(): { // last indentation was 0, list item will be indented based on this value + // foo: number; + // }: {}; + indentationOnListStartToken = indentationOnLastIndentedLine; + } + else { + const startLinePosition = getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile); + indentationOnListStartToken = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options); + } + + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize!); // TODO: GH#18217 } else { // consume any tokens that precede the list as child elements of 'node' using its indentation scope @@ -753,24 +779,24 @@ namespace ts.formatting { const listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== SyntaxKind.Unknown && formattingScanner.isOnToken()) { - let tokenInfo = formattingScanner.readTokenInfo(parent); + let tokenInfo: TokenInfo | undefined = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === SyntaxKind.CommaToken && isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && rangeContainsRange(parent, tokenInfo.token)) { // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true); } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation, container: Node): void { + function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation, container: Node, isListEndToken?: boolean): void { Debug.assert(rangeContainsRange(parent, currentTokenInfo.token)); const lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); @@ -808,33 +834,14 @@ namespace ts.formatting { if (indentToken) { const tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : Constants.Unknown; let indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { const commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); - - for (const triviaItem of currentTokenInfo.leadingTrivia) { - const triviaInRange = rangeContainsRange(originalRange, triviaItem); - switch (triviaItem.kind) { - case SyntaxKind.MultiLineCommentTrivia: - if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); - } - indentNextTokenOrTrivia = false; - break; - case SyntaxKind.SingleLineCommentTrivia: - if (indentNextTokenOrTrivia && triviaInRange) { - insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); - } - indentNextTokenOrTrivia = false; - break; - case SyntaxKind.NewLineTrivia: - indentNextTokenOrTrivia = true; - break; - } - } + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation, indentNextTokenOrTrivia, + item => insertIndentation(item.pos, commentIndentation, /*lineAdded*/ false)); } // indent token only if is it is in target range and does not overlap with any error ranges @@ -852,6 +859,34 @@ namespace ts.formatting { } } + function indentTriviaItems( + trivia: TextRangeWithKind[], + commentIndentation: number, + indentNextTokenOrTrivia: boolean, + indentSingleLine: (item: TextRangeWithKind) => void) { + for (const triviaItem of trivia) { + const triviaInRange = rangeContainsRange(originalRange, triviaItem); + switch (triviaItem.kind) { + case SyntaxKind.MultiLineCommentTrivia: + if (triviaInRange) { + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + } + indentNextTokenOrTrivia = false; + break; + case SyntaxKind.SingleLineCommentTrivia: + if (indentNextTokenOrTrivia && triviaInRange) { + indentSingleLine(triviaItem); + } + indentNextTokenOrTrivia = false; + break; + case SyntaxKind.NewLineTrivia: + indentNextTokenOrTrivia = true; + break; + } + } + return indentNextTokenOrTrivia; + } + function processTrivia(trivia: TextRangeWithKind[], parent: Node, contextNode: Node, dynamicIndentation: DynamicIndentation): void { for (const triviaItem of trivia) { if (isComment(triviaItem.kind) && rangeContainsRange(originalRange, triviaItem)) { @@ -861,7 +896,6 @@ namespace ts.formatting { } } - // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range: TextRangeWithKind, rangeStart: LineAndCharacter, parent: Node, @@ -1211,6 +1245,9 @@ namespace ts.formatting { if ((node).typeArguments === list) { return SyntaxKind.LessThanToken; } + break; + case SyntaxKind.TypeLiteral: + return SyntaxKind.OpenBraceToken; } return SyntaxKind.Unknown; @@ -1222,6 +1259,8 @@ namespace ts.formatting { return SyntaxKind.CloseParenToken; case SyntaxKind.LessThanToken: return SyntaxKind.GreaterThanToken; + case SyntaxKind.OpenBraceToken: + return SyntaxKind.CloseBraceToken; } return SyntaxKind.Unknown; diff --git a/src/services/formatting/formattingContext.ts b/src/services/formatting/formattingContext.ts index 0ccf87680fe..e5a1ff5d4ac 100644 --- a/src/services/formatting/formattingContext.ts +++ b/src/services/formatting/formattingContext.ts @@ -10,11 +10,11 @@ namespace ts.formatting { } export class FormattingContext { - public currentTokenSpan: TextRangeWithKind; - public nextTokenSpan: TextRangeWithKind; - public contextNode: Node; - public currentTokenParent: Node; - public nextTokenParent: Node; + public currentTokenSpan!: TextRangeWithKind; + public nextTokenSpan!: TextRangeWithKind; + public contextNode!: Node; + public currentTokenParent!: Node; + public nextTokenParent!: Node; private contextNodeAllOnSameLine: boolean | undefined; private nextNodeAllOnSameLine: boolean | undefined; @@ -26,17 +26,11 @@ namespace ts.formatting { } public updateContext(currentRange: TextRangeWithKind, currentTokenParent: Node, nextRange: TextRangeWithKind, nextTokenParent: Node, commonParent: Node) { - Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); - Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); - Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); - Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); - Debug.assert(commonParent !== undefined, "commonParent is null"); - - this.currentTokenSpan = currentRange; - this.currentTokenParent = currentTokenParent; - this.nextTokenSpan = nextRange; - this.nextTokenParent = nextTokenParent; - this.contextNode = commonParent; + this.currentTokenSpan = Debug.assertDefined(currentRange); + this.currentTokenParent = Debug.assertDefined(currentTokenParent); + this.nextTokenSpan = Debug.assertDefined(nextRange); + this.nextTokenParent = Debug.assertDefined(nextTokenParent); + this.contextNode = Debug.assertDefined(commonParent); // drop cached results this.contextNodeAllOnSameLine = undefined; diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 5e64119fcb1..b2dac950323 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -22,8 +22,8 @@ namespace ts.formatting { const binaryKeywordOperators = [SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]; const unaryPrefixOperators = [SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]; const unaryPrefixExpressions = [ - SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, - SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; + SyntaxKind.NumericLiteral, SyntaxKind.BigIntLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, + SyntaxKind.OpenBracketToken, SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; const unaryPreincrementExpressions = [SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; const unaryPostincrementExpressions = [SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]; const unaryPredecrementExpressions = [SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index c5554afd45e..0c9e7b186f7 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -66,6 +66,12 @@ namespace ts.formatting { } } + const containerList = getListByPosition(position, precedingToken.parent, sourceFile); + // use list position if the preceding token is before any list items + if (containerList && !rangeContainsRange(containerList, precedingToken)) { + return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize!; // TODO: GH#18217 + } + return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); } @@ -79,14 +85,14 @@ namespace ts.formatting { return findFirstNonWhitespaceColumn(getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); } - const startPostionOfLine = getStartPositionOfLine(previousLine, sourceFile); - const { column, character } = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options); + const startPositionOfLine = getStartPositionOfLine(previousLine, sourceFile); + const { column, character } = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options); if (column === 0) { return column; } - const firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + const firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); return firstNonWhitespaceCharacterCode === CharacterCodes.asterisk ? column - 1 : column; } @@ -124,14 +130,13 @@ namespace ts.formatting { } // check if current node is a list item - if yes, take indentation from it - let actualIndentation = getActualIndentationForListItem(current, sourceFile, options); + // do not consider parent-child line sharing yet: + // function foo(a + // | preceding node 'a' does share line with its parent but indentation is expected + const actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true); if (actualIndentation !== Value.Unknown) { return actualIndentation; } - actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); - if (actualIndentation !== Value.Unknown) { - return actualIndentation + options.indentSize!; // TODO: GH#18217 - } previous = current; current = current.parent; @@ -169,26 +174,20 @@ namespace ts.formatting { useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; } - if (useActualIndentation) { - // check if current node is a list item - if yes, take indentation from it - const actualIndentation = getActualIndentationForListItem(current, sourceFile, options); - if (actualIndentation !== Value.Unknown) { - return actualIndentation + indentationDelta; - } - } - const containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); const parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { - // try to fetch actual indentation for current node from source text - let actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); + // check if current node is a list item - if yes, take indentation from it + let actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); if (actualIndentation !== Value.Unknown) { return actualIndentation + indentationDelta; } - actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + + // try to fetch actual indentation for current node from source text + actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); if (actualIndentation !== Value.Unknown) { return actualIndentation + indentationDelta; } @@ -323,112 +322,92 @@ namespace ts.formatting { return false; } - function getListIfStartEndIsInListRange(list: NodeArray | undefined, start: number, end: number) { - return list && rangeContainsStartEnd(list, start, end) ? list : undefined; + export function getContainingList(node: Node, sourceFile: SourceFile): NodeArray | undefined { + return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile); } - export function getContainingList(node: Node, sourceFile: SourceFile): NodeArray | undefined { - if (node.parent) { - const { end } = node; - switch (node.parent.kind) { - case SyntaxKind.TypeReference: - return getListIfStartEndIsInListRange((node.parent).typeArguments, node.getStart(sourceFile), end); - case SyntaxKind.ObjectLiteralExpression: - return (node.parent).properties; - case SyntaxKind.ArrayLiteralExpression: - return (node.parent).elements; - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - case SyntaxKind.CallSignature: - case SyntaxKind.Constructor: - case SyntaxKind.ConstructorType: - case SyntaxKind.ConstructSignature: { - const start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange((node.parent).typeParameters, start, end) || - getListIfStartEndIsInListRange((node.parent).parameters, start, end); - } - case SyntaxKind.ClassDeclaration: - case SyntaxKind.ClassExpression: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.TypeAliasDeclaration: - case SyntaxKind.JSDocTemplateTag: { - const { typeParameters } = node.parent; - return getListIfStartEndIsInListRange(typeParameters, node.getStart(sourceFile), end); - } - case SyntaxKind.NewExpression: - case SyntaxKind.CallExpression: { - const start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange((node.parent).typeArguments, start, end) || - getListIfStartEndIsInListRange((node.parent).arguments, start, end); - } - case SyntaxKind.VariableDeclarationList: - return getListIfStartEndIsInListRange((node.parent).declarations, node.getStart(sourceFile), end); - case SyntaxKind.NamedImports: - case SyntaxKind.NamedExports: - return getListIfStartEndIsInListRange((node.parent).elements, node.getStart(sourceFile), end); - case SyntaxKind.ObjectBindingPattern: - case SyntaxKind.ArrayBindingPattern: - return getListIfStartEndIsInListRange((node.parent).elements, node.getStart(sourceFile), end); + function getListByPosition(pos: number, node: Node, sourceFile: SourceFile): NodeArray | undefined { + return node && getListByRange(pos, pos, node, sourceFile); + } + + function getListByRange(start: number, end: number, node: Node, sourceFile: SourceFile): NodeArray | undefined { + switch (node.kind) { + case SyntaxKind.TypeReference: + return getList((node).typeArguments); + case SyntaxKind.ObjectLiteralExpression: + return getList((node).properties); + case SyntaxKind.ArrayLiteralExpression: + return getList((node).elements); + case SyntaxKind.TypeLiteral: + return getList((node).members); + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.CallSignature: + case SyntaxKind.Constructor: + case SyntaxKind.ConstructorType: + case SyntaxKind.ConstructSignature: + return getList((node).typeParameters) || getList((node).parameters); + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.JSDocTemplateTag: + return getList((node).typeParameters); + case SyntaxKind.NewExpression: + case SyntaxKind.CallExpression: + return getList((node).typeArguments) || getList((node).arguments); + case SyntaxKind.VariableDeclarationList: + return getList((node).declarations); + case SyntaxKind.NamedImports: + case SyntaxKind.NamedExports: + return getList((node).elements); + case SyntaxKind.ObjectBindingPattern: + case SyntaxKind.ArrayBindingPattern: + return getList((node).elements); + } + + function getList(list: NodeArray | undefined): NodeArray | undefined { + return list && rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined; + } + } + + function getVisualListRange(node: Node, list: TextRange, sourceFile: SourceFile): TextRange { + const children = node.getChildren(sourceFile); + for (let i = 1; i < children.length - 1; i++) { + if (children[i].pos === list.pos && children[i].end === list.end) { + return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) }; } } - return undefined; + return list; } - function getActualIndentationForListItem(node: Node, sourceFile: SourceFile, options: EditorSettings): number { + function getActualIndentationForListStartLine(list: NodeArray, sourceFile: SourceFile, options: EditorSettings): number { + if (!list) { + return Value.Unknown; + } + return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); + } + + function getActualIndentationForListItem(node: Node, sourceFile: SourceFile, options: EditorSettings, listIndentsChild: boolean): number { + if (node.parent && node.parent.kind === SyntaxKind.VariableDeclarationList) { + // VariableDeclarationList has no wrapping tokens + return Value.Unknown; + } const containingList = getContainingList(node, sourceFile); if (containingList) { const index = containingList.indexOf(node); if (index !== -1) { - return deriveActualIndentationFromList(containingList, index, sourceFile, options); - } - } - return Value.Unknown; - } - - function getLineIndentationWhenExpressionIsInMultiLine(node: Node, sourceFile: SourceFile, options: EditorSettings): number { - // actual indentation should not be used when: - // - node is close parenthesis - this is the end of the expression - if (node.kind === SyntaxKind.CloseParenToken) { - return Value.Unknown; - } - - if (node.parent && isCallOrNewExpression(node.parent) && node.parent.expression !== node) { - const fullCallOrNewExpression = node.parent.expression; - const startingExpression = getStartingExpression(fullCallOrNewExpression); - - if (fullCallOrNewExpression === startingExpression) { - return Value.Unknown; - } - - const fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); - const startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); - - if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { - return Value.Unknown; - } - - return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); - } - - return Value.Unknown; - - function getStartingExpression(node: Expression) { - while (true) { - switch (node.kind) { - case SyntaxKind.CallExpression: - case SyntaxKind.NewExpression: - case SyntaxKind.PropertyAccessExpression: - case SyntaxKind.ElementAccessExpression: - node = (node).expression; - break; - default: - return node; + const result = deriveActualIndentationFromList(containingList, index, sourceFile, options); + if (result !== Value.Unknown) { + return result; } } + return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize! : 0); // TODO: GH#18217 } + return Value.Unknown; } function deriveActualIndentationFromList(list: ReadonlyArray, index: number, sourceFile: SourceFile, options: EditorSettings): number { diff --git a/src/services/getEditsForFileRename.ts b/src/services/getEditsForFileRename.ts index 07c3eb7ad22..66cc88c2677 100644 --- a/src/services/getEditsForFileRename.ts +++ b/src/services/getEditsForFileRename.ts @@ -14,7 +14,7 @@ namespace ts { const oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); const newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return textChanges.ChangeTracker.with({ host, formatContext }, changeTracker => { - updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } @@ -25,7 +25,7 @@ namespace ts { export function getPathUpdater(oldFileOrDirPath: string, newFileOrDirPath: string, getCanonicalFileName: GetCanonicalFileName, sourceMapper: SourceMapper | undefined): PathUpdater { const canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); return path => { - const originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + const originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 }); const updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); return originalPath ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) @@ -45,7 +45,7 @@ namespace ts { return combinePathsSafe(getDirectoryPath(a1), rel); } - function updateTsconfigFiles(program: Program, changeTracker: textChanges.ChangeTracker, oldToNew: PathUpdater, newFileOrDirPath: string, currentDirectory: string, useCaseSensitiveFileNames: boolean): void { + function updateTsconfigFiles(program: Program, changeTracker: textChanges.ChangeTracker, oldToNew: PathUpdater, oldFileOrDirPath: string, newFileOrDirPath: string, currentDirectory: string, useCaseSensitiveFileNames: boolean): void { const { configFile } = program.getCompilerOptions(); if (!configFile) return; const configDir = getDirectoryPath(configFile.fileName); @@ -63,7 +63,8 @@ namespace ts { const includes = mapDefined(property.initializer.elements, e => isStringLiteral(e) ? e.text : undefined); const matchers = getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); // If there isn't some include for this, add a new one. - if (!getRegexFromPattern(Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if (getRegexFromPattern(Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !getRegexFromPattern(Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), createStringLiteral(relativePath(newFileOrDirPath))); } } @@ -72,7 +73,7 @@ namespace ts { case "compilerOptions": forEachProperty(property.initializer, (property, propertyName) => { const option = getOptionFromName(propertyName); - if (option && (option.isFilePath || option.type === "list" && (option as CommandLineOptionOfListType).element.isFilePath)) { + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { updatePaths(property); } else if (propertyName === "paths") { @@ -150,7 +151,7 @@ namespace ts { const toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. // TODO:GH#18217 - ? getSourceFileToImportFromResolved(resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host as ModuleResolutionHost), oldToNew, host) + ? getSourceFileToImportFromResolved(resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host as ModuleResolutionHost), oldToNew) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. @@ -191,20 +192,35 @@ namespace ts { const resolved = host.resolveModuleNames ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); - return getSourceFileToImportFromResolved(resolved, oldToNew, host); + return getSourceFileToImportFromResolved(resolved, oldToNew); } } - function getSourceFileToImportFromResolved(resolved: ResolvedModuleWithFailedLookupLocations | undefined, oldToNew: PathUpdater, host: LanguageServiceHost): ToImport | undefined { - return resolved && ( - (resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || firstDefined(resolved.failedLookupLocations, getIfExists)); + function getSourceFileToImportFromResolved(resolved: ResolvedModuleWithFailedLookupLocations | undefined, oldToNew: PathUpdater): ToImport | undefined { + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + if (!resolved) return undefined; - function getIfExists(oldLocation: string): ToImport | undefined { - const newLocation = oldToNew(oldLocation); + // First try resolved module + if (resolved.resolvedModule) { + const result = tryChange(resolved.resolvedModule.resolvedFileName); + if (result) return result; + } - return host.fileExists!(oldLocation) || newLocation !== undefined && host.fileExists!(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Then failed lookups except package.json since we dont want to touch them (only included ts/js files) + const result = forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson); + if (result) return result; + + // If nothing changed, then result is resolved module file thats not updated + return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false }; + + function tryChangeWithIgnoringPackageJson(oldFileName: string) { + return !endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : undefined; + } + + function tryChange(oldFileName: string) { + const newFileName = oldToNew(oldFileName); + return newFileName && { newFileName, updated: true }; } } diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 02d590bb8b6..8f495aadfe1 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -1,6 +1,6 @@ /* @internal */ namespace ts.GoToDefinition { - export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): DefinitionInfo[] | undefined { + export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): ReadonlyArray | undefined { const reference = getReferenceAtPosition(sourceFile, position, program); if (reference) { return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; @@ -129,7 +129,7 @@ namespace ts.GoToDefinition { } /// Goto type - export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): DefinitionInfo[] | undefined { + export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): ReadonlyArray | undefined { const node = getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { return undefined; @@ -145,7 +145,7 @@ namespace ts.GoToDefinition { return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); } - function definitionFromType(type: Type, checker: TypeChecker, node: Node): DefinitionInfo[] { + function definitionFromType(type: Type, checker: TypeChecker, node: Node): ReadonlyArray { return flatMap(type.isUnion() && !(type.flags & TypeFlags.Enum) ? type.types : [type], t => t.symbol && getDefinitionFromSymbol(checker, t.symbol, node)); } diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index 77b3c02c80b..6b50d62d9b4 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -385,7 +385,7 @@ namespace ts.FindAllReferences { } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ - function forEachPossibleImportOrExportStatement(sourceFileLike: SourceFileLike, action: (statement: Statement) => T): T | undefined { + function forEachPossibleImportOrExportStatement(sourceFileLike: SourceFileLike, action: (statement: Statement) => T) { return forEach(sourceFileLike.kind === SyntaxKind.SourceFile ? sourceFileLike.statements : sourceFileLike.body!.statements, statement => // TODO: GH#18217 action(statement) || (isAmbientModuleDeclaration(statement) && forEach(statement.body && statement.body.statements, action))); } @@ -424,7 +424,6 @@ namespace ts.FindAllReferences { export interface ImportedSymbol { kind: ImportExport.Import; symbol: Symbol; - isNamedImport: boolean; } export interface ExportedSymbol { kind: ImportExport.Export; @@ -467,7 +466,7 @@ namespace ts.FindAllReferences { } const lhsSymbol = checker.getSymbolAtLocation(exportNode.name)!; - return { kind: ImportExport.Import, symbol: lhsSymbol, isNamedImport: false }; + return { kind: ImportExport.Import, symbol: lhsSymbol }; } else { return exportInfo(symbol, getExportKindForDeclaration(exportNode)); @@ -502,11 +501,11 @@ namespace ts.FindAllReferences { function getSpecialPropertyExport(node: BinaryExpression, useLhsSymbol: boolean): ExportedSymbol | undefined { let kind: ExportKind; - switch (getSpecialPropertyAssignmentKind(node)) { - case SpecialPropertyAssignmentKind.ExportsProperty: + switch (getAssignmentDeclarationKind(node)) { + case AssignmentDeclarationKind.ExportsProperty: kind = ExportKind.Named; break; - case SpecialPropertyAssignmentKind.ModuleExports: + case AssignmentDeclarationKind.ModuleExports: kind = ExportKind.ExportEquals; break; default: @@ -542,7 +541,7 @@ namespace ts.FindAllReferences { // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) const importedName = symbolEscapedNameNoDefault(importedSymbol); if (importedName === undefined || importedName === InternalSymbolName.Default || importedName === symbol.escapedName) { - return { kind: ImportExport.Import, symbol: importedSymbol, ...isImport }; + return { kind: ImportExport.Import, symbol: importedSymbol }; } } @@ -588,22 +587,20 @@ namespace ts.FindAllReferences { } } - function isNodeImport(node: Node): { isNamedImport: boolean } | undefined { + function isNodeImport(node: Node): boolean { const { parent } = node; switch (parent.kind) { case SyntaxKind.ImportEqualsDeclaration: - return (parent as ImportEqualsDeclaration).name === node && isExternalModuleImportEquals(parent as ImportEqualsDeclaration) - ? { isNamedImport: false } - : undefined; + return (parent as ImportEqualsDeclaration).name === node && isExternalModuleImportEquals(parent as ImportEqualsDeclaration); case SyntaxKind.ImportSpecifier: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. - return (parent as ImportSpecifier).propertyName ? undefined : { isNamedImport: true }; + return !(parent as ImportSpecifier).propertyName; case SyntaxKind.ImportClause: case SyntaxKind.NamespaceImport: Debug.assert((parent as ImportClause | NamespaceImport).name === node); - return { isNamedImport: false }; + return true; default: - return undefined; + return false; } } diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index d9fa8446b13..8016b0e9ff6 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -208,7 +208,7 @@ namespace ts.JsDoc { kindModifiers: "", displayParts: [textPart(name)], documentation: emptyArray, - tags: emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -242,7 +242,7 @@ namespace ts.JsDoc { kindModifiers: "", displayParts: [textPart(name)], documentation: emptyArray, - tags: emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -312,7 +312,7 @@ namespace ts.JsDoc { const preamble = "/**" + newLine + indentationStr + " * "; const result = preamble + newLine + - parameterDocComments(parameters, hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); @@ -383,7 +383,7 @@ namespace ts.JsDoc { case SyntaxKind.BinaryExpression: { const be = commentOwner as BinaryExpression; - if (getSpecialPropertyAssignmentKind(be) === SpecialPropertyAssignmentKind.None) { + if (getAssignmentDeclarationKind(be) === AssignmentDeclarationKind.None) { return "quit"; } const parameters = isFunctionLike(be.right) ? be.right.parameters : emptyArray; diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 504311a4a2d..60f1283f7e6 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -270,17 +270,20 @@ namespace ts.NavigationBar { break; case SyntaxKind.BinaryExpression: { - const special = getSpecialPropertyAssignmentKind(node as BinaryExpression); + const special = getAssignmentDeclarationKind(node as BinaryExpression); switch (special) { - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ModuleExports: - case SpecialPropertyAssignmentKind.PrototypeProperty: - case SpecialPropertyAssignmentKind.Prototype: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.ModuleExports: + case AssignmentDeclarationKind.PrototypeProperty: + case AssignmentDeclarationKind.Prototype: addNodeWithRecursiveChild(node, (node as BinaryExpression).right); return; - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.ThisProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.None: + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: break; default: Debug.assertNever(special); @@ -631,28 +634,50 @@ namespace ts.NavigationBar { } function getFunctionOrClassName(node: FunctionExpression | FunctionDeclaration | ArrowFunction | ClassLikeDeclaration): string { + const { parent } = node; if (node.name && getFullWidth(node.name) > 0) { return declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === SyntaxKind.VariableDeclaration) { - return declarationNameToString((node.parent as VariableDeclaration).name); + else if (isVariableDeclaration(parent)) { + return declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === SyntaxKind.BinaryExpression && - (node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { - return nodeText((node.parent as BinaryExpression).left).replace(whiteSpaceRegex, ""); + else if (isBinaryExpression(parent) && parent.operatorToken.kind === SyntaxKind.EqualsToken) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === SyntaxKind.PropertyAssignment && (node.parent as PropertyAssignment).name) { - return nodeText((node.parent as PropertyAssignment).name); + else if (isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (getModifierFlags(node) & ModifierFlags.Default) { return "default"; } + else if (isClassLike(node)) { + return ""; + } + else if (isCallExpression(parent)) { + const name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + const args = mapDefined(parent.arguments, a => isStringLiteralLike(a) ? a.getText(curSourceFile) : undefined).join(", "); + return `${name}(${args}) callback`; + } + } + return ""; + } + + function getCalledExpressionName(expr: Expression): string | undefined { + if (isIdentifier(expr)) { + return expr.text; + } + else if (isPropertyAccessExpression(expr)) { + const left = getCalledExpressionName(expr.expression); + const right = expr.name.text; + return left === undefined ? right : `${left}.${right}`; + } else { - return isClassLike(node) ? "" : ""; + return undefined; } } diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts index 460cb3dd5a2..157ba98e262 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -28,12 +28,12 @@ namespace ts.OrganizeImports { organizeImportsWorker(topLevelExportDecls, coalesceExports); for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) { - const ambientModuleBody = getModuleBlock(ambientModule as ModuleDeclaration)!; // TODO: GH#18217 + if (!ambientModule.body) { continue; } - const ambientModuleImportDecls = ambientModuleBody.statements.filter(isImportDeclaration); + const ambientModuleImportDecls = ambientModule.body.statements.filter(isImportDeclaration); organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); - const ambientModuleExportDecls = ambientModuleBody.statements.filter(isExportDeclaration); + const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration); organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } @@ -81,14 +81,9 @@ namespace ts.OrganizeImports { } } - function getModuleBlock(moduleDecl: ModuleDeclaration): ModuleBlock | undefined { - const body = moduleDecl.body; - return body && !isIdentifier(body) ? (isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; - } - function removeUnusedImports(oldImports: ReadonlyArray, sourceFile: SourceFile, program: Program) { const typeChecker = program.getTypeChecker(); - const jsxNamespace = typeChecker.getJsxNamespace(); + const jsxNamespace = typeChecker.getJsxNamespace(sourceFile); const jsxElementsPresent = !!(sourceFile.transformFlags & TransformFlags.ContainsJsx); const usedImports: ImportDeclaration[] = []; @@ -146,7 +141,7 @@ namespace ts.OrganizeImports { : undefined; } - /* @internal */ // Internal for testing + // Internal for testing /** * @param importGroup a list of ImportDeclarations, all with the same module name. */ @@ -266,7 +261,7 @@ namespace ts.OrganizeImports { } } - /* @internal */ // Internal for testing + // Internal for testing /** * @param exportGroup a list of ExportDeclarations, all with the same module name. */ diff --git a/src/services/outliningElementsCollector.ts b/src/services/outliningElementsCollector.ts index 9d2c61a1a7d..6f834512f0b 100644 --- a/src/services/outliningElementsCollector.ts +++ b/src/services/outliningElementsCollector.ts @@ -37,6 +37,10 @@ namespace ts.OutliningElementsCollector { addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); } + if (isFunctionExpressionAssignedToVariable(n)) { + addOutliningForLeadingCommentsForNode(n.parent.parent.parent, sourceFile, cancellationToken, out); + } + const span = getOutliningSpanForNode(n, sourceFile); if (span) out.push(span); @@ -54,6 +58,14 @@ namespace ts.OutliningElementsCollector { } depthRemaining++; } + + function isFunctionExpressionAssignedToVariable(n: Node) { + if (!isFunctionExpression(n) && !isArrowFunction(n)) { + return false; + } + const ancestor = findAncestor(n, isVariableStatement); + return !!ancestor && getSingleInitializerOfVariableStatementOrPropertyDeclaration(ancestor) === n; + } } function addRegionOutliningSpans(sourceFile: SourceFile, out: Push): void { @@ -175,6 +187,7 @@ namespace ts.OutliningElementsCollector { case SyntaxKind.ModuleBlock: return spanForNode(n.parent); case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.CaseBlock: @@ -206,10 +219,10 @@ namespace ts.OutliningElementsCollector { } function spanForObjectOrArrayLiteral(node: Node, open: SyntaxKind.OpenBraceToken | SyntaxKind.OpenBracketToken = SyntaxKind.OpenBraceToken): OutliningSpan | undefined { - // If the block has no leading keywords and is inside an array literal, + // If the block has no leading keywords and is inside an array literal or call expression, // we only want to collapse the span of the block. // Otherwise, the collapsed section will include the end of the previous line. - return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !isArrayLiteralExpression(node.parent), open); + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !isArrayLiteralExpression(node.parent) && !isCallExpression(node.parent), open); } function spanForNode(hintSpanNode: Node, autoCollapse = false, useFullStart = true, open: SyntaxKind.OpenBraceToken | SyntaxKind.OpenBracketToken = SyntaxKind.OpenBraceToken): OutliningSpan | undefined { diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts deleted file mode 100644 index 8ab7cc315ad..00000000000 --- a/src/services/pathCompletions.ts +++ /dev/null @@ -1,479 +0,0 @@ -/* @internal */ -namespace ts.Completions.PathCompletions { - export interface NameAndKind { - readonly name: string; - readonly kind: ScriptElementKind.scriptElement | ScriptElementKind.directory | ScriptElementKind.externalModuleName; - } - export interface PathCompletion extends NameAndKind { - readonly span: TextSpan | undefined; - } - - function nameAndKind(name: string, kind: NameAndKind["kind"]): NameAndKind { - return { name, kind }; - } - function addReplacementSpans(text: string, textStart: number, names: ReadonlyArray): ReadonlyArray { - const span = getDirectoryFragmentTextSpan(text, textStart); - return names.map(({ name, kind }): PathCompletion => ({ name, kind, span })); - } - - export function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { - return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); - } - - function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { - const literalValue = normalizeSlashes(node.text); - - const scriptPath = sourceFile.path; - const scriptDirectory = getDirectoryPath(scriptPath); - - if (isPathRelativeToScript(literalValue) || isRootedDiskPath(literalValue)) { - const extensions = getSupportedExtensionsForModuleResolution(compilerOptions); - if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs( - compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); - } - else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); - } - } - else { - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); - } - } - - function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions) { - const extensions = getSupportedExtensions(compilerOptions); - return compilerOptions.resolveJsonModule && getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs ? - extensions.concat(Extension.Json) : - extensions; - } - - /** - * Takes a script path and returns paths for all potential folders that could be merged with its - * containing folder via the "rootDirs" compiler option - */ - function getBaseDirectoriesFromRootDirs(rootDirs: string[], basePath: string, scriptPath: string, ignoreCase: boolean): string[] { - // Make all paths absolute/normalized if they are not already - rootDirs = rootDirs.map(rootDirectory => normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory))); - - // Determine the path to the directory containing the script relative to the root directory it is contained within - const relativeDirectory = firstDefined(rootDirs, rootDirectory => - containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined)!; // TODO: GH#18217 - - // Now find a path for each potential directory that is to be merged with the one containing the script - return deduplicate( - rootDirs.map(rootDirectory => combinePaths(rootDirectory, relativeDirectory)), - equateStringsCaseSensitive, - compareStringsCaseSensitive); - } - - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs: string[], fragment: string, scriptPath: string, extensions: ReadonlyArray, includeExtensions: boolean, compilerOptions: CompilerOptions, host: LanguageServiceHost, exclude?: string): NameAndKind[] { - const basePath = compilerOptions.project || host.getCurrentDirectory(); - const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); - - const result: NameAndKind[] = []; - - for (const baseDirectory of baseDirectories) { - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); - } - - return result; - } - - /** - * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. - */ - function getCompletionEntriesForDirectoryFragment(fragment: string, scriptPath: string, extensions: ReadonlyArray, includeExtensions: boolean, host: LanguageServiceHost, exclude?: string, result: NameAndKind[] = []): NameAndKind[] { - if (fragment === undefined) { - fragment = ""; - } - - fragment = normalizeSlashes(fragment); - - /** - * Remove the basename from the path. Note that we don't use the basename to filter completions; - * the client is responsible for refining completions. - */ - if (!hasTrailingDirectorySeparator(fragment)) { - fragment = getDirectoryPath(fragment); - } - - if (fragment === "") { - fragment = "." + directorySeparator; - } - - fragment = ensureTrailingDirectorySeparator(fragment); - - // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths - const absolutePath = resolvePath(scriptPath, fragment); - const baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath); - const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - - if (tryDirectoryExists(host, baseDirectory)) { - // Enumerate the available files if possible - const files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); - - if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - const foundFiles = createMap(); - for (let filePath of files) { - filePath = normalizePath(filePath); - if (exclude && comparePaths(filePath, exclude, scriptPath, ignoreCase) === Comparison.EqualTo) { - continue; - } - - const foundFileName = includeExtensions || fileExtensionIs(filePath, Extension.Json) ? getBaseFileName(filePath) : removeFileExtension(getBaseFileName(filePath)); - - if (!foundFiles.has(foundFileName)) { - foundFiles.set(foundFileName, true); - } - } - - forEachKey(foundFiles, foundFile => { - result.push(nameAndKind(foundFile, ScriptElementKind.scriptElement)); - }); - } - - // If possible, get folder completion as well - const directories = tryGetDirectories(host, baseDirectory); - - if (directories) { - for (const directory of directories) { - const directoryName = getBaseFileName(normalizePath(directory)); - if (directoryName !== "@types") { - result.push(nameAndKind(directoryName, ScriptElementKind.directory)); - } - } - } - } - - return result; - } - - /** - * Check all of the declared modules and those in node modules. Possible sources of modules: - * Modules that are found by the type checker - * Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option) - * Modules from node_modules (i.e. those listed in package.json) - * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions - */ - function getCompletionEntriesForNonRelativeModules(fragment: string, scriptPath: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): NameAndKind[] { - const { baseUrl, paths } = compilerOptions; - - const result: NameAndKind[] = []; - - const fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); - if (baseUrl) { - const projectDir = compilerOptions.project || host.getCurrentDirectory(); - const absolute = isRootedDiskPath(baseUrl) ? baseUrl : combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - - for (const path in paths!) { - const patterns = paths![path]; - if (paths!.hasOwnProperty(path) && patterns) { - for (const { name, kind } of getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host)) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(entry => entry.name === name)) { - result.push(nameAndKind(name, kind)); - } - } - } - } - } - - const fragmentDirectory = containsSlash(fragment) ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : undefined; - for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker)) { - result.push(nameAndKind(ambientName, ScriptElementKind.externalModuleName)); - } - - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); - - if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs) { - // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. - // (But do if we didn't find anything, e.g. 'package.json' missing.) - let foundGlobal = false; - if (fragmentDirectory === undefined) { - for (const moduleName of enumerateNodeModulesVisibleToScript(host, scriptPath)) { - if (!result.some(entry => entry.name === moduleName)) { - foundGlobal = true; - result.push(nameAndKind(moduleName, ScriptElementKind.externalModuleName)); - } - } - } - if (!foundGlobal) { - forEachAncestorDirectory(scriptPath, ancestor => { - const nodeModules = combinePaths(ancestor, "node_modules"); - if (tryDirectoryExists(host, nodeModules)) { - getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - } - }); - } - } - - return result; - } - - function getCompletionsForPathMapping( - path: string, patterns: ReadonlyArray, fragment: string, baseUrl: string, fileExtensions: ReadonlyArray, host: LanguageServiceHost, - ): ReadonlyArray { - if (!endsWith(path, "*")) { - // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !stringContains(path, "*") ? justPathMappingName(path) : emptyArray; - } - - const pathPrefix = path.slice(0, path.length - 1); - const remainingFragment = tryRemovePrefix(fragment, pathPrefix); - return remainingFragment === undefined ? justPathMappingName(pathPrefix) : flatMap(patterns, pattern => - getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host)); - - function justPathMappingName(name: string): ReadonlyArray { - return startsWith(name, fragment) ? [{ name, kind: ScriptElementKind.directory }] : emptyArray; - } - } - - function getModulesForPathsPattern(fragment: string, baseUrl: string, pattern: string, fileExtensions: ReadonlyArray, host: LanguageServiceHost): ReadonlyArray | undefined { - if (!host.readDirectory) { - return undefined; - } - - const parsed = hasZeroOrOneAsteriskCharacter(pattern) ? tryParsePattern(pattern) : undefined; - if (!parsed) { - return undefined; - } - - // The prefix has two effective parts: the directory path and the base component after the filepath that is not a - // full directory component. For example: directory/path/of/prefix/base* - const normalizedPrefix = resolvePath(parsed.prefix); - const normalizedPrefixDirectory = hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : getDirectoryPath(normalizedPrefix); - const normalizedPrefixBase = hasTrailingDirectorySeparator(parsed.prefix) ? "" : getBaseFileName(normalizedPrefix); - - const fragmentHasPath = containsSlash(fragment); - const fragmentDirectory = fragmentHasPath ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : undefined; - - // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; - - const normalizedSuffix = normalizePath(parsed.suffix); - // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". - const baseDirectory = normalizePath(combinePaths(baseUrl, expandedPrefixDirectory)); - const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - const includeGlob = normalizedSuffix ? "**/*" : "./*"; - - const matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]).map(name => ({ name, kind: ScriptElementKind.scriptElement })); - const directories = tryGetDirectories(host, baseDirectory).map(d => combinePaths(baseDirectory, d)).map(name => ({ name, kind: ScriptElementKind.directory })); - - // Trim away prefix and suffix - return mapDefined(concatenate(matches, directories), ({ name, kind }) => { - const normalizedMatch = normalizePath(name); - const inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix); - return inner !== undefined ? { name: removeLeadingDirectorySeparator(removeFileExtension(inner)), kind } : undefined; - }); - } - - function withoutStartAndEnd(s: string, start: string, end: string): string | undefined { - return startsWith(s, start) && endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; - } - - function removeLeadingDirectorySeparator(path: string): string { - return path[0] === directorySeparator ? path.slice(1) : path; - } - - function getAmbientModuleCompletions(fragment: string, fragmentDirectory: string | undefined, checker: TypeChecker): ReadonlyArray { - // Get modules that the type checker picked up - const ambientModules = checker.getAmbientModules().map(sym => stripQuotes(sym.name)); - const nonRelativeModuleNames = ambientModules.filter(moduleName => startsWith(moduleName, fragment)); - - // Nested modules of the form "module-name/sub" need to be adjusted to only return the string - // after the last '/' that appears in the fragment because that's where the replacement span - // starts - if (fragmentDirectory !== undefined) { - const moduleNameWithSeparator = ensureTrailingDirectorySeparator(fragmentDirectory); - return nonRelativeModuleNames.map(nonRelativeModuleName => removePrefix(nonRelativeModuleName, moduleNameWithSeparator)); - } - return nonRelativeModuleNames; - } - - export function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): ReadonlyArray | undefined { - const token = getTokenAtPosition(sourceFile, position); - const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); - const range = commentRanges && find(commentRanges, commentRange => position >= commentRange.pos && position <= commentRange.end); - if (!range) { - return undefined; - } - const text = sourceFile.text.slice(range.pos, position); - const match = tripleSlashDirectiveFragmentRegex.exec(text); - if (!match) { - return undefined; - } - - const [, prefix, kind, toComplete] = match; - const scriptPath = getDirectoryPath(sourceFile.path); - const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) - : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) - : undefined; - return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); - } - - function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, result: NameAndKind[] = []): NameAndKind[] { - // Check for typings specified in compiler options - const seen = createMap(); - if (options.types) { - for (const typesName of options.types) { - const moduleName = getUnmangledNameForScopedPackage(typesName); - pushResult(moduleName); - } - } - else if (host.getDirectories) { - let typeRoots: ReadonlyArray | undefined; - try { - typeRoots = getEffectiveTypeRoots(options, host); - } - catch { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ } - - if (typeRoots) { - for (const root of typeRoots) { - getCompletionEntriesFromDirectories(root); - } - } - - // Also get all @types typings installed in visible node_modules directories - for (const packageJson of findPackageJsons(scriptPath, host)) { - const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(typesDir); - } - } - - return result; - - function getCompletionEntriesFromDirectories(directory: string) { - Debug.assert(!!host.getDirectories); - if (tryDirectoryExists(host, directory)) { - const directories = tryGetDirectories(host, directory); - if (directories) { - for (let typeDirectory of directories) { - typeDirectory = normalizePath(typeDirectory); - const directoryName = getBaseFileName(typeDirectory); - const moduleName = getUnmangledNameForScopedPackage(directoryName); - pushResult(moduleName); - } - } - } - } - - function pushResult(moduleName: string) { - if (!seen.has(moduleName)) { - result.push(nameAndKind(moduleName, ScriptElementKind.externalModuleName)); - seen.set(moduleName, true); - } - } - } - - function findPackageJsons(directory: string, host: LanguageServiceHost): string[] { - const paths: string[] = []; - forEachAncestorDirectory(directory, ancestor => { - const currentConfigPath = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); - if (!currentConfigPath) { - return true; // break out - } - paths.push(currentConfigPath); - }); - return paths; - } - - function enumerateNodeModulesVisibleToScript(host: LanguageServiceHost, scriptPath: string): ReadonlyArray { - if (!host.readFile || !host.fileExists) return emptyArray; - - const result: string[] = []; - for (const packageJson of findPackageJsons(scriptPath, host)) { - const contents = readJson(packageJson, host as { readFile: (filename: string) => string | undefined }); // Cast to assert that readFile is defined - // Provide completions for all non @types dependencies - for (const key of nodeModulesDependencyKeys) { - const dependencies: object | undefined = (contents as any)[key]; - if (!dependencies) continue; - for (const dep in dependencies) { - if (dependencies.hasOwnProperty(dep) && !startsWith(dep, "@types/")) { - result.push(dep); - } - } - } - } - return result; - } - - // Replace everything after the last directory separator that appears - function getDirectoryFragmentTextSpan(text: string, textStart: number): TextSpan | undefined { - const index = Math.max(text.lastIndexOf(directorySeparator), text.lastIndexOf("\\")); - const offset = index !== -1 ? index + 1 : 0; - // If the range is an identifier, span is unnecessary. - const length = text.length - offset; - return length === 0 || isIdentifierText(text.substr(offset, length), ScriptTarget.ESNext) ? undefined : createTextSpan(textStart + offset, length); - } - - // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) - function isPathRelativeToScript(path: string) { - if (path && path.length >= 2 && path.charCodeAt(0) === CharacterCodes.dot) { - const slashIndex = path.length >= 3 && path.charCodeAt(1) === CharacterCodes.dot ? 2 : 1; - const slashCharCode = path.charCodeAt(slashIndex); - return slashCharCode === CharacterCodes.slash || slashCharCode === CharacterCodes.backslash; - } - return false; - } - - /** - * Matches a triple slash reference directive with an incomplete string literal for its path. Used - * to determine if the caret is currently within the string literal and capture the literal fragment - * for completions. - * For example, this matches - * - * /// , exclude?: ReadonlyArray, include?: ReadonlyArray): ReadonlyArray { - return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || emptyArray; - } - - function tryFileExists(host: LanguageServiceHost, path: string): boolean { - return tryIOAndConsumeErrors(host, host.fileExists, path); - } - - function tryDirectoryExists(host: LanguageServiceHost, path: string): boolean { - try { - return directoryProbablyExists(path, host); - } - catch { /*ignore*/ } - return false; - } - - function tryIOAndConsumeErrors(host: LanguageServiceHost, toApply: ((...a: any[]) => T) | undefined, ...args: any[]) { - try { - return toApply && toApply.apply(host, args); - } - catch { /*ignore*/ } - return undefined; - } - - function containsSlash(fragment: string) { - return stringContains(fragment, directorySeparator); - } -} diff --git a/src/services/patternMatcher.ts b/src/services/patternMatcher.ts index f81900e28e7..1020c97b432 100644 --- a/src/services/patternMatcher.ts +++ b/src/services/patternMatcher.ts @@ -461,11 +461,11 @@ namespace ts { }; } - /* @internal */ export function breakIntoCharacterSpans(identifier: string): TextSpan[] { + export function breakIntoCharacterSpans(identifier: string): TextSpan[] { return breakIntoSpans(identifier, /*word:*/ false); } - /* @internal */ export function breakIntoWordSpans(identifier: string): TextSpan[] { + export function breakIntoWordSpans(identifier: string): TextSpan[] { return breakIntoSpans(identifier, /*word:*/ true); } diff --git a/src/services/refactorProvider.ts b/src/services/refactorProvider.ts index adb3af3ea7a..e1ac6a58f8d 100644 --- a/src/services/refactorProvider.ts +++ b/src/services/refactorProvider.ts @@ -5,7 +5,7 @@ namespace ts { getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined; /** Compute (quickly) which actions are available here */ - getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined; + getAvailableActions(context: RefactorContext): ReadonlyArray; } export interface RefactorContext extends textChanges.TextChangesContext { diff --git a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts index 57e7dbd97a7..c5fccde13db 100644 --- a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts +++ b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts @@ -15,10 +15,10 @@ namespace ts.refactor.addOrRemoveBracesToArrowFunction { addBraces: boolean; } - function getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined { + function getAvailableActions(context: RefactorContext): ReadonlyArray { const { file, startPosition } = context; const info = getConvertibleArrowFunctionAtPosition(file, startPosition); - if (!info) return undefined; + if (!info) return emptyArray; return [{ name: refactorName, diff --git a/src/services/refactors/convertExport.ts b/src/services/refactors/convertExport.ts index ca31ef58100..64c7e7567b8 100644 --- a/src/services/refactors/convertExport.ts +++ b/src/services/refactors/convertExport.ts @@ -4,9 +4,9 @@ namespace ts.refactor { const actionNameDefaultToNamed = "Convert default export to named export"; const actionNameNamedToDefault = "Convert named export to default export"; registerRefactor(refactorName, { - getAvailableActions(context): ApplicableRefactorInfo[] | undefined { + getAvailableActions(context): ReadonlyArray { const info = getInfo(context); - if (!info) return undefined; + if (!info) return emptyArray; const description = info.wasDefault ? Diagnostics.Convert_default_export_to_named_export.message : Diagnostics.Convert_named_export_to_default_export.message; const actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; return [{ name: refactorName, description, actions: [{ name: actionName, description }] }]; @@ -166,38 +166,35 @@ namespace ts.refactor { } function changeNamedToDefaultImport(importingSourceFile: SourceFile, ref: Identifier, changes: textChanges.ChangeTracker): void { - const { parent } = ref; + const parent = ref.parent as PropertyAccessExpression | ImportSpecifier | ExportSpecifier; switch (parent.kind) { case SyntaxKind.PropertyAccessExpression: // `a.foo` --> `a.default` changes.replaceNode(importingSourceFile, ref, createIdentifier("default")); break; - case SyntaxKind.ImportSpecifier: - case SyntaxKind.ExportSpecifier: { - const spec = parent as ImportSpecifier | ExportSpecifier; - if (spec.kind === SyntaxKind.ImportSpecifier) { - // `import { foo } from "./a";` --> `import foo from "./a";` - // `import { foo as bar } from "./a";` --> `import bar from "./a";` - const defaultImport = createIdentifier(spec.name.text); - if (spec.parent.elements.length === 1) { - changes.replaceNode(importingSourceFile, spec.parent, defaultImport); - } - else { - changes.delete(importingSourceFile, spec); - changes.insertNodeBefore(importingSourceFile, spec.parent, defaultImport); - } + case SyntaxKind.ImportSpecifier: { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + const defaultImport = createIdentifier(parent.name.text); + if (parent.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent.parent, defaultImport); } else { - // `export { foo } from "./a";` --> `export { default as foo } from "./a";` - // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` - // `export { foo as default } from "./a";` --> `export { default } from "./a";` - // (Because `export foo from "./a";` isn't valid syntax.) - changes.replaceNode(importingSourceFile, spec, makeExportSpecifier("default", spec.name.text)); + changes.delete(importingSourceFile, parent); + changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport); } break; } + case SyntaxKind.ExportSpecifier: { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text)); + break; + } default: - Debug.failBadSyntaxKind(parent); + Debug.assertNever(parent); } } diff --git a/src/services/refactors/convertImport.ts b/src/services/refactors/convertImport.ts index c91c06cb1fa..862717e728a 100644 --- a/src/services/refactors/convertImport.ts +++ b/src/services/refactors/convertImport.ts @@ -4,9 +4,9 @@ namespace ts.refactor { const actionNameNamespaceToNamed = "Convert namespace import to named imports"; const actionNameNamedToNamespace = "Convert named imports to namespace import"; registerRefactor(refactorName, { - getAvailableActions(context): ApplicableRefactorInfo[] | undefined { + getAvailableActions(context): ReadonlyArray { const i = getImportToConvert(context); - if (!i) return undefined; + if (!i) return emptyArray; const description = i.kind === SyntaxKind.NamespaceImport ? Diagnostics.Convert_namespace_import_to_named_imports.message : Diagnostics.Convert_named_imports_to_namespace_import.message; const actionName = i.kind === SyntaxKind.NamespaceImport ? actionNameNamespaceToNamed : actionNameNamedToNamespace; return [{ name: refactorName, description, actions: [{ name: actionName, description }] }]; diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 93baf2b4209..823bd640a59 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -7,18 +7,18 @@ namespace ts.refactor.extractSymbol { * Compute the associated code actions * Exported for tests. */ - export function getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined { + export function getAvailableActions(context: RefactorContext): ReadonlyArray { const rangeToExtract = getRangeToExtract(context.file, getRefactorContextSpan(context)); const targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { - return undefined; + return emptyArray; } const extractions = getPossibleExtractions(targetRange, context); if (extractions === undefined) { // No extractions possible - return undefined; + return emptyArray; } const functionActions: RefactorActionInfo[] = []; @@ -82,7 +82,7 @@ namespace ts.refactor.extractSymbol { }); } - return infos.length ? infos : undefined; + return infos.length ? infos : emptyArray; } /* Exported for tests */ @@ -449,8 +449,7 @@ namespace ts.refactor.extractSymbol { case SyntaxKind.ThisKeyword: rangeFacts |= RangeFacts.UsesThis; break; - case SyntaxKind.LabeledStatement: - { + case SyntaxKind.LabeledStatement: { const label = (node).label; (seenLabels || (seenLabels = [])).push(label.escapedText); forEachChild(node, visit); @@ -458,8 +457,7 @@ namespace ts.refactor.extractSymbol { break; } case SyntaxKind.BreakStatement: - case SyntaxKind.ContinueStatement: - { + case SyntaxKind.ContinueStatement: { const label = (node).label; if (label) { if (!contains(seenLabels, label.escapedText)) { @@ -677,7 +675,7 @@ namespace ts.refactor.extractSymbol { case SyntaxKind.ArrowFunction: return "arrow function"; case SyntaxKind.MethodDeclaration: - return `method '${scope.name.getText()}`; + return `method '${scope.name.getText()}'`; case SyntaxKind.GetAccessor: return `'get ${scope.name.getText()}'`; case SyntaxKind.SetAccessor: @@ -719,7 +717,7 @@ namespace ts.refactor.extractSymbol { // Make a unique name for the extracted function const file = scope.getSourceFile(); const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); - const isJS = isInJavaScriptFile(scope); + const isJS = isInJSFile(scope); const functionName = createIdentifier(functionNameText); @@ -1006,7 +1004,7 @@ namespace ts.refactor.extractSymbol { // Make a unique name for the extracted variable const file = scope.getSourceFile(); const localNameText = getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); - const isJS = isInJavaScriptFile(scope); + const isJS = isInJSFile(scope); const variableType = isJS || !checker.isContextSensitive(node) ? undefined @@ -1424,7 +1422,7 @@ namespace ts.refactor.extractSymbol { if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (isClassLike(scope) && isInJavaScriptFile(scope)) { + if (isClassLike(scope) && isInJSFile(scope)) { constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (isArrowFunction(scope) && !isBlock(scope.body)) { diff --git a/src/services/refactors/generateGetAccessorAndSetAccessor.ts b/src/services/refactors/generateGetAccessorAndSetAccessor.ts index e39eb20f8d8..dbc73781871 100644 --- a/src/services/refactors/generateGetAccessorAndSetAccessor.ts +++ b/src/services/refactors/generateGetAccessorAndSetAccessor.ts @@ -16,12 +16,12 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { readonly declaration: AcceptedDeclaration; readonly fieldName: AcceptedNameType; readonly accessorName: AcceptedNameType; - readonly originalName: AcceptedNameType; + readonly originalName: string; readonly renameAccessor: boolean; } - function getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined { - if (!getConvertibleFieldAtPosition(context)) return undefined; + function getAvailableActions(context: RefactorContext): ReadonlyArray { + if (!getConvertibleFieldAtPosition(context)) return emptyArray; return [{ name: actionName, @@ -41,7 +41,7 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { const fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - const isJS = isSourceFileJavaScript(file); + const isJS = isSourceFileJS(file); const changeTracker = textChanges.ChangeTracker.fromContext(context); const { isStatic, isReadonly, fieldName, accessorName, originalName, type, container, declaration, renameAccessor } = fieldInfo; @@ -69,7 +69,7 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { // readonly modifier only existed in classLikeDeclaration const constructor = getFirstConstructorWithBody(container); if (constructor) { - updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); } } else { @@ -135,7 +135,7 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { isReadonly: hasReadonlyModifier(declaration), type: getTypeAnnotationNode(declaration), container: declaration.kind === SyntaxKind.Parameter ? declaration.parent.parent : declaration.parent, - originalName: declaration.name, + originalName: (declaration.name).text, declaration, fieldName, accessorName, @@ -221,22 +221,22 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { : changeTracker.insertNodeAfter(file, declaration, accessor); } - function updateReadonlyPropertyInitializerStatementConstructor(changeTracker: textChanges.ChangeTracker, context: RefactorContext, constructor: ConstructorDeclaration, fieldName: AcceptedNameType, originalName: AcceptedNameType) { + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker: textChanges.ChangeTracker, file: SourceFile, constructor: ConstructorDeclaration, fieldName: string, originalName: string) { if (!constructor.body) return; - const { file, program, cancellationToken } = context; - - const referenceEntries = mapDefined(FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken!), entry => // TODO: GH#18217 - (entry.type === "node" && rangeContainsRange(constructor, entry.node) && isIdentifier(entry.node) && isWriteAccess(entry.node)) ? entry.node : undefined); - - forEach(referenceEntries, entry => { - const parent = entry.parent; - const accessorName = createIdentifier(fieldName.text); - const node = isBinaryExpression(parent) - ? updateBinary(parent, accessorName, parent.right, parent.operatorToken) - : isPropertyAccessExpression(parent) - ? updatePropertyAccess(parent, parent.expression, accessorName) - : Debug.fail("Unexpected write access token"); - changeTracker.replaceNode(file, parent, node); + constructor.body.forEachChild(function recur(node) { + if (isElementAccessExpression(node) && + node.expression.kind === SyntaxKind.ThisKeyword && + isStringLiteral(node.argumentExpression) && + node.argumentExpression.text === originalName && + isWriteAccess(node)) { + changeTracker.replaceNode(file, node.argumentExpression, createStringLiteral(fieldName)); + } + if (isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.ThisKeyword && node.name.text === originalName && isWriteAccess(node)) { + changeTracker.replaceNode(file, node.name, createIdentifier(fieldName)); + } + if (!isFunctionLike(node) && !isClassLike(node)) { + node.forEachChild(recur); + } }); } } diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index 9953293e3d1..ad60a6da5fc 100644 --- a/src/services/refactors/moveToNewFile.ts +++ b/src/services/refactors/moveToNewFile.ts @@ -2,8 +2,8 @@ namespace ts.refactor { const refactorName = "Move to a new file"; registerRefactor(refactorName, { - getAvailableActions(context): ApplicableRefactorInfo[] | undefined { - if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return undefined; + getAvailableActions(context): ReadonlyArray { + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return emptyArray; const description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description, actions: [{ name: refactorName, description }] }]; }, @@ -158,7 +158,7 @@ namespace ts.refactor { const shouldMove = (name: Identifier): boolean => { const symbol = isBindingElement(name.parent) - ? getPropertySymbolFromBindingElement(checker, name.parent as BindingElement & { name: Identifier }) + ? getPropertySymbolFromBindingElement(checker, name.parent as ObjectBindingElementWithoutPropertyName) : skipAlias(checker.getSymbolAtLocation(name)!, checker); // TODO: GH#18217 return !!symbol && movedSymbols.has(symbol); }; @@ -460,6 +460,12 @@ namespace ts.refactor { const oldImportsNeededByNewFile = new SymbolSet(); const newFileImportsFromOldFile = new SymbolSet(); + const containsJsx = find(toMove, statement => !!(statement.transformFlags & TransformFlags.ContainsJsx)); + const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); + if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code) + oldImportsNeededByNewFile.add(jsxNamespaceSymbol); + } + for (const statement of toMove) { forEachTopLevelDeclaration(statement, decl => { movedSymbols.add(Debug.assertDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); @@ -485,6 +491,11 @@ namespace ts.refactor { for (const statement of oldFile.statements) { if (contains(toMove, statement)) continue; + // jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile. + if (jsxNamespaceSymbol && !!(statement.transformFlags & TransformFlags.ContainsJsx)) { + unusedImportsFromOldFile.delete(jsxNamespaceSymbol); + } + forEachReference(statement, checker, symbol => { if (movedSymbols.has(symbol)) oldFileImportsFromNewFile.add(symbol); unusedImportsFromOldFile.delete(symbol); @@ -492,6 +503,23 @@ namespace ts.refactor { } return { movedSymbols, newFileImportsFromOldFile, oldFileImportsFromNewFile, oldImportsNeededByNewFile, unusedImportsFromOldFile }; + + function getJsxNamespaceSymbol(containsJsx: Node | undefined) { + if (containsJsx === undefined) { + return undefined; + } + + const jsxNamespace = checker.getJsxNamespace(containsJsx); + + // Strictly speaking, this could resolve to a symbol other than the JSX namespace. + // This will produce erroneous output (probably, an incorrectly copied import) but + // is expected to be very rare and easily reversible. + const jsxNamespaceSymbol = checker.resolveName(jsxNamespace, containsJsx, SymbolFlags.Namespace, /*excludeGlobals*/ true); + + return !!jsxNamespaceSymbol && some(jsxNamespaceSymbol.declarations, isInImport) + ? jsxNamespaceSymbol + : undefined; + } } // Below should all be utilities @@ -512,7 +540,7 @@ namespace ts.refactor { } function isVariableDeclarationInImport(decl: VariableDeclaration) { return isSourceFile(decl.parent.parent.parent) && - decl.initializer && isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); + !!decl.initializer && isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); } function filterImport(i: SupportedImport, moduleSpecifier: StringLiteralLike, keep: (name: Identifier) => boolean): SupportedImportStatement | undefined { @@ -612,7 +640,7 @@ namespace ts.refactor { | ImportEqualsDeclaration; type TopLevelDeclarationStatement = NonVariableTopLevelDeclaration | VariableStatement; interface TopLevelVariableDeclaration extends VariableDeclaration { parent: VariableDeclarationList & { parent: VariableStatement; }; } - type TopLevelDeclaration = NonVariableTopLevelDeclaration | TopLevelVariableDeclaration; + type TopLevelDeclaration = NonVariableTopLevelDeclaration | TopLevelVariableDeclaration | BindingElement; function isTopLevelDeclaration(node: Node): node is TopLevelDeclaration { return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); } @@ -653,23 +681,42 @@ namespace ts.refactor { return cb(statement as FunctionDeclaration | ClassDeclaration | EnumDeclaration | ModuleDeclaration | TypeAliasDeclaration | InterfaceDeclaration | ImportEqualsDeclaration); case SyntaxKind.VariableStatement: - return forEach((statement as VariableStatement).declarationList.declarations as ReadonlyArray, cb); + return firstDefined((statement as VariableStatement).declarationList.declarations, decl => forEachTopLevelDeclarationInBindingName(decl.name, cb)); case SyntaxKind.ExpressionStatement: { const { expression } = statement as ExpressionStatement; - return isBinaryExpression(expression) && getSpecialPropertyAssignmentKind(expression) === SpecialPropertyAssignmentKind.ExportsProperty + return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === AssignmentDeclarationKind.ExportsProperty ? cb(statement as TopLevelExpressionStatement) : undefined; } } } + function forEachTopLevelDeclarationInBindingName(name: BindingName, cb: (node: TopLevelDeclaration) => T): T | undefined { + switch (name.kind) { + case SyntaxKind.Identifier: + return cb(cast(name.parent, (x): x is TopLevelVariableDeclaration | BindingElement => isVariableDeclaration(x) || isBindingElement(x))); + case SyntaxKind.ArrayBindingPattern: + case SyntaxKind.ObjectBindingPattern: + return firstDefined(name.elements, em => isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb)); + default: + return Debug.assertNever(name); + } + } function nameOfTopLevelDeclaration(d: TopLevelDeclaration): Identifier | undefined { - return d.kind === SyntaxKind.ExpressionStatement ? d.expression.left.name : tryCast(d.name, isIdentifier); + return isExpressionStatement(d) ? d.expression.left.name : tryCast(d.name, isIdentifier); } function getTopLevelDeclarationStatement(d: TopLevelDeclaration): TopLevelDeclarationStatement { - return isVariableDeclaration(d) ? d.parent.parent : d; + switch (d.kind) { + case SyntaxKind.VariableDeclaration: + return d.parent.parent; + case SyntaxKind.BindingElement: + return getTopLevelDeclarationStatement( + cast(d.parent.parent, (p): p is TopLevelVariableDeclaration | BindingElement => isVariableDeclaration(p) || isBindingElement(p))); + default: + return d; + } } function addExportToChanges(sourceFile: SourceFile, decl: TopLevelDeclarationStatement, changes: textChanges.ChangeTracker, useEs6Exports: boolean): void { diff --git a/src/services/rename.ts b/src/services/rename.ts index 43f76ff4428..484349acc86 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -1,14 +1,14 @@ /* @internal */ namespace ts.Rename { - export function getRenameInfo(program: Program, sourceFile: SourceFile, position: number): RenameInfo { + export function getRenameInfo(program: Program, sourceFile: SourceFile, position: number, options?: RenameInfoOptions): RenameInfo { const node = getTouchingPropertyName(sourceFile, position); const renameInfo = node && nodeIsEligibleForRename(node) - ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile())) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile()), options) : undefined; return renameInfo || getRenameInfoError(Diagnostics.You_cannot_rename_this_element); } - function getRenameInfoForNode(node: Node, typeChecker: TypeChecker, sourceFile: SourceFile, isDefinedInLibraryFile: (declaration: Node) => boolean): RenameInfo | undefined { + function getRenameInfoForNode(node: Node, typeChecker: TypeChecker, sourceFile: SourceFile, isDefinedInLibraryFile: (declaration: Node) => boolean, options?: RenameInfoOptions): RenameInfo | undefined { const symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) return; // Only allow a symbol to be renamed if it actually has at least one declaration. @@ -25,8 +25,9 @@ namespace ts.Rename { return undefined; } - // Can't rename a module name. - if (isStringLiteralLike(node) && tryGetImportFromModuleSpecifier(node)) return undefined; + if (isStringLiteralLike(node) && tryGetImportFromModuleSpecifier(node)) { + return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + } const kind = SymbolDisplay.getSymbolKind(typeChecker, symbol, node); const specifierName = (isImportOrExportSpecifierName(node) || isStringOrNumericLiteralLike(node) && node.parent.kind === SyntaxKind.ComputedPropertyName) @@ -37,29 +38,44 @@ namespace ts.Rename { return getRenameInfoSuccess(displayName, fullDisplayName, kind, SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } - function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo { + function getRenameInfoForModule(node: StringLiteralLike, sourceFile: SourceFile, moduleSymbol: Symbol): RenameInfo | undefined { + if (!isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + + const moduleSourceFile = find(moduleSymbol.declarations, isSourceFile); + if (!moduleSourceFile) return undefined; + const withoutIndex = endsWith(node.text, "/index") || endsWith(node.text, "/index.js") ? undefined : tryRemoveSuffix(removeFileExtension(moduleSourceFile.fileName), "/index"); + const name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + const kind = withoutIndex === undefined ? ScriptElementKind.moduleElement : ScriptElementKind.directory; + const indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + const triggerSpan = createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); return { canRename: true, + fileToRename: name, + kind, + displayName: name, + fullDisplayName: name, + kindModifiers: ScriptElementKindModifier.none, + triggerSpan, + }; + } + + function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfoSuccess { + return { + canRename: true, + fileToRename: undefined, kind, displayName, - localizedErrorMessage: undefined, fullDisplayName, kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } - function getRenameInfoError(diagnostic: DiagnosticMessage): RenameInfo { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: getLocaleSpecificMessage(diagnostic), - displayName: undefined!, - fullDisplayName: undefined!, - kind: undefined!, - kindModifiers: undefined!, - triggerSpan: undefined! - }; + function getRenameInfoError(diagnostic: DiagnosticMessage): RenameInfoFailure { + return { canRename: false, localizedErrorMessage: getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node: Node, sourceFile: SourceFile) { diff --git a/src/services/services.ts b/src/services/services.ts index dcc321b00d5..6a63497d7e6 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -17,9 +17,9 @@ namespace ts { public end: number; public flags: NodeFlags; public parent: Node; - public symbol: Symbol; - public jsDoc: JSDoc[]; - public original: Node; + public symbol!: Symbol; // Actually optional, but it was too annoying to access `node.symbol!` everywhere since in many cases we know it must be defined + public jsDoc?: JSDoc[]; + public original?: Node; public transformFlags: TransformFlags; private _children: Node[] | undefined; @@ -196,14 +196,14 @@ namespace ts { } class TokenOrIdentifierObject implements Node { - public kind: SyntaxKind; + public kind!: SyntaxKind; public pos: number; public end: number; public flags: NodeFlags; public parent: Node; - public symbol: Symbol; - public jsDocComments: JSDoc[]; - public transformFlags: TransformFlags; + public symbol!: Symbol; + public jsDocComments?: JSDoc[]; + public transformFlags!: TransformFlags; constructor(pos: number, end: number) { // Set properties in same order as NodeObject @@ -280,8 +280,8 @@ namespace ts { class SymbolObject implements Symbol { flags: SymbolFlags; escapedName: __String; - declarations: Declaration[]; - valueDeclaration: Declaration; + declarations!: Declaration[]; + valueDeclaration!: Declaration; // Undefined is used to indicate the value has not been computed. If, after computing, the // symbol has no doc comment, then the empty array will be returned. @@ -334,7 +334,7 @@ namespace ts { } class TokenObject extends TokenOrIdentifierObject implements Token { - public symbol: Symbol; + public symbol!: Symbol; public kind: TKind; constructor(kind: TKind, pos: number, end: number) { @@ -344,10 +344,10 @@ namespace ts { } class IdentifierObject extends TokenOrIdentifierObject implements Identifier { - public kind: SyntaxKind.Identifier; - public escapedText: __String; - public symbol: Symbol; - public autoGenerateFlags: GeneratedIdentifierFlags; + public kind!: SyntaxKind.Identifier; + public escapedText!: __String; + public symbol!: Symbol; + public autoGenerateFlags!: GeneratedIdentifierFlags; _primaryExpressionBrand: any; _memberExpressionBrand: any; _leftHandSideExpressionBrand: any; @@ -355,7 +355,7 @@ namespace ts { _unaryExpressionBrand: any; _expressionBrand: any; _declarationBrand: any; - /*@internal*/typeArguments: NodeArray; + /*@internal*/typeArguments!: NodeArray; constructor(_kind: SyntaxKind.Identifier, pos: number, end: number) { super(pos, end); } @@ -370,8 +370,8 @@ namespace ts { checker: TypeChecker; flags: TypeFlags; objectFlags?: ObjectFlags; - id: number; - symbol: Symbol; + id!: number; + symbol!: Symbol; constructor(checker: TypeChecker, flags: TypeFlags) { this.checker = checker; this.flags = flags; @@ -447,16 +447,16 @@ namespace ts { class SignatureObject implements Signature { checker: TypeChecker; - declaration: SignatureDeclaration; + declaration!: SignatureDeclaration; typeParameters?: TypeParameter[]; - parameters: Symbol[]; - thisParameter: Symbol; - resolvedReturnType: Type; + parameters!: Symbol[]; + thisParameter!: Symbol; + resolvedReturnType!: Type; resolvedTypePredicate: TypePredicate | undefined; - minTypeArgumentCount: number; - minArgumentCount: number; - hasRestParameter: boolean; - hasLiteralTypes: boolean; + minTypeArgumentCount!: number; + minArgumentCount!: number; + hasRestParameter!: boolean; + hasLiteralTypes!: boolean; // Undefined is used to indicate the value has not been computed. If, after computing, the // symbol has no doc comment, then the empty array will be returned. @@ -536,54 +536,55 @@ namespace ts { } class SourceFileObject extends NodeObject implements SourceFile { - public kind: SyntaxKind.SourceFile; + public kind!: SyntaxKind.SourceFile; public _declarationBrand: any; - public fileName: string; - public path: Path; - public resolvedPath: Path; - public text: string; - public scriptSnapshot: IScriptSnapshot; - public lineMap: ReadonlyArray; + public fileName!: string; + public path!: Path; + public resolvedPath!: Path; + public originalFileName!: string; + public text!: string; + public scriptSnapshot!: IScriptSnapshot; + public lineMap!: ReadonlyArray; - public statements: NodeArray; - public endOfFileToken: Token; + public statements!: NodeArray; + public endOfFileToken!: Token; - public amdDependencies: { name: string; path: string }[]; - public moduleName: string; - public referencedFiles: FileReference[]; - public typeReferenceDirectives: FileReference[]; - public libReferenceDirectives: FileReference[]; + public amdDependencies!: { name: string; path: string }[]; + public moduleName!: string; + public referencedFiles!: FileReference[]; + public typeReferenceDirectives!: FileReference[]; + public libReferenceDirectives!: FileReference[]; - public syntacticDiagnostics: DiagnosticWithLocation[]; - public parseDiagnostics: DiagnosticWithLocation[]; - public bindDiagnostics: DiagnosticWithLocation[]; + public syntacticDiagnostics!: DiagnosticWithLocation[]; + public parseDiagnostics!: DiagnosticWithLocation[]; + public bindDiagnostics!: DiagnosticWithLocation[]; public bindSuggestionDiagnostics?: DiagnosticWithLocation[]; - public isDeclarationFile: boolean; - public isDefaultLib: boolean; - public hasNoDefaultLib: boolean; - public externalModuleIndicator: Node; // The first node that causes this file to be an external module - public commonJsModuleIndicator: Node; // The first node that causes this file to be a CommonJS module - public nodeCount: number; - public identifierCount: number; - public symbolCount: number; - public version: string; - public scriptKind: ScriptKind; - public languageVersion: ScriptTarget; - public languageVariant: LanguageVariant; - public identifiers: Map; - public nameTable: UnderscoreEscapedMap; - public resolvedModules: Map; - public resolvedTypeReferenceDirectiveNames: Map; - public imports: ReadonlyArray; - public moduleAugmentations: StringLiteral[]; - private namedDeclarations: Map; - public ambientModuleNames: string[]; + public isDeclarationFile!: boolean; + public isDefaultLib!: boolean; + public hasNoDefaultLib!: boolean; + public externalModuleIndicator!: Node; // The first node that causes this file to be an external module + public commonJsModuleIndicator!: Node; // The first node that causes this file to be a CommonJS module + public nodeCount!: number; + public identifierCount!: number; + public symbolCount!: number; + public version!: string; + public scriptKind!: ScriptKind; + public languageVersion!: ScriptTarget; + public languageVariant!: LanguageVariant; + public identifiers!: Map; + public nameTable: UnderscoreEscapedMap | undefined; + public resolvedModules: Map | undefined; + public resolvedTypeReferenceDirectiveNames!: Map; + public imports!: ReadonlyArray; + public moduleAugmentations!: StringLiteral[]; + private namedDeclarations: Map | undefined; + public ambientModuleNames!: string[]; public checkJsDirective: CheckJsDirective | undefined; - public possiblyContainDynamicImport: boolean; - public pragmas: PragmaMap; - public localJsxFactory: EntityName; - public localJsxNamespace: __String; + public possiblyContainDynamicImport?: boolean; + public pragmas!: PragmaMap; + public localJsxFactory: EntityName | undefined; + public localJsxNamespace: __String | undefined; constructor(kind: SyntaxKind, pos: number, end: number) { super(kind, pos, end); @@ -601,8 +602,8 @@ namespace ts { return getLineStarts(this); } - public getPositionOfLineAndCharacter(line: number, character: number): number { - return getPositionOfLineAndCharacter(this, line, character); + public getPositionOfLineAndCharacter(line: number, character: number, allowEdits?: true): number { + return computePositionOfLineAndCharacter(getLineStarts(this), line, character, this.text, allowEdits); } public getLineEndOfPosition(pos: number): number { @@ -760,7 +761,7 @@ namespace ts { break; case SyntaxKind.BinaryExpression: - if (getSpecialPropertyAssignmentKind(node as BinaryExpression) !== SpecialPropertyAssignmentKind.None) { + if (getAssignmentDeclarationKind(node as BinaryExpression) !== AssignmentDeclarationKind.None) { addDeclaration(node as BinaryExpression); } // falls through @@ -773,7 +774,7 @@ namespace ts { } class SourceMapSourceObject implements SourceMapSource { - lineMap: number[]; + lineMap!: number[]; constructor(public fileName: string, public text: string, public skipTrivia?: (pos: number) => number) { } public getLineAndCharacterOfPosition(pos: number): LineAndCharacter { @@ -954,10 +955,10 @@ namespace ts { class SyntaxTreeCache { // For our syntactic only features, we also keep a cache of the syntax tree for the // currently edited file. - private currentFileName: string; - private currentFileVersion: string; - private currentFileScriptSnapshot: IScriptSnapshot; - private currentSourceFile: SourceFile; + private currentFileName: string | undefined; + private currentFileVersion: string | undefined; + private currentFileScriptSnapshot: IScriptSnapshot | undefined; + private currentSourceFile: SourceFile | undefined; constructor(private host: LanguageServiceHost) { } @@ -979,8 +980,8 @@ namespace ts { } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. - const editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); - sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); + const editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot!); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile!, scriptSnapshot, version, editRange); } if (sourceFile) { @@ -991,7 +992,7 @@ namespace ts { this.currentSourceFile = sourceFile; } - return this.currentSourceFile; + return this.currentSourceFile!; } } @@ -1138,7 +1139,16 @@ namespace ts { const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); - const sourceMapper = getSourceMapper(getCanonicalFileName, currentDirectory, log, host, () => program); + const sourceMapper = getSourceMapper({ + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, + getCurrentDirectory: () => currentDirectory, + getProgram, + fileExists: host.fileExists && (f => host.fileExists!(f)), + readFile: host.readFile && ((f, encoding) => host.readFile!(f, encoding)), + getDocumentPositionMapper: host.getDocumentPositionMapper && ((generatedFileName, sourceFileName) => host.getDocumentPositionMapper!(generatedFileName, sourceFileName)), + getSourceFileLike: host.getSourceFileLike && (f => host.getSourceFileLike!(f)), + log + }); function getValidSourceFile(fileName: string): SourceFile { const sourceFile = program.getSourceFile(fileName); @@ -1175,9 +1185,10 @@ namespace ts { const rootFileNames = hostCache.getRootFileNames(); const hasInvalidatedResolution: HasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse; + const projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), path => hostCache!.getVersion(path), fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), path => hostCache!.getVersion(path), fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } @@ -1201,15 +1212,7 @@ namespace ts { writeFile: noop, getCurrentDirectory: () => currentDirectory, fileExists, - readFile(fileName) { - // stub missing host functionality - const path = toPath(fileName, currentDirectory, getCanonicalFileName); - const entry = hostCache && hostCache.getEntryByPath(path); - if (entry) { - return isString(entry) ? undefined : getSnapshotText(entry.scriptSnapshot); - } - return host.readFile && host.readFile(fileName); - }, + readFile, realpath: host.realpath && (path => host.realpath!(path)), directoryExists: directoryName => { return directoryProbablyExists(directoryName, host); @@ -1217,6 +1220,10 @@ namespace ts { getDirectories: path => { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory(path, extensions, exclude, include, depth) { + Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory!(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -1226,11 +1233,11 @@ namespace ts { } if (host.resolveModuleNames) { - compilerHost.resolveModuleNames = (moduleNames, containingFile, reusedNames) => host.resolveModuleNames!(moduleNames, containingFile, reusedNames); + compilerHost.resolveModuleNames = (moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(moduleNames, containingFile, reusedNames, redirectedReference); } if (host.resolveTypeReferenceDirectives) { - compilerHost.resolveTypeReferenceDirectives = (typeReferenceDirectiveNames, containingFile) => { - return host.resolveTypeReferenceDirectives!(typeReferenceDirectiveNames, containingFile); + compilerHost.resolveTypeReferenceDirectives = (typeReferenceDirectiveNames, containingFile, redirectedReference) => { + return host.resolveTypeReferenceDirectives!(typeReferenceDirectiveNames, containingFile, redirectedReference); }; } @@ -1240,7 +1247,7 @@ namespace ts { options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences }; program = createProgram(options); @@ -1266,11 +1273,21 @@ namespace ts { (!!host.fileExists && host.fileExists(fileName)); } + function readFile(fileName: string) { + // stub missing host functionality + const path = toPath(fileName, currentDirectory, getCanonicalFileName); + const entry = hostCache && hostCache.getEntryByPath(path); + if (entry) { + return isString(entry) ? undefined : getSnapshotText(entry.scriptSnapshot); + } + return host.readFile && host.readFile(fileName); + } + // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile: SourceFile, oldOptions: CompilerOptions) { const oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); } function getOrCreateSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined { @@ -1377,7 +1394,7 @@ namespace ts { // Therefore only get diagnostics for given file. const semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } @@ -1475,7 +1492,7 @@ namespace ts { function shouldGetType(sourceFile: SourceFile, node: Node, position: number): boolean { switch (node.kind) { case SyntaxKind.Identifier: - return !isLabelName(node); + return !isLabelName(node) && !isTagName(node); case SyntaxKind.PropertyAccessExpression: case SyntaxKind.QualifiedName: // Don't return quickInfo if inside the comment in `a/**/.b` @@ -1490,7 +1507,7 @@ namespace ts { } /// Goto definition - function getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined { + function getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined { synchronizeHostData(); return GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } @@ -1500,7 +1517,7 @@ namespace ts { return GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); } - function getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined { + function getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined { synchronizeHostData(); return GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } @@ -1513,7 +1530,7 @@ namespace ts { } /// References and Occurrences - function getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined { + function getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined { return flatMap(getDocumentHighlights(fileName, position, [fileName]), entry => entry.highlightSpans.map(highlightSpan => ({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, @@ -1527,31 +1544,32 @@ namespace ts { const normalizedFileName = normalizePath(fileName); Debug.assert(filesToSearch.some(f => normalizePath(f) === normalizedFileName)); synchronizeHostData(); - const sourceFilesToSearch = map(filesToSearch, f => Debug.assertDefined(program.getSourceFile(f))); + const sourceFilesToSearch = filesToSearch.map(getValidSourceFile); const sourceFile = getValidSourceFile(fileName); return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } - function findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined { + function findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): RenameLocation[] | undefined { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const node = getTouchingPropertyName(sourceFile, position); - if (isIdentifier(node) && isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) { + if (isIdentifier(node) && (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) && isIntrinsicJsxName(node.escapedText)) { const { openingElement, closingElement } = node.parent.parent; - return [openingElement, closingElement].map((node): RenameLocation => ({ fileName: sourceFile.fileName, textSpan: createTextSpanFromNode(node.tagName, sourceFile) })); + return [openingElement, closingElement].map((node): RenameLocation => + ({ fileName: sourceFile.fileName, textSpan: createTextSpanFromNode(node.tagName, sourceFile) })); } else { - const refs = getReferences(node, position, { findInStrings, findInComments, isForRename: true }); - return refs && refs.map(({ fileName, textSpan }): RenameLocation => ({ fileName, textSpan })); + return getReferencesWorker(node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, isForRename: true }, + (entry, originalNode, checker) => FindAllReferences.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false)); } } function getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined { synchronizeHostData(); - return getReferences(getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, FindAllReferences.toReferenceEntry); } - function getReferences(node: Node, position: number, options?: FindAllReferences.Options): ReferenceEntry[] | undefined { + function getReferencesWorker(node: Node, position: number, options: FindAllReferences.Options, cb: FindAllReferences.ToReferenceOrRenameEntry): T[] | undefined { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. @@ -1559,7 +1577,7 @@ namespace ts { ? program.getSourceFiles().filter(sourceFile => !program.isSourceFileDefaultLibrary(sourceFile)) : program.getSourceFiles(); - return FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined { @@ -1803,25 +1821,36 @@ namespace ts { return ts.getEditsForFileRename(getProgram()!, oldFilePath, newFilePath, host, formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(action: CodeActionCommand): Promise; - function applyCodeActionCommand(action: CodeActionCommand[]): Promise; - function applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + function applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + function applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + function applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; function applyCodeActionCommand(fileName: Path, action: CodeActionCommand): Promise; function applyCodeActionCommand(fileName: Path, action: CodeActionCommand[]): Promise; - function applyCodeActionCommand(fileName: Path | CodeActionCommand | CodeActionCommand[], actionOrUndefined?: CodeActionCommand | CodeActionCommand[]): Promise { - const action = typeof fileName === "string" ? actionOrUndefined! : fileName as CodeActionCommand[]; - return isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName: Path | CodeActionCommand | CodeActionCommand[], actionOrFormatSettingsOrUndefined?: CodeActionCommand | CodeActionCommand[] | FormatCodeSettings): Promise { + const action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined as CodeActionCommand | CodeActionCommand[] : fileName as CodeActionCommand[]; + const formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined as FormatCodeSettings : undefined; + return isArray(action) ? Promise.all(action.map(a => applySingleCodeActionCommand(a, formatSettings))) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action: CodeActionCommand): Promise { + function applySingleCodeActionCommand(action: CodeActionCommand, formatSettings: FormatCodeSettings | undefined): Promise { + const getPath = (path: string): Path => toPath(path, currentDirectory, getCanonicalFileName); switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + const { fileToGenerateTypesFor, outputFileName } = action; + if (!host.inspectValue) return Promise.reject("Host does not implement `installPackage`"); + const valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(valueInfo => { + const fullOut = getPath(outputFileName); + host.writeFile!(fullOut, valueInfoToDeclarationFileText(valueInfo, formatSettings || testFormatSettings)); // TODO: GH#18217 + return { successMessage: `Wrote types to '${fullOut}'` }; + }); + } default: - return Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return Debug.assertNever(action); } } @@ -2034,9 +2063,9 @@ namespace ts { } } - function getRenameInfo(fileName: string, position: number): RenameInfo { + function getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo { synchronizeHostData(); - return Rename.getRenameInfo(program, getValidSourceFile(fileName), position); + return Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options); } function getRefactorContext(file: SourceFile, positionOrRange: number | TextRange, preferences: UserPreferences, formatOptions?: FormatCodeSettings): RefactorContext { @@ -2142,7 +2171,7 @@ namespace ts { function initializeNameTable(sourceFile: SourceFile): void { const nameTable = sourceFile.nameTable = createUnderscoreEscapedMap(); sourceFile.forEachChild(function walk(node) { - if (isIdentifier(node) && node.escapedText || isStringOrNumericLiteralLike(node) && literalIsName(node)) { + if (isIdentifier(node) && !isTagName(node) && node.escapedText || isStringOrNumericLiteralLike(node) && literalIsName(node)) { const text = getEscapedTextOfIdentifierOrLiteral(node); nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } diff --git a/src/services/shims.ts b/src/services/shims.ts index 8bff0db731f..208cf3dbc3c 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -164,13 +164,13 @@ namespace ts { * Returns a JSON-encoded value of the type: * { canRename: boolean, localizedErrorMessage: string, displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, triggerSpan: { start; length } } */ - getRenameInfo(fileName: string, position: number): string; + getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): string; /** * Returns a JSON-encoded value of the type: * { fileName: string, textSpan: { start: number, length: number } }[] */ - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): string; /** * Returns a JSON-encoded value of the type: @@ -331,19 +331,19 @@ namespace ts { private loggingEnabled = false; private tracingEnabled = false; - public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModuleFull[]; - public resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[]; - public directoryExists: (directoryName: string) => boolean; + public resolveModuleNames: ((moduleName: string[], containingFile: string) => (ResolvedModuleFull | undefined)[]) | undefined; + public resolveTypeReferenceDirectives: ((typeDirectiveNames: string[], containingFile: string) => (ResolvedTypeReferenceDirective | undefined)[]) | undefined; + public directoryExists: ((directoryName: string) => boolean) | undefined; constructor(private shimHost: LanguageServiceShimHost) { // if shimHost is a COM object then property check will become method call with no arguments. // 'in' does not have this effect. if ("getModuleResolutionsForFile" in this.shimHost) { - this.resolveModuleNames = (moduleNames: string[], containingFile: string): ResolvedModuleFull[] => { + this.resolveModuleNames = (moduleNames, containingFile) => { const resolutionsInFile = >JSON.parse(this.shimHost.getModuleResolutionsForFile!(containingFile)); // TODO: GH#18217 return map(moduleNames, name => { const result = getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: extensionFromPath(result), isExternalLibraryImport: false } : undefined!; // TODO: GH#18217 + return result ? { resolvedFileName: result, extension: extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -351,9 +351,9 @@ namespace ts { this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName); } if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { - this.resolveTypeReferenceDirectives = (typeDirectiveNames: string[], containingFile: string) => { + this.resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile) => { const typeDirectivesForFile = >JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile!(containingFile)); // TODO: GH#18217 - return map(typeDirectiveNames, name => getProperty(typeDirectivesForFile, name)!); // TODO: GH#18217 + return map(typeDirectiveNames, name => getProperty(typeDirectivesForFile, name)); }; } } @@ -490,13 +490,19 @@ namespace ts { public useCaseSensitiveFileNames: boolean; constructor(private shimHost: CoreServicesShimHost) { - this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; if ("directoryExists" in this.shimHost) { this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName); } + else { + this.directoryExists = undefined!; // TODO: GH#18217 + } if ("realpath" in this.shimHost) { this.realpath = path => this.shimHost.realpath!(path); // TODO: GH#18217 } + else { + this.realpath = undefined!; // TODO: GH#18217 + } } public readDirectory(rootDir: string, extensions: ReadonlyArray, exclude: ReadonlyArray, include: ReadonlyArray, depth?: number): string[] { @@ -825,17 +831,17 @@ namespace ts { ); } - public getRenameInfo(fileName: string, position: number): string { + public getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): string { return this.forwardJSONCall( `getRenameInfo('${fileName}', ${position})`, - () => this.languageService.getRenameInfo(fileName, position) + () => this.languageService.getRenameInfo(fileName, position, options) ); } - public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string { + public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): string { return this.forwardJSONCall( - `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`, - () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments) + `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments}, ${providePrefixAndSuffixTextForRename})`, + () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) ); } @@ -1182,7 +1188,7 @@ namespace ts { export class TypeScriptServicesFactory implements ShimFactory { private _shims: Shim[] = []; - private documentRegistry: DocumentRegistry; + private documentRegistry: DocumentRegistry | undefined; /* * Returns script API version. diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index b6174be75e0..d63e16ce801 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -38,7 +38,8 @@ namespace ts.SignatureHelp { return undefined; } - const argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + const isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + const argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); @@ -50,7 +51,7 @@ namespace ts.SignatureHelp { if (!candidateInfo) { // 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. - return isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } return typeChecker.runWithCancellationToken(cancellationToken, typeChecker => @@ -115,7 +116,7 @@ namespace ts.SignatureHelp { } } - function createJavaScriptSignatureHelpItems(argumentInfo: ArgumentListInfo, program: Program, cancellationToken: CancellationToken): SignatureHelpItems | undefined { + function createJSSignatureHelpItems(argumentInfo: ArgumentListInfo, program: Program, cancellationToken: CancellationToken): SignatureHelpItems | undefined { if (argumentInfo.invocation.kind === InvocationKind.Contextual) return undefined; // See if we can find some symbol with the call expression name that has call signatures. const expression = getExpressionFromInvocation(argumentInfo.invocation); @@ -450,8 +451,8 @@ namespace ts.SignatureHelp { return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node: Node, position: number, sourceFile: SourceFile, checker: TypeChecker): ArgumentListInfo | undefined { - for (let n = node; !isBlock(n) && !isSourceFile(n); n = n.parent) { + function getContainingArgumentInfo(node: Node, position: number, sourceFile: SourceFile, checker: TypeChecker, isManuallyInvoked: boolean): ArgumentListInfo | undefined { + for (let n = node; isManuallyInvoked || (!isBlock(n) && !isSourceFile(n)); n = n.parent) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. Debug.assert(rangeContainsRange(n.parent, n), "Not a subspan", () => `Child: ${Debug.showSyntaxKind(n)}, parent: ${Debug.showSyntaxKind(n.parent)}`); diff --git a/src/services/sourcemaps.ts b/src/services/sourcemaps.ts index 1833c415be4..d07c21a9f43 100644 --- a/src/services/sourcemaps.ts +++ b/src/services/sourcemaps.ts @@ -1,130 +1,191 @@ /* @internal */ namespace ts { - // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) - const sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; - const whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; const base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; export interface SourceMapper { toLineColumnOffset(fileName: string, position: number): LineAndCharacter; - tryGetOriginalLocation(info: sourcemaps.SourceMappableLocation): sourcemaps.SourceMappableLocation | undefined; - tryGetGeneratedLocation(info: sourcemaps.SourceMappableLocation): sourcemaps.SourceMappableLocation | undefined; + tryGetSourcePosition(info: DocumentPosition): DocumentPosition | undefined; + tryGetGeneratedPosition(info: DocumentPosition): DocumentPosition | undefined; clearCache(): void; } - export function getSourceMapper( - getCanonicalFileName: GetCanonicalFileName, - currentDirectory: string, - log: (message: string) => void, - host: LanguageServiceHost, - getProgram: () => Program, - ): SourceMapper { - let sourcemappedFileCache: SourceFileLikeCache; - return { tryGetOriginalLocation, tryGetGeneratedLocation, toLineColumnOffset, clearCache }; + export interface SourceMapperHost { + useCaseSensitiveFileNames(): boolean; + getCurrentDirectory(): string; + getProgram(): Program | undefined; + fileExists?(path: string): boolean; + readFile?(path: string, encoding?: string): string | undefined; + getSourceFileLike?(fileName: string): SourceFileLike | undefined; + getDocumentPositionMapper?(generatedFileName: string, sourceFileName?: string): DocumentPositionMapper | undefined; + log(s: string): void; + } - function scanForSourcemapURL(fileName: string) { - const mappedFile = sourcemappedFileCache.get(toPath(fileName, currentDirectory, getCanonicalFileName)); - if (!mappedFile) { - return; - } - const starts = getLineStarts(mappedFile); - for (let index = starts.length - 1; index >= 0; index--) { - const lineText = mappedFile.text.substring(starts[index], starts[index + 1]); - const comment = sourceMapCommentRegExp.exec(lineText); - if (comment) { - return comment[1]; - } - // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file - else if (!lineText.match(whitespaceOrMapCommentRegExp)) { - break; - } - } + export function getSourceMapper(host: SourceMapperHost): SourceMapper { + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + const currentDirectory = host.getCurrentDirectory(); + const sourceFileLike = createMap(); + const documentPositionMappers = createMap(); + return { tryGetSourcePosition, tryGetGeneratedPosition, toLineColumnOffset, clearCache }; + + function toPath(fileName: string) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } - function convertDocumentToSourceMapper(file: { sourceMapper?: sourcemaps.SourceMapper }, contents: string, mapFileName: string) { - let maps: sourcemaps.SourceMapData | undefined; - try { - maps = JSON.parse(contents); + function getDocumentPositionMapper(generatedFileName: string, sourceFileName?: string) { + const path = toPath(generatedFileName); + const value = documentPositionMappers.get(path); + if (value) return value; + + let mapper: DocumentPositionMapper | undefined; + if (host.getDocumentPositionMapper) { + mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName); } - catch { - // swallow error + else if (host.readFile) { + const file = getSourceFileLike(generatedFileName); + mapper = file && ts.getDocumentPositionMapper( + { getSourceFileLike, getCanonicalFileName, log: s => host.log(s) }, + generatedFileName, + getLineInfo(file.text, getLineStarts(file)), + f => !host.fileExists || host.fileExists(f) ? host.readFile!(f) : undefined + ); } - if (!maps || !maps.sources || !maps.file || !maps.mappings) { - // obviously invalid map - return file.sourceMapper = sourcemaps.identitySourceMapper; - } - return file.sourceMapper = sourcemaps.decode({ - readFile: s => host.readFile!(s), // TODO: GH#18217 - fileExists: s => host.fileExists!(s), // TODO: GH#18217 - getCanonicalFileName, - log, - }, mapFileName, maps, getProgram(), sourcemappedFileCache); + documentPositionMappers.set(path, mapper || identitySourceMapConsumer); + return mapper || identitySourceMapConsumer; } - function getSourceMapper(fileName: string, file: SourceFileLike): sourcemaps.SourceMapper { - if (!host.readFile || !host.fileExists) { - return file.sourceMapper = sourcemaps.identitySourceMapper; - } - if (file.sourceMapper) { - return file.sourceMapper; - } - let mapFileName = scanForSourcemapURL(fileName); - if (mapFileName) { - const match = base64UrlRegExp.exec(mapFileName); - if (match) { - if (match[1]) { - const base64Object = match[1]; - return convertDocumentToSourceMapper(file, base64decode(sys, base64Object), fileName); - } - // Not a data URL we can parse, skip it - mapFileName = undefined; - } - } - const possibleMapLocations: string[] = []; - if (mapFileName) { - possibleMapLocations.push(mapFileName); - } - possibleMapLocations.push(fileName + ".map"); - for (const location of possibleMapLocations) { - const mapPath = toPath(location, getDirectoryPath(fileName), getCanonicalFileName); - if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath)!, mapPath); // TODO: GH#18217 - } - } - return file.sourceMapper = sourcemaps.identitySourceMapper; - } - - function tryGetOriginalLocation(info: sourcemaps.SourceMappableLocation): sourcemaps.SourceMappableLocation | undefined { + function tryGetSourcePosition(info: DocumentPosition): DocumentPosition | undefined { if (!isDeclarationFileName(info.fileName)) return undefined; - const file = getFile(info.fileName); + const file = getSourceFile(info.fileName); if (!file) return undefined; - const newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); - return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + + const newLoc = getDocumentPositionMapper(info.fileName).getSourcePosition(info); + return !newLoc || newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; } - function tryGetGeneratedLocation(info: sourcemaps.SourceMappableLocation): sourcemaps.SourceMappableLocation | undefined { - const program = getProgram(); - const declarationPath = getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + function tryGetGeneratedPosition(info: DocumentPosition): DocumentPosition | undefined { + if (isDeclarationFileName(info.fileName)) return undefined; + + const sourceFile = getSourceFile(info.fileName); + if (!sourceFile) return undefined; + + const program = host.getProgram()!; + const options = program.getCompilerOptions(); + const outPath = options.outFile || options.out; + + const declarationPath = outPath ? + removeFileExtension(outPath) + Extension.Dts : + getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); if (declarationPath === undefined) return undefined; - const declarationFile = getFile(declarationPath); - if (!declarationFile) return undefined; - const newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + + const newLoc = getDocumentPositionMapper(declarationPath, info.fileName).getGeneratedPosition(info); return newLoc === info ? undefined : newLoc; } - function getFile(fileName: string): SourceFileLike | undefined { - return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(toPath(fileName, currentDirectory, getCanonicalFileName)); + function getSourceFile(fileName: string) { + const program = host.getProgram(); + if (!program) return undefined; + + const path = toPath(fileName); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + const file = program.getSourceFileByPath(path); + return file && file.resolvedPath === path ? file : undefined; + } + + function getOrCreateSourceFileLike(fileName: string): SourceFileLike | undefined { + const path = toPath(fileName); + const fileFromCache = sourceFileLike.get(path); + if (fileFromCache !== undefined) return fileFromCache ? fileFromCache : undefined; + + if (!host.readFile || host.fileExists && !host.fileExists(path)) { + sourceFileLike.set(path, false); + return undefined; + } + + // And failing that, check the disk + const text = host.readFile(path); + const file = text ? createSourceFileLike(text) : false; + sourceFileLike.set(path, file); + return file ? file : undefined; + } + + // This can be called from source mapper in either source program or program that includes generated file + function getSourceFileLike(fileName: string) { + return !host.getSourceFileLike ? + getSourceFile(fileName) || getOrCreateSourceFileLike(fileName) : + host.getSourceFileLike(fileName); } function toLineColumnOffset(fileName: string, position: number): LineAndCharacter { - const path = toPath(fileName, currentDirectory, getCanonicalFileName); - const file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path)!; // TODO: GH#18217 + const file = getSourceFileLike(fileName)!; // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } function clearCache(): void { - sourcemappedFileCache = createSourceFileLikeCache(host); + sourceFileLike.clear(); + documentPositionMappers.clear(); } } + + /** + * string | undefined to contents of map file to create DocumentPositionMapper from it + * DocumentPositionMapper | false to give back cached DocumentPositionMapper + */ + export type ReadMapFile = (mapFileName: string, mapFileNameFromDts: string | undefined) => string | undefined | DocumentPositionMapper | false; + + export function getDocumentPositionMapper( + host: DocumentPositionMapperHost, + generatedFileName: string, + generatedFileLineInfo: LineInfo, + readMapFile: ReadMapFile) { + let mapFileName = tryGetSourceMappingURL(generatedFileLineInfo); + if (mapFileName) { + const match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + const base64Object = match[1]; + return convertDocumentToSourceMapper(host, base64decode(sys, base64Object), generatedFileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + const possibleMapLocations: string[] = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(generatedFileName + ".map"); + const originalMapFileName = mapFileName && getNormalizedAbsolutePath(mapFileName, getDirectoryPath(generatedFileName)); + for (const location of possibleMapLocations) { + const mapFileName = getNormalizedAbsolutePath(location, getDirectoryPath(generatedFileName)); + const mapFileContents = readMapFile(mapFileName, originalMapFileName); + if (isString(mapFileContents)) { + return convertDocumentToSourceMapper(host, mapFileContents, mapFileName); + } + if (mapFileContents !== undefined) { + return mapFileContents || undefined; + } + } + return undefined; + } + + function convertDocumentToSourceMapper(host: DocumentPositionMapperHost, contents: string, mapFileName: string) { + const map = tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { + // obviously invalid map + return undefined; + } + + return createDocumentPositionMapper(host, map, mapFileName); + } + + function createSourceFileLike(text: string, lineMap?: SourceFileLike["lineMap"]): SourceFileLike { + return { + text, + lineMap, + getLineAndCharacterOfPosition(pos: number) { + return computeLineAndCharacterOfPosition(getLineStarts(this), pos); + } + }; + } } diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts new file mode 100644 index 00000000000..9548397a22d --- /dev/null +++ b/src/services/stringCompletions.ts @@ -0,0 +1,726 @@ +/* @internal */ +namespace ts.Completions.StringCompletions { + export function getStringLiteralCompletions(sourceFile: SourceFile, position: number, contextToken: Node | undefined, checker: TypeChecker, options: CompilerOptions, host: LanguageServiceHost, log: Log, preferences: UserPreferences): CompletionInfo | undefined { + if (isInReferenceComment(sourceFile, position)) { + const entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (isInString(sourceFile, position, contextToken)) { + return !contextToken || !isStringLiteralLike(contextToken) + ? undefined + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host), sourceFile, checker, log, preferences); + } + } + + function convertStringLiteralCompletions(completion: StringLiteralCompletion | undefined, sourceFile: SourceFile, checker: TypeChecker, log: Log, preferences: UserPreferences): CompletionInfo | undefined { + if (completion === undefined) { + return undefined; + } + switch (completion.kind) { + case StringLiteralCompletionKind.Paths: + return convertPathCompletions(completion.paths); + case StringLiteralCompletionKind.Properties: { + const entries: CompletionEntry[] = []; + getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, ScriptTarget.ESNext, log, CompletionKind.String, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries }; + } + case StringLiteralCompletionKind.Types: { + const entries = completion.types.map(type => ({ name: type.value, kindModifiers: ScriptElementKindModifier.none, kind: ScriptElementKind.string, sortText: "0" })); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries }; + } + default: + return Debug.assertNever(completion); + } + } + + export function getStringLiteralCompletionDetails(name: string, sourceFile: SourceFile, position: number, contextToken: Node | undefined, checker: TypeChecker, options: CompilerOptions, host: LanguageServiceHost, cancellationToken: CancellationToken) { + if (!contextToken || !isStringLiteralLike(contextToken)) return undefined; + const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); + } + + function stringLiteralCompletionDetails(name: string, location: Node, completion: StringLiteralCompletion, sourceFile: SourceFile, checker: TypeChecker, cancellationToken: CancellationToken): CompletionEntryDetails | undefined { + switch (completion.kind) { + case StringLiteralCompletionKind.Paths: { + const match = find(completion.paths, p => p.name === name); + return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [textPart(name)]); + } + case StringLiteralCompletionKind.Properties: { + const match = find(completion.symbols, s => s.name === name); + return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case StringLiteralCompletionKind.Types: + return find(completion.types, t => t.value === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.typeElement, [textPart(name)]) : undefined; + default: + return Debug.assertNever(completion); + } + } + + function convertPathCompletions(pathCompletions: ReadonlyArray): CompletionInfo { + const isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. + const isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. + const entries = pathCompletions.map(({ name, kind, span, extension }): CompletionEntry => + ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span })); + return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries }; + } + function kindModifiersFromExtension(extension: Extension | undefined): ScriptElementKindModifier { + switch (extension) { + case Extension.Dts: return ScriptElementKindModifier.dtsModifier; + case Extension.Js: return ScriptElementKindModifier.jsModifier; + case Extension.Json: return ScriptElementKindModifier.jsonModifier; + case Extension.Jsx: return ScriptElementKindModifier.jsxModifier; + case Extension.Ts: return ScriptElementKindModifier.tsModifier; + case Extension.Tsx: return ScriptElementKindModifier.tsxModifier; + case undefined: return ScriptElementKindModifier.none; + default: + return Debug.assertNever(extension); + } + } + + const enum StringLiteralCompletionKind { Paths, Properties, Types } + interface StringLiteralCompletionsFromProperties { + readonly kind: StringLiteralCompletionKind.Properties; + readonly symbols: ReadonlyArray; + readonly hasIndexSignature: boolean; + } + interface StringLiteralCompletionsFromTypes { + readonly kind: StringLiteralCompletionKind.Types; + readonly types: ReadonlyArray; + readonly isNewIdentifier: boolean; + } + type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: ReadonlyArray } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; + function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost): StringLiteralCompletion | undefined { + const { parent } = node; + switch (parent.kind) { + case SyntaxKind.LiteralType: + switch (parent.parent.kind) { + case SyntaxKind.TypeReference: + return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent as LiteralTypeNode)), isNewIdentifier: false }; + case SyntaxKind.IndexedAccessType: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((parent.parent as IndexedAccessTypeNode).objectType)); + case SyntaxKind.ImportType: + return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case SyntaxKind.UnionType: { + if (!isTypeReferenceNode(parent.parent.parent)) return undefined; + const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(parent.parent as UnionTypeNode, parent as LiteralTypeNode); + const types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent as UnionTypeNode)).filter(t => !contains(alreadyUsedTypes, t.value)); + return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier: false }; + } + default: + return undefined; + } + + case SyntaxKind.PropertyAssignment: + if (isObjectLiteralExpression(parent.parent) && (parent).name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); + } + return fromContextualType(); + + case SyntaxKind.ElementAccessExpression: { + const { expression, argumentExpression } = parent as ElementAccessExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return undefined; + } + + case SyntaxKind.CallExpression: + case SyntaxKind.NewExpression: + if (!isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(parent)) { + const argumentInfo = SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through (is `require("")` or `import("")`) + + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ExportDeclaration: + case SyntaxKind.ExternalModuleReference: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + + default: + return fromContextualType(); + } + + function fromContextualType(): StringLiteralCompletion { + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; + } + } + + function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current: LiteralTypeNode): ReadonlyArray { + return mapDefined(union.types, type => + type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined); + } + + function getStringLiteralCompletionsFromSignature(argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker): StringLiteralCompletionsFromTypes { + let isNewIdentifier = false; + + const uniques = createMap(); + const candidates: Signature[] = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + const types = flatMap(candidates, candidate => { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) return; + const type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & TypeFlags.String); + return getStringLiteralTypes(type, uniques); + }); + + return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier }; + } + + function stringLiteralCompletionsFromProperties(type: Type | undefined): StringLiteralCompletionsFromProperties | undefined { + return type && { kind: StringLiteralCompletionKind.Properties, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; + } + + function getStringLiteralTypes(type: Type | undefined, uniques = createMap()): ReadonlyArray { + if (!type) return emptyArray; + type = skipConstraint(type); + return type.isUnion() + ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) + : type.isStringLiteral() && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, type.value) + ? [type] + : emptyArray; + } + + interface NameAndKind { + readonly name: string; + readonly kind: ScriptElementKind.scriptElement | ScriptElementKind.directory | ScriptElementKind.externalModuleName; + readonly extension: Extension | undefined; + } + interface PathCompletion extends NameAndKind { + readonly span: TextSpan | undefined; + } + + function nameAndKind(name: string, kind: NameAndKind["kind"], extension: Extension | undefined): NameAndKind { + return { name, kind, extension }; + } + function directoryResult(name: string): NameAndKind { + return nameAndKind(name, ScriptElementKind.directory, /*extension*/ undefined); + } + + function addReplacementSpans(text: string, textStart: number, names: ReadonlyArray): ReadonlyArray { + const span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(({ name, kind, extension }): PathCompletion => ({ name, kind, extension, span })); + } + + function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + } + + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { + const literalValue = normalizeSlashes(node.text); + + const scriptPath = sourceFile.path; + const scriptDirectory = getDirectoryPath(scriptPath); + + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (isRootedDiskPath(literalValue) || isUrl(literalValue)) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + } + + interface ExtensionOptions { + readonly extensions: ReadonlyArray; + readonly includeExtensions: boolean; + } + function getExtensionOptions(compilerOptions: CompilerOptions, includeExtensions = false): ExtensionOptions { + return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions }; + } + function getCompletionEntriesForRelativeModules(literalValue: string, scriptDirectory: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, scriptPath: Path) { + const extensionOptions = getExtensionOptions(compilerOptions); + if (compilerOptions.rootDirs) { + return getCompletionEntriesForDirectoryFragmentWithRootDirs( + compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); + } + else { + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + } + } + + function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions): ReadonlyArray { + const extensions = getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs ? + extensions.concat(Extension.Json) : + extensions; + } + + /** + * Takes a script path and returns paths for all potential folders that could be merged with its + * containing folder via the "rootDirs" compiler option + */ + function getBaseDirectoriesFromRootDirs(rootDirs: string[], basePath: string, scriptDirectory: string, ignoreCase: boolean): ReadonlyArray { + // Make all paths absolute/normalized if they are not already + rootDirs = rootDirs.map(rootDirectory => normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory))); + + // Determine the path to the directory containing the script relative to the root directory it is contained within + const relativeDirectory = firstDefined(rootDirs, rootDirectory => + containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined)!; // TODO: GH#18217 + + // Now find a path for each potential directory that is to be merged with the one containing the script + return deduplicate( + [...rootDirs.map(rootDirectory => combinePaths(rootDirectory, relativeDirectory)), scriptDirectory], + equateStringsCaseSensitive, + compareStringsCaseSensitive); + } + + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs: string[], fragment: string, scriptDirectory: string, extensionOptions: ExtensionOptions, compilerOptions: CompilerOptions, host: LanguageServiceHost, exclude: string): ReadonlyArray { + const basePath = compilerOptions.project || host.getCurrentDirectory(); + const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); + return flatMap(baseDirectories, baseDirectory => getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude)); + } + + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ + function getCompletionEntriesForDirectoryFragment(fragment: string, scriptPath: string, { extensions, includeExtensions }: ExtensionOptions, host: LanguageServiceHost, exclude?: string, result: NameAndKind[] = []): NameAndKind[] { + if (fragment === undefined) { + fragment = ""; + } + + fragment = normalizeSlashes(fragment); + + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ + if (!hasTrailingDirectorySeparator(fragment)) { + fragment = getDirectoryPath(fragment); + } + + if (fragment === "") { + fragment = "." + directorySeparator; + } + + fragment = ensureTrailingDirectorySeparator(fragment); + + // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths + const absolutePath = resolvePath(scriptPath, fragment); + const baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath); + + const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (!tryDirectoryExists(host, baseDirectory)) return result; + + // Enumerate the available files if possible + const files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + + if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ + const foundFiles = createMap(); // maps file to its extension + for (let filePath of files) { + filePath = normalizePath(filePath); + if (exclude && comparePaths(filePath, exclude, scriptPath, ignoreCase) === Comparison.EqualTo) { + continue; + } + + const foundFileName = includeExtensions || fileExtensionIs(filePath, Extension.Json) ? getBaseFileName(filePath) : removeFileExtension(getBaseFileName(filePath)); + foundFiles.set(foundFileName, tryGetExtensionFromPath(filePath)); + } + + foundFiles.forEach((ext, foundFile) => { + result.push(nameAndKind(foundFile, ScriptElementKind.scriptElement, ext)); + }); + } + + // If possible, get folder completion as well + const directories = tryGetDirectories(host, baseDirectory); + + if (directories) { + for (const directory of directories) { + const directoryName = getBaseFileName(normalizePath(directory)); + if (directoryName !== "@types") { + result.push(directoryResult(directoryName)); + } + } + } + + // check for a version redirect + const packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + const packageJson = readJson(packageJsonPath, host as { readFile: (filename: string) => string | undefined }); + const typesVersions = (packageJson as any).typesVersions; + if (typeof typesVersions === "object") { + const versionResult = getPackageJsonTypesVersionsPaths(typesVersions); + const versionPaths = versionResult && versionResult.paths; + const rest = absolutePath.slice(ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } + + return result; + } + + function addCompletionEntriesFromPaths(result: NameAndKind[], fragment: string, baseDirectory: string, fileExtensions: ReadonlyArray, paths: MapLike, host: LanguageServiceHost) { + for (const path in paths) { + if (!hasProperty(paths, path)) continue; + const patterns = paths[path]; + if (patterns) { + for (const { name, kind, extension } of getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host)) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(entry => entry.name === name)) { + result.push(nameAndKind(name, kind, extension)); + } + } + } + } + } + + /** + * Check all of the declared modules and those in node modules. Possible sources of modules: + * Modules that are found by the type checker + * Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option) + * Modules from node_modules (i.e. those listed in package.json) + * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions + */ + function getCompletionEntriesForNonRelativeModules(fragment: string, scriptPath: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { + const { baseUrl, paths } = compilerOptions; + + const result: NameAndKind[] = []; + + const extensionOptions = getExtensionOptions(compilerOptions); + if (baseUrl) { + const projectDir = compilerOptions.project || host.getCurrentDirectory(); + const absolute = normalizePath(combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); + } + } + + const fragmentDirectory = getFragmentDirectory(fragment); + for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker)) { + result.push(nameAndKind(ambientName, ScriptElementKind.externalModuleName, /*extension*/ undefined)); + } + + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); + + if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs) { + // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. + // (But do if we didn't find anything, e.g. 'package.json' missing.) + let foundGlobal = false; + if (fragmentDirectory === undefined) { + for (const moduleName of enumerateNodeModulesVisibleToScript(host, scriptPath)) { + if (!result.some(entry => entry.name === moduleName)) { + foundGlobal = true; + result.push(nameAndKind(moduleName, ScriptElementKind.externalModuleName, /*extension*/ undefined)); + } + } + } + if (!foundGlobal) { + forEachAncestorDirectory(scriptPath, ancestor => { + const nodeModules = combinePaths(ancestor, "node_modules"); + if (tryDirectoryExists(host, nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result); + } + }); + } + } + + return result; + } + + function getFragmentDirectory(fragment: string): string | undefined { + return containsSlash(fragment) ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : undefined; + } + + function getCompletionsForPathMapping( + path: string, patterns: ReadonlyArray, fragment: string, baseUrl: string, fileExtensions: ReadonlyArray, host: LanguageServiceHost, + ): ReadonlyArray { + if (!endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !stringContains(path, "*") ? justPathMappingName(path) : emptyArray; + } + + const pathPrefix = path.slice(0, path.length - 1); + const remainingFragment = tryRemovePrefix(fragment, pathPrefix); + return remainingFragment === undefined ? justPathMappingName(pathPrefix) : flatMap(patterns, pattern => + getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host)); + + function justPathMappingName(name: string): ReadonlyArray { + return startsWith(name, fragment) ? [directoryResult(name)] : emptyArray; + } + } + + function getModulesForPathsPattern(fragment: string, baseUrl: string, pattern: string, fileExtensions: ReadonlyArray, host: LanguageServiceHost): ReadonlyArray | undefined { + if (!host.readDirectory) { + return undefined; + } + + const parsed = hasZeroOrOneAsteriskCharacter(pattern) ? tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + const normalizedPrefix = resolvePath(parsed.prefix); + const normalizedPrefixDirectory = hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : getDirectoryPath(normalizedPrefix); + const normalizedPrefixBase = hasTrailingDirectorySeparator(parsed.prefix) ? "" : getBaseFileName(normalizedPrefix); + + const fragmentHasPath = containsSlash(fragment); + const fragmentDirectory = fragmentHasPath ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : undefined; + + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; + + const normalizedSuffix = normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + const baseDirectory = normalizePath(combinePaths(baseUrl, expandedPrefixDirectory)); + const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + const includeGlob = normalizedSuffix ? "**/*" : "./*"; + + const matches = mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), match => { + const extension = tryGetExtensionFromPath(match); + const name = trimPrefixAndSuffix(match); + return name === undefined ? undefined : nameAndKind(removeFileExtension(name), ScriptElementKind.scriptElement, extension); + }); + const directories = mapDefined(tryGetDirectories(host, baseDirectory).map(d => combinePaths(baseDirectory, d)), dir => { + const name = trimPrefixAndSuffix(dir); + return name === undefined ? undefined : directoryResult(name); + }); + return [...matches, ...directories]; + + function trimPrefixAndSuffix(path: string): string | undefined { + const inner = withoutStartAndEnd(normalizePath(path), completePrefix, normalizedSuffix); + return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner); + } + } + + function withoutStartAndEnd(s: string, start: string, end: string): string | undefined { + return startsWith(s, start) && endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; + } + + function removeLeadingDirectorySeparator(path: string): string { + return path[0] === directorySeparator ? path.slice(1) : path; + } + + function getAmbientModuleCompletions(fragment: string, fragmentDirectory: string | undefined, checker: TypeChecker): ReadonlyArray { + // Get modules that the type checker picked up + const ambientModules = checker.getAmbientModules().map(sym => stripQuotes(sym.name)); + const nonRelativeModuleNames = ambientModules.filter(moduleName => startsWith(moduleName, fragment)); + + // Nested modules of the form "module-name/sub" need to be adjusted to only return the string + // after the last '/' that appears in the fragment because that's where the replacement span + // starts + if (fragmentDirectory !== undefined) { + const moduleNameWithSeparator = ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(nonRelativeModuleName => removePrefix(nonRelativeModuleName, moduleNameWithSeparator)); + } + return nonRelativeModuleNames; + } + + function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): ReadonlyArray | undefined { + const token = getTokenAtPosition(sourceFile, position); + const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); + const range = commentRanges && find(commentRanges, commentRange => position >= commentRange.pos && position <= commentRange.end); + if (!range) { + return undefined; + } + const text = sourceFile.text.slice(range.pos, position); + const match = tripleSlashDirectiveFragmentRegex.exec(text); + if (!match) { + return undefined; + } + + const [, prefix, kind, toComplete] = match; + const scriptPath = getDirectoryPath(sourceFile.path); + const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) + : Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, names); + } + + function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, fragmentDirectory: string | undefined, extensionOptions: ExtensionOptions, result: NameAndKind[] = []): ReadonlyArray { + // Check for typings specified in compiler options + const seen = createMap(); + + const typeRoots = tryAndIgnoreErrors(() => getEffectiveTypeRoots(options, host)) || emptyArray; + + for (const root of typeRoots) { + getCompletionEntriesFromDirectories(root); + } + + // Also get all @types typings installed in visible node_modules directories + for (const packageJson of findPackageJsons(scriptPath, host)) { + const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); + } + + return result; + + function getCompletionEntriesFromDirectories(directory: string): void { + if (!tryDirectoryExists(host, directory)) return; + + for (const typeDirectoryName of tryGetDirectories(host, directory)) { + const packageName = unmangleScopedPackageName(typeDirectoryName); + if (options.types && !contains(options.types, packageName)) continue; + + if (fragmentDirectory === undefined) { + if (!seen.has(packageName)) { + result.push(nameAndKind(packageName, ScriptElementKind.externalModuleName, /*extension*/ undefined)); + seen.set(packageName, true); + } + } + else { + const baseDirectory = combinePaths(directory, typeDirectoryName); + const remainingFragment = tryRemoveDirectoryPrefix(fragmentDirectory, packageName, hostGetCanonicalFileName(host)); + if (remainingFragment !== undefined) { + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result); + } + } + } + } + } + + function findPackageJsons(directory: string, host: LanguageServiceHost): string[] { + const paths: string[] = []; + forEachAncestorDirectory(directory, ancestor => { + const currentConfigPath = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); + if (!currentConfigPath) { + return true; // break out + } + paths.push(currentConfigPath); + }); + return paths; + } + + function findPackageJson(directory: string, host: LanguageServiceHost): string | undefined { + let packageJson: string | undefined; + forEachAncestorDirectory(directory, ancestor => { + if (ancestor === "node_modules") return true; + packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } + + function enumerateNodeModulesVisibleToScript(host: LanguageServiceHost, scriptPath: string): ReadonlyArray { + if (!host.readFile || !host.fileExists) return emptyArray; + + const result: string[] = []; + for (const packageJson of findPackageJsons(scriptPath, host)) { + const contents = readJson(packageJson, host as { readFile: (filename: string) => string | undefined }); // Cast to assert that readFile is defined + // Provide completions for all non @types dependencies + for (const key of nodeModulesDependencyKeys) { + const dependencies: object | undefined = (contents as any)[key]; + if (!dependencies) continue; + for (const dep in dependencies) { + if (dependencies.hasOwnProperty(dep) && !startsWith(dep, "@types/")) { + result.push(dep); + } + } + } + } + return result; + } + + // Replace everything after the last directory separator that appears + function getDirectoryFragmentTextSpan(text: string, textStart: number): TextSpan | undefined { + const index = Math.max(text.lastIndexOf(directorySeparator), text.lastIndexOf("\\")); + const offset = index !== -1 ? index + 1 : 0; + // If the range is an identifier, span is unnecessary. + const length = text.length - offset; + return length === 0 || isIdentifierText(text.substr(offset, length), ScriptTarget.ESNext) ? undefined : createTextSpan(textStart + offset, length); + } + + // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) + function isPathRelativeToScript(path: string) { + if (path && path.length >= 2 && path.charCodeAt(0) === CharacterCodes.dot) { + const slashIndex = path.length >= 3 && path.charCodeAt(1) === CharacterCodes.dot ? 2 : 1; + const slashCharCode = path.charCodeAt(slashIndex); + return slashCharCode === CharacterCodes.slash || slashCharCode === CharacterCodes.backslash; + } + return false; + } + + /** + * Matches a triple slash reference directive with an incomplete string literal for its path. Used + * to determine if the caret is currently within the string literal and capture the literal fragment + * for completions. + * For example, this matches + * + * /// = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; + + function tryGetDirectories(host: LanguageServiceHost, directoryName: string): string[] { + return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || []; + } + + function tryReadDirectory(host: LanguageServiceHost, path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray): ReadonlyArray { + return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || emptyArray; + } + + function tryFileExists(host: LanguageServiceHost, path: string): boolean { + return tryIOAndConsumeErrors(host, host.fileExists, path); + } + + function tryDirectoryExists(host: LanguageServiceHost, path: string): boolean { + return tryAndIgnoreErrors(() => directoryProbablyExists(path, host)) || false; + } + + function tryIOAndConsumeErrors(host: LanguageServiceHost, toApply: ((...a: any[]) => T) | undefined, ...args: any[]) { + return tryAndIgnoreErrors(() => toApply && toApply.apply(host, args)); + } + + function tryAndIgnoreErrors(cb: () => T): T | undefined { + try { return cb(); } + catch { return undefined; } + } + + function containsSlash(fragment: string) { + return stringContains(fragment, directorySeparator); + } +} diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index 167bcb6bbac..63691a72c8b 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -1,5 +1,7 @@ /* @internal */ namespace ts { + const visitedNestedConvertibleFunctions = createMap(); + export function computeSuggestionDiagnostics(sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): DiagnosticWithLocation[] { program.getSemanticDiagnostics(sourceFile, cancellationToken); const diags: DiagnosticWithLocation[] = []; @@ -11,8 +13,9 @@ namespace ts { diags.push(createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - const isJsFile = isSourceFileJavaScript(sourceFile); + const isJsFile = isSourceFileJS(sourceFile); + visitedNestedConvertibleFunctions.clear(); check(sourceFile); if (getAllowSyntheticDefaultImports(program.getCompilerOptions())) { @@ -36,7 +39,7 @@ namespace ts { if (isJsFile) { switch (node.kind) { case SyntaxKind.FunctionExpression: - const decl = getDeclarationOfJSInitializer(node); + const decl = getDeclarationOfExpando(node); if (decl) { const symbol = decl.symbol; if (symbol && (symbol.exports && symbol.exports.size || symbol.members && symbol.members.size)) { @@ -82,12 +85,12 @@ namespace ts { switch (statement.kind) { case SyntaxKind.VariableStatement: return (statement as VariableStatement).declarationList.declarations.some(decl => - isRequireCall(propertyAccessLeftHandSide(decl.initializer!), /*checkArgumentIsStringLiteralLike*/ true)); // TODO: GH#18217 + !!decl.initializer && isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true)); case SyntaxKind.ExpressionStatement: { const { expression } = statement as ExpressionStatement; if (!isBinaryExpression(expression)) return isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - const kind = getSpecialPropertyAssignmentKind(expression); - return kind === SpecialPropertyAssignmentKind.ExportsProperty || kind === SpecialPropertyAssignmentKind.ModuleExports; + const kind = getAssignmentDeclarationKind(expression); + return kind === AssignmentDeclarationKind.ExportsProperty || kind === AssignmentDeclarationKind.ModuleExports; } default: return false; @@ -113,65 +116,81 @@ namespace ts { } } - function addConvertToAsyncFunctionDiagnostics(node: FunctionLikeDeclaration, checker: TypeChecker, diags: DiagnosticWithLocation[]): void { - - if (isAsyncFunction(node) || !node.body) { - return; + function addConvertToAsyncFunctionDiagnostics(node: FunctionLikeDeclaration, checker: TypeChecker, diags: Push): void { + // need to check function before checking map so that deeper levels of nested callbacks are checked + if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) { + diags.push(createDiagnosticForNode( + !node.name && isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) ? node.parent.name : node, + Diagnostics.This_may_be_converted_to_an_async_function)); } + } + function isConvertibleFunction(node: FunctionLikeDeclaration, checker: TypeChecker) { + return !isAsyncFunction(node) && + node.body && + isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker); + } + + function returnsPromise(node: FunctionLikeDeclaration, checker: TypeChecker): boolean { const functionType = checker.getTypeAtLocation(node); - const callSignatures = checker.getSignaturesOfType(functionType, SignatureKind.Call); const returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; - - if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { - return; - } - - // collect all the return statements - // check that a property access expression exists in there and that it is a handler - const returnStatements = getReturnStatementsWithPromiseHandlers(node); - if (returnStatements.length > 0) { - diags.push(createDiagnosticForNode(isVariableDeclaration(node.parent) ? node.parent.name : node, Diagnostics.This_may_be_converted_to_an_async_function)); - } + return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator: Node): Node { return isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - /** @internal */ - export function getReturnStatementsWithPromiseHandlers(node: Node): Node[] { - const returnStatements: Node[] = []; - if (isFunctionLike(node)) { - forEachChild(node, visit); - } - else { - visit(node); - } - - function visit(child: Node) { - if (isFunctionLike(child)) { - return; - } - - if (isReturnStatement(child)) { - forEachChild(child, addHandlers); - } - - function addHandlers(returnChild: Node) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child as ReturnStatement); - } - } - - forEachChild(child, visit); - } - return returnStatements; + function hasReturnStatementWithPromiseHandler(body: Block): boolean { + return !!forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); } - function isPromiseHandler(node: Node): boolean { - return (isCallExpression(node) && isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + export function isReturnStatementWithFixablePromiseHandler(node: Node): node is ReturnStatement { + return isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + } + + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + export function isFixablePromiseHandler(node: Node): boolean { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + + // ensure all chained calls are valid + let currentNode = node.expression; + while (isPromiseHandler(currentNode) || isPropertyAccessExpression(currentNode)) { + if (isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + + function isPromiseHandler(node: Node): node is CallExpression { + return isCallExpression(node) && (hasPropertyAccessExpressionWithName(node, "then") || hasPropertyAccessExpressionWithName(node, "catch")); + } + + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg: Expression): boolean { + switch (arg.kind) { + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + visitedNestedConvertibleFunctions.set(getKeyFromNode(arg as FunctionLikeDeclaration), true); + /* falls through */ + case SyntaxKind.NullKeyword: + case SyntaxKind.Identifier: // identifier includes undefined + return true; + default: + return false; + } + } + + function getKeyFromNode(exp: FunctionLikeDeclaration) { + return `${exp.pos.toString()}:${exp.end.toString()}`; } } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index d1d8709bef2..e0728f98a29 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -128,14 +128,18 @@ namespace ts.SymbolDisplay { let documentation: SymbolDisplayPart[] | undefined; let tags: JSDocTagInfo[] | undefined; const symbolFlags = getCombinedLocalAndExportSymbolFlags(symbol); - let symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + let symbolKind = semanticMeaning & SemanticMeaning.Value ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : ScriptElementKind.unknown; let hasAddedSymbolInfo = false; - const isThisExpression = location.kind === SyntaxKind.ThisKeyword && isExpression(location); + const isThisExpression = location.kind === SyntaxKind.ThisKeyword && isInExpressionContext(location); let type: Type | undefined; let printer: Printer; let documentationFromAlias: SymbolDisplayPart[] | undefined; let tagsFromAlias: JSDocTagInfo[] | undefined; + if (location.kind === SyntaxKind.ThisKeyword && !isThisExpression) { + return { displayParts: [keywordPart(SyntaxKind.ThisKeyword)], documentation: [], symbolKind: ScriptElementKind.primitiveType, tags: undefined }; + } + // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== ScriptElementKind.unknown || symbolFlags & SymbolFlags.Class || symbolFlags & SymbolFlags.Alias) { // If it is accessor they are allowed only if location is at name of the accessor @@ -285,7 +289,7 @@ namespace ts.SymbolDisplay { addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & SymbolFlags.TypeAlias) { + if ((symbolFlags & SymbolFlags.TypeAlias) && (semanticMeaning & SemanticMeaning.Type)) { prefixNextMeaning(); displayParts.push(keywordPart(SyntaxKind.TypeKeyword)); displayParts.push(spacePart()); @@ -530,7 +534,7 @@ namespace ts.SymbolDisplay { tags = tagsFromAlias; } - return { displayParts, documentation, symbolKind, tags: tags! }; + return { displayParts, documentation, symbolKind, tags: tags!.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 32d6360e90c..4689e18508c 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -211,8 +211,8 @@ namespace ts.textChanges { export class ChangeTracker { private readonly changes: Change[] = []; - private readonly newFiles: { readonly oldFile: SourceFile, readonly fileName: string, readonly statements: ReadonlyArray }[] = []; - private readonly classesWithNodesInsertedAtStart = createMap(); // Set implemented as Map + private readonly newFiles: { readonly oldFile: SourceFile | undefined, readonly fileName: string, readonly statements: ReadonlyArray }[] = []; + private readonly classesWithNodesInsertedAtStart = createMap<{ readonly node: ClassDeclaration | InterfaceDeclaration | ObjectLiteralExpression, readonly sourceFile: SourceFile }>(); // Set implemented as Map private readonly deletedNodes: { readonly sourceFile: SourceFile, readonly node: Node | NodeArray }[] = []; public static fromContext(context: TextChangesContext): ChangeTracker { @@ -228,9 +228,8 @@ namespace ts.textChanges { /** Public for tests only. Other callers should use `ChangeTracker.with`. */ constructor(private readonly newLineCharacter: string, private readonly formatContext: formatting.FormatContext) {} - public deleteRange(sourceFile: SourceFile, range: TextRange) { + public deleteRange(sourceFile: SourceFile, range: TextRange): void { this.changes.push({ kind: ChangeKind.Remove, sourceFile, range }); - return this; } delete(sourceFile: SourceFile, node: Node | NodeArray): void { @@ -241,11 +240,10 @@ namespace ts.textChanges { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); } - public deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd = {}) { + public deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd = {}): void { const startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); const endPosition = getAdjustedEndPosition(sourceFile, endNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - return this; } public deleteNodeRangeExcludingEnd(sourceFile: SourceFile, startNode: Node, afterEndNode: Node | undefined, options: ConfigurableStartEnd = {}): void { @@ -254,48 +252,50 @@ namespace ts.textChanges { this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); } - public replaceRange(sourceFile: SourceFile, range: TextRange, newNode: Node, options: InsertNodeOptions = {}) { + public replaceRange(sourceFile: SourceFile, range: TextRange, newNode: Node, options: InsertNodeOptions = {}): void { this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile, range, options, node: newNode }); - return this; } - public replaceNode(sourceFile: SourceFile, oldNode: Node, newNode: Node, options: ChangeNodeOptions = useNonAdjustedPositions) { - return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); + public replaceNode(sourceFile: SourceFile, oldNode: Node, newNode: Node, options: ChangeNodeOptions = useNonAdjustedPositions): void { + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); } - public replaceNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, newNode: Node, options: ChangeNodeOptions = useNonAdjustedPositions) { + public replaceNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, newNode: Node, options: ChangeNodeOptions = useNonAdjustedPositions): void { this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); } - private replaceRangeWithNodes(sourceFile: SourceFile, range: TextRange, newNodes: ReadonlyArray, options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = {}) { + private replaceRangeWithNodes(sourceFile: SourceFile, range: TextRange, newNodes: ReadonlyArray, options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = {}): void { this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile, range, options, nodes: newNodes }); - return this; } - public replaceNodeWithNodes(sourceFile: SourceFile, oldNode: Node, newNodes: ReadonlyArray, options: ChangeNodeOptions = useNonAdjustedPositions) { - return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); + public replaceNodeWithNodes(sourceFile: SourceFile, oldNode: Node, newNodes: ReadonlyArray, options: ChangeNodeOptions = useNonAdjustedPositions): void { + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); } - public replaceNodeRangeWithNodes(sourceFile: SourceFile, startNode: Node, endNode: Node, newNodes: ReadonlyArray, options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = useNonAdjustedPositions) { - return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + public replaceNodeWithText(sourceFile: SourceFile, oldNode: Node, text: string): void { + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text); } - private nextCommaToken (sourceFile: SourceFile, node: Node): Node | undefined { + public replaceNodeRangeWithNodes(sourceFile: SourceFile, startNode: Node, endNode: Node, newNodes: ReadonlyArray, options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = useNonAdjustedPositions): void { + this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + } + + private nextCommaToken(sourceFile: SourceFile, node: Node): Node | undefined { const next = findNextToken(node, node.parent, sourceFile); return next && next.kind === SyntaxKind.CommaToken ? next : undefined; } - public replacePropertyAssignment(sourceFile: SourceFile, oldNode: PropertyAssignment, newNode: PropertyAssignment) { + public replacePropertyAssignment(sourceFile: SourceFile, oldNode: PropertyAssignment, newNode: PropertyAssignment): void { const suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); - return this.replaceNode(sourceFile, oldNode, newNode, { suffix }); + this.replaceNode(sourceFile, oldNode, newNode, { suffix }); } - public insertNodeAt(sourceFile: SourceFile, pos: number, newNode: Node, options: InsertNodeOptions = {}) { + public insertNodeAt(sourceFile: SourceFile, pos: number, newNode: Node, options: InsertNodeOptions = {}): void { this.replaceRange(sourceFile, createRange(pos), newNode, options); } private insertNodesAt(sourceFile: SourceFile, pos: number, newNodes: ReadonlyArray, options: ReplaceWithMultipleNodesOptions = {}): void { - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile, options, nodes: newNodes, range: { pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, createRange(pos), newNodes, options); } public insertNodeAtTopOfFile(sourceFile: SourceFile, newNode: Statement, blankLineBetween: boolean): void { @@ -306,13 +306,23 @@ namespace ts.textChanges { }); } - public insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, blankLineBetween = false) { + public insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, blankLineBetween = false): void { this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); } public insertModifierBefore(sourceFile: SourceFile, modifier: SyntaxKind, before: Node): void { const pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos, end: pos }, createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, createToken(modifier), { suffix: " " }); + } + + public insertLastModifierBefore(sourceFile: SourceFile, modifier: SyntaxKind, before: Node): void { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + + const pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, createToken(modifier), { prefix: " " }); } public insertCommentBeforeLine(sourceFile: SourceFile, lineNumber: number, position: number, commentText: string): void { @@ -329,7 +339,22 @@ namespace ts.textChanges { this.insertText(sourceFile, token.getStart(sourceFile), text); } - public replaceRangeWithText(sourceFile: SourceFile, range: TextRange, text: string) { + public insertJsdocCommentBefore(sourceFile: SourceFile, node: HasJSDoc, tag: JSDoc): void { + const fnStart = node.getStart(sourceFile); + if (node.jsDoc) { + for (const jsdoc of node.jsDoc) { + this.deleteRange(sourceFile, { + pos: getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + }); + } + } + const startPosition = getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); + const indent = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); + } + + public replaceRangeWithText(sourceFile: SourceFile, range: TextRange, text: string): void { this.changes.push({ kind: ChangeKind.Text, sourceFile, range, text }); } @@ -403,32 +428,40 @@ namespace ts.textChanges { public insertNodeAtEndOfScope(sourceFile: SourceFile, scope: Node, newNode: Node): void { const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken()!, {}, Position.Start); - this.replaceRange(sourceFile, { pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken()!.pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); } public insertNodeAtClassStart(sourceFile: SourceFile, cls: ClassLikeDeclaration | InterfaceDeclaration, newElement: ClassElement): void { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + } + public insertNodeAtObjectStart(sourceFile: SourceFile, obj: ObjectLiteralExpression, newElement: ObjectLiteralElementLike): void { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + } + + private insertNodeAtStartWorker(sourceFile: SourceFile, cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression, newElement: ClassElement | ObjectLiteralElementLike): void { const clsStart = cls.getStart(sourceFile); const indentation = formatting.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize!; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation, ...this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls) }); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, { indentation, ...this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls) }); } - private getInsertNodeAtClassStartPrefixSuffix(sourceFile: SourceFile, cls: ClassLikeDeclaration | InterfaceDeclaration): { prefix: string, suffix: string } { - if (cls.members.length === 0) { - if (addToSeen(this.classesWithNodesInsertedAtStart, getNodeId(cls), cls)) { + private getInsertNodeAtStartPrefixSuffix(sourceFile: SourceFile, cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression): { prefix: string, suffix: string } { + const comma = isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (addToSeen(this.classesWithNodesInsertedAtStart, getNodeId(cls), { node: cls, sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - const shouldSuffix = (positionsAreOnSameLine as any)(...getClassBraceEnds(cls, sourceFile), sourceFile); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + const shouldSuffix = (positionsAreOnSameLine as any)(...getClassOrObjectBraceEnds(cls, sourceFile), sourceFile); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } } @@ -463,7 +496,7 @@ namespace ts.textChanges { return endPosition; } - private getInsertNodeAfterOptions(sourceFile: SourceFile, after: Node) { + private getInsertNodeAfterOptions(sourceFile: SourceFile, after: Node): InsertNodeOptions { const options = this.getInsertNodeAfterOptionsWorker(after); return { ...options, @@ -534,14 +567,14 @@ namespace ts.textChanges { * i.e. arguments in arguments lists, parameters in parameter lists etc. * Note that separators are part of the node in statements and class elements. */ - public insertNodeInListAfter(sourceFile: SourceFile, after: Node, newNode: Node, containingList = formatting.SmartIndenter.getContainingList(after, sourceFile)) { + public insertNodeInListAfter(sourceFile: SourceFile, after: Node, newNode: Node, containingList = formatting.SmartIndenter.getContainingList(after, sourceFile)): void { if (!containingList) { Debug.fail("node is not a list element"); - return this; + return; } const index = indexOfNode(containingList, after); if (index < 0) { - return this; + return; } const end = after.getEnd(); if (index !== containingList.length - 1) { @@ -643,13 +676,11 @@ namespace ts.textChanges { this.replaceRange(sourceFile, createRange(end), newNode, { prefix: `${tokenToString(separator)} ` }); } } - return this; } private finishClassesWithNodesInsertedAtStart(): void { - this.classesWithNodesInsertedAtStart.forEach(cls => { - const sourceFile = cls.getSourceFile(); - const [openBraceEnd, closeBraceEnd] = getClassBraceEnds(cls, sourceFile); + this.classesWithNodesInsertedAtStart.forEach(({ node, sourceFile }) => { + const [openBraceEnd, closeBraceEnd] = getClassOrObjectBraceEnds(node, sourceFile); // For `class C { }` remove the whitespace inside the braces. if (positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { this.deleteRange(sourceFile, createRange(openBraceEnd, closeBraceEnd - 1)); @@ -658,7 +689,7 @@ namespace ts.textChanges { } private finishDeleteDeclarations(): void { - const deletedNodesInLists = new NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + const deletedNodesInLists = new NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. for (const { sourceFile, node } of this.deletedNodes) { if (!this.deletedNodes.some(d => d.sourceFile === sourceFile && rangeContainsRangeExclusive(d.node, node))) { if (isArray(node)) { @@ -698,7 +729,7 @@ namespace ts.textChanges { return changes; } - public createNewFile(oldFile: SourceFile, fileName: string, statements: ReadonlyArray) { + public createNewFile(oldFile: SourceFile | undefined, fileName: string, statements: ReadonlyArray): void { this.newFiles.push({ oldFile, fileName, statements }); } } @@ -708,12 +739,19 @@ namespace ts.textChanges { return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls: ClassLikeDeclaration | InterfaceDeclaration, sourceFile: SourceFile): [number, number] { + function getClassOrObjectBraceEnds(cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression, sourceFile: SourceFile): [number, number] { return [findChildOfKind(cls, SyntaxKind.OpenBraceToken, sourceFile)!.end, findChildOfKind(cls, SyntaxKind.CloseBraceToken, sourceFile)!.end]; } + function getMembersOrProperties(cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression): NodeArray { + return isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } export type ValidateNonFormattedText = (node: Node, text: string) => void; + export function getNewFileText(statements: ReadonlyArray, scriptKind: ScriptKind, newLineCharacter: string, formatContext: formatting.FormatContext): string { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + namespace changesToText { export function getTextChangesFromChanges(changes: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText | undefined): FileTextChanges[] { return group(changes, c => c.sourceFile.path).map(changesInFile => { @@ -732,13 +770,17 @@ namespace ts.textChanges { }); } - export function newFileChanges(oldFile: SourceFile, fileName: string, statements: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext): FileTextChanges { + export function newFileChanges(oldFile: SourceFile | undefined, fileName: string, statements: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext): FileTextChanges { + const text = newFileChangesWorker(oldFile, getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true }; + } + + export function newFileChangesWorker(oldFile: SourceFile | undefined, scriptKind: ScriptKind, statements: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext): string { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this const nonFormattedText = statements.map(s => getNonformattedText(s, oldFile, newLineCharacter).text).join(newLineCharacter); - const sourceFile = createSourceFile(fileName, nonFormattedText, ScriptTarget.ESNext, /*setParentNodes*/ true); + const sourceFile = createSourceFile("any file name", nonFormattedText, ScriptTarget.ESNext, /*setParentNodes*/ true, scriptKind); const changes = formatting.formatDocument(sourceFile, formatContext); - const text = applyChanges(nonFormattedText, changes); - return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true }; + return applyChanges(nonFormattedText, changes) + newLineCharacter; } function computeNewText(change: Change, sourceFile: SourceFile, newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText | undefined): string { @@ -778,10 +820,10 @@ namespace ts.textChanges { } /** Note: output node may be mutated input node. */ - function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLineCharacter: string): { text: string, node: Node } { + export function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLineCharacter: string): { text: string, node: Node } { const writer = new Writer(newLineCharacter); const newLine = newLineCharacter === "\n" ? NewLineKind.LineFeed : NewLineKind.CarriageReturnLineFeed; - createPrinter({ newLine }, writer).writeNode(EmitHint.Unspecified, node, sourceFile, writer); + createPrinter({ newLine, neverAsciiEscape: true }, writer).writeNode(EmitHint.Unspecified, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } } @@ -878,6 +920,9 @@ namespace ts.textChanges { this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); } + writeComment(s: string): void { + this.writer.writeComment(s); + } writeKeyword(s: string): void { this.writer.writeKeyword(s); this.setLastNonTriviaPosition(s, /*force*/ false); @@ -890,6 +935,10 @@ namespace ts.textChanges { this.writer.writePunctuation(s); this.setLastNonTriviaPosition(s, /*force*/ false); } + writeTrailingSemicolon(s: string): void { + this.writer.writeTrailingSemicolon(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + } writeParameter(s: string): void { this.writer.writeParameter(s); this.setLastNonTriviaPosition(s, /*force*/ false); @@ -910,9 +959,6 @@ namespace ts.textChanges { this.writer.writeSymbol(s, sym); this.setLastNonTriviaPosition(s, /*force*/ false); } - writeTextOfNode(text: string, node: Node): void { - this.writer.writeTextOfNode(text, node); - } writeLine(): void { this.writer.writeLine(); } @@ -954,9 +1000,26 @@ namespace ts.textChanges { } } - function getInsertionPositionAtSourceFileTop({ text }: SourceFile): number { - const shebang = getShebang(text); + function getInsertionPositionAtSourceFileTop(sourceFile: SourceFile): number { + let lastPrologue: PrologueDirective | undefined; + for (const node of sourceFile.statements) { + if (isPrologueDirective(node)) { + lastPrologue = node; + } + else { + break; + } + } + let position = 0; + const text = sourceFile.text; + if (lastPrologue) { + position = lastPrologue.end; + advancePastLineBreak(); + return position; + } + + const shebang = getShebang(text); if (shebang !== undefined) { position = shebang.length; advancePastLineBreak(); @@ -997,7 +1060,7 @@ namespace ts.textChanges { } export function isValidLocationToAddComment(sourceFile: SourceFile, position: number) { - return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position); + return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position) && !isInJSXText(sourceFile, position); } function needSemicolonBetween(a: Node, b: Node): boolean { @@ -1010,25 +1073,13 @@ namespace ts.textChanges { switch (node.kind) { case SyntaxKind.Parameter: { const oldFunction = node.parent; - if (isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + if (isArrowFunction(oldFunction) && + oldFunction.parameters.length === 1 && + !findChildOfKind(oldFunction, SyntaxKind.OpenParenToken, sourceFile)) { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the // case if the parameter is simply removed (e.g. in `x => 1`). - const newFunction = updateArrowFunction( - oldFunction, - oldFunction.modifiers, - oldFunction.typeParameters, - /*parameters*/ undefined!, // TODO: GH#18217 - oldFunction.type, - oldFunction.equalsGreaterThanToken, - oldFunction.body); - - // Drop leading and trailing trivia of the new function because we're only going - // to replace the span (vs the full span) of the old function - the old leading - // and trailing trivia will remain. - suppressLeadingAndTrailingTrivia(newFunction); - - changes.replaceNode(sourceFile, oldFunction, newFunction); + changes.replaceNodeWithText(sourceFile, node, "()"); } else { deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); diff --git a/src/services/transpile.ts b/src/services/transpile.ts index 70ca5b64314..030d2273b62 100644 --- a/src/services/transpile.ts +++ b/src/services/transpile.ts @@ -48,6 +48,7 @@ namespace ts { options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index fee6da0f8a3..21be663055a 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -11,7 +11,7 @@ "types.ts", "utilities.ts", "classifier.ts", - "pathCompletions.ts", + "stringCompletions.ts", "completions.ts", "documentHighlights.ts", "documentRegistry.ts", @@ -43,8 +43,11 @@ "textChanges.ts", "codeFixProvider.ts", "refactorProvider.ts", + "codefixes/addConvertToUnknownForNonOverlappingTypes.ts", "codefixes/addMissingInvocationForDecorator.ts", + "codefixes/addNameToNamelessParameter.ts", "codefixes/annotateWithTypeFromJSDoc.ts", + "codefixes/inferFromUsage.ts", "codefixes/convertFunctionToEs6Class.ts", "codefixes/convertToAsyncFunction.ts", "codefixes/convertToEs6Module.ts", @@ -53,10 +56,12 @@ "codefixes/importFixes.ts", "codefixes/fixSpelling.ts", "codefixes/fixAddMissingMember.ts", + "codefixes/fixAddMissingNewOperator.ts", "codefixes/fixCannotFindModule.ts", "codefixes/fixClassDoesntImplementInheritedAbstractMember.ts", "codefixes/fixClassSuperMustPrecedeThisAccess.ts", "codefixes/fixConstructorForDerivedNeedSuperCall.ts", + "codefixes/fixEnableExperimentalDecorators.ts", "codefixes/fixExtendsInterfaceBecomesImplements.ts", "codefixes/fixForgottenThisPropertyAccess.ts", "codefixes/fixUnusedIdentifier.ts", @@ -66,9 +71,9 @@ "codefixes/fixAwaitInSyncFunction.ts", "codefixes/disableJsDiagnostics.ts", "codefixes/helpers.ts", - "codefixes/inferFromUsage.ts", "codefixes/fixInvalidImportSyntax.ts", "codefixes/fixStrictClassInitialization.ts", + "codefixes/generateTypes.ts", "codefixes/requireInTs.ts", "codefixes/useDefaultImport.ts", "codefixes/fixAddModuleReferTypeMissingTypeof.ts", @@ -82,6 +87,6 @@ "services.ts", "breakpoints.ts", "transform.ts", - "shims.ts" + "shims.ts", ] } diff --git a/src/services/types.ts b/src/services/types.ts index 9bf0edf3150..3502e3e0671 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -86,12 +86,11 @@ namespace ts { getPositionOfLineAndCharacter(line: number, character: number): number; update(newText: string, textChangeRange: TextChangeRange): SourceFile; - /* @internal */ sourceMapper?: sourcemaps.SourceMapper; + /* @internal */ sourceMapper?: DocumentPositionMapper; } export interface SourceFileLike { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; - /*@internal*/ sourceMapper?: sourcemaps.SourceMapper; } export interface SourceMapSource { @@ -212,9 +211,9 @@ namespace ts { * * If this is implemented, `getResolvedModuleWithFailedLookupLocationsFromCache` should be too. */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution; /* @internal */ hasChangedAutomaticTypeDirectiveNames?: boolean; @@ -231,11 +230,20 @@ namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; + /* @internal */ inspectValue?(options: InspectValueOptions): Promise; + writeFile?(fileName: string, content: string): void; + + /* @internal */ + getDocumentPositionMapper?(generatedFileName: string, sourceFileName?: string): DocumentPositionMapper | undefined; + /* @internal */ + getSourceFileLike?(fileName: string): SourceFileLike | undefined; } /* @internal */ export const emptyOptions = {}; + export type WithMetadata = T & { metadata?: unknown; }; + // // Public services of a language service instance associated // with a language service host instance @@ -266,7 +274,7 @@ namespace ts { getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; // "options" and "source" are optional only for backwards-compatibility getCompletionEntryDetails( fileName: string, @@ -286,20 +294,20 @@ namespace ts { getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; - getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; + getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): ReadonlyArray | undefined; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; @@ -331,9 +339,9 @@ namespace ts { getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -485,7 +493,7 @@ namespace ts { position: number; } - export class TextChange { + export interface TextChange { span: TextSpan; newText: string; } @@ -526,12 +534,22 @@ namespace ts { // Publicly, this type is just `{}`. Internally it is a union of all the actions we use. // See `commands?: {}[]` in protocol.ts - export type CodeActionCommand = InstallPackageAction; + export type CodeActionCommand = InstallPackageAction | GenerateTypesAction; export interface InstallPackageAction { - /* @internal */ file: string; - /* @internal */ type: "install package"; - /* @internal */ packageName: string; + /* @internal */ readonly type: "install package"; + /* @internal */ readonly file: string; + /* @internal */ readonly packageName: string; + } + + export interface GenerateTypesAction extends GenerateTypesOptions { + /* @internal */ readonly type: "generate types"; + } + + export interface GenerateTypesOptions { + readonly file: string; // File that was importing fileToGenerateTypesFor; used for formatting options. + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; } /** @@ -607,6 +625,8 @@ namespace ts { } export interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } export interface ReferenceEntry extends DocumentSpan { @@ -698,25 +718,52 @@ namespace ts { } export interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter?: boolean; - insertSpaceAfterSemicolonInForStatements?: boolean; - insertSpaceBeforeAndAfterBinaryOperators?: boolean; - insertSpaceAfterConstructor?: boolean; - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - insertSpaceAfterTypeAssertion?: boolean; - insertSpaceBeforeFunctionParenthesis?: boolean; - placeOpenBraceOnNewLineForFunctions?: boolean; - placeOpenBraceOnNewLineForControlBlocks?: boolean; - insertSpaceBeforeTypeAnnotation?: boolean; - indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + readonly insertSpaceAfterCommaDelimiter?: boolean; + readonly insertSpaceAfterSemicolonInForStatements?: boolean; + readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; + readonly insertSpaceAfterConstructor?: boolean; + readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + readonly insertSpaceAfterTypeAssertion?: boolean; + readonly insertSpaceBeforeFunctionParenthesis?: boolean; + readonly placeOpenBraceOnNewLineForFunctions?: boolean; + readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; + readonly insertSpaceBeforeTypeAnnotation?: boolean; + readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } + export function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: newLineCharacter || "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + + /* @internal */ + export const testFormatSettings = getDefaultFormatCodeSettings("\n"); + export interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; @@ -782,15 +829,28 @@ namespace ts { tags?: JSDocTagInfo[]; } - export interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + export type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + export interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + export interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } + + export interface RenameInfoOptions { + readonly allowRenameOfImportPath?: boolean; + } export interface SignatureHelpParameter { name: string; @@ -928,6 +988,7 @@ namespace ts { Whitespace, Identifier, NumberLiteral, + BigIntLiteral, StringLiteral, RegExpLiteral, } @@ -1076,7 +1137,14 @@ namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional" + optionalModifier = "optional", + + dtsModifier = ".d.ts", + tsModifier = ".ts", + tsxModifier = ".tsx", + jsModifier = ".js", + jsxModifier = ".jsx", + jsonModifier = ".json", } export const enum ClassificationTypeNames { @@ -1084,6 +1152,7 @@ namespace ts { identifier = "identifier", keyword = "keyword", numericLiteral = "number", + bigintLiteral = "bigint", operator = "operator", stringLiteral = "string", whiteSpace = "whitespace", @@ -1132,5 +1201,6 @@ namespace ts { jsxAttribute = 22, jsxText = 23, jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25, } } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index b8a235bbeb4..2f78ef2324b 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -23,8 +23,10 @@ namespace ts { export function getMeaningFromDeclaration(node: Node): SemanticMeaning { switch (node.kind) { - case SyntaxKind.Parameter: case SyntaxKind.VariableDeclaration: + return isInJSFile(node) && getJSDocEnumTag(node) ? SemanticMeaning.All : SemanticMeaning.Value; + + case SyntaxKind.Parameter: case SyntaxKind.BindingElement: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: @@ -88,7 +90,7 @@ namespace ts { if (node.kind === SyntaxKind.SourceFile) { return SemanticMeaning.Value; } - else if (node.parent.kind === SyntaxKind.ExportAssignment) { + else if (node.parent.kind === SyntaxKind.ExportAssignment || node.parent.kind === SyntaxKind.ExternalModuleReference) { return SemanticMeaning.All; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -224,6 +226,14 @@ namespace ts { return undefined; } + export function hasPropertyAccessExpressionWithName(node: CallExpression, funcName: string): boolean { + if (!isPropertyAccessExpression(node.expression)) { + return false; + } + + return node.expression.name.text === funcName; + } + export function isJumpStatementTarget(node: Node): node is Identifier & { parent: BreakOrContinueStatement } { return node.kind === SyntaxKind.Identifier && isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -236,6 +246,10 @@ namespace ts { return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } + export function isTagName(node: Node): boolean { + return isJSDocTag(node.parent) && node.parent.tagName === node; + } + export function isRightSideOfQualifiedName(node: Node) { return node.parent.kind === SyntaxKind.QualifiedName && (node.parent).right === node; } @@ -355,23 +369,26 @@ namespace ts { case SyntaxKind.NamespaceImport: return ScriptElementKind.alias; case SyntaxKind.BinaryExpression: - const kind = getSpecialPropertyAssignmentKind(node as BinaryExpression); + const kind = getAssignmentDeclarationKind(node as BinaryExpression); const { right } = node as BinaryExpression; switch (kind) { - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: + case AssignmentDeclarationKind.None: return ScriptElementKind.unknown; - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ModuleExports: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.ModuleExports: const rightKind = getNodeKind(right); return rightKind === ScriptElementKind.unknown ? ScriptElementKind.constElement : rightKind; - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.PrototypeProperty: return isFunctionExpression(right) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement; - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ThisProperty: return ScriptElementKind.memberVariableElement; // property - case SpecialPropertyAssignmentKind.Property: + case AssignmentDeclarationKind.Property: // static method / property return isFunctionExpression(right) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement; - case SpecialPropertyAssignmentKind.Prototype: + case AssignmentDeclarationKind.Prototype: return ScriptElementKind.localClassElement; default: { assertType(kind); @@ -896,6 +913,20 @@ namespace ts { return isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } + export function isInJSXText(sourceFile: SourceFile, position: number) { + const token = getTokenAtPosition(sourceFile, position); + if (isJsxText(token)) { + return true; + } + if (token.kind === SyntaxKind.OpenBraceToken && isJsxExpression(token.parent) && isJsxElement(token.parent.parent)) { + return true; + } + if (token.kind === SyntaxKind.LessThanToken && isJsxOpeningLikeElement(token.parent) && isJsxElement(token.parent.parent)) { + return true; + } + return false; + } + export function findPrecedingMatchingToken(token: Node, matchingTokenKind: SyntaxKind, sourceFile: SourceFile) { const tokenKind = token.kind; let remainingMatchingTokens = 0; @@ -1001,6 +1032,7 @@ namespace ts { case SyntaxKind.Identifier: case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: @@ -1184,6 +1216,7 @@ namespace ts { export const typeKeywords: ReadonlyArray = [ SyntaxKind.AnyKeyword, + SyntaxKind.BigIntKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.FalseKeyword, SyntaxKind.KeyOfKeyword, @@ -1249,11 +1282,11 @@ namespace ts { return !!compilerOptions.module || compilerOptions.target! >= ScriptTarget.ES2015 || !!compilerOptions.noEmit; } - export function hostUsesCaseSensitiveFileNames(host: LanguageServiceHost): boolean { + export function hostUsesCaseSensitiveFileNames(host: { useCaseSensitiveFileNames?(): boolean; }): boolean { return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; } - export function hostGetCanonicalFileName(host: LanguageServiceHost): GetCanonicalFileName { + export function hostGetCanonicalFileName(host: { useCaseSensitiveFileNames?(): boolean; }): GetCanonicalFileName { return createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } @@ -1315,15 +1348,18 @@ namespace ts { }); } - export function getPropertySymbolFromBindingElement(checker: TypeChecker, bindingElement: BindingElement & { name: Identifier }) { + export type ObjectBindingElementWithoutPropertyName = BindingElement & { name: Identifier }; + + export function isObjectBindingElementWithoutPropertyName(bindingElement: Node): bindingElement is ObjectBindingElementWithoutPropertyName { + return isBindingElement(bindingElement) && + isObjectBindingPattern(bindingElement.parent) && + isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + + export function getPropertySymbolFromBindingElement(checker: TypeChecker, bindingElement: ObjectBindingElementWithoutPropertyName): Symbol | undefined { const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - const propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & SymbolFlags.Accessor) { - // See GH#16922 - Debug.assert(!!(propSymbol.flags & SymbolFlags.Transient)); - return (propSymbol as TransientSymbol).target; - } - return propSymbol; + return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } /** @@ -1379,7 +1415,6 @@ namespace ts { return node.modifiers && find(node.modifiers, m => m.kind === kind); } - /* @internal */ export function insertImport(changes: textChanges.ChangeTracker, sourceFile: SourceFile, importDecl: Statement): void { const lastImportDeclaration = findLast(sourceFile.statements, isAnyImportSyntax); if (lastImportDeclaration) { @@ -1429,6 +1464,7 @@ namespace ts { writeKeyword: text => writeKind(text, SymbolDisplayPartKind.keyword), writeOperator: text => writeKind(text, SymbolDisplayPartKind.operator), writePunctuation: text => writeKind(text, SymbolDisplayPartKind.punctuation), + writeTrailingSemicolon: text => writeKind(text, SymbolDisplayPartKind.punctuation), writeSpace: text => writeKind(text, SymbolDisplayPartKind.space), writeStringLiteral: text => writeKind(text, SymbolDisplayPartKind.stringLiteral), writeParameter: text => writeKind(text, SymbolDisplayPartKind.parameterName), @@ -1437,7 +1473,7 @@ namespace ts { writeSymbol, writeLine, write: unknownWrite, - writeTextOfNode: unknownWrite, + writeComment: unknownWrite, getText: () => "", getTextPos: () => 0, getColumn: () => 0, @@ -1567,7 +1603,6 @@ namespace ts { return displayPart("\n", SymbolDisplayPartKind.lineBreak); } - /* @internal */ export function mapToDisplayParts(writeDisplayParts: (writer: DisplayPartsSymbolWriter) => void): SymbolDisplayPart[] { try { writeDisplayParts(displayPartWriter); @@ -1598,9 +1633,7 @@ namespace ts { } export function isImportOrExportSpecifierName(location: Node): location is Identifier { - return !!location.parent && - (location.parent.kind === SyntaxKind.ImportSpecifier || location.parent.kind === SyntaxKind.ExportSpecifier) && - (location.parent).propertyName === location; + return !!location.parent && isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; } /** @@ -1642,6 +1675,13 @@ namespace ts { return position; } + export function getPrecedingNonSpaceCharacterPosition(text: string, position: number) { + while (position > -1 && isWhiteSpaceSingleLine(text.charCodeAt(position))) { + position -= 1; + } + return position + 1; + } + /** * Creates a deep, memberwise clone of a node with no source map location. * @@ -1654,11 +1694,10 @@ namespace ts { return clone; } - export function getSynthesizedDeepCloneWithRenames(node: T, includeTrivia = true, renameMap?: Map, checker?: TypeChecker, callback?: (originalNode: Node, clone: Node) => any): T { - + export function getSynthesizedDeepCloneWithRenames(node: T, includeTrivia = true, renameMap?: Map, checker?: TypeChecker, callback?: (originalNode: Node, clone: Node) => any): T { let clone; - if (node && isIdentifier(node!) && renameMap && checker) { - const symbol = checker.getSymbolAtLocation(node!); + if (isIdentifier(node) && renameMap && checker) { + const symbol = checker.getSymbolAtLocation(node); const renameInfo = symbol && renameMap.get(String(getSymbolId(symbol))); if (renameInfo) { @@ -1667,11 +1706,11 @@ namespace ts { } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node as NonNullable, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node as NonNullable, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) callback(node!, clone); + if (callback && clone) callback(node, clone); return clone as T; } @@ -1714,7 +1753,6 @@ namespace ts { /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - /* @internal */ export function suppressLeadingAndTrailingTrivia(node: Node) { suppressLeadingTrivia(node); suppressTrailingTrivia(node); @@ -1723,7 +1761,6 @@ namespace ts { /** * Sets EmitFlags to suppress leading trivia on the node. */ - /* @internal */ export function suppressLeadingTrivia(node: Node) { addEmitFlagsRecursively(node, EmitFlags.NoLeadingComments, getFirstChild); } @@ -1731,7 +1768,6 @@ namespace ts { /** * Sets EmitFlags to suppress trailing trivia on the node. */ - /* @internal */ export function suppressTrailingTrivia(node: Node) { addEmitFlagsRecursively(node, EmitFlags.NoTrailingComments, getLastChild); } @@ -1746,7 +1782,6 @@ namespace ts { return node.forEachChild(child => child); } - /* @internal */ export function getUniqueName(baseName: string, sourceFile: SourceFile): string { let nameText = baseName; for (let i = 1; !isFileLevelUniqueName(sourceFile, nameText); i++) { @@ -1760,7 +1795,6 @@ namespace ts { * to be on the reference, rather than the declaration, because it's closer to where the * user was before extracting it. */ - /* @internal */ export function getRenameLocation(edits: ReadonlyArray, renameFilename: string, name: string, preferLastLocation: boolean): number { let delta = 0; let lastPos = -1; @@ -1811,4 +1845,70 @@ namespace ts { if (idx === -1) idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + + export function getContextualTypeFromParent(node: Expression, checker: TypeChecker): Type | undefined { + const { parent } = node; + switch (parent.kind) { + case SyntaxKind.NewExpression: + return checker.getContextualType(parent as NewExpression); + case SyntaxKind.BinaryExpression: { + const { left, operatorToken, right } = parent as BinaryExpression; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case SyntaxKind.CaseClause: + return (parent as CaseClause).expression === node ? getSwitchedType(parent as CaseClause, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + + export function quote(text: string, preferences: UserPreferences): string { + if (/^\d+$/.test(text)) { + return text; + } + const quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return `'${stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"')}'`; + default: + return Debug.assertNever(preferences.quotePreference); + } + } + + export function isEqualityOperatorKind(kind: SyntaxKind): kind is EqualityOperator { + switch (kind) { + case SyntaxKind.EqualsEqualsEqualsToken: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.ExclamationEqualsEqualsToken: + case SyntaxKind.ExclamationEqualsToken: + return true; + default: + return false; + } + } + + export function isStringLiteralOrTemplate(node: Node): node is StringLiteralLike | TemplateExpression | TaggedTemplateExpression { + switch (node.kind) { + case SyntaxKind.StringLiteral: + case SyntaxKind.NoSubstitutionTemplateLiteral: + case SyntaxKind.TemplateExpression: + case SyntaxKind.TaggedTemplateExpression: + return true; + default: + return false; + } + } + + export function hasIndexSignature(type: Type): boolean { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + + export function getSwitchedType(caseClause: CaseClause, checker: TypeChecker): Type | undefined { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } } diff --git a/src/testRunner/compilerRunner.ts b/src/testRunner/compilerRunner.ts index a0af5d88f3b..c55cd1aa511 100644 --- a/src/testRunner/compilerRunner.ts +++ b/src/testRunner/compilerRunner.ts @@ -13,7 +13,7 @@ class CompilerBaselineRunner extends RunnerBase { private testSuiteName: TestRunnerKind; private emit: boolean; - public options: string; + public options: string | undefined; constructor(public testType: CompilerTestType) { super(); @@ -208,7 +208,7 @@ class CompilerTest { public verifyModuleResolution() { if (this.options.traceResolution) { Harness.Baseline.runBaseline(this.justName.replace(/\.tsx?$/, ".trace.json"), - utils.removeTestPathPrefixes(JSON.stringify(this.result.traces, undefined, 4))); + JSON.stringify(this.result.traces.map(utils.sanitizeTraceResolutionLogEntry), undefined, 4)); } } diff --git a/src/testRunner/externalCompileRunner.ts b/src/testRunner/externalCompileRunner.ts index 33d8c15a31f..a8a240a5161 100644 --- a/src/testRunner/externalCompileRunner.ts +++ b/src/testRunner/externalCompileRunner.ts @@ -1,6 +1,6 @@ -const fs = require("fs"); -const path = require("path"); -const del = require("del"); +const fs: typeof import("fs") = require("fs"); +const path: typeof import("path") = require("path"); +const del: typeof import("del") = require("del"); interface ExecResult { stdout: Buffer; @@ -40,7 +40,7 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { const timeout = 600_000; // 10 minutes describe(directoryName, function(this: Mocha.ISuiteCallbackContext) { this.timeout(timeout); - const cp = require("child_process"); + const cp: typeof import("child_process") = require("child_process"); it("should build successfully", () => { let cwd = path.join(Harness.IO.getWorkspaceRoot(), cls.testDir, directoryName); @@ -49,12 +49,9 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { let types: string[] | undefined; if (fs.existsSync(path.join(cwd, "test.json"))) { const submoduleDir = path.join(cwd, directoryName); - const reset = cp.spawnSync("git", ["reset", "HEAD", "--hard"], { cwd: submoduleDir, timeout, shell: true, stdio }); - if (reset.status !== 0) throw new Error(`git reset for ${directoryName} failed: ${reset.stderr.toString()}`); - const clean = cp.spawnSync("git", ["clean", "-f"], { cwd: submoduleDir, timeout, shell: true, stdio }); - if (clean.status !== 0) throw new Error(`git clean for ${directoryName} failed: ${clean.stderr.toString()}`); - const update = cp.spawnSync("git", ["submodule", "update", "--remote", "."], { cwd: submoduleDir, timeout, shell: true, stdio }); - if (update.status !== 0) throw new Error(`git submodule update for ${directoryName} failed: ${update.stderr.toString()}`); + exec("git", ["reset", "HEAD", "--hard"], { cwd: submoduleDir }); + exec("git", ["clean", "-f"], { cwd: submoduleDir }); + exec("git", ["submodule", "update", "--init", "--remote", "."], { cwd: submoduleDir }); const config = JSON.parse(fs.readFileSync(path.join(cwd, "test.json"), { encoding: "utf8" })) as UserConfig; ts.Debug.assert(!!config.types, "Bad format from test.json: Types field must be present."); @@ -69,18 +66,23 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { if (fs.existsSync(path.join(cwd, "node_modules"))) { del.sync(path.join(cwd, "node_modules"), { force: true }); } - const install = cp.spawnSync(`npm`, ["i", "--ignore-scripts"], { cwd, timeout: timeout / 2, shell: true, stdio }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure - if (install.status !== 0) throw new Error(`NPM Install for ${directoryName} failed: ${install.stderr.toString()}`); + exec("npm", ["i", "--ignore-scripts"], { cwd, timeout: timeout / 2 }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure } const args = [path.join(Harness.IO.getWorkspaceRoot(), "built/local/tsc.js")]; if (types) { args.push("--types", types.join(",")); // Also actually install those types (for, eg, the js projects which need node) - const install = cp.spawnSync(`npm`, ["i", ...types.map(t => `@types/${t}`), "--no-save", "--ignore-scripts"], { cwd: originalCwd, timeout: timeout / 2, shell: true, stdio }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure - if (install.status !== 0) throw new Error(`NPM Install types for ${directoryName} failed: ${install.stderr.toString()}`); + exec("npm", ["i", ...types.map(t => `@types/${t}`), "--no-save", "--ignore-scripts"], { cwd: originalCwd, timeout: timeout / 2 }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure } args.push("--noEmit"); Harness.Baseline.runBaseline(`${cls.kind()}/${directoryName}.log`, cls.report(cp.spawnSync(`node`, args, { cwd, timeout, shell: true }), cwd)); + + function exec(command: string, args: string[], options: { cwd: string, timeout?: number }): void { + const res = cp.spawnSync(command, args, { timeout, shell: true, stdio, ...options }); + if (res.status !== 0) { + throw new Error(`${command} ${args.join(" ")} for ${directoryName} failed: ${res.stderr && res.stderr.toString()}`); + } + } }); }); } diff --git a/src/testRunner/fourslashRunner.ts b/src/testRunner/fourslashRunner.ts index 583311ba30e..f7d7bf621d5 100644 --- a/src/testRunner/fourslashRunner.ts +++ b/src/testRunner/fourslashRunner.ts @@ -21,6 +21,8 @@ class FourSlashRunner extends RunnerBase { this.basePath = "tests/cases/fourslash/server"; this.testSuiteName = "fourslash-server"; break; + default: + throw ts.Debug.assertNever(testType); } } diff --git a/src/testRunner/parallel/host.ts b/src/testRunner/parallel/host.ts index c10be2a9ff8..376896a4697 100644 --- a/src/testRunner/parallel/host.ts +++ b/src/testRunner/parallel/host.ts @@ -28,9 +28,9 @@ namespace Harness.Parallel.Host { let totalCost = 0; class RemoteSuite extends Mocha.Suite { - suites: RemoteSuite[]; + suites!: RemoteSuite[]; suiteMap = ts.createMap(); - tests: RemoteTest[]; + tests!: RemoteTest[]; constructor(title: string) { super(title); this.pending = false; diff --git a/src/testRunner/projectsRunner.ts b/src/testRunner/projectsRunner.ts index 3dcf1911dde..f4e51afab4c 100644 --- a/src/testRunner/projectsRunner.ts +++ b/src/testRunner/projectsRunner.ts @@ -23,7 +23,7 @@ namespace project { program?: ts.Program; compilerOptions?: ts.CompilerOptions; errors: ReadonlyArray; - sourceMapData?: ReadonlyArray; + sourceMapData?: ReadonlyArray; } interface BatchCompileProjectTestCaseResult extends CompileProjectFilesResult { @@ -67,7 +67,7 @@ namespace project { class ProjectCompilerHost extends fakes.CompilerHost { private _testCase: ProjectRunnerTestCase & ts.CompilerOptions; - private _projectParseConfigHost: ProjectParseConfigHost; + private _projectParseConfigHost: ProjectParseConfigHost | undefined; constructor(sys: fakes.System | vfs.FileSystem, compilerOptions: ts.CompilerOptions, _testCaseJustName: string, testCase: ProjectRunnerTestCase & ts.CompilerOptions, _moduleKind: ts.ModuleKind) { super(sys, compilerOptions); @@ -310,18 +310,16 @@ namespace project { const program = ts.createProgram(getInputFiles(), compilerOptions, compilerHost); const errors = ts.getPreEmitDiagnostics(program); - const emitResult = program.emit(); - ts.addRange(errors, emitResult.diagnostics); - const sourceMapData = emitResult.sourceMaps; + const { sourceMaps: sourceMapData, diagnostics: emitDiagnostics } = program.emit(); // Clean up source map data that will be used in baselining if (sourceMapData) { for (const data of sourceMapData) { - for (let j = 0; j < data.sourceMapSources.length; j++) { - data.sourceMapSources[j] = this.cleanProjectUrl(data.sourceMapSources[j]); - } - data.jsSourceMappingURL = this.cleanProjectUrl(data.jsSourceMappingURL); - data.sourceMapSourceRoot = this.cleanProjectUrl(data.sourceMapSourceRoot); + data.sourceMap = { + ...data.sourceMap, + sources: data.sourceMap.sources.map(source => this.cleanProjectUrl(source)), + sourceRoot: data.sourceMap.sourceRoot && this.cleanProjectUrl(data.sourceMap.sourceRoot) + }; } } @@ -329,7 +327,7 @@ namespace project { configFileSourceFiles, moduleKind, program, - errors, + errors: ts.concatenate(errors, emitDiagnostics), sourceMapData }; } @@ -427,6 +425,7 @@ namespace project { skipDefaultLibCheck: false, moduleResolution: ts.ModuleResolutionKind.Classic, module: moduleKind, + newLine: ts.NewLineKind.CarriageReturnLineFeed, mapRoot: testCase.resolveMapRoot && testCase.mapRoot ? vpath.resolve(vfs.srcFolder, testCase.mapRoot) : testCase.mapRoot, diff --git a/src/testRunner/runner.ts b/src/testRunner/runner.ts index 6e430b08734..e528678ab83 100644 --- a/src/testRunner/runner.ts +++ b/src/testRunner/runner.ts @@ -138,7 +138,6 @@ function handleTestConfig() { case "compiler": runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance)); runners.push(new CompilerBaselineRunner(CompilerTestType.Regressions)); - runners.push(new project.ProjectRunner()); break; case "conformance": runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance)); diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 27dca8296ed..2e5341732b5 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -36,61 +36,109 @@ "runner.ts", - "unittests/extractTestHelpers.ts", - "unittests/tsserverProjectSystem.ts", - "unittests/typingsInstaller.ts", + "unittests/services/extract/helpers.ts", + "unittests/tscWatch/helpers.ts", + "unittests/tsserver/helpers.ts", "unittests/asserts.ts", "unittests/base64.ts", "unittests/builder.ts", - "unittests/cancellableLanguageServiceOperations.ts", - "unittests/commandLineParsing.ts", - "unittests/compileOnSave.ts", "unittests/compilerCore.ts", - "unittests/configurationExtension.ts", - "unittests/convertCompilerOptionsFromJson.ts", - "unittests/convertToAsyncFunction.ts", "unittests/convertToBase64.ts", - "unittests/convertTypeAcquisitionFromJson.ts", "unittests/customTransforms.ts", - "unittests/extractConstants.ts", - "unittests/extractFunctions.ts", - "unittests/extractRanges.ts", "unittests/factory.ts", - "unittests/hostNewLineSupport.ts", "unittests/incrementalParser.ts", - "unittests/initializeTSConfig.ts", "unittests/jsDocParsing.ts", - "unittests/languageService.ts", - "unittests/matchFiles.ts", "unittests/moduleResolution.ts", - "unittests/organizeImports.ts", + "unittests/parsePseudoBigInt.ts", "unittests/paths.ts", "unittests/printer.ts", - "unittests/programMissingFiles.ts", - "unittests/programNoParseFalsyFileNames.ts", - "unittests/projectErrors.ts", - "unittests/projectReferences.ts", + "unittests/programApi.ts", "unittests/publicApi.ts", "unittests/reuseProgramStructure.ts", - "unittests/session.ts", - "unittests/symbolWalker.ts", - "unittests/telemetry.ts", - "unittests/textChanges.ts", - "unittests/textStorage.ts", + "unittests/semver.ts", "unittests/transform.ts", - "unittests/transpile.ts", "unittests/tsbuild.ts", "unittests/tsbuildWatchMode.ts", - "unittests/tsconfigParsing.ts", - "unittests/tscWatchMode.ts", - "unittests/versionCache.ts", + "unittests/config/commandLineParsing.ts", + "unittests/config/configurationExtension.ts", + "unittests/config/convertCompilerOptionsFromJson.ts", + "unittests/config/convertTypeAcquisitionFromJson.ts", + "unittests/config/initializeTSConfig.ts", + "unittests/config/matchFiles.ts", + "unittests/config/projectReferences.ts", + "unittests/config/showConfig.ts", + "unittests/config/tsconfigParsing.ts", "unittests/evaluation/asyncArrow.ts", "unittests/evaluation/asyncGenerator.ts", "unittests/evaluation/forAwaitOf.ts", + "unittests/services/cancellableLanguageServiceOperations.ts", "unittests/services/colorization.ts", + "unittests/services/convertToAsyncFunction.ts", "unittests/services/documentRegistry.ts", + "unittests/services/extract/constants.ts", + "unittests/services/extract/functions.ts", + "unittests/services/extract/symbolWalker.ts", + "unittests/services/extract/ranges.ts", + "unittests/services/hostNewLineSupport.ts", + "unittests/services/languageService.ts", + "unittests/services/organizeImports.ts", "unittests/services/patternMatcher.ts", - "unittests/services/preProcessFile.ts" + "unittests/services/preProcessFile.ts", + "unittests/services/textChanges.ts", + "unittests/services/transpile.ts", + "unittests/tscWatch/consoleClearing.ts", + "unittests/tscWatch/emit.ts", + "unittests/tscWatch/emitAndErrorUpdates.ts", + "unittests/tscWatch/programUpdates.ts", + "unittests/tscWatch/resolutionCache.ts", + "unittests/tscWatch/watchEnvironment.ts", + "unittests/tscWatch/watchApi.ts", + "unittests/tsserver/cachingFileSystemInformation.ts", + "unittests/tsserver/cancellationToken.ts", + "unittests/tsserver/compileOnSave.ts", + "unittests/tsserver/completions.ts", + "unittests/tsserver/configFileSearch.ts", + "unittests/tsserver/configuredProjects.ts", + "unittests/tsserver/declarationFileMaps.ts", + "unittests/tsserver/documentRegistry.ts", + "unittests/tsserver/duplicatePackages.ts", + "unittests/tsserver/events/largeFileReferenced.ts", + "unittests/tsserver/events/projectLanguageServiceState.ts", + "unittests/tsserver/events/projectLoading.ts", + "unittests/tsserver/events/projectUpdatedInBackground.ts", + "unittests/tsserver/events/surveyReady.ts", + "unittests/tsserver/externalProjects.ts", + "unittests/tsserver/forceConsistentCasingInFileNames.ts", + "unittests/tsserver/formatSettings.ts", + "unittests/tsserver/getApplicableRefactors.ts", + "unittests/tsserver/getEditsForFileRename.ts", + "unittests/tsserver/importHelpers.ts", + "unittests/tsserver/inferredProjects.ts", + "unittests/tsserver/languageService.ts", + "unittests/tsserver/maxNodeModuleJsDepth.ts", + "unittests/tsserver/metadataInResponse.ts", + "unittests/tsserver/navTo.ts", + "unittests/tsserver/occurences.ts", + "unittests/tsserver/openFile.ts", + "unittests/tsserver/projectErrors.ts", + "unittests/tsserver/projectReferences.ts", + "unittests/tsserver/projects.ts", + "unittests/tsserver/refactors.ts", + "unittests/tsserver/reload.ts", + "unittests/tsserver/rename.ts", + "unittests/tsserver/resolutionCache.ts", + "unittests/tsserver/session.ts", + "unittests/tsserver/skipLibCheck.ts", + "unittests/tsserver/symLinks.ts", + "unittests/tsserver/syntaxOperations.ts", + "unittests/tsserver/textStorage.ts", + "unittests/tsserver/telemetry.ts", + "unittests/tsserver/typeAquisition.ts", + "unittests/tsserver/typeReferenceDirectives.ts", + "unittests/tsserver/typingsInstaller.ts", + "unittests/tsserver/untitledFiles.ts", + "unittests/tsserver/versionCache.ts", + "unittests/tsserver/watchEnvironment.ts" ] } diff --git a/src/testRunner/unittests/asserts.ts b/src/testRunner/unittests/asserts.ts index 8d5138085a8..c54173e2f90 100644 --- a/src/testRunner/unittests/asserts.ts +++ b/src/testRunner/unittests/asserts.ts @@ -1,5 +1,5 @@ namespace ts { - describe("assert", () => { + describe("unittests:: assert", () => { it("deepEqual", () => { assert.throws(() => assert.deepEqual(createNodeArray([createIdentifier("A")]), createNodeArray([createIdentifier("B")]))); assert.throws(() => assert.deepEqual(createNodeArray([], /*hasTrailingComma*/ true), createNodeArray([], /*hasTrailingComma*/ false))); diff --git a/src/testRunner/unittests/base64.ts b/src/testRunner/unittests/base64.ts index 11c2623df65..1dc51a8fbf5 100644 --- a/src/testRunner/unittests/base64.ts +++ b/src/testRunner/unittests/base64.ts @@ -1,5 +1,5 @@ namespace ts { - describe("base64", () => { + describe("unittests:: base64", () => { describe("base64decode", () => { it("can decode input strings correctly without needing a host implementation", () => { const tests = [ diff --git a/src/testRunner/unittests/builder.ts b/src/testRunner/unittests/builder.ts index 4a163d6b56b..709222a4dff 100644 --- a/src/testRunner/unittests/builder.ts +++ b/src/testRunner/unittests/builder.ts @@ -1,5 +1,5 @@ namespace ts { - describe("builder", () => { + describe("unittests:: builder", () => { it("emits dependent files", () => { const files: NamedSourceText[] = [ { name: "/a.ts", text: SourceText.New("", 'import { b } from "./b";', "") }, diff --git a/src/testRunner/unittests/compilerCore.ts b/src/testRunner/unittests/compilerCore.ts index 27f5cdc0887..4c3918c3149 100644 --- a/src/testRunner/unittests/compilerCore.ts +++ b/src/testRunner/unittests/compilerCore.ts @@ -1,5 +1,5 @@ namespace ts { - describe("compilerCore", () => { + describe("unittests:: compilerCore", () => { describe("equalOwnProperties", () => { it("correctly equates objects", () => { assert.isTrue(equalOwnProperties({}, {})); diff --git a/src/testRunner/unittests/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts similarity index 96% rename from src/testRunner/unittests/commandLineParsing.ts rename to src/testRunner/unittests/config/commandLineParsing.ts index 7ac9504f1f8..25fa3a45050 100644 --- a/src/testRunner/unittests/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -1,5 +1,5 @@ namespace ts { - describe("parseCommandLine", () => { + describe("unittests:: config:: commandLineParsing:: parseCommandLine", () => { function assertParseResult(commandLine: string[], expectedParsedCommandLine: ParsedCommandLine) { const parsed = parseCommandLine(commandLine); @@ -57,7 +57,7 @@ namespace ts { assertParseResult(["--lib", "es5,invalidOption", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -259,7 +259,7 @@ namespace ts { assertParseResult(["--lib", "es5,", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -278,7 +278,7 @@ namespace ts { assertParseResult(["--lib", "es5, ", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -367,7 +367,7 @@ namespace ts { }); }); - describe("parseBuildOptions", () => { + describe("unittests:: config:: commandLineParsing:: parseBuildOptions", () => { function assertParseResult(commandLine: string[], expectedParsedBuildCommand: ParsedBuildCommand) { const parsed = parseBuildCommand(commandLine); const parsedBuildOptions = JSON.stringify(parsed.buildOptions); diff --git a/src/testRunner/unittests/configurationExtension.ts b/src/testRunner/unittests/config/configurationExtension.ts similarity index 62% rename from src/testRunner/unittests/configurationExtension.ts rename to src/testRunner/unittests/config/configurationExtension.ts index 012b8e0d2fa..25e975c0fb2 100644 --- a/src/testRunner/unittests/configurationExtension.ts +++ b/src/testRunner/unittests/config/configurationExtension.ts @@ -4,6 +4,83 @@ namespace ts { cwd, files: { [root]: { + "dev/node_modules/config-box/package.json": JSON.stringify({ + name: "config-box", + version: "1.0.0", + tsconfig: "./strict.json" + }), + "dev/node_modules/config-box/strict.json": JSON.stringify({ + compilerOptions: { + strict: true, + } + }), + "dev/node_modules/config-box/unstrict.json": JSON.stringify({ + compilerOptions: { + strict: false, + } + }), + "dev/tsconfig.extendsBox.json": JSON.stringify({ + extends: "config-box", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsStrict.json": JSON.stringify({ + extends: "config-box/strict", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsUnStrict.json": JSON.stringify({ + extends: "config-box/unstrict", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsStrictExtension.json": JSON.stringify({ + extends: "config-box/strict.json", + files: [ + "main.ts", + ] + }), + "dev/node_modules/config-box-implied/package.json": JSON.stringify({ + name: "config-box-implied", + version: "1.0.0", + }), + "dev/node_modules/config-box-implied/tsconfig.json": JSON.stringify({ + compilerOptions: { + strict: true, + } + }), + "dev/node_modules/config-box-implied/unstrict/tsconfig.json": JSON.stringify({ + compilerOptions: { + strict: false, + } + }), + "dev/tsconfig.extendsBoxImplied.json": JSON.stringify({ + extends: "config-box-implied", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsBoxImpliedUnstrict.json": JSON.stringify({ + extends: "config-box-implied/unstrict", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsBoxImpliedUnstrictExtension.json": JSON.stringify({ + extends: "config-box-implied/unstrict/tsconfig", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsBoxImpliedPath.json": JSON.stringify({ + extends: "config-box-implied/tsconfig.json", + files: [ + "main.ts", + ] + }), "dev/tsconfig.json": JSON.stringify({ extends: "./configs/base", files: [ @@ -96,6 +173,11 @@ namespace ts { include: null, files: ["../main.ts"] }), + "dev/configs/fifth.json": JSON.stringify({ + extends: "./fourth", + include: ["../tests/utils.ts"], + files: [] + }), "dev/extends.json": JSON.stringify({ extends: 42 }), "dev/extends2.json": JSON.stringify({ extends: "configs/base" }), "dev/main.ts": "", @@ -126,7 +208,7 @@ namespace ts { } } - describe("configurationExtension", () => { + describe("unittests:: config:: configurationExtension", () => { forEach<[string, string, fakes.ParseConfigHost], void>([ ["under a case insensitive host", caseInsensitiveBasePath, caseInsensitiveHost], ["under a case sensitive host", caseSensitiveBasePath, caseSensitiveHost] @@ -221,12 +303,6 @@ namespace ts { messageText: `Compiler option 'extends' requires a value of type string.` }]); - testFailure("can error when 'extends' is neither relative nor rooted.", "extends2.json", [{ - code: 18001, - category: DiagnosticCategory.Error, - messageText: `A path in an 'extends' option must be relative or rooted, but 'configs/base' is not.` - }]); - testSuccess("can overwrite compiler options using extended 'null'", "configs/third.json", { allowJs: true, noImplicitAny: true, @@ -244,6 +320,40 @@ namespace ts { }, [ combinePaths(basePath, "main.ts") ]); + + testSuccess("can overwrite top-level files using extended []", "configs/fifth.json", { + allowJs: true, + noImplicitAny: true, + strictNullChecks: true, + module: ModuleKind.System + }, [ + combinePaths(basePath, "tests/utils.ts") + ]); + + describe("finding extended configs from node_modules", () => { + testSuccess("can lookup via tsconfig field", "tsconfig.extendsBox.json", { strict: true }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via package-relative path", "tsconfig.extendsStrict.json", { strict: true }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via non-redirected-to package-relative path", "tsconfig.extendsUnStrict.json", { strict: false }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via package-relative path with extension", "tsconfig.extendsStrictExtension.json", { strict: true }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via an implicit tsconfig", "tsconfig.extendsBoxImplied.json", { strict: true }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via an implicit tsconfig in a package-relative directory", "tsconfig.extendsBoxImpliedUnstrict.json", { strict: false }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via an implicit tsconfig in a package-relative directory with name", "tsconfig.extendsBoxImpliedUnstrictExtension.json", { strict: false }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via an implicit tsconfig in a package-relative directory with extension", "tsconfig.extendsBoxImpliedPath.json", { strict: true }, [combinePaths(basePath, "main.ts")]); + }); + + it("adds extendedSourceFiles only once", () => { + const sourceFile = readJsonConfigFile("configs/fourth.json", (path) => host.readFile(path)); + const dir = combinePaths(basePath, "configs"); + const expected = [ + combinePaths(dir, "third.json"), + combinePaths(dir, "second.json"), + combinePaths(dir, "base.json"), + ]; + parseJsonSourceFileConfigFileContent(sourceFile, host, dir, {}, "fourth.json"); + assert.deepEqual(sourceFile.extendedSourceFiles, expected); + parseJsonSourceFileConfigFileContent(sourceFile, host, dir, {}, "fourth.json"); + assert.deepEqual(sourceFile.extendedSourceFiles, expected); + }); }); }); }); diff --git a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts similarity index 82% rename from src/testRunner/unittests/convertCompilerOptionsFromJson.ts rename to src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts index 3b422e9a645..318bc0ceb26 100644 --- a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts @@ -1,33 +1,50 @@ namespace ts { - describe("convertCompilerOptionsFromJson", () => { - function assertCompilerOptions(json: any, configFileName: string, expectedResult: { compilerOptions: CompilerOptions, errors: Diagnostic[] }) { + describe("unittests:: config:: convertCompilerOptionsFromJson", () => { + const formatDiagnosticHost: FormatDiagnosticsHost = { + getCurrentDirectory: () => "/apath/", + getCanonicalFileName: createGetCanonicalFileName(/*useCaseSensitiveFileNames*/ true), + getNewLine: () => "\n" + }; + + interface ExpectedResultWithParsingSuccess { + compilerOptions: CompilerOptions; + errors: ReadonlyArray; + } + + interface ExpectedResultWithParsingFailure { + compilerOptions: CompilerOptions; + hasParseErrors: true; + } + + type ExpectedResult = ExpectedResultWithParsingSuccess | ExpectedResultWithParsingFailure; + + function isExpectedResultWithParsingFailure(expectedResult: ExpectedResult): expectedResult is ExpectedResultWithParsingFailure { + return !!(expectedResult as ExpectedResultWithParsingFailure).hasParseErrors; + } + + function assertCompilerOptions(json: any, configFileName: string, expectedResult: ExpectedResultWithParsingSuccess) { assertCompilerOptionsWithJson(json, configFileName, expectedResult); assertCompilerOptionsWithJsonNode(json, configFileName, expectedResult); } - function assertCompilerOptionsWithJson(json: any, configFileName: string, expectedResult: { compilerOptions: CompilerOptions, errors: Diagnostic[] }) { - const { options: actualCompilerOptions, errors: actualErrors} = convertCompilerOptionsFromJson(json.compilerOptions, "/apath/", configFileName); + function assertCompilerOptionsWithJson(json: any, configFileName: string, expectedResult: ExpectedResultWithParsingSuccess) { + const { options: actualCompilerOptions, errors: actualErrors } = convertCompilerOptionsFromJson(json.compilerOptions, "/apath/", configFileName); const parsedCompilerOptions = JSON.stringify(actualCompilerOptions); const expectedCompilerOptions = JSON.stringify({ ...expectedResult.compilerOptions, configFilePath: configFileName }); assert.equal(parsedCompilerOptions, expectedCompilerOptions); - const expectedErrors = expectedResult.errors; - assert.isTrue(expectedResult.errors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedResult.errors)}. Actual error: ${JSON.stringify(actualErrors)}.`); - for (let i = 0; i < actualErrors.length; i++) { - const actualError = actualErrors[i]; - const expectedError = expectedErrors[i]; - assert.equal(actualError.code, expectedError.code); - assert.equal(actualError.category, expectedError.category); - assert.equal(actualError.messageText, expectedError.messageText); - } + verifyErrors(actualErrors, expectedResult.errors, /*ignoreLocation*/ true); } - function assertCompilerOptionsWithJsonNode(json: any, configFileName: string, expectedResult: { compilerOptions: CompilerOptions, errors: Diagnostic[] }) { - const fileText = JSON.stringify(json); + function assertCompilerOptionsWithJsonNode(json: any, configFileName: string, expectedResult: ExpectedResultWithParsingSuccess) { + assertCompilerOptionsWithJsonText(JSON.stringify(json), configFileName, expectedResult); + } + + function assertCompilerOptionsWithJsonText(fileText: string, configFileName: string, expectedResult: ExpectedResult) { const result = parseJsonText(configFileName, fileText); - assert(!result.parseDiagnostics.length); assert(!!result.endOfFileToken); + assert.equal(!!result.parseDiagnostics.length, isExpectedResultWithParsingFailure(expectedResult)); const host: ParseConfigHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ false, { cwd: "/apath/" })); const { options: actualCompilerOptions, errors: actualParseErrors } = parseJsonSourceFileConfigFileContent(result, host, "/apath/", /*existingOptions*/ undefined, configFileName); expectedResult.compilerOptions.configFilePath = configFileName; @@ -37,17 +54,32 @@ namespace ts { assert.equal(parsedCompilerOptions, expectedCompilerOptions); assert.equal(actualCompilerOptions.configFile, result); - const actualErrors = filter(actualParseErrors, error => error.code !== Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code); - const expectedErrors = expectedResult.errors; - assert.isTrue(expectedResult.errors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedResult.errors)}. Actual error: ${JSON.stringify(actualErrors)}.`); + if (!isExpectedResultWithParsingFailure(expectedResult)) { + verifyErrors(actualParseErrors.filter(error => error.code !== Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code), expectedResult.errors); + } + } + + function verifyErrors(actualErrors: Diagnostic[], expectedErrors: ReadonlyArray, ignoreLocation?: boolean) { + assert.isTrue(expectedErrors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedErrors.map(getDiagnosticString), undefined, " ")}. Actual error: ${JSON.stringify(actualErrors.map(getDiagnosticString), undefined, " ")}.`); for (let i = 0; i < actualErrors.length; i++) { const actualError = actualErrors[i]; const expectedError = expectedErrors[i]; + assert.equal(actualError.code, expectedError.code, `Expected error-code: ${JSON.stringify(expectedError.code)}. Actual error-code: ${JSON.stringify(actualError.code)}.`); assert.equal(actualError.category, expectedError.category, `Expected error-category: ${JSON.stringify(expectedError.category)}. Actual error-category: ${JSON.stringify(actualError.category)}.`); - assert(actualError.file); - assert(actualError.start); - assert(actualError.length); + if (!ignoreLocation) { + assert(actualError.file); + assert(actualError.start); + assert(actualError.length); + } + } + + function getDiagnosticString(diagnostic: Diagnostic) { + if (ignoreLocation) { + const { file, ...rest } = diagnostic; + diagnostic = { file: undefined, ...rest }; + } + return formatDiagnostic(diagnostic, formatDiagnosticHost); } } @@ -263,7 +295,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -294,7 +326,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -325,7 +357,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -356,7 +388,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -539,5 +571,37 @@ namespace ts { } ); }); + + it("Convert tsconfig options when there are multiple invalid strings", () => { + assertCompilerOptionsWithJsonText(`{ + "compilerOptions": { + "target": "<%- options.useTsWithBabel ? 'esnext' : 'es5' %>", + "module": "esnext", + <%_ if (options.classComponent) { _%> + "experimentalDecorators": true, + <%_ } _%> + "sourceMap": true, + "types": [ + "webpack-env"<% if (hasMocha || hasJest) { %>,<% } %> + <%_ if (hasMocha) { _%> + "mocha", + "chai" + <%_ } else if (hasJest) { _%> + "jest" + <%_ } _%> + ] + } +} +`, "tsconfig.json", + { + compilerOptions: { + target: undefined, + module: ModuleKind.ESNext, + experimentalDecorators: true, + }, + hasParseErrors: true + } + ); + }); }); } diff --git a/src/testRunner/unittests/convertTypeAcquisitionFromJson.ts b/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts similarity index 96% rename from src/testRunner/unittests/convertTypeAcquisitionFromJson.ts rename to src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts index b46d37f0428..890cad4ade6 100644 --- a/src/testRunner/unittests/convertTypeAcquisitionFromJson.ts +++ b/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts @@ -1,6 +1,6 @@ namespace ts { interface ExpectedResult { typeAcquisition: TypeAcquisition; errors: Diagnostic[]; } - describe("convertTypeAcquisitionFromJson", () => { + describe("unittests:: config:: convertTypeAcquisitionFromJson", () => { function assertTypeAcquisition(json: any, configFileName: string, expectedResult: ExpectedResult) { assertTypeAcquisitionWithJson(json, configFileName, expectedResult); assertTypeAcquisitionWithJsonNode(json, configFileName, expectedResult); diff --git a/src/testRunner/unittests/initializeTSConfig.ts b/src/testRunner/unittests/config/initializeTSConfig.ts similarity index 95% rename from src/testRunner/unittests/initializeTSConfig.ts rename to src/testRunner/unittests/config/initializeTSConfig.ts index 679eecf71b1..f7fb7d2a439 100644 --- a/src/testRunner/unittests/initializeTSConfig.ts +++ b/src/testRunner/unittests/config/initializeTSConfig.ts @@ -1,5 +1,5 @@ namespace ts { - describe("initTSConfig", () => { + describe("unittests:: config:: initTSConfig", () => { function initTSConfigCorrectly(name: string, commandLinesArgs: string[]) { describe(name, () => { const commandLine = parseCommandLine(commandLinesArgs); @@ -30,4 +30,4 @@ namespace ts { initTSConfigCorrectly("Initialized TSConfig with advanced options", ["--init", "--declaration", "--declarationDir", "lib", "--skipLibCheck", "--noErrorTruncation"]); }); -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/matchFiles.ts b/src/testRunner/unittests/config/matchFiles.ts similarity index 97% rename from src/testRunner/unittests/matchFiles.ts rename to src/testRunner/unittests/config/matchFiles.ts index 5ece71245bb..a30fa468443 100644 --- a/src/testRunner/unittests/matchFiles.ts +++ b/src/testRunner/unittests/config/matchFiles.ts @@ -143,7 +143,7 @@ namespace ts { return createFileDiagnostic(file, start, length, diagnosticMessage, arg0); } - describe("matchFiles", () => { + describe("unittests:: config:: matchFiles", () => { it("with defaults", () => { const json = {}; const expected: ParsedCommandLine = { diff --git a/src/testRunner/unittests/projectReferences.ts b/src/testRunner/unittests/config/projectReferences.ts similarity index 86% rename from src/testRunner/unittests/projectReferences.ts rename to src/testRunner/unittests/config/projectReferences.ts index 4702c0c26ce..6c8863314fa 100644 --- a/src/testRunner/unittests/projectReferences.ts +++ b/src/testRunner/unittests/config/projectReferences.ts @@ -85,7 +85,7 @@ namespace ts { // We shouldn't have any errors about invalid tsconfig files in these tests assert(config && !error, flattenDiagnosticMessageText(error && error.messageText, "\n")); - const file = parseJsonConfigFileContent(config, parseConfigHostFromCompilerHost(host), getDirectoryPath(entryPointConfigFileName), {}, entryPointConfigFileName); + const file = parseJsonConfigFileContent(config, parseConfigHostFromCompilerHostLike(host), getDirectoryPath(entryPointConfigFileName), {}, entryPointConfigFileName); file.options.configFilePath = entryPointConfigFileName; const prog = createProgram({ rootNames: file.fileNames, @@ -96,7 +96,7 @@ namespace ts { checkResult(prog, host); } - describe("project-references meta check", () => { + describe("unittests:: config:: project-references meta check", () => { it("default setup was created correctly", () => { const spec: TestSpecification = { "/primary": { @@ -118,7 +118,7 @@ namespace ts { /** * Validate that we enforce the basic settings constraints for referenced projects */ - describe("project-references constraint checking for settings", () => { + describe("unittests:: config:: project-references constraint checking for settings", () => { it("errors when declaration = false", () => { const spec: TestSpecification = { "/primary": { @@ -147,7 +147,10 @@ namespace ts { }, "/reference": { files: { "/secondary/b.ts": moduleImporting("../primary/a") }, - references: ["../primary"] + references: ["../primary"], + config: { + files: ["b.ts"] + } } }; testProjectReferences(spec, "/reference/tsconfig.json", program => { @@ -156,6 +159,26 @@ namespace ts { }); }); + it("does not error when the referenced project doesn't have composite:true if its a container project", () => { + const spec: TestSpecification = { + "/primary": { + files: { "/primary/a.ts": emptyModule }, + references: [], + options: { + composite: false + } + }, + "/reference": { + files: { "/secondary/b.ts": moduleImporting("../primary/a") }, + references: ["../primary"], + } + }; + testProjectReferences(spec, "/reference/tsconfig.json", program => { + const errs = program.getOptionsDiagnostics(); + assertNoErrors("Reports an error about 'composite' not being set", errs); + }); + }); + it("errors when the file list is not exhaustive", () => { const spec: TestSpecification = { "/primary": { @@ -184,7 +207,7 @@ namespace ts { }; testProjectReferences(spec, "/primary/tsconfig.json", program => { const errs = program.getOptionsDiagnostics(); - assertHasError("Reports an error about a missing file", errs, Diagnostics.File_0_does_not_exist); + assertHasError("Reports an error about a missing file", errs, Diagnostics.File_0_not_found); }); }); @@ -225,7 +248,7 @@ namespace ts { /** * Path mapping behavior */ - describe("project-references path mapping", () => { + describe("unittests:: config:: project-references path mapping", () => { it("redirects to the output .d.ts file", () => { const spec: TestSpecification = { "/alpha": { @@ -245,7 +268,7 @@ namespace ts { }); }); - describe("project-references nice-behavior", () => { + describe("unittests:: config:: project-references nice-behavior", () => { it("issues a nice error when the input file is missing", () => { const spec: TestSpecification = { "/alpha": { @@ -266,7 +289,7 @@ namespace ts { /** * 'composite' behavior */ - describe("project-references behavior changes under composite: true", () => { + describe("unittests:: config:: project-references behavior changes under composite: true", () => { it("doesn't infer the rootDir from source paths", () => { const spec: TestSpecification = { "/alpha": { @@ -285,7 +308,7 @@ namespace ts { }); }); - describe("errors when a file in a composite project occurs outside the root", () => { + describe("unittests:: config:: project-references errors when a file in a composite project occurs outside the root", () => { it("Errors when a file is outside the rootdir", () => { const spec: TestSpecification = { "/alpha": { diff --git a/src/testRunner/unittests/config/showConfig.ts b/src/testRunner/unittests/config/showConfig.ts new file mode 100644 index 00000000000..afe8f878d27 --- /dev/null +++ b/src/testRunner/unittests/config/showConfig.ts @@ -0,0 +1,151 @@ +namespace ts { + describe("unittests:: config:: showConfig", () => { + function showTSConfigCorrectly(name: string, commandLinesArgs: string[], configJson?: object) { + describe(name, () => { + const outputFileName = `showConfig/${name.replace(/[^a-z0-9\-./ ]/ig, "")}/tsconfig.json`; + + it(`Correct output for ${outputFileName}`, () => { + const cwd = `/${name}`; + const configPath = combinePaths(cwd, "tsconfig.json"); + const configContents = configJson ? JSON.stringify(configJson) : undefined; + const configParseHost: ParseConfigFileHost = { + fileExists: path => + comparePaths(getNormalizedAbsolutePath(path, cwd), configPath) === Comparison.EqualTo ? true : false, + getCurrentDirectory() { return cwd; }, + useCaseSensitiveFileNames: true, + onUnRecoverableConfigFileDiagnostic: d => { + throw new Error(flattenDiagnosticMessageText(d.messageText, "\n")); + }, + readDirectory() { return []; }, + readFile: path => + comparePaths(getNormalizedAbsolutePath(path, cwd), configPath) === Comparison.EqualTo ? configContents : undefined, + }; + let commandLine = parseCommandLine(commandLinesArgs); + if (commandLine.options.project) { + const result = getParsedCommandLineOfConfigFile(commandLine.options.project, commandLine.options, configParseHost); + if (result) { + commandLine = result; + } + } + const initResult = convertToTSConfig(commandLine, configPath, configParseHost); + + // tslint:disable-next-line:no-null-keyword + Harness.Baseline.runBaseline(outputFileName, JSON.stringify(initResult, null, 4) + "\n"); + }); + }); + } + + showTSConfigCorrectly("Default initialized TSConfig", ["--showConfig"]); + + showTSConfigCorrectly("Show TSConfig with files options", ["--showConfig", "file0.st", "file1.ts", "file2.ts"]); + + showTSConfigCorrectly("Show TSConfig with boolean value compiler options", ["--showConfig", "--noUnusedLocals"]); + + showTSConfigCorrectly("Show TSConfig with enum value compiler options", ["--showConfig", "--target", "es5", "--jsx", "react"]); + + showTSConfigCorrectly("Show TSConfig with list compiler options", ["--showConfig", "--types", "jquery,mocha"]); + + showTSConfigCorrectly("Show TSConfig with list compiler options with enum value", ["--showConfig", "--lib", "es5,es2015.core"]); + + showTSConfigCorrectly("Show TSConfig with incorrect compiler option", ["--showConfig", "--someNonExistOption"]); + + showTSConfigCorrectly("Show TSConfig with incorrect compiler option value", ["--showConfig", "--lib", "nonExistLib,es5,es2015.promise"]); + + showTSConfigCorrectly("Show TSConfig with advanced options", ["--showConfig", "--declaration", "--declarationDir", "lib", "--skipLibCheck", "--noErrorTruncation"]); + + // Regression test for https://github.com/Microsoft/TypeScript/issues/28836 + showTSConfigCorrectly("Show TSConfig with paths and more", ["-p", "tsconfig.json"], { + compilerOptions: { + allowJs: true, + outDir: "./lib", + esModuleInterop: true, + module: "commonjs", + moduleResolution: "node", + target: "ES2017", + sourceMap: true, + baseUrl: ".", + paths: { + "@root/*": ["./*"], + "@configs/*": ["src/configs/*"], + "@common/*": ["src/common/*"], + "*": [ + "node_modules/*", + "src/types/*" + ] + }, + experimentalDecorators: true, + emitDecoratorMetadata: true, + resolveJsonModule: true + }, + include: [ + "./src/**/*" + ] +}); + + // Bulk validation of all option declarations + for (const option of optionDeclarations) { + if (option.name === "project") continue; + let configObject: object | undefined; + let args: string[]; + switch (option.type) { + case "boolean": { + if (option.isTSConfigOnly) { + args = ["-p", "tsconfig.json"]; + configObject = { compilerOptions: { [option.name]: true } }; + } + else { + args = [`--${option.name}`]; + } + break; + } + case "list": { + if (option.isTSConfigOnly) { + args = ["-p", "tsconfig.json"]; + configObject = { compilerOptions: { [option.name]: [] } }; + } + else { + args = [`--${option.name}`]; + } + break; + } + case "string": { + if (option.isTSConfigOnly) { + args = ["-p", "tsconfig.json"]; + configObject = { compilerOptions: { [option.name]: "someString" } }; + } + else { + args = [`--${option.name}`, "someString"]; + } + break; + } + case "number": { + if (option.isTSConfigOnly) { + args = ["-p", "tsconfig.json"]; + configObject = { compilerOptions: { [option.name]: 0 } }; + } + else { + args = [`--${option.name}`, "0"]; + } + break; + } + case "object": { + args = ["-p", "tsconfig.json"]; + configObject = { compilerOptions: { [option.name]: {} } }; + break; + } + default: { + const val = option.type.keys().next().value; + if (option.isTSConfigOnly) { + args = ["-p", "tsconfig.json"]; + configObject = { compilerOptions: { [option.name]: val } }; + } + else { + args = [`--${option.name}`, val]; + } + break; + } + } + showTSConfigCorrectly(`Shows tsconfig for single option/${option.name}`, args, configObject); + } + }); +} diff --git a/src/testRunner/unittests/tsconfigParsing.ts b/src/testRunner/unittests/config/tsconfigParsing.ts similarity index 85% rename from src/testRunner/unittests/tsconfigParsing.ts rename to src/testRunner/unittests/config/tsconfigParsing.ts index 6ef5697046f..638a394a34e 100644 --- a/src/testRunner/unittests/tsconfigParsing.ts +++ b/src/testRunner/unittests/config/tsconfigParsing.ts @@ -1,5 +1,5 @@ namespace ts { - describe("parseConfigFileTextToJson", () => { + describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () => { function assertParseResult(jsonText: string, expectedConfigObject: { config?: any; error?: Diagnostic[] }) { const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", jsonText); assert.equal(JSON.stringify(parsed), JSON.stringify(expectedConfigObject)); @@ -61,6 +61,19 @@ namespace ts { } } + function assertParseFileDiagnosticsExclusion(jsonText: string, configFileName: string, basePath: string, allFileList: string[], expectedExcludedDiagnosticCode: number) { + { + const parsed = getParsedCommandJson(jsonText, configFileName, basePath, allFileList); + assert.isTrue(parsed.errors.length >= 0); + assert.isTrue(parsed.errors.findIndex(e => e.code === expectedExcludedDiagnosticCode) === -1, `Expected error code ${expectedExcludedDiagnosticCode} to not be in ${JSON.stringify(parsed.errors)}`); + } + { + const parsed = getParsedCommandJsonNode(jsonText, configFileName, basePath, allFileList); + assert.isTrue(parsed.errors.length >= 0); + assert.isTrue(parsed.errors.findIndex(e => e.code === expectedExcludedDiagnosticCode) === -1, `Expected error code ${expectedExcludedDiagnosticCode} to not be in ${JSON.stringify(parsed.errors)}`); + } + } + it("returns empty config for file with only whitespaces", () => { assertParseResult("", { config : {} }); assertParseResult(" ", { config : {} }); @@ -128,7 +141,7 @@ namespace ts { it("returns object with error when json is invalid", () => { const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", "invalid"); - assert.deepEqual(parsed.config, { invalid: undefined }); + assert.deepEqual(parsed.config, {}); const expected = createCompilerDiagnostic(Diagnostics._0_expected, "{"); const error = parsed.error!; assert.equal(error.messageText, expected.messageText); @@ -280,6 +293,30 @@ namespace ts { Diagnostics.The_files_list_in_config_file_0_is_empty.code); }); + it("generates errors for empty files list when no references are provided", () => { + const content = `{ + "files": [], + "references": [] + }`; + assertParseFileDiagnostics(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + ["/apath/a.ts"], + Diagnostics.The_files_list_in_config_file_0_is_empty.code); + }); + + it("does not generate errors for empty files list when one or more references are provided", () => { + const content = `{ + "files": [], + "references": [{ "path": "/apath" }] + }`; + assertParseFileDiagnosticsExclusion(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + ["/apath/a.ts"], + Diagnostics.The_files_list_in_config_file_0_is_empty.code); + }); + it("generates errors for directory with no .ts files", () => { const content = `{ }`; diff --git a/src/testRunner/unittests/convertToBase64.ts b/src/testRunner/unittests/convertToBase64.ts index 56c95622977..37e38da8da7 100644 --- a/src/testRunner/unittests/convertToBase64.ts +++ b/src/testRunner/unittests/convertToBase64.ts @@ -1,5 +1,5 @@ namespace ts { - describe("convertToBase64", () => { + describe("unittests:: convertToBase64", () => { function runTest(input: string): void { const actual = convertToBase64(input); const expected = sys.base64encode!(input); diff --git a/src/testRunner/unittests/customTransforms.ts b/src/testRunner/unittests/customTransforms.ts index 819b5d80df5..aef9ed745ec 100644 --- a/src/testRunner/unittests/customTransforms.ts +++ b/src/testRunner/unittests/customTransforms.ts @@ -1,5 +1,5 @@ namespace ts { - describe("customTransforms", () => { + describe("unittests:: customTransforms", () => { function emitsCorrectly(name: string, sources: { file: string, text: string }[], customTransformers: CustomTransformers, options: CompilerOptions = {}) { it(name, () => { const roots = sources.map(source => createSourceFile(source.file, source.text, ScriptTarget.ES2015)); @@ -18,7 +18,7 @@ namespace ts { writeFile: (fileName, text) => outputs.set(fileName, text), }; - const program = createProgram(arrayFrom(fileMap.keys()), options, host); + const program = createProgram(arrayFrom(fileMap.keys()), { newLine: NewLineKind.LineFeed, ...options }, host); program.emit(/*targetSourceFile*/ undefined, host.writeFile, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ false, customTransformers); let content = ""; for (const [file, text] of arrayFrom(outputs.entries())) { @@ -95,6 +95,39 @@ namespace ts { module: ModuleKind.ES2015, emitDecoratorMetadata: true, experimentalDecorators: true - }); + }); + + emitsCorrectly("sourceMapExternalSourceFiles", + [ + { + file: "source.ts", + // The text of length 'changed' is made to be on two lines so we know the line map change + text: `\`multi + line\` +'change'` + }, + ], + { + before: [ + context => node => visitNode(node, function visitor(node: Node): Node { + if (isStringLiteral(node) && node.text === "change") { + const text = "'changed'"; + const lineMap = computeLineStarts(text); + setSourceMapRange(node, { + pos: 0, end: text.length, source: { + text, + fileName: "another.html", + lineMap, + getLineAndCharacterOfPosition: pos => computeLineAndCharacterOfPosition(lineMap, pos) + } + }); + return node; + } + return visitEachChild(node, visitor, context); + }) + ] + }, + { sourceMap: true } + ); }); -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/evaluation/asyncArrow.ts b/src/testRunner/unittests/evaluation/asyncArrow.ts index 994fe8a84be..04a7af613fa 100644 --- a/src/testRunner/unittests/evaluation/asyncArrow.ts +++ b/src/testRunner/unittests/evaluation/asyncArrow.ts @@ -1,4 +1,4 @@ -describe("asyncArrowEvaluation", () => { +describe("unittests:: evaluation:: asyncArrowEvaluation", () => { // https://github.com/Microsoft/TypeScript/issues/24722 it("this capture (es5)", async () => { const result = evaluator.evaluateTypeScript(` @@ -15,4 +15,4 @@ describe("asyncArrowEvaluation", () => { await result.main(); assert.instanceOf(result.output[0].a(), result.A); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/evaluation/asyncGenerator.ts b/src/testRunner/unittests/evaluation/asyncGenerator.ts index 9963ea921fa..8ca531f0759 100644 --- a/src/testRunner/unittests/evaluation/asyncGenerator.ts +++ b/src/testRunner/unittests/evaluation/asyncGenerator.ts @@ -1,4 +1,4 @@ -describe("asyncGeneratorEvaluation", () => { +describe("unittests:: evaluation:: asyncGeneratorEvaluation", () => { it("return (es5)", async () => { const result = evaluator.evaluateTypeScript(` async function * g() { @@ -27,4 +27,4 @@ describe("asyncGeneratorEvaluation", () => { { value: 0, done: true } ]); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/evaluation/forAwaitOf.ts b/src/testRunner/unittests/evaluation/forAwaitOf.ts index 20ab5eed0cc..c7be018cbc9 100644 --- a/src/testRunner/unittests/evaluation/forAwaitOf.ts +++ b/src/testRunner/unittests/evaluation/forAwaitOf.ts @@ -1,4 +1,4 @@ -describe("forAwaitOfEvaluation", () => { +describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { it("sync (es5)", async () => { const result = evaluator.evaluateTypeScript(` let i = 0; diff --git a/src/testRunner/unittests/factory.ts b/src/testRunner/unittests/factory.ts index 402c399d728..cc760059c19 100644 --- a/src/testRunner/unittests/factory.ts +++ b/src/testRunner/unittests/factory.ts @@ -1,5 +1,5 @@ namespace ts { - describe("FactoryAPI", () => { + describe("unittests:: FactoryAPI", () => { function assertSyntaxKind(node: Node, expected: SyntaxKind) { assert.strictEqual(node.kind, expected, `Actual: ${Debug.showSyntaxKind(node)} Expected: ${(ts as any).SyntaxKind[expected]}`); } diff --git a/src/testRunner/unittests/incrementalParser.ts b/src/testRunner/unittests/incrementalParser.ts index fb3408b1fc3..8af44494803 100644 --- a/src/testRunner/unittests/incrementalParser.ts +++ b/src/testRunner/unittests/incrementalParser.ts @@ -120,7 +120,7 @@ namespace ts { } } - describe("Incremental", () => { + describe("unittests:: Incremental Parser", () => { it("Inserting into method", () => { const source = "class C {\r\n" + " public foo1() { }\r\n" + diff --git a/src/testRunner/unittests/jsDocParsing.ts b/src/testRunner/unittests/jsDocParsing.ts index 931785aa94d..4171a330f32 100644 --- a/src/testRunner/unittests/jsDocParsing.ts +++ b/src/testRunner/unittests/jsDocParsing.ts @@ -1,5 +1,5 @@ namespace ts { - describe("JSDocParsing", () => { + describe("unittests:: JSDocParsing", () => { describe("TypeExpressions", () => { function parsesCorrectly(name: string, content: string) { it(name, () => { diff --git a/src/testRunner/unittests/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index 7a9e4278c57..69560e5449c 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -80,10 +80,10 @@ namespace ts { } } - describe("Node module resolution - relative paths", () => { + describe("unittests:: moduleResolution:: Node module resolution - relative paths", () => { function testLoadAsFile(containingFileName: string, moduleFileNameNoExt: string, moduleName: string): void { - for (const ext of supportedTypeScriptExtensions) { + for (const ext of supportedTSExtensions) { test(ext, /*hasDirectoryExists*/ false); test(ext, /*hasDirectoryExists*/ true); } @@ -96,7 +96,7 @@ namespace ts { const failedLookupLocations: string[] = []; const dir = getDirectoryPath(containingFileName); - for (const e of supportedTypeScriptExtensions) { + for (const e of supportedTSExtensions) { if (e === ext) { break; } @@ -137,7 +137,7 @@ namespace ts { const resolution = nodeModuleNameResolver(moduleName, containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, packageJson, moduleFile)); checkResolvedModule(resolution.resolvedModule, createResolvedModule(moduleFile.name)); // expect three failed lookup location - attempt to load module as file with all supported extensions - assert.equal(resolution.failedLookupLocations.length, supportedTypeScriptExtensions.length); + assert.equal(resolution.failedLookupLocations.length, supportedTSExtensions.length); } } @@ -200,7 +200,7 @@ namespace ts { }); }); - describe("Node module resolution - non-relative paths", () => { + describe("unittests:: moduleResolution:: Node module resolution - non-relative paths", () => { it("computes correct commonPrefix for moduleName cache", () => { const resolutionCache = createModuleResolutionCache("/", (f) => f); let cache = resolutionCache.getOrCreateCacheForModuleName("a"); @@ -457,7 +457,7 @@ namespace ts { }); }); - describe("Module resolution - relative imports", () => { + describe("unittests:: moduleResolution:: Relative imports", () => { function test(files: Map, currentDirectory: string, rootFiles: string[], expectedFilesCount: number, relativeNamesToCheck: string[]) { const options: CompilerOptions = { module: ModuleKind.CommonJS }; const host: CompilerHost = { @@ -530,7 +530,7 @@ export = C; }); }); - describe("Files with different casing", () => { + describe("unittests:: moduleResolution:: Files with different casing", () => { let library: SourceFile; function test(files: Map, options: CompilerOptions, currentDirectory: string, useCaseSensitiveFileNames: boolean, rootFiles: string[], diagnosticCodes: number[]): void { const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); @@ -651,7 +651,7 @@ import b = require("./moduleB"); }); }); - describe("baseUrl augmented module resolution", () => { + describe("unittests:: moduleResolution:: baseUrl augmented module resolution", () => { it("module resolution without path mappings/rootDirs", () => { test(/*hasDirectoryExists*/ false); @@ -757,6 +757,9 @@ import b = require("./moduleB"); ], "somefolder/*": [ "someanotherfolder/*" + ], + "/rooted/*": [ + "generated/*" ] } }; @@ -773,6 +776,7 @@ import b = require("./moduleB"); "/root/folder1/file2/index.d.ts", // then first attempt on 'generated/*' was successful ]); + check("/rooted/folder1/file2", file2, []); check("folder2/file3", file3, [ // first try '*' "/root/folder2/file3.ts", @@ -900,6 +904,9 @@ import b = require("./moduleB"); ], "somefolder/*": [ "someanotherfolder/*" + ], + "/rooted/*": [ + "generated/*" ] } }; @@ -911,6 +918,7 @@ import b = require("./moduleB"); "/root/folder1/file2.d.ts", // success when using 'generated/*' ]); + check("/rooted/folder1/file2", file2, []); check("folder1/file3", file3, [ // first try '*' "/root/folder1/file3.ts", @@ -1090,7 +1098,7 @@ import b = require("./moduleB"); }); }); - describe("ModuleResolutionHost.directoryExists", () => { + describe("unittests:: moduleResolution:: ModuleResolutionHost.directoryExists", () => { it("No 'fileExists' calls if containing directory is missing", () => { const host: ModuleResolutionHost = { readFile: notImplemented, @@ -1103,15 +1111,19 @@ import b = require("./moduleB"); }); }); - describe("Type reference directive resolution: ", () => { - function test(typesRoot: string, typeDirective: string, primary: boolean, initialFile: File, targetFile: File, ...otherFiles: File[]) { - const host = createModuleResolutionHost(/*hasDirectoryExists*/ false, ...[initialFile, targetFile].concat(...otherFiles)); - const result = resolveTypeReferenceDirective(typeDirective, initialFile.name, { typeRoots: [typesRoot] }, host); + describe("unittests:: moduleResolution:: Type reference directive resolution: ", () => { + function testWorker(hasDirectoryExists: boolean, typesRoot: string | undefined, typeDirective: string, primary: boolean, initialFile: File, targetFile: File, ...otherFiles: File[]) { + const host = createModuleResolutionHost(hasDirectoryExists, ...[initialFile, targetFile].concat(...otherFiles)); + const result = resolveTypeReferenceDirective(typeDirective, initialFile.name, typesRoot ? { typeRoots: [typesRoot] } : {}, host); assert(result.resolvedTypeReferenceDirective!.resolvedFileName !== undefined, "expected type directive to be resolved"); assert.equal(result.resolvedTypeReferenceDirective!.resolvedFileName, targetFile.name, "unexpected result of type reference resolution"); assert.equal(result.resolvedTypeReferenceDirective!.primary, primary, "unexpected 'primary' value"); } + function test(typesRoot: string, typeDirective: string, primary: boolean, initialFile: File, targetFile: File, ...otherFiles: File[]) { + testWorker(/*hasDirectoryExists*/ false, typesRoot, typeDirective, primary, initialFile, targetFile, ...otherFiles); + } + it("Can be resolved from primary location", () => { { const f1 = { name: "/root/src/app.ts" }; @@ -1194,7 +1206,7 @@ import b = require("./moduleB"); const names = map(files, f => f.name); const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES2015)), f => f.fileName); const compilerHost: CompilerHost = { - fileExists : fileName => sourceFiles.has(fileName), + fileExists: fileName => sourceFiles.has(fileName), getSourceFile: fileName => sourceFiles.get(fileName), getDefaultLibFileName: () => "lib.d.ts", writeFile: notImplemented, @@ -1219,7 +1231,7 @@ import b = require("./moduleB"); assert.equal(diagnostics1[0].messageText, diagnostics2[0].messageText, "expected one diagnostic"); }); - it ("Modules in the same .d.ts file are preferred to external files", () => { + it("Modules in the same .d.ts file are preferred to external files", () => { const f = { name: "/a/b/c/c/app.d.ts", content: ` @@ -1233,7 +1245,7 @@ import b = require("./moduleB"); }; const file = createSourceFile(f.name, f.content, ScriptTarget.ES2015); const compilerHost: CompilerHost = { - fileExists : fileName => fileName === file.fileName, + fileExists: fileName => fileName === file.fileName, getSourceFile: fileName => fileName === file.fileName ? file : undefined, getDefaultLibFileName: () => "lib.d.ts", writeFile: notImplemented, @@ -1248,7 +1260,7 @@ import b = require("./moduleB"); createProgram([f.name], {}, compilerHost); }); - it ("Modules in .ts file are not checked in the same file", () => { + it("Modules in .ts file are not checked in the same file", () => { const f = { name: "/a/b/c/c/app.ts", content: ` @@ -1262,7 +1274,7 @@ import b = require("./moduleB"); }; const file = createSourceFile(f.name, f.content, ScriptTarget.ES2015); const compilerHost: CompilerHost = { - fileExists : fileName => fileName === file.fileName, + fileExists: fileName => fileName === file.fileName, getSourceFile: fileName => fileName === file.fileName ? file : undefined, getDefaultLibFileName: () => "lib.d.ts", writeFile: notImplemented, @@ -1279,5 +1291,15 @@ import b = require("./moduleB"); }; createProgram([f.name], {}, compilerHost); }); + describe("can be resolved when typeReferenceDirective is relative and in a sibling folder", () => { + const initialFile = { name: "/root/src/background/app.ts" }; + const targetFile = { name: "/root/src/typedefs/filesystem.d.ts" }; + it("when host doesnt have directoryExists", () => { + testWorker(/*hasDirectoryExists*/ false, /*typesRoot*/ undefined, /*typeDirective*/ "../typedefs/filesystem", /*primary*/ false, initialFile, targetFile); + }); + it("when host has directoryExists", () => { + testWorker(/*hasDirectoryExists*/ true, /*typesRoot*/ undefined, /*typeDirective*/ "../typedefs/filesystem", /*primary*/ false, initialFile, targetFile); + }); + }); }); } diff --git a/src/testRunner/unittests/parsePseudoBigInt.ts b/src/testRunner/unittests/parsePseudoBigInt.ts new file mode 100644 index 00000000000..db1a841dc2b --- /dev/null +++ b/src/testRunner/unittests/parsePseudoBigInt.ts @@ -0,0 +1,71 @@ +namespace ts { + describe("unittests:: BigInt literal base conversions", () => { + describe("parsePseudoBigInt", () => { + const testNumbers: number[] = []; + for (let i = 0; i < 1e3; i++) testNumbers.push(i); + for (let bits = 0; bits <= 52; bits++) { + testNumbers.push(2 ** bits, 2 ** bits - 1); + } + it("can strip base-10 strings", () => { + for (const testNumber of testNumbers) { + for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) { + assert.equal( + parsePseudoBigInt("0".repeat(leadingZeros) + testNumber + "n"), + String(testNumber) + ); + } + } + }); + it("can parse binary literals", () => { + for (const testNumber of testNumbers) { + for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) { + const binary = "0".repeat(leadingZeros) + testNumber.toString(2) + "n"; + for (const prefix of ["0b", "0B"]) { + assert.equal(parsePseudoBigInt(prefix + binary), String(testNumber)); + } + } + } + }); + it("can parse octal literals", () => { + for (const testNumber of testNumbers) { + for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) { + const octal = "0".repeat(leadingZeros) + testNumber.toString(8) + "n"; + for (const prefix of ["0o", "0O"]) { + assert.equal(parsePseudoBigInt(prefix + octal), String(testNumber)); + } + } + } + }); + it("can parse hex literals", () => { + for (const testNumber of testNumbers) { + for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) { + const hex = "0".repeat(leadingZeros) + testNumber.toString(16) + "n"; + for (const prefix of ["0x", "0X"]) { + for (const hexCase of [hex.toLowerCase(), hex.toUpperCase()]) { + assert.equal(parsePseudoBigInt(prefix + hexCase), String(testNumber)); + } + } + } + } + }); + it("can parse large literals", () => { + assert.equal( + parsePseudoBigInt("123456789012345678901234567890n"), + "123456789012345678901234567890" + ); + assert.equal( + parsePseudoBigInt("0b1100011101110100100001111111101101100001101110011111000001110111001001110001111110000101011010010n"), + "123456789012345678901234567890" + ); + assert.equal( + parsePseudoBigInt("0o143564417755415637016711617605322n"), + "123456789012345678901234567890" + ); + assert.equal( + parsePseudoBigInt("0x18ee90ff6c373e0ee4e3f0ad2n"), + "123456789012345678901234567890" + ); + }); + }); + }); +} diff --git a/src/testRunner/unittests/paths.ts b/src/testRunner/unittests/paths.ts index 0b28bedc929..b1555ab2174 100644 --- a/src/testRunner/unittests/paths.ts +++ b/src/testRunner/unittests/paths.ts @@ -1,4 +1,4 @@ -describe("core paths", () => { +describe("unittests:: core paths", () => { it("normalizeSlashes", () => { assert.strictEqual(ts.normalizeSlashes("a"), "a"); assert.strictEqual(ts.normalizeSlashes("a/b"), "a/b"); @@ -289,4 +289,4 @@ describe("core paths", () => { assert.strictEqual(ts.getRelativePathFromDirectory("file:///a/b/c", "file:///a/b", /*ignoreCase*/ false), ".."); assert.strictEqual(ts.getRelativePathFromDirectory("file:///c:", "file:///d:", /*ignoreCase*/ false), "file:///d:/"); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/printer.ts b/src/testRunner/unittests/printer.ts index 2e69cf60876..8e217aa6a3a 100644 --- a/src/testRunner/unittests/printer.ts +++ b/src/testRunner/unittests/printer.ts @@ -1,5 +1,5 @@ namespace ts { - describe("PrinterAPI", () => { + describe("unittests:: PrinterAPI", () => { function makePrintsCorrectly(prefix: string) { return function printsCorrectly(name: string, options: PrinterOptions, printCallback: (printer: Printer) => string) { it(name, () => { diff --git a/src/testRunner/unittests/programMissingFiles.ts b/src/testRunner/unittests/programApi.ts similarity index 50% rename from src/testRunner/unittests/programMissingFiles.ts rename to src/testRunner/unittests/programApi.ts index 37d4c791196..01ef6610dba 100644 --- a/src/testRunner/unittests/programMissingFiles.ts +++ b/src/testRunner/unittests/programApi.ts @@ -11,7 +11,7 @@ namespace ts { assert.equal(notFound.length, 0, `Not found ${notFound} in actual: ${missingPaths} expected: ${expected}`); } - describe("Program.getMissingFilePaths", () => { + describe("unittests:: Program.getMissingFilePaths", () => { const options: CompilerOptions = { noLib: true, @@ -97,5 +97,67 @@ namespace ts { "d:/pretend/nonexistent4.tsx" ]); }); + + it("should not have missing file paths", () => { + const testSource = ` + class Foo extends HTMLElement { + bar: string = 'baz'; + }`; + + const host: CompilerHost = { + getSourceFile: (fileName: string, languageVersion: ScriptTarget, _onError?: (message: string) => void) => { + return fileName === "test.ts" ? createSourceFile(fileName, testSource, languageVersion) : undefined; + }, + getDefaultLibFileName: () => "", + writeFile: (_fileName, _content) => { throw new Error("unsupported"); }, + getCurrentDirectory: () => sys.getCurrentDirectory(), + getCanonicalFileName: fileName => sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(), + getNewLine: () => sys.newLine, + useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames, + fileExists: fileName => fileName === "test.ts", + readFile: fileName => fileName === "test.ts" ? testSource : undefined, + resolveModuleNames: (_moduleNames: string[], _containingFile: string) => { throw new Error("unsupported"); }, + getDirectories: _path => { throw new Error("unsupported"); }, + }; + + const program = createProgram(["test.ts"], { module: ModuleKind.ES2015 }, host); + assert(program.getSourceFiles().length === 1, "expected 'getSourceFiles' length to be 1"); + assert(program.getMissingFilePaths().length === 0, "expected 'getMissingFilePaths' length to be 0"); + assert(program.getFileProcessingDiagnostics().getDiagnostics().length === 0, "expected 'getFileProcessingDiagnostics' length to be 0"); + }); + }); + + describe("unittests:: Program.isSourceFileFromExternalLibrary", () => { + it("works on redirect files", () => { + // In this example '/node_modules/foo/index.d.ts' will redirect to '/node_modules/bar/node_modules/foo/index.d.ts'. + const a = new documents.TextDocument("/a.ts", 'import * as bar from "bar"; import * as foo from "foo";'); + const bar = new documents.TextDocument("/node_modules/bar/index.d.ts", 'import * as foo from "foo";'); + const fooPackageJsonText = '{ "name": "foo", "version": "1.2.3" }'; + const fooIndexText = "export const x: number;"; + const barFooPackage = new documents.TextDocument("/node_modules/bar/node_modules/foo/package.json", fooPackageJsonText); + const barFooIndex = new documents.TextDocument("/node_modules/bar/node_modules/foo/index.d.ts", fooIndexText); + const fooPackage = new documents.TextDocument("/node_modules/foo/package.json", fooPackageJsonText); + const fooIndex = new documents.TextDocument("/node_modules/foo/index.d.ts", fooIndexText); + + const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [a, bar, barFooPackage, barFooIndex, fooPackage, fooIndex], cwd: "/" }); + const program = createProgram(["/a.ts"], emptyOptions, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed })); + assertIsExternal(program, [a, bar, barFooIndex, fooIndex], f => f !== a); + }); + + it('works on `/// `', () => { + const a = new documents.TextDocument("/a.ts", '/// '); + const fooIndex = new documents.TextDocument("/node_modules/foo/index.d.ts", "declare const foo: number;"); + const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [a, fooIndex], cwd: "/" }); + const program = createProgram(["/a.ts"], emptyOptions, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed })); + assertIsExternal(program, [a, fooIndex], f => f !== a); + }); + + function assertIsExternal(program: Program, files: ReadonlyArray, isExternalExpected: (file: documents.TextDocument) => boolean): void { + for (const file of files) { + const actual = program.isSourceFileFromExternalLibrary(program.getSourceFile(file.file)!); + const expected = isExternalExpected(file); + assert.equal(actual, expected, `Expected ${file.file} isSourceFileFromExternalLibrary to be ${expected}, got ${actual}`); + } + } }); } diff --git a/src/testRunner/unittests/programNoParseFalsyFileNames.ts b/src/testRunner/unittests/programNoParseFalsyFileNames.ts deleted file mode 100644 index 8040e7c7f43..00000000000 --- a/src/testRunner/unittests/programNoParseFalsyFileNames.ts +++ /dev/null @@ -1,36 +0,0 @@ -namespace ts { - describe("programNoParseFalsyFileNames", () => { - let program: Program; - - beforeEach(() => { - const testSource = ` - class Foo extends HTMLElement { - bar: string = 'baz'; - }`; - - const host: CompilerHost = { - getSourceFile: (fileName: string, languageVersion: ScriptTarget, _onError?: (message: string) => void) => { - return fileName === "test.ts" ? createSourceFile(fileName, testSource, languageVersion) : undefined; - }, - getDefaultLibFileName: () => "", - writeFile: (_fileName, _content) => { throw new Error("unsupported"); }, - getCurrentDirectory: () => sys.getCurrentDirectory(), - getCanonicalFileName: fileName => sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(), - getNewLine: () => sys.newLine, - useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames, - fileExists: fileName => fileName === "test.ts", - readFile: fileName => fileName === "test.ts" ? testSource : undefined, - resolveModuleNames: (_moduleNames: string[], _containingFile: string) => { throw new Error("unsupported"); }, - getDirectories: _path => { throw new Error("unsupported"); }, - }; - - program = createProgram(["test.ts"], { module: ModuleKind.ES2015 }, host); - }); - - it("should not have missing file paths", () => { - assert(program.getSourceFiles().length === 1, "expected 'getSourceFiles' length to be 1"); - assert(program.getMissingFilePaths().length === 0, "expected 'getMissingFilePaths' length to be 0"); - assert(program.getFileProcessingDiagnostics().getDiagnostics().length === 0, "expected 'getFileProcessingDiagnostics' length to be 0"); - }); - }); -} \ No newline at end of file diff --git a/src/testRunner/unittests/projectErrors.ts b/src/testRunner/unittests/projectErrors.ts deleted file mode 100644 index b17494b59fb..00000000000 --- a/src/testRunner/unittests/projectErrors.ts +++ /dev/null @@ -1,202 +0,0 @@ -namespace ts.projectSystem { - describe("Project errors", () => { - function checkProjectErrors(projectFiles: server.ProjectFilesWithTSDiagnostics, expectedErrors: ReadonlyArray): void { - assert.isTrue(projectFiles !== undefined, "missing project files"); - checkProjectErrorsWorker(projectFiles.projectErrors, expectedErrors); - } - - function checkProjectErrorsWorker(errors: ReadonlyArray, expectedErrors: ReadonlyArray): void { - assert.equal(errors ? errors.length : 0, expectedErrors.length, `expected ${expectedErrors.length} error in the list`); - if (expectedErrors.length) { - for (let i = 0; i < errors.length; i++) { - const actualMessage = flattenDiagnosticMessageText(errors[i].messageText, "\n"); - const expectedMessage = expectedErrors[i]; - assert.isTrue(actualMessage.indexOf(expectedMessage) === 0, `error message does not match, expected ${actualMessage} to start with ${expectedMessage}`); - } - } - } - - function checkDiagnosticsWithLinePos(errors: server.protocol.DiagnosticWithLinePosition[], expectedErrors: string[]) { - assert.equal(errors ? errors.length : 0, expectedErrors.length, `expected ${expectedErrors.length} error in the list`); - if (expectedErrors.length) { - zipWith(errors, expectedErrors, ({ message: actualMessage }, expectedMessage) => { - assert.isTrue(startsWith(actualMessage, actualMessage), `error message does not match, expected ${actualMessage} to start with ${expectedMessage}`); - }); - } - } - - it("external project - diagnostics for missing files", () => { - const file1 = { - path: "/a/b/app.ts", - content: "" - }; - const file2 = { - path: "/a/b/applib.ts", - content: "" - }; - const host = createServerHost([file1, libFile]); - const session = createSession(host); - const projectService = session.getProjectService(); - const projectFileName = "/a/b/test.csproj"; - const compilerOptionsRequest: server.protocol.CompilerOptionsDiagnosticsRequest = { - type: "request", - command: server.CommandNames.CompilerOptionsDiagnosticsFull, - seq: 2, - arguments: { projectFileName } - }; - - { - projectService.openExternalProject({ - projectFileName, - options: {}, - rootFiles: toExternalFiles([file1.path, file2.path]) - }); - - checkNumberOfProjects(projectService, { externalProjects: 1 }); - const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; - // only file1 exists - expect error - checkDiagnosticsWithLinePos(diags, ["File '/a/b/applib.ts' not found."]); - } - host.reloadFS([file2, libFile]); - { - // only file2 exists - expect error - checkNumberOfProjects(projectService, { externalProjects: 1 }); - const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; - checkDiagnosticsWithLinePos(diags, ["File '/a/b/app.ts' not found."]); - } - - host.reloadFS([file1, file2, libFile]); - { - // both files exist - expect no errors - checkNumberOfProjects(projectService, { externalProjects: 1 }); - const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; - checkDiagnosticsWithLinePos(diags, []); - } - }); - - it("configured projects - diagnostics for missing files", () => { - const file1 = { - path: "/a/b/app.ts", - content: "" - }; - const file2 = { - path: "/a/b/applib.ts", - content: "" - }; - const config = { - path: "/a/b/tsconfig.json", - content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) }) - }; - const host = createServerHost([file1, config, libFile]); - const session = createSession(host); - const projectService = session.getProjectService(); - openFilesForSession([file1], session); - checkNumberOfProjects(projectService, { configuredProjects: 1 }); - const project = configuredProjectAt(projectService, 0); - const compilerOptionsRequest: server.protocol.CompilerOptionsDiagnosticsRequest = { - type: "request", - command: server.CommandNames.CompilerOptionsDiagnosticsFull, - seq: 2, - arguments: { projectFileName: project.getProjectName() } - }; - let diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; - checkDiagnosticsWithLinePos(diags, ["File '/a/b/applib.ts' not found."]); - - host.reloadFS([file1, file2, config, libFile]); - - checkNumberOfProjects(projectService, { configuredProjects: 1 }); - diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; - checkDiagnosticsWithLinePos(diags, []); - }); - - it("configured projects - diagnostics for corrupted config 1", () => { - const file1 = { - path: "/a/b/app.ts", - content: "" - }; - const file2 = { - path: "/a/b/lib.ts", - content: "" - }; - const correctConfig = { - path: "/a/b/tsconfig.json", - content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) }) - }; - const corruptedConfig = { - path: correctConfig.path, - content: correctConfig.content.substr(1) - }; - const host = createServerHost([file1, file2, corruptedConfig]); - const projectService = createProjectService(host); - - projectService.openClientFile(file1.path); - { - projectService.checkNumberOfProjects({ configuredProjects: 1 }); - const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; - assert.isTrue(configuredProject !== undefined, "should find configured project"); - checkProjectErrors(configuredProject, []); - const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); - checkProjectErrorsWorker(projectErrors, [ - "'{' expected." - ]); - assert.isNotNull(projectErrors[0].file); - assert.equal(projectErrors[0].file!.fileName, corruptedConfig.path); - } - // fix config and trigger watcher - host.reloadFS([file1, file2, correctConfig]); - { - projectService.checkNumberOfProjects({ configuredProjects: 1 }); - const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; - assert.isTrue(configuredProject !== undefined, "should find configured project"); - checkProjectErrors(configuredProject, []); - const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); - checkProjectErrorsWorker(projectErrors, []); - } - }); - - it("configured projects - diagnostics for corrupted config 2", () => { - const file1 = { - path: "/a/b/app.ts", - content: "" - }; - const file2 = { - path: "/a/b/lib.ts", - content: "" - }; - const correctConfig = { - path: "/a/b/tsconfig.json", - content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) }) - }; - const corruptedConfig = { - path: correctConfig.path, - content: correctConfig.content.substr(1) - }; - const host = createServerHost([file1, file2, correctConfig]); - const projectService = createProjectService(host); - - projectService.openClientFile(file1.path); - { - projectService.checkNumberOfProjects({ configuredProjects: 1 }); - const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; - assert.isTrue(configuredProject !== undefined, "should find configured project"); - checkProjectErrors(configuredProject, []); - const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); - checkProjectErrorsWorker(projectErrors, []); - } - // break config and trigger watcher - host.reloadFS([file1, file2, corruptedConfig]); - { - projectService.checkNumberOfProjects({ configuredProjects: 1 }); - const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; - assert.isTrue(configuredProject !== undefined, "should find configured project"); - checkProjectErrors(configuredProject, []); - const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); - checkProjectErrorsWorker(projectErrors, [ - "'{' expected." - ]); - assert.isNotNull(projectErrors[0].file); - assert.equal(projectErrors[0].file!.fileName, corruptedConfig.path); - } - }); - }); -} diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index f0f9cc6493b..c9ea0e77fec 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -27,7 +27,7 @@ namespace ts { } export class SourceText implements IScriptSnapshot { - private fullText: string; + private fullText: string | undefined; constructor(private references: string, private importsAndExports: string, @@ -104,7 +104,7 @@ namespace ts { return file; } - export function createTestCompilerHost(texts: ReadonlyArray, target: ScriptTarget, oldProgram?: ProgramWithSourceTexts): TestCompilerHost { + export function createTestCompilerHost(texts: ReadonlyArray, target: ScriptTarget, oldProgram?: ProgramWithSourceTexts, useGetSourceFileByPath?: boolean) { const files = arrayToMap(texts, t => t.name, t => { if (oldProgram) { let oldFile = oldProgram.getSourceFile(t.name); @@ -117,55 +117,47 @@ namespace ts { } return createSourceFileWithText(t.name, t.text, target); }); + const useCaseSensitiveFileNames = sys && sys.useCaseSensitiveFileNames; + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); const trace: string[] = []; - - return { + const result: TestCompilerHost = { trace: s => trace.push(s), getTrace: () => trace, - getSourceFile(fileName): SourceFile { - return files.get(fileName)!; - }, - getDefaultLibFileName(): string { - return "lib.d.ts"; - }, + getSourceFile: fileName => files.get(fileName), + getDefaultLibFileName: () => "lib.d.ts", writeFile: notImplemented, - getCurrentDirectory(): string { - return ""; - }, - getDirectories(): string[] { - return []; - }, - getCanonicalFileName(fileName): string { - return sys && sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - }, - useCaseSensitiveFileNames(): boolean { - return sys && sys.useCaseSensitiveFileNames; - }, - getNewLine(): string { - return sys ? sys.newLine : newLine; - }, + getCurrentDirectory: () => "", + getDirectories: () => [], + getCanonicalFileName, + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, + getNewLine: () => sys ? sys.newLine : newLine, fileExists: fileName => files.has(fileName), readFile: fileName => { const file = files.get(fileName); return file && file.text; }, }; + if (useGetSourceFileByPath) { + const filesByPath = mapEntries(files, (fileName, file) => [toPath(fileName, "", getCanonicalFileName), file]); + result.getSourceFileByPath = (_fileName, path) => filesByPath.get(path); + } + return result; } - export function newProgram(texts: NamedSourceText[], rootNames: string[], options: CompilerOptions): ProgramWithSourceTexts { - const host = createTestCompilerHost(texts, options.target!); + export function newProgram(texts: NamedSourceText[], rootNames: string[], options: CompilerOptions, useGetSourceFileByPath?: boolean): ProgramWithSourceTexts { + const host = createTestCompilerHost(texts, options.target!, /*oldProgram*/ undefined, useGetSourceFileByPath); const program = createProgram(rootNames, options, host); program.sourceTexts = texts; program.host = host; return program; } - export function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: ReadonlyArray, options: CompilerOptions, updater: (files: NamedSourceText[]) => void, newTexts?: NamedSourceText[]) { + export function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: ReadonlyArray, options: CompilerOptions, updater: (files: NamedSourceText[]) => void, newTexts?: NamedSourceText[], useGetSourceFileByPath?: boolean) { if (!newTexts) { newTexts = oldProgram.sourceTexts!.slice(0); } updater(newTexts); - const host = createTestCompilerHost(newTexts, options.target!, oldProgram); + const host = createTestCompilerHost(newTexts, options.target!, oldProgram, useGetSourceFileByPath); const program = createProgram(rootNames, options, host, oldProgram); program.sourceTexts = newTexts; program.host = host; @@ -218,7 +210,7 @@ namespace ts { checkCache("resolved type directives", program, fileName, expectedContent, f => f.resolvedTypeReferenceDirectiveNames, checkResolvedTypeDirective); } - describe("Reuse program structure", () => { + describe("unittests:: Reuse program structure:: General", () => { const target = ScriptTarget.Latest; const files: NamedSourceText[] = [ { @@ -305,10 +297,10 @@ namespace ts { assert.equal(program1.structureIsReused, StructureIsReused.Not); }); - it("fails if rootdir changes", () => { + it("succeeds if rootdir changes", () => { const program1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/b" }); updateProgram(program1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, noop); - assert.equal(program1.structureIsReused, StructureIsReused.Not); + assert.equal(program1.structureIsReused, StructureIsReused.Completely); }); it("fails if config path changes", () => { @@ -809,7 +801,7 @@ namespace ts { const root = "/a.ts"; const compilerOptions = { target, moduleResolution: ModuleResolutionKind.NodeJs }; - function createRedirectProgram(options?: { bText: string, bVersion: string }): ProgramWithSourceTexts { + function createRedirectProgram(useGetSourceFileByPath: boolean, options?: { bText: string, bVersion: string }): ProgramWithSourceTexts { const files: NamedSourceText[] = [ { name: "/node_modules/a/index.d.ts", @@ -841,60 +833,69 @@ namespace ts { }, ]; - return newProgram(files, [root], compilerOptions); + return newProgram(files, [root], compilerOptions, useGetSourceFileByPath); } - function updateRedirectProgram(program: ProgramWithSourceTexts, updater: (files: NamedSourceText[]) => void): ProgramWithSourceTexts { - return updateProgram(program, [root], compilerOptions, updater); + function updateRedirectProgram(program: ProgramWithSourceTexts, updater: (files: NamedSourceText[]) => void, useGetSourceFileByPath: boolean): ProgramWithSourceTexts { + return updateProgram(program, [root], compilerOptions, updater, /*newTexts*/ undefined, useGetSourceFileByPath); } - it("No changes -> redirect not broken", () => { - const program1 = createRedirectProgram(); + function verifyRedirects(useGetSourceFileByPath: boolean) { + it("No changes -> redirect not broken", () => { + const program1 = createRedirectProgram(useGetSourceFileByPath); - const program2 = updateRedirectProgram(program1, files => { - updateProgramText(files, root, "const x = 1;"); + const program2 = updateRedirectProgram(program1, files => { + updateProgramText(files, root, "const x = 1;"); + }, useGetSourceFileByPath); + assert.equal(program1.structureIsReused, StructureIsReused.Completely); + assert.lengthOf(program2.getSemanticDiagnostics(), 0); }); - assert.equal(program1.structureIsReused, StructureIsReused.Completely); - assert.lengthOf(program2.getSemanticDiagnostics(), 0); + + it("Target changes -> redirect broken", () => { + const program1 = createRedirectProgram(useGetSourceFileByPath); + assert.lengthOf(program1.getSemanticDiagnostics(), 0); + + const program2 = updateRedirectProgram(program1, files => { + updateProgramText(files, axIndex, "export default class X { private x: number; private y: number; }"); + updateProgramText(files, axPackage, JSON.stringify('{ name: "x", version: "1.2.4" }')); + }, useGetSourceFileByPath); + assert.equal(program1.structureIsReused, StructureIsReused.Not); + assert.lengthOf(program2.getSemanticDiagnostics(), 1); + }); + + it("Underlying changes -> redirect broken", () => { + const program1 = createRedirectProgram(useGetSourceFileByPath); + + const program2 = updateRedirectProgram(program1, files => { + updateProgramText(files, bxIndex, "export default class X { private x: number; private y: number; }"); + updateProgramText(files, bxPackage, JSON.stringify({ name: "x", version: "1.2.4" })); + }, useGetSourceFileByPath); + assert.equal(program1.structureIsReused, StructureIsReused.Not); + assert.lengthOf(program2.getSemanticDiagnostics(), 1); + }); + + it("Previously duplicate packages -> program structure not reused", () => { + const program1 = createRedirectProgram(useGetSourceFileByPath, { bVersion: "1.2.4", bText: "export = class X { private x: number; }" }); + + const program2 = updateRedirectProgram(program1, files => { + updateProgramText(files, bxIndex, "export default class X { private x: number; }"); + updateProgramText(files, bxPackage, JSON.stringify({ name: "x", version: "1.2.3" })); + }, useGetSourceFileByPath); + assert.equal(program1.structureIsReused, StructureIsReused.Not); + assert.deepEqual(program2.getSemanticDiagnostics(), []); + }); + } + + describe("when host implements getSourceFile", () => { + verifyRedirects(/*useGetSourceFileByPath*/ false); }); - - it("Target changes -> redirect broken", () => { - const program1 = createRedirectProgram(); - assert.lengthOf(program1.getSemanticDiagnostics(), 0); - - const program2 = updateRedirectProgram(program1, files => { - updateProgramText(files, axIndex, "export default class X { private x: number; private y: number; }"); - updateProgramText(files, axPackage, JSON.stringify('{ name: "x", version: "1.2.4" }')); - }); - assert.equal(program1.structureIsReused, StructureIsReused.Not); - assert.lengthOf(program2.getSemanticDiagnostics(), 1); - }); - - it("Underlying changes -> redirect broken", () => { - const program1 = createRedirectProgram(); - - const program2 = updateRedirectProgram(program1, files => { - updateProgramText(files, bxIndex, "export default class X { private x: number; private y: number; }"); - updateProgramText(files, bxPackage, JSON.stringify({ name: "x", version: "1.2.4" })); - }); - assert.equal(program1.structureIsReused, StructureIsReused.Not); - assert.lengthOf(program2.getSemanticDiagnostics(), 1); - }); - - it("Previously duplicate packages -> program structure not reused", () => { - const program1 = createRedirectProgram({ bVersion: "1.2.4", bText: "export = class X { private x: number; }" }); - - const program2 = updateRedirectProgram(program1, files => { - updateProgramText(files, bxIndex, "export default class X { private x: number; }"); - updateProgramText(files, bxPackage, JSON.stringify({ name: "x", version: "1.2.3" })); - }); - assert.equal(program1.structureIsReused, StructureIsReused.Not); - assert.deepEqual(program2.getSemanticDiagnostics(), []); + describe("when host implements getSourceFileByPath", () => { + verifyRedirects(/*useGetSourceFileByPath*/ true); }); }); }); - describe("host is optional", () => { + describe("unittests:: Reuse program structure:: host is optional", () => { it("should work if host is not provided", () => { createProgram([], {}); }); @@ -904,7 +905,7 @@ namespace ts { import createTestSystem = TestFSWithWatch.createWatchedSystem; import libFile = TestFSWithWatch.libFile; - describe("isProgramUptoDate should return true when there is no change in compiler options and", () => { + describe("unittests:: Reuse program structure:: isProgramUptoDate should return true when there is no change in compiler options and", () => { function verifyProgramIsUptoDate( program: Program, newRootFileNames: string[], @@ -914,7 +915,8 @@ namespace ts { program, newRootFileNames, newOptions, path => program.getSourceFileByPath(path)!.version, /*fileExists*/ returnFalse, /*hasInvalidatedResolution*/ returnFalse, - /*hasChangedAutomaticTypeDirectiveNames*/ false + /*hasChangedAutomaticTypeDirectiveNames*/ false, + /*projectReferences*/ undefined ); assert.isTrue(actual); } diff --git a/src/testRunner/unittests/semver.ts b/src/testRunner/unittests/semver.ts new file mode 100644 index 00000000000..079bdc3d512 --- /dev/null +++ b/src/testRunner/unittests/semver.ts @@ -0,0 +1,228 @@ +namespace ts { + import theory = utils.theory; + describe("unittests:: semver", () => { + describe("Version", () => { + function assertVersion(version: Version, [major, minor, patch, prerelease, build]: [number, number, number, string[]?, string[]?]) { + assert.strictEqual(version.major, major); + assert.strictEqual(version.minor, minor); + assert.strictEqual(version.patch, patch); + assert.deepEqual(version.prerelease, prerelease || emptyArray); + assert.deepEqual(version.build, build || emptyArray); + } + describe("new", () => { + it("text", () => { + assertVersion(new Version("1.2.3-pre.4+build.5"), [1, 2, 3, ["pre", "4"], ["build", "5"]]); + }); + it("parts", () => { + assertVersion(new Version(1, 2, 3, "pre.4", "build.5"), [1, 2, 3, ["pre", "4"], ["build", "5"]]); + assertVersion(new Version(1, 2, 3), [1, 2, 3]); + assertVersion(new Version(1, 2), [1, 2, 0]); + assertVersion(new Version(1), [1, 0, 0]); + }); + }); + it("toString", () => { + assert.strictEqual(new Version(1, 2, 3, "pre.4", "build.5").toString(), "1.2.3-pre.4+build.5"); + assert.strictEqual(new Version(1, 2, 3, "pre.4").toString(), "1.2.3-pre.4"); + assert.strictEqual(new Version(1, 2, 3, /*prerelease*/ undefined, "build.5").toString(), "1.2.3+build.5"); + assert.strictEqual(new Version(1, 2, 3).toString(), "1.2.3"); + assert.strictEqual(new Version(1, 2).toString(), "1.2.0"); + assert.strictEqual(new Version(1).toString(), "1.0.0"); + }); + it("compareTo", () => { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + assert.strictEqual(new Version("1.0.0").compareTo(new Version("2.0.0")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.1.0")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.0.1")), Comparison.LessThan); + assert.strictEqual(new Version("2.0.0").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.1.0").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.1").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.0.0")), Comparison.EqualTo); + + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower + // > precedence than a normal version. + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.0.0-pre")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.1-pre").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-pre").compareTo(new Version("1.0.0")), Comparison.LessThan); + + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-1")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-1").compareTo(new Version("1.0.0-0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-2").compareTo(new Version("1.0.0-10")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-10").compareTo(new Version("1.0.0-2")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-0")), Comparison.EqualTo); + + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + assert.strictEqual(new Version("1.0.0-a").compareTo(new Version("1.0.0-b")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-a-2").compareTo(new Version("1.0.0-a-10")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-b").compareTo(new Version("1.0.0-a")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-a").compareTo(new Version("1.0.0-a")), Comparison.EqualTo); + assert.strictEqual(new Version("1.0.0-A").compareTo(new Version("1.0.0-a")), Comparison.LessThan); + + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-alpha")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-alpha").compareTo(new Version("1.0.0-0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-0")), Comparison.EqualTo); + assert.strictEqual(new Version("1.0.0-alpha").compareTo(new Version("1.0.0-alpha")), Comparison.EqualTo); + + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + assert.strictEqual(new Version("1.0.0-alpha").compareTo(new Version("1.0.0-alpha.0")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-alpha.0").compareTo(new Version("1.0.0-alpha")), Comparison.GreaterThan); + + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + assert.strictEqual(new Version("1.0.0-a.0.b.1").compareTo(new Version("1.0.0-a.0.b.2")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-a.0.b.1").compareTo(new Version("1.0.0-b.0.a.1")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-a.0.b.2").compareTo(new Version("1.0.0-a.0.b.1")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-b.0.a.1").compareTo(new Version("1.0.0-a.0.b.1")), Comparison.GreaterThan); + + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + assert.strictEqual(new Version("1.0.0+build").compareTo(new Version("1.0.0")), Comparison.EqualTo); + }); + it("increment", () => { + assertVersion(new Version(1, 2, 3, "pre.4", "build.5").increment("major"), [2, 0, 0]); + assertVersion(new Version(1, 2, 3, "pre.4", "build.5").increment("minor"), [1, 3, 0]); + assertVersion(new Version(1, 2, 3, "pre.4", "build.5").increment("patch"), [1, 2, 4]); + }); + }); + describe("VersionRange", () => { + function assertRange(rangeText: string, versionText: string, inRange = true) { + const range = new VersionRange(rangeText); + const version = new Version(versionText); + assert.strictEqual(range.test(version), inRange, `Expected version '${version}' ${inRange ? `to be` : `to not be`} in range '${rangeText}' (${range})`); + } + theory("comparators", assertRange, [ + ["", "1.0.0"], + ["*", "1.0.0"], + ["1", "1.0.0"], + ["1", "2.0.0", false], + ["1.0", "1.0.0"], + ["1.0", "1.1.0", false], + ["1.0.0", "1.0.0"], + ["1.0.0", "1.0.1", false], + ["1.*", "1.0.0"], + ["1.*", "2.0.0", false], + ["1.x", "1.0.0"], + ["1.x", "2.0.0", false], + ["=1", "1.0.0"], + ["=1", "1.1.0"], + ["=1", "1.0.1"], + ["=1.0", "1.0.0"], + ["=1.0", "1.0.1"], + ["=1.0.0", "1.0.0"], + ["=*", "0.0.0"], + ["=*", "1.0.0"], + [">1", "2"], + [">1.0", "1.1"], + [">1.0.0", "1.0.1"], + [">1.0.0", "1.0.1-pre"], + [">*", "0.0.0", false], + [">*", "1.0.0", false], + [">=1", "1.0.0"], + [">=1.0", "1.0.0"], + [">=1.0.0", "1.0.0"], + [">=1.0.0", "1.0.1-pre"], + [">=*", "0.0.0"], + [">=*", "1.0.0"], + ["<2", "1.0.0"], + ["<2.1", "2.0.0"], + ["<2.0.1", "2.0.0"], + ["<2.0.0", "2.0.0-pre"], + ["<*", "0.0.0", false], + ["<*", "1.0.0", false], + ["<=2", "2.0.0"], + ["<=2.1", "2.1.0"], + ["<=2.0.1", "2.0.1"], + ["<=*", "0.0.0"], + ["<=*", "1.0.0"], + ]); + theory("conjunctions", assertRange, [ + [">1.0.0 <2.0.0", "1.0.1"], + [">1.0.0 <2.0.0", "2.0.0", false], + [">1.0.0 <2.0.0", "1.0.0", false], + [">1 >2", "3.0.0"], + ]); + theory("disjunctions", assertRange, [ + [">=1.0.0 <2.0.0 || >=3.0.0 <4.0.0", "1.0.0"], + [">=1.0.0 <2.0.0 || >=3.0.0 <4.0.0", "2.0.0", false], + [">=1.0.0 <2.0.0 || >=3.0.0 <4.0.0", "3.0.0"], + ]); + theory("hyphen", assertRange, [ + ["1.0.0 - 2.0.0", "1.0.0"], + ["1.0.0 - 2.0.0", "2.0.0"], + ["1.0.0 - 2.0.0", "3.0.0", false], + ]); + theory("tilde", assertRange, [ + ["~0", "0.0.0"], + ["~0", "0.1.0"], + ["~0", "0.1.2"], + ["~0", "0.1.9"], + ["~0", "1.0.0", false], + ["~0.1", "0.1.0"], + ["~0.1", "0.1.2"], + ["~0.1", "0.1.9"], + ["~0.1", "0.2.0", false], + ["~0.1.2", "0.1.2"], + ["~0.1.2", "0.1.9"], + ["~0.1.2", "0.2.0", false], + ["~1", "1.0.0"], + ["~1", "1.2.0"], + ["~1", "1.2.3"], + ["~1", "1.2.0"], + ["~1", "1.2.3"], + ["~1", "0.0.0", false], + ["~1", "2.0.0", false], + ["~1.2", "1.2.0"], + ["~1.2", "1.2.3"], + ["~1.2", "1.1.0", false], + ["~1.2", "1.3.0", false], + ["~1.2.3", "1.2.3"], + ["~1.2.3", "1.2.9"], + ["~1.2.3", "1.1.0", false], + ["~1.2.3", "1.3.0", false], + ]); + theory("caret", assertRange, [ + ["^0", "0.0.0"], + ["^0", "0.1.0"], + ["^0", "0.9.0"], + ["^0", "0.1.2"], + ["^0", "0.1.9"], + ["^0", "1.0.0", false], + ["^0.1", "0.1.0"], + ["^0.1", "0.1.2"], + ["^0.1", "0.1.9"], + ["^0.1.2", "0.1.2"], + ["^0.1.2", "0.1.9"], + ["^0.1.2", "0.0.0", false], + ["^0.1.2", "0.2.0", false], + ["^0.1.2", "1.0.0", false], + ["^1", "1.0.0"], + ["^1", "1.2.0"], + ["^1", "1.2.3"], + ["^1", "1.9.0"], + ["^1", "0.0.0", false], + ["^1", "2.0.0", false], + ["^1.2", "1.2.0"], + ["^1.2", "1.2.3"], + ["^1.2", "1.9.0"], + ["^1.2", "1.1.0", false], + ["^1.2", "2.0.0", false], + ["^1.2.3", "1.2.3"], + ["^1.2.3", "1.9.0"], + ["^1.2.3", "1.2.2", false], + ["^1.2.3", "2.0.0", false], + ]); + }); + }); +} diff --git a/src/testRunner/unittests/cancellableLanguageServiceOperations.ts b/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts similarity index 96% rename from src/testRunner/unittests/cancellableLanguageServiceOperations.ts rename to src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts index 37f829d67a7..9868d628d0c 100644 --- a/src/testRunner/unittests/cancellableLanguageServiceOperations.ts +++ b/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts @@ -1,5 +1,5 @@ namespace ts { - describe("cancellableLanguageServiceOperations", () => { + describe("unittests:: services:: cancellableLanguageServiceOperations", () => { const file = ` function foo(): void; function foo(x: T): T; diff --git a/src/testRunner/unittests/services/colorization.ts b/src/testRunner/unittests/services/colorization.ts index e3295e6fee8..71ba8bad394 100644 --- a/src/testRunner/unittests/services/colorization.ts +++ b/src/testRunner/unittests/services/colorization.ts @@ -6,7 +6,7 @@ interface ClassificationEntry { position?: number; } -describe("Colorization", () => { +describe("unittests:: services:: Colorization", () => { // Use the shim adapter to ensure test coverage of the shim layer for the classifier const languageServiceAdapter = new Harness.LanguageService.ShimLanguageServiceAdapter(/*preprocessToResolve*/ false); const classifier = languageServiceAdapter.getClassifier(); diff --git a/src/testRunner/unittests/convertToAsyncFunction.ts b/src/testRunner/unittests/services/convertToAsyncFunction.ts similarity index 80% rename from src/testRunner/unittests/convertToAsyncFunction.ts rename to src/testRunner/unittests/services/convertToAsyncFunction.ts index 99788e1310e..8c426effa4c 100644 --- a/src/testRunner/unittests/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/services/convertToAsyncFunction.ts @@ -1,68 +1,4 @@ namespace ts { - interface Range { - pos: number; - end: number; - name: string; - } - - interface Test { - source: string; - ranges: Map; - } - - function getTest(source: string): Test { - const activeRanges: Range[] = []; - let text = ""; - let lastPos = 0; - let pos = 0; - const ranges = createMap(); - - while (pos < source.length) { - if (source.charCodeAt(pos) === CharacterCodes.openBracket && - (source.charCodeAt(pos + 1) === CharacterCodes.hash || source.charCodeAt(pos + 1) === CharacterCodes.$)) { - const saved = pos; - pos += 2; - const s = pos; - consumeIdentifier(); - const e = pos; - if (source.charCodeAt(pos) === CharacterCodes.bar) { - pos++; - text += source.substring(lastPos, saved); - const name = s === e - ? source.charCodeAt(saved + 1) === CharacterCodes.hash ? "selection" : "extracted" - : source.substring(s, e); - activeRanges.push({ name, pos: text.length, end: undefined! }); - lastPos = pos; - continue; - } - else { - pos = saved; - } - } - else if (source.charCodeAt(pos) === CharacterCodes.bar && source.charCodeAt(pos + 1) === CharacterCodes.closeBracket) { - text += source.substring(lastPos, pos); - activeRanges[activeRanges.length - 1].end = text.length; - const range = activeRanges.pop()!; - if (range.name in ranges) { - throw new Error(`Duplicate name of range ${range.name}`); - } - ranges.set(range.name, range); - pos += 2; - lastPos = pos; - continue; - } - pos++; - } - text += source.substring(lastPos, pos); - - function consumeIdentifier() { - while (isIdentifierPart(source.charCodeAt(pos), ScriptTarget.Latest)) { - pos++; - } - } - return { source: text, ranges }; - } - const libFile: TestFSWithWatch.File = { path: "/a/lib/lib.d.ts", content: `/// @@ -319,19 +255,22 @@ interface String { charAt: any; } interface Array {}` }; - function testConvertToAsyncFunction(caption: string, text: string, baselineFolder: string, diagnosticDescription: DiagnosticMessage, codeFixDescription: DiagnosticMessage, includeLib?: boolean) { - const t = getTest(text); + function testConvertToAsyncFunction(caption: string, text: string, baselineFolder: string, includeLib?: boolean, expectFailure = false, onlyProvideAction = false) { + const t = extractTest(text); const selectionRange = t.ranges.get("selection")!; if (!selectionRange) { throw new Error(`Test ${caption} does not specify selection range`); } - [Extension.Ts, Extension.Js].forEach(extension => + const extensions = expectFailure ? [Extension.Ts] : [Extension.Ts, Extension.Js]; + + extensions.forEach(extension => it(`${caption} [${extension}]`, () => runBaseline(extension))); function runBaseline(extension: Extension) { const path = "/a" + extension; - const program = makeProgram({ path, content: t.source }, includeLib)!; + const languageService = makeLanguageService({ path, content: t.source }, includeLib); + const program = languageService.getProgram()!; if (hasSyntacticDiagnostics(program)) { // Don't bother generating JS baselines for inputs that aren't valid JS. @@ -345,10 +284,6 @@ interface Array {}` }; const sourceFile = program.getSourceFile(path)!; - const host = projectSystem.createServerHost([f, libFile]); - const projectService = projectSystem.createProjectService(host); - projectService.openClientFile(f.path); - const languageService = projectService.inferredProjects[0].getLanguageService(); const context: CodeFixContext = { errorCode: 80006, span: { start: selectionRange.pos, length: selectionRange.end - selectionRange.pos }, @@ -357,41 +292,49 @@ interface Array {}` cancellationToken: { throwIfCancellationRequested: noop, isCancellationRequested: returnFalse }, preferences: emptyOptions, host: notImplementedHost, - formatContext: formatting.getFormatContext(testFormatOptions) + formatContext: formatting.getFormatContext(testFormatSettings) }; const diagnostics = languageService.getSuggestionDiagnostics(f.path); - const diagnostic = find(diagnostics, diagnostic => diagnostic.messageText === diagnosticDescription.message); - assert.exists(diagnostic); - assert.equal(diagnostic!.start, context.span.start); - assert.equal(diagnostic!.length, context.span.length); + const diagnostic = find(diagnostics, diagnostic => diagnostic.messageText === Diagnostics.This_may_be_converted_to_an_async_function.message && + diagnostic.start === context.span.start && diagnostic.length === context.span.length); + if (expectFailure) { + assert.isUndefined(diagnostic); + } + else { + assert.exists(diagnostic); + } const actions = codefix.getFixes(context); - const action = find(actions, action => action.description === codeFixDescription.message)!; - assert.exists(action); + const action = find(actions, action => action.description === Diagnostics.Convert_to_async_function.message); + if (expectFailure && !onlyProvideAction) { + assert.isNotTrue(action && action.changes.length > 0); + return; + } + + assert.isTrue(action && action.changes.length > 0); const data: string[] = []; data.push(`// ==ORIGINAL==`); data.push(text.replace("[#|", "/*[#|*/").replace("|]", "/*|]*/")); - const changes = action.changes; + const changes = action!.changes; assert.lengthOf(changes, 1); - data.push(`// ==ASYNC FUNCTION::${action.description}==`); + data.push(`// ==ASYNC FUNCTION::${action!.description}==`); const newText = textChanges.applyChanges(sourceFile.text, changes[0].textChanges); data.push(newText); - const diagProgram = makeProgram({ path, content: newText }, includeLib)!; + const diagProgram = makeLanguageService({ path, content: newText }, includeLib).getProgram()!; assert.isFalse(hasSyntacticDiagnostics(diagProgram)); Harness.Baseline.runBaseline(`${baselineFolder}/${caption}${extension}`, data.join(newLineCharacter)); } - function makeProgram(f: { path: string, content: string }, includeLib?: boolean) { + function makeLanguageService(f: { path: string, content: string }, includeLib?: boolean) { const host = projectSystem.createServerHost(includeLib ? [f, libFile] : [f]); // libFile is expensive to parse repeatedly - only test when required const projectService = projectSystem.createProjectService(host); projectService.openClientFile(f.path); - const program = projectService.inferredProjects[0].getLanguageService().getProgram(); - return program; + return projectService.inferredProjects[0].getLanguageService(); } function hasSyntacticDiagnostics(program: Program) { @@ -400,28 +343,7 @@ interface Array {}` } } - function testConvertToAsyncFunctionFailed(caption: string, text: string, description: DiagnosticMessage) { - it(caption, () => { - const t = extractTest(text); - const selectionRange = t.ranges.get("selection"); - if (!selectionRange) { - throw new Error(`Test ${caption} does not specify selection range`); - } - const f = { - path: "/a.ts", - content: t.source - }; - const host = projectSystem.createServerHost([f, libFile]); - const projectService = projectSystem.createProjectService(host); - projectService.openClientFile(f.path); - const languageService = projectService.inferredProjects[0].getLanguageService(); - - const actions = languageService.getSuggestionDiagnostics(f.path); - assert.isUndefined(find(actions, action => action.messageText === description.message)); - }); - } - - describe("convertToAsyncFunctions", () => { + describe("unittests:: services:: convertToAsyncFunctions", () => { _testConvertToAsyncFunction("convertToAsyncFunction_basic", ` function [#|f|](): Promise{ return fetch('https://typescriptlang.org').then(result => { console.log(result) }); @@ -494,6 +416,20 @@ function [#|f|](): Promise { return fetch('https://typescriptlang.org').then( () => console.log("done") ); }` ); + _testConvertToAsyncFunction("convertToAsyncFunction_IgnoreArgs3", ` +function [#|f|](): Promise { + return fetch('https://typescriptlang.org').then( () => console.log("almost done") ).then( () => console.log("done") ); +}` + ); + _testConvertToAsyncFunction("convertToAsyncFunction_IgnoreArgs4", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(res); +} +function res(){ + console.log("done"); +}` + ); + _testConvertToAsyncFunction("convertToAsyncFunction_Method", ` class Parser { [#|f|]():Promise { @@ -545,6 +481,18 @@ function [#|f|]():Promise { function [#|f|]():Promise { return fetch('https://typescriptlang.org').catch(rej => console.log(rej)); } +` + ); + _testConvertToAsyncFunction("convertToAsyncFunction_NoRes4", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(undefined, rejection => console.log("rejected:", rejection)); +} +` + ); + _testConvertToAsyncFunction("convertToAsyncFunction_NoCatchHandler", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(x => x.statusText).catch(undefined); +} ` ); _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestion", ` @@ -823,7 +771,7 @@ function [#|f|](): Promise { } return x.then(resp => { var blob = resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); - return fetch("https://micorosft.com").then(res => console.log("Another one!")); + return fetch("https://microsoft.com").then(res => console.log("Another one!")); }); } ` @@ -889,7 +837,7 @@ function [#|f|]() { ); _testConvertToAsyncFunction("convertToAsyncFunction_Scope1", ` function [#|f|]() { - var var1:Promise, var2; + var var1: Response, var2; return fetch('https://typescriptlang.org').then( _ => Promise.resolve().then( res => { var2 = "test"; @@ -1157,7 +1105,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NestedFunction", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NestedFunctionWrongLocation", ` function [#|f|]() { function fn2(){ function fn3(){ @@ -1167,6 +1115,18 @@ function [#|f|]() { } return fn2(); } +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_NestedFunctionRightLocation", ` +function f() { + function fn2(){ + function [#|fn3|](){ + return fetch("https://typescriptlang.org").then(res => console.log(res)); + } + return fn3(); + } + return fn2(); +} `); _testConvertToAsyncFunction("convertToAsyncFunction_UntypedFunction", ` @@ -1191,17 +1151,149 @@ function [#|f|]() { _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpression", ` const [#|foo|] = function () { return fetch('https://typescriptlang.org').then(result => { console.log(result) }); -} +} `); + _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionWithName", ` +const foo = function [#|f|]() { + return fetch('https://typescriptlang.org').then(result => { console.log(result) }); +} +`); + _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionAssignedToBindingPattern", ` +const { length } = [#|function|] () { + return fetch('https://typescriptlang.org').then(result => { console.log(result) }); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParams", ` +function [#|f|]() { + return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_bindingPattern", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(res); +} +function res({ status, trailer }){ + console.log(status); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_bindingPatternNameCollision", ` +function [#|f|]() { + const result = 'https://typescriptlang.org'; + return fetch(result).then(res); +} +function res({ status, trailer }){ + console.log(status); +} +`); + + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunction", ` +function [#|f|]() { + return Promise.resolve().then(f ? (x => x) : (y => y)); +} +`); + + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunctionNotLastInChain", ` +function [#|f|]() { + return Promise.resolve().then(f ? (x => x) : (y => y)).then(q => q); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_runEffectfulContinuation", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(res).then(_ => console.log("done")); +} +function res(result) { + return Promise.resolve().then(x => console.log(result)); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromise", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText.length)).then(x => console.log(x + 5)); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseInBlock", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(s => { return Promise.resolve(s.statusText.length) }).then(x => x + 5); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsFixablePromise", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText).then(st => st.length)).then(x => console.log(x + 5)); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseLastInChain", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText.length)); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsRejectedPromiseInTryBlock", ` +function [#|f|]() { + return Promise.resolve(1) + .then(x => Promise.reject(x)) + .catch(err => console.log(err)); +} +`); + +_testConvertToAsyncFunction("convertToAsyncFunction_nestedPromises", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(x => Promise.resolve(3).then(y => Promise.resolve(x.statusText.length + y))); +} +`); +_testConvertToAsyncFunction("convertToAsyncFunction_noArgs", ` +function delay(millis: number): Promise { + throw "no" +} + +function [#|main2|]() { + console.log("Please wait. Loading."); + return delay(500) + .then(() => { console.log("."); return delay(500); }) + .then(() => { console.log("."); return delay(500); }) + .then(() => { console.log("."); return delay(500); }) +} +`); +_testConvertToAsyncFunction("convertToAsyncFunction_exportModifier", ` +export function [#|foo|]() { + return fetch('https://typescriptlang.org').then(s => console.log(s)); +} +`); + +_testConvertToAsyncFunction("convertToAsyncFunction_OutermostOnlySuccess", ` +function [#|foo|]() { + return fetch('a').then(() => { + return fetch('b').then(() => 'c'); + }) +} +`); + +_testConvertToAsyncFunctionFailedSuggestion("convertToAsyncFunction_OutermostOnlyFailure", ` +function foo() { + return fetch('a').then([#|() => {|] + return fetch('b').then(() => 'c'); + }) +} +`); }); function _testConvertToAsyncFunction(caption: string, text: string) { - testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", Diagnostics.This_may_be_converted_to_an_async_function, Diagnostics.Convert_to_async_function, /*includeLib*/ true); + testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true); } function _testConvertToAsyncFunctionFailed(caption: string, text: string) { - testConvertToAsyncFunctionFailed(caption, text, Diagnostics.Convert_to_async_function); + testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true, /*expectFailure*/ true); } -} \ No newline at end of file + + function _testConvertToAsyncFunctionFailedSuggestion(caption: string, text: string) { + testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true, /*expectFailure*/ true, /*onlyProvideAction*/ true); + } +} diff --git a/src/testRunner/unittests/services/documentRegistry.ts b/src/testRunner/unittests/services/documentRegistry.ts index a3dad56f42b..e7c80486e97 100644 --- a/src/testRunner/unittests/services/documentRegistry.ts +++ b/src/testRunner/unittests/services/documentRegistry.ts @@ -1,4 +1,4 @@ -describe("DocumentRegistry", () => { +describe("unittests:: services:: DocumentRegistry", () => { it("documents are shared between projects", () => { const documentRegistry = ts.createDocumentRegistry(); const defaultCompilerOptions = ts.getDefaultCompilerOptions(); diff --git a/src/testRunner/unittests/extractConstants.ts b/src/testRunner/unittests/services/extract/constants.ts similarity index 94% rename from src/testRunner/unittests/extractConstants.ts rename to src/testRunner/unittests/services/extract/constants.ts index e0ef305812c..d9cd5010d5b 100644 --- a/src/testRunner/unittests/extractConstants.ts +++ b/src/testRunner/unittests/services/extract/constants.ts @@ -1,5 +1,5 @@ namespace ts { - describe("extractConstants", () => { + describe("unittests:: services:: extract:: extractConstants", () => { testExtractConstant("extractConstant_TopLevel", `let x = [#|1|];`); diff --git a/src/testRunner/unittests/extractFunctions.ts b/src/testRunner/unittests/services/extract/functions.ts similarity index 95% rename from src/testRunner/unittests/extractFunctions.ts rename to src/testRunner/unittests/services/extract/functions.ts index 1f90e1cc600..d872ad81a63 100644 --- a/src/testRunner/unittests/extractFunctions.ts +++ b/src/testRunner/unittests/services/extract/functions.ts @@ -1,5 +1,5 @@ namespace ts { - describe("extractFunctions", () => { + describe("unittests:: services:: extract:: extractFunctions", () => { testExtractFunction("extractFunction1", `namespace A { let x = 1; diff --git a/src/testRunner/unittests/extractTestHelpers.ts b/src/testRunner/unittests/services/extract/helpers.ts similarity index 85% rename from src/testRunner/unittests/extractTestHelpers.ts rename to src/testRunner/unittests/services/extract/helpers.ts index 6e46c1304ab..cc3ba9f372e 100644 --- a/src/testRunner/unittests/extractTestHelpers.ts +++ b/src/testRunner/unittests/services/extract/helpers.ts @@ -64,27 +64,6 @@ namespace ts { } export const newLineCharacter = "\n"; - export const testFormatOptions: FormatCodeSettings = { - indentSize: 4, - tabSize: 4, - newLineCharacter, - convertTabsToSpaces: true, - indentStyle: IndentStyle.Smart, - insertSpaceAfterConstructor: false, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceBeforeFunctionParenthesis: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - }; export const notImplementedHost: LanguageServiceHost = { getCompilationSettings: notImplemented, @@ -123,12 +102,12 @@ namespace ts { startPosition: selectionRange.pos, endPosition: selectionRange.end, host: notImplementedHost, - formatContext: formatting.getFormatContext(testFormatOptions), + formatContext: formatting.getFormatContext(testFormatSettings), preferences: emptyOptions, }; const rangeToExtract = refactor.extractSymbol.getRangeToExtract(sourceFile, createTextSpanFromRange(selectionRange)); assert.equal(rangeToExtract.errors, undefined, rangeToExtract.errors && "Range error: " + rangeToExtract.errors[0].messageText); - const infos = refactor.extractSymbol.getAvailableActions(context)!; + const infos = refactor.extractSymbol.getAvailableActions(context); const actions = find(infos, info => info.description === description.message)!.actions; const data: string[] = []; @@ -185,12 +164,12 @@ namespace ts { startPosition: selectionRange.pos, endPosition: selectionRange.end, host: notImplementedHost, - formatContext: formatting.getFormatContext(testFormatOptions), + formatContext: formatting.getFormatContext(testFormatSettings), preferences: emptyOptions, }; const rangeToExtract = refactor.extractSymbol.getRangeToExtract(sourceFile, createTextSpanFromRange(selectionRange)); assert.isUndefined(rangeToExtract.errors, rangeToExtract.errors && "Range error: " + rangeToExtract.errors[0].messageText); - const infos = refactor.extractSymbol.getAvailableActions(context)!; + const infos = refactor.extractSymbol.getAvailableActions(context); assert.isUndefined(find(infos, info => info.description === description.message)); }); } diff --git a/src/testRunner/unittests/extractRanges.ts b/src/testRunner/unittests/services/extract/ranges.ts similarity index 95% rename from src/testRunner/unittests/extractRanges.ts rename to src/testRunner/unittests/services/extract/ranges.ts index 9cd76dd49e9..265dd33e60a 100644 --- a/src/testRunner/unittests/extractRanges.ts +++ b/src/testRunner/unittests/services/extract/ranges.ts @@ -42,7 +42,7 @@ namespace ts { } } - describe("extractRanges", () => { + describe("unittests:: services:: extract:: extractRanges", () => { it("get extract range from selection", () => { testExtractRange(` [#| @@ -418,4 +418,4 @@ switch (x) { testExtractRangeFailed("extract-method-not-for-token-expression-statement", `[#|a|]`, [refactor.extractSymbol.Messages.cannotExtractIdentifier.message]); }); -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/symbolWalker.ts b/src/testRunner/unittests/services/extract/symbolWalker.ts similarity index 93% rename from src/testRunner/unittests/symbolWalker.ts rename to src/testRunner/unittests/services/extract/symbolWalker.ts index 4743b87133b..58d9dcb577f 100644 --- a/src/testRunner/unittests/symbolWalker.ts +++ b/src/testRunner/unittests/services/extract/symbolWalker.ts @@ -1,5 +1,5 @@ namespace ts { - describe("Symbol Walker", () => { + describe("unittests:: services:: extract:: Symbol Walker", () => { function test(description: string, source: string, verifier: (file: SourceFile, checker: TypeChecker) => void) { it(description, () => { const result = Harness.Compiler.compileFiles([{ @@ -42,4 +42,4 @@ export default function foo(a: number, b: Bar): void {}`, (file, checker) => { assert.equal(stdLibRefSymbols, 1); // Expect 1 stdlib entry symbol - the implicit Array referenced by Bar.history }); }); -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/hostNewLineSupport.ts b/src/testRunner/unittests/services/hostNewLineSupport.ts similarity index 95% rename from src/testRunner/unittests/hostNewLineSupport.ts rename to src/testRunner/unittests/services/hostNewLineSupport.ts index abd79210086..cafe4813431 100644 --- a/src/testRunner/unittests/hostNewLineSupport.ts +++ b/src/testRunner/unittests/services/hostNewLineSupport.ts @@ -1,5 +1,5 @@ namespace ts { - describe("hostNewLineSupport", () => { + describe("unittests:: services:: hostNewLineSupport", () => { function testLSWithFiles(settings: CompilerOptions, files: Harness.Compiler.TestFile[]) { function snapFor(path: string): IScriptSnapshot | undefined { if (path === "lib.d.ts") { @@ -46,4 +46,4 @@ namespace ts { `); }); }); -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/languageService.ts b/src/testRunner/unittests/services/languageService.ts similarity index 94% rename from src/testRunner/unittests/languageService.ts rename to src/testRunner/unittests/services/languageService.ts index ce8fa93d1f9..d646f32383f 100644 --- a/src/testRunner/unittests/languageService.ts +++ b/src/testRunner/unittests/services/languageService.ts @@ -1,5 +1,5 @@ namespace ts { - describe("languageService", () => { + describe("unittests:: services:: languageService", () => { const files: {[index: string]: string} = { "foo.ts": `import Vue from "./vue"; import Component from "./vue-class-component"; @@ -43,4 +43,4 @@ export function Component(x: Config): any;` expect(definitions).to.exist; // tslint:disable-line no-unused-expression }); }); -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/organizeImports.ts b/src/testRunner/unittests/services/organizeImports.ts similarity index 92% rename from src/testRunner/unittests/organizeImports.ts rename to src/testRunner/unittests/services/organizeImports.ts index b4f54afa21b..8116b1e268a 100644 --- a/src/testRunner/unittests/organizeImports.ts +++ b/src/testRunner/unittests/services/organizeImports.ts @@ -1,5 +1,5 @@ namespace ts { - describe("Organize imports", () => { + describe("unittests:: services:: Organize imports", () => { describe("Sort imports", () => { it("Sort - non-relative vs non-relative", () => { assertSortsBefore( @@ -270,7 +270,17 @@ export const Other = 1; content: "function F() { }", }; const languageService = makeLanguageService(testFile); - const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, testFormatOptions, emptyOptions); + const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, testFormatSettings, emptyOptions); + assert.isEmpty(changes); + }); + + it("doesn't crash on shorthand ambient module", () => { + const testFile = { + path: "/a.ts", + content: "declare module '*';", + }; + const languageService = makeLanguageService(testFile); + const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, testFormatSettings, emptyOptions); assert.isEmpty(changes); }); @@ -586,6 +596,34 @@ import { React, Other } from "react"; }, reactLibFile); + testOrganizeImports("JsxPragmaTsx", + { + path: "/test.tsx", + content: `/** @jsx jsx */ + +import { Global, jsx } from '@emotion/core'; +import * as React from 'react'; + +export const App: React.FunctionComponent = _ =>

Hello!

+`, + }, + { + path: "/@emotion/core/index.d.ts", + content: `import { createElement } from 'react' +export const jsx: typeof createElement; +export function Global(props: any): ReactElement;` + }, + { + path: reactLibFile.path, + content: `${reactLibFile.content} +export namespace React { + interface FunctionComponent { + } +} +` + } + ); + describe("Exports", () => { testOrganizeExports("MoveToTop", @@ -741,7 +779,7 @@ export * from "lib"; function runBaseline(baselinePath: string, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) { const { path: testPath, content: testContent } = testFile; const languageService = makeLanguageService(testFile, ...otherFiles); - const changes = languageService.organizeImports({ type: "file", fileName: testPath }, testFormatOptions, emptyOptions); + const changes = languageService.organizeImports({ type: "file", fileName: testPath }, testFormatSettings, emptyOptions); assert.equal(changes.length, 1); assert.equal(changes[0].fileName, testPath); diff --git a/src/testRunner/unittests/services/patternMatcher.ts b/src/testRunner/unittests/services/patternMatcher.ts index 5e35d2020db..9f3cbf4b6d7 100644 --- a/src/testRunner/unittests/services/patternMatcher.ts +++ b/src/testRunner/unittests/services/patternMatcher.ts @@ -1,4 +1,4 @@ -describe("PatternMatcher", () => { +describe("unittests:: services:: PatternMatcher", () => { describe("BreakIntoCharacterSpans", () => { it("EmptyIdentifier", () => { verifyBreakIntoCharacterSpans(""); diff --git a/src/testRunner/unittests/services/preProcessFile.ts b/src/testRunner/unittests/services/preProcessFile.ts index a89b6337c84..3e9d16672db 100644 --- a/src/testRunner/unittests/services/preProcessFile.ts +++ b/src/testRunner/unittests/services/preProcessFile.ts @@ -1,4 +1,4 @@ -describe("PreProcessFile:", () => { +describe("unittests:: services:: PreProcessFile:", () => { function test(sourceText: string, readImportFile: boolean, detectJavaScriptImports: boolean, expectedPreProcess: ts.PreProcessedFileInfo): void { const resultPreProcess = ts.preProcessFile(sourceText, readImportFile, detectJavaScriptImports); diff --git a/src/testRunner/unittests/textChanges.ts b/src/testRunner/unittests/services/textChanges.ts similarity index 97% rename from src/testRunner/unittests/textChanges.ts rename to src/testRunner/unittests/services/textChanges.ts index 699f668b552..de92efafbeb 100644 --- a/src/testRunner/unittests/textChanges.ts +++ b/src/testRunner/unittests/services/textChanges.ts @@ -2,7 +2,7 @@ // tslint:disable trim-trailing-whitespace namespace ts { - describe("textChanges", () => { + describe("unittests:: services:: textChanges", () => { function findChild(name: string, n: Node) { return find(n)!; @@ -20,7 +20,7 @@ namespace ts { const newLineCharacter = getNewLineCharacter(printerOptions); function getRuleProvider(placeOpenBraceOnNewLineForFunctions: boolean): formatting.FormatContext { - return formatting.getFormatContext(placeOpenBraceOnNewLineForFunctions ? { ...testFormatOptions, placeOpenBraceOnNewLineForFunctions: true } : testFormatOptions); + return formatting.getFormatContext(placeOpenBraceOnNewLineForFunctions ? { ...testFormatSettings, placeOpenBraceOnNewLineForFunctions: true } : testFormatSettings); } // validate that positions that were recovered from the printed text actually match positions that will be created if the same text is parsed. @@ -753,4 +753,4 @@ let x = foo }); } }); -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/transpile.ts b/src/testRunner/unittests/services/transpile.ts similarity index 97% rename from src/testRunner/unittests/transpile.ts rename to src/testRunner/unittests/services/transpile.ts index b545b76c3db..d197d6db621 100644 --- a/src/testRunner/unittests/transpile.ts +++ b/src/testRunner/unittests/services/transpile.ts @@ -1,5 +1,5 @@ namespace ts { - describe("Transpile", () => { + describe("unittests:: services:: Transpile", () => { interface TranspileTestSettings { options?: TranspileOptions; diff --git a/src/testRunner/unittests/textStorage.ts b/src/testRunner/unittests/textStorage.ts deleted file mode 100644 index 5486cf57745..00000000000 --- a/src/testRunner/unittests/textStorage.ts +++ /dev/null @@ -1,67 +0,0 @@ -namespace ts.textStorage { - describe("Text storage", () => { - const f = { - path: "/a/app.ts", - content: ` - let x = 1; - let y = 2; - function bar(a: number) { - return a + 1; - }` - }; - - it("text based storage should be have exactly the same as script version cache", () => { - - const host = projectSystem.createServerHost([f]); - // Since script info is not used in these tests, just cheat by passing undefined - const ts1 = new server.TextStorage(host, server.asNormalizedPath(f.path), /*initialVersion*/ undefined, /*info*/undefined!); - const ts2 = new server.TextStorage(host, server.asNormalizedPath(f.path), /*initialVersion*/ undefined, /*info*/undefined!); - - ts1.useScriptVersionCache_TestOnly(); - ts2.useText(); - - const lineMap = computeLineStarts(f.content); - - for (let line = 0; line < lineMap.length; line++) { - const start = lineMap[line]; - const end = line === lineMap.length - 1 ? f.path.length : lineMap[line + 1]; - - for (let offset = 0; offset < end - start; offset++) { - const pos1 = ts1.lineOffsetToPosition(line + 1, offset + 1); - const pos2 = ts2.lineOffsetToPosition(line + 1, offset + 1); - assert.isTrue(pos1 === pos2, `lineOffsetToPosition ${line + 1}-${offset + 1}: expected ${pos1} to equal ${pos2}`); - } - - const {start: start1, length: length1 } = ts1.lineToTextSpan(line); - const {start: start2, length: length2 } = ts2.lineToTextSpan(line); - assert.isTrue(start1 === start2, `lineToTextSpan ${line}::start:: expected ${start1} to equal ${start2}`); - assert.isTrue(length1 === length2, `lineToTextSpan ${line}::length:: expected ${length1} to equal ${length2}`); - } - - for (let pos = 0; pos < f.content.length; pos++) { - const { line: line1, offset: offset1 } = ts1.positionToLineOffset(pos); - const { line: line2, offset: offset2 } = ts2.positionToLineOffset(pos); - assert.isTrue(line1 === line2, `positionToLineOffset ${pos}::line:: expected ${line1} to equal ${line2}`); - assert.isTrue(offset1 === offset2, `positionToLineOffset ${pos}::offset:: expected ${offset1} to equal ${offset2}`); - } - }); - - it("should switch to script version cache if necessary", () => { - const host = projectSystem.createServerHost([f]); - // Since script info is not used in these tests, just cheat by passing undefined - const ts1 = new server.TextStorage(host, server.asNormalizedPath(f.path), /*initialVersion*/ undefined, /*info*/undefined!); - - ts1.getSnapshot(); - assert.isTrue(!ts1.hasScriptVersionCache_TestOnly(), "should not have script version cache - 1"); - - ts1.edit(0, 5, " "); - assert.isTrue(ts1.hasScriptVersionCache_TestOnly(), "have script version cache - 1"); - - ts1.useText(); - assert.isTrue(!ts1.hasScriptVersionCache_TestOnly(), "should not have script version cache - 2"); - - ts1.getLineInfo(0); - assert.isTrue(ts1.hasScriptVersionCache_TestOnly(), "have script version cache - 2"); - }); - }); -} diff --git a/src/testRunner/unittests/transform.ts b/src/testRunner/unittests/transform.ts index e975e10c09c..98c29025d5f 100644 --- a/src/testRunner/unittests/transform.ts +++ b/src/testRunner/unittests/transform.ts @@ -1,5 +1,5 @@ namespace ts { - describe("TransformAPI", () => { + describe("unittests:: TransformAPI", () => { function replaceUndefinedWithVoid0(context: TransformationContext) { const previousOnSubstituteNode = context.onSubstituteNode; context.enableSubstitution(SyntaxKind.Identifier); @@ -40,6 +40,16 @@ namespace ts { return (file: SourceFile) => file; } + function replaceIdentifiersNamedOldNameWithNewName2(context: TransformationContext) { + const visitor: Visitor = (node) => { + if (isIdentifier(node) && node.text === "oldName") { + return createIdentifier("newName"); + } + return visitEachChild(node, visitor, context); + }; + return (node: SourceFile) => visitNode(node, visitor); + } + function transformSourceFile(sourceText: string, transformers: TransformerFactory[]) { const transformed = transform(createSourceFile("source.ts", sourceText, ScriptTarget.ES2015), transformers); const printer = createPrinter({ newLine: NewLineKind.CarriageReturnLineFeed }, { @@ -81,6 +91,18 @@ namespace ts { }).outputText; }); + testBaseline("issue27854", () => { + return transpileModule(`oldName<{ a: string; }>\` ... \`;`, { + transformers: { + before: [replaceIdentifiersNamedOldNameWithNewName2] + }, + compilerOptions: { + newLine: NewLineKind.CarriageReturnLineFeed, + target: ScriptTarget.Latest + } + }).outputText; + }); + testBaseline("rewrittenNamespace", () => { return transpileModule(`namespace Reflect { const x = 1; }`, { transformers: { diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index ea99ee92457..ba94072b230 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -8,7 +8,7 @@ namespace ts { "/src/core/index.js", "/src/core/index.d.ts", "/src/core/index.d.ts.map", "/src/logic/index.js", "/src/logic/index.js.map", "/src/logic/index.d.ts"]; - describe("tsbuild - sanity check of clean build of 'sample1' project", () => { + describe("unittests:: tsbuild - sanity check of clean build of 'sample1' project", () => { it("can build the sample project 'sample1' without error", () => { const fs = projFs.shadow(); const host = new fakes.SolutionBuilderHost(fs); @@ -23,9 +23,45 @@ namespace ts { assert(fs.existsSync(output), `Expect file ${output} to exist`); } }); + + it("builds correctly when outDir is specified", () => { + const fs = projFs.shadow(); + fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({ + compilerOptions: { composite: true, declaration: true, sourceMap: true, outDir: "outDir" }, + references: [{ path: "../core" }] + })); + + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], {}); + builder.buildAllProjects(); + host.assertDiagnosticMessages(/*empty*/); + const expectedOutputs = allExpectedOutputs.map(f => f.replace("/logic/", "/logic/outDir/")); + // Check for outputs. Not an exhaustive list + for (const output of expectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + }); + + it("builds correctly when declarationDir is specified", () => { + const fs = projFs.shadow(); + fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({ + compilerOptions: { composite: true, declaration: true, sourceMap: true, declarationDir: "out/decls" }, + references: [{ path: "../core" }] + })); + + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], {}); + builder.buildAllProjects(); + host.assertDiagnosticMessages(/*empty*/); + const expectedOutputs = allExpectedOutputs.map(f => f.replace("/logic/index.d.ts", "/logic/out/decls/index.d.ts")); + // Check for outputs. Not an exhaustive list + for (const output of expectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + }); }); - describe("tsbuild - dry builds", () => { + describe("unittests:: tsbuild - dry builds", () => { it("doesn't write any files in a dry build", () => { const fs = projFs.shadow(); const host = new fakes.SolutionBuilderHost(fs); @@ -54,7 +90,7 @@ namespace ts { }); }); - describe("tsbuild - clean builds", () => { + describe("unittests:: tsbuild - clean builds", () => { it("removes all files it built", () => { const fs = projFs.shadow(); const host = new fakes.SolutionBuilderHost(fs); @@ -75,7 +111,7 @@ namespace ts { }); }); - describe("tsbuild - force builds", () => { + describe("unittests:: tsbuild - force builds", () => { it("always builds under --force", () => { const fs = projFs.shadow(); const host = new fakes.SolutionBuilderHost(fs); @@ -101,7 +137,7 @@ namespace ts { }); }); - describe("tsbuild - can detect when and what to rebuild", () => { + describe("unittests:: tsbuild - can detect when and what to rebuild", () => { const fs = projFs.shadow(); const host = new fakes.SolutionBuilderHost(fs); const builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: true }); @@ -164,7 +200,7 @@ namespace ts { }); }); - describe("tsbuild - downstream-blocked compilations", () => { + describe("unittests:: tsbuild - downstream-blocked compilations", () => { it("won't build downstream projects if upstream projects have errors", () => { const fs = projFs.shadow(); const host = new fakes.SolutionBuilderHost(fs); @@ -186,7 +222,7 @@ namespace ts { }); }); - describe("tsbuild - project invalidation", () => { + describe("unittests:: tsbuild - project invalidation", () => { it("invalidates projects correctly", () => { const fs = projFs.shadow(); const host = new fakes.SolutionBuilderHost(fs); @@ -198,32 +234,59 @@ namespace ts { // Update a timestamp in the middle project tick(); touch(fs, "/src/logic/index.ts"); + const originalWriteFile = fs.writeFileSync; + const writtenFiles = createMap(); + fs.writeFileSync = (path, data, encoding) => { + writtenFiles.set(path, true); + originalWriteFile.call(fs, path, data, encoding); + }; // Because we haven't reset the build context, the builder should assume there's nothing to do right now - const status = builder.getUpToDateStatusOfFile(builder.resolveProjectName("/src/logic")!); + const status = builder.getUpToDateStatusOfFile(builder.resolveProjectName("/src/logic")); assert.equal(status.type, UpToDateStatusType.UpToDate, "Project should be assumed to be up-to-date"); + verifyInvalidation(/*expectedToWriteTests*/ false); // Rebuild this project - tick(); - builder.invalidateProject("/src/logic"); - builder.buildInvalidatedProject(); - // The file should be updated - assert.equal(fs.statSync("/src/logic/index.js").mtimeMs, time(), "JS file should have been rebuilt"); - assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should *not* have been rebuilt"); + fs.writeFileSync("/src/logic/index.ts", `${fs.readFileSync("/src/logic/index.ts")} +export class cNew {}`); + verifyInvalidation(/*expectedToWriteTests*/ true); - // Build downstream projects should update 'tests', but not 'core' - tick(); - builder.buildInvalidatedProject(); - assert.equal(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should have been rebuilt"); - assert.isBelow(fs.statSync("/src/core/index.js").mtimeMs, time(), "Upstream JS file should not have been rebuilt"); + function verifyInvalidation(expectedToWriteTests: boolean) { + // Rebuild this project + tick(); + builder.invalidateProject("/src/logic"); + builder.buildInvalidatedProject(); + // The file should be updated + assert.isTrue(writtenFiles.has("/src/logic/index.js"), "JS file should have been rebuilt"); + assert.equal(fs.statSync("/src/logic/index.js").mtimeMs, time(), "JS file should have been rebuilt"); + assert.isFalse(writtenFiles.has("/src/tests/index.js"), "Downstream JS file should *not* have been rebuilt"); + assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should *not* have been rebuilt"); + writtenFiles.clear(); + + // Build downstream projects should update 'tests', but not 'core' + tick(); + builder.buildInvalidatedProject(); + if (expectedToWriteTests) { + assert.isTrue(writtenFiles.has("/src/tests/index.js"), "Downstream JS file should have been rebuilt"); + } + else { + assert.equal(writtenFiles.size, 0, "Should not write any new files"); + } + assert.equal(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should have new timestamp"); + assert.isBelow(fs.statSync("/src/core/index.js").mtimeMs, time(), "Upstream JS file should not have been rebuilt"); + } }); }); - describe("tsbuild - with resolveJsonModule option", () => { + describe("unittests:: tsbuild - with resolveJsonModule option", () => { const projFs = loadProjectFromDisk("tests/projects/resolveJsonModuleAndComposite"); const allExpectedOutputs = ["/src/tests/dist/src/index.js", "/src/tests/dist/src/index.d.ts", "/src/tests/dist/src/hello.json"]; function verifyProjectWithResolveJsonModule(configFile: string, ...expectedDiagnosticMessages: DiagnosticMessage[]) { const fs = projFs.shadow(); + verifyProjectWithResolveJsonModuleWithFs(fs, configFile, allExpectedOutputs, ...expectedDiagnosticMessages); + } + + function verifyProjectWithResolveJsonModuleWithFs(fs: vfs.FileSystem, configFile: string, allExpectedOutputs: ReadonlyArray, ...expectedDiagnosticMessages: DiagnosticMessage[]) { const host = new fakes.SolutionBuilderHost(fs); const builder = createSolutionBuilder(host, [configFile], { dry: false, force: false, verbose: false }); builder.buildAllProjects(); @@ -240,6 +303,21 @@ namespace ts { verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withInclude.json", Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern); }); + it("with resolveJsonModule and include of *.json along with other include", () => { + verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withIncludeOfJson.json"); + }); + + it("with resolveJsonModule and include of *.json along with other include and file name matches ts file", () => { + const fs = projFs.shadow(); + fs.rimrafSync("/src/tests/src/hello.json"); + fs.writeFileSync("/src/tests/src/index.json", JSON.stringify({ hello: "world" })); + fs.writeFileSync("/src/tests/src/index.ts", `import hello from "./index.json" + +export default hello.hello`); + const allExpectedOutputs = ["/src/tests/dist/src/index.js", "/src/tests/dist/src/index.d.ts", "/src/tests/dist/src/index.json"]; + verifyProjectWithResolveJsonModuleWithFs(fs, "/src/tests/tsconfig_withIncludeOfJson.json", allExpectedOutputs); + }); + it("with resolveJsonModule and files containing json file", () => { verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withFiles.json"); }); @@ -248,12 +326,148 @@ namespace ts { verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withIncludeAndFiles.json"); }); }); + + describe("unittests:: tsbuild - lists files", () => { + it("listFiles", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], { listFiles: true }); + builder.buildAllProjects(); + assert.deepEqual(host.traces, [ + ...getLibs(), + "/src/core/anotherModule.ts", + "/src/core/index.ts", + "/src/core/some_decl.d.ts", + ...getLibs(), + ...getCoreOutputs(), + "/src/logic/index.ts", + ...getLibs(), + ...getCoreOutputs(), + "/src/logic/index.d.ts", + "/src/tests/index.ts" + ]); + + function getCoreOutputs() { + return [ + "/src/core/index.d.ts", + "/src/core/anotherModule.d.ts" + ]; + } + }); + + it("listEmittedFiles", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], { listEmittedFiles: true }); + builder.buildAllProjects(); + assert.deepEqual(host.traces, [ + "TSFILE: /src/core/anotherModule.js", + "TSFILE: /src/core/anotherModule.d.ts", + "TSFILE: /src/core/anotherModule.d.ts.map", + "TSFILE: /src/core/index.js", + "TSFILE: /src/core/index.d.ts", + "TSFILE: /src/core/index.d.ts.map", + "TSFILE: /src/logic/index.js", + "TSFILE: /src/logic/index.js.map", + "TSFILE: /src/logic/index.d.ts", + "TSFILE: /src/tests/index.js", + "TSFILE: /src/tests/index.d.ts", + ]); + }); + }); + + describe("unittests:: tsbuild - with rootDir of project reference in parentDirectory", () => { + const projFs = loadProjectFromDisk("tests/projects/projectReferenceWithRootDirInParent"); + const allExpectedOutputs = [ + "/src/dist/other/other.js", "/src/dist/other/other.d.ts", + "/src/dist/main/a.js", "/src/dist/main/a.d.ts", + "/src/dist/main/b.js", "/src/dist/main/b.d.ts" + ]; + it("verify that it builds correctly", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/src/main", "/src/src/other"], {}); + builder.buildAllProjects(); + host.assertDiagnosticMessages(/*empty*/); + for (const output of allExpectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + }); + }); + + describe("unittests:: tsbuild - when project reference is referenced transitively", () => { + const projFs = loadProjectFromDisk("tests/projects/transitiveReferences"); + const allExpectedOutputs = [ + "/src/a.js", "/src/a.d.ts", + "/src/b.js", "/src/b.d.ts", + "/src/c.js" + ]; + const expectedFileTraces = [ + ...getLibs(), + "/src/a.ts", + ...getLibs(), + "/src/a.d.ts", + "/src/b.ts", + ...getLibs(), + "/src/a.d.ts", + "/src/b.d.ts", + "/src/refs/a.d.ts", + "/src/c.ts" + ]; + + function verifyBuild(modifyDiskLayout: (fs: vfs.FileSystem) => void, allExpectedOutputs: ReadonlyArray, expectedDiagnostics: DiagnosticMessage[], expectedFileTraces: ReadonlyArray) { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + modifyDiskLayout(fs); + const builder = createSolutionBuilder(host, ["/src/tsconfig.c.json"], { listFiles: true }); + builder.buildAllProjects(); + host.assertDiagnosticMessages(...expectedDiagnostics); + for (const output of allExpectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + assert.deepEqual(host.traces, expectedFileTraces); + } + + function modifyFsBTsToNonRelativeImport(fs: vfs.FileSystem, moduleResolution: "node" | "classic") { + fs.writeFileSync("/src/b.ts", `import {A} from 'a'; +export const b = new A();`); + fs.writeFileSync("/src/tsconfig.b.json", JSON.stringify({ + compilerOptions: { + composite: true, + moduleResolution + }, + files: ["b.ts"], + references: [{ path: "tsconfig.a.json" }] + })); + } + + it("verify that it builds correctly", () => { + verifyBuild(noop, allExpectedOutputs, emptyArray, expectedFileTraces); + }); + + it("verify that it builds correctly when the referenced project uses different module resolution", () => { + verifyBuild(fs => modifyFsBTsToNonRelativeImport(fs, "classic"), allExpectedOutputs, emptyArray, expectedFileTraces); + }); + + it("verify that it build reports error about module not found with node resolution with external module name", () => { + // Error in b build only a + const allExpectedOutputs = ["/src/a.js", "/src/a.d.ts"]; + const expectedFileTraces = [ + ...getLibs(), + "/src/a.ts", + ]; + verifyBuild(fs => modifyFsBTsToNonRelativeImport(fs, "node"), + allExpectedOutputs, + [Diagnostics.Cannot_find_module_0], + expectedFileTraces); + }); + }); } export namespace OutFile { const outFileFs = loadProjectFromDisk("tests/projects/outfile-concat"); - describe("tsbuild - baseline sectioned sourcemaps", () => { + describe("unittests:: tsbuild - baseline sectioned sourcemaps", () => { let fs: vfs.FileSystem | undefined; before(() => { fs = outFileFs.shadow(); @@ -273,7 +487,7 @@ namespace ts { }); }); - describe("tsbuild - downstream prepend projects always get rebuilt", () => { + describe("unittests:: tsbuild - downstream prepend projects always get rebuilt", () => { it("", () => { const fs = outFileFs.shadow(); const host = new fakes.SolutionBuilderHost(fs); @@ -292,7 +506,49 @@ namespace ts { }); } - describe("tsbuild - graph-ordering", () => { + export namespace EmptyFiles { + const projFs = loadProjectFromDisk("tests/projects/empty-files"); + + const allExpectedOutputs = [ + "/src/core/index.js", + "/src/core/index.d.ts", + "/src/core/index.d.ts.map", + ]; + + describe("unittests:: tsbuild - empty files option in tsconfig", () => { + it("has empty files diagnostic when files is empty and no references are provided", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/no-references"], { dry: false, force: false, verbose: false }); + + host.clearDiagnostics(); + builder.buildAllProjects(); + host.assertDiagnosticMessages(Diagnostics.The_files_list_in_config_file_0_is_empty); + + // Check for outputs to not be written. + for (const output of allExpectedOutputs) { + assert(!fs.existsSync(output), `Expect file ${output} to not exist`); + } + }); + + it("does not have empty files diagnostic when files is empty and references are provided", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/with-references"], { dry: false, force: false, verbose: false }); + + host.clearDiagnostics(); + builder.buildAllProjects(); + host.assertDiagnosticMessages(/*empty*/); + + // Check for outputs to be written. + for (const output of allExpectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + }); + }); + } + + describe("unittests:: tsbuild - graph-ordering", () => { let host: fakes.SolutionBuilderHost | undefined; const deps: [string, string][] = [ ["A", "B"], @@ -335,7 +591,6 @@ namespace ts { const projFileNames = rootNames.map(getProjectFileName); const graph = builder.getBuildGraph(projFileNames); - if (graph === undefined) throw new Error("Graph shouldn't be undefined"); assert.sameMembers(graph.buildQueue, expectedBuildSet.map(getProjectFileName)); @@ -415,4 +670,14 @@ namespace ts { fs.makeReadonly(); return fs; } + + function getLibs() { + return [ + "/lib/lib.d.ts", + "/lib/lib.es5.d.ts", + "/lib/lib.dom.d.ts", + "/lib/lib.webworker.importscripts.d.ts", + "/lib/lib.scripthost.d.ts" + ]; + } } diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index daa1276e023..1f410667c60 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -1,19 +1,39 @@ namespace ts.tscWatch { - export import libFile = TestFSWithWatch.libFile; - function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { - const host = createSolutionBuilderWithWatchHost(system); - return ts.createSolutionBuilder(host, rootNames, defaultOptions || { dry: false, force: false, verbose: false, watch: true }); + import projectsLocation = TestFSWithWatch.tsbuildProjectsLocation; + import getFilePathInProject = TestFSWithWatch.getTsBuildProjectFilePath; + import getFileFromProject = TestFSWithWatch.getTsBuildProjectFile; + type TsBuildWatchSystem = WatchedSystem & { writtenFiles: Map; }; + + function createTsBuildWatchSystem(fileOrFolderList: ReadonlyArray, params?: TestFSWithWatch.TestServerHostCreationParameters) { + const host = createWatchedSystem(fileOrFolderList, params) as TsBuildWatchSystem; + const originalWriteFile = host.writeFile; + host.writtenFiles = createMap(); + host.writeFile = (fileName, content) => { + originalWriteFile.call(host, fileName, content); + const path = host.toFullPath(fileName); + host.writtenFiles.set(path, true); + }; + return host; } - function createSolutionBuilderWithWatch(host: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { + export function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { + const host = createSolutionBuilderWithWatchHost(system); + return ts.createSolutionBuilder(host, rootNames, defaultOptions || { watch: true }); + } + + function createSolutionBuilderWithWatch(host: TsBuildWatchSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { const solutionBuilder = createSolutionBuilder(host, rootNames, defaultOptions); solutionBuilder.buildAllProjects(); solutionBuilder.startWatching(); return solutionBuilder; } - describe("tsbuild-watch program updates", () => { - const projectsLocation = "/user/username/projects"; + type OutputFileStamp = [string, Date | undefined, boolean]; + function transformOutputToOutputFileStamp(f: string, host: TsBuildWatchSystem): OutputFileStamp { + return [f, host.getModifiedTime(f), host.writtenFiles.has(host.toFullPath(f))] as OutputFileStamp; + } + + describe("unittests:: tsbuild-watch program updates", () => { const project = "sample1"; const enum SubProject { core = "core", @@ -24,17 +44,24 @@ namespace ts.tscWatch { type ReadonlyFile = Readonly; /** [tsconfig, index] | [tsconfig, index, anotherModule, someDecl] */ type SubProjectFiles = [ReadonlyFile, ReadonlyFile] | [ReadonlyFile, ReadonlyFile, ReadonlyFile, ReadonlyFile]; - const root = Harness.IO.getWorkspaceRoot(); + function getProjectPath(project: string) { + return `${projectsLocation}/${project}`; + } + + function projectPath(subProject: SubProject) { + return getFilePathInProject(project, subProject); + } function projectFilePath(subProject: SubProject, baseFileName: string) { - return `${projectsLocation}/${project}/${subProject}/${baseFileName.toLowerCase()}`; + return `${projectPath(subProject)}/${baseFileName.toLowerCase()}`; + } + + function projectFileName(subProject: SubProject, baseFileName: string) { + return `${projectPath(subProject)}/${baseFileName}`; } function projectFile(subProject: SubProject, baseFileName: string): File { - return { - path: projectFilePath(subProject, baseFileName), - content: Harness.IO.readFile(`${root}/tests/projects/${project}/${subProject}/${baseFileName}`)! - }; + return getFileFromProject(project, `${subProject}/${baseFileName}`); } function subProjectFiles(subProject: SubProject, anotherModuleAndSomeDecl?: true): SubProjectFiles { @@ -53,29 +80,35 @@ namespace ts.tscWatch { return [`${file}.js`, `${file}.d.ts`]; } - type OutputFileStamp = [string, Date | undefined]; - function getOutputStamps(host: WatchedSystem, subProject: SubProject, baseFileNameWithoutExtension: string): OutputFileStamp[] { - return getOutputFileNames(subProject, baseFileNameWithoutExtension).map(f => [f, host.getModifiedTime(f)] as OutputFileStamp); + function getOutputStamps(host: TsBuildWatchSystem, subProject: SubProject, baseFileNameWithoutExtension: string): OutputFileStamp[] { + return getOutputFileNames(subProject, baseFileNameWithoutExtension).map(f => transformOutputToOutputFileStamp(f, host)); } - function getOutputFileStamps(host: WatchedSystem): OutputFileStamp[] { - return [ + function getOutputFileStamps(host: TsBuildWatchSystem, additionalFiles?: ReadonlyArray<[SubProject, string]>): OutputFileStamp[] { + const result = [ ...getOutputStamps(host, SubProject.core, "anotherModule"), ...getOutputStamps(host, SubProject.core, "index"), ...getOutputStamps(host, SubProject.logic, "index"), ...getOutputStamps(host, SubProject.tests, "index"), ]; + if (additionalFiles) { + additionalFiles.forEach(([subProject, baseFileNameWithoutExtension]) => result.push(...getOutputStamps(host, subProject, baseFileNameWithoutExtension))); + } + host.writtenFiles.clear(); + return result; } - function verifyChangedFiles(actualStamps: OutputFileStamp[], oldTimeStamps: OutputFileStamp[], changedFiles: string[]) { + function verifyChangedFiles(actualStamps: OutputFileStamp[], oldTimeStamps: OutputFileStamp[], changedFiles: ReadonlyArray, modifiedTimeStampFiles: ReadonlyArray) { for (let i = 0; i < oldTimeStamps.length; i++) { const actual = actualStamps[i]; const old = oldTimeStamps[i]; - if (contains(changedFiles, actual[0])) { - assert.isTrue((actual[1] || 0) > (old[1] || 0), `${actual[0]} expected to written`); + const expectedIsChanged = contains(changedFiles, actual[0]); + assert.equal(actual[2], contains(changedFiles, actual[0]), `Expected ${actual[0]} to be written.`); + if (expectedIsChanged || contains(modifiedTimeStampFiles, actual[0])) { + assert.isTrue((actual[1] || 0) > (old[1] || 0), `${actual[0]} file expected to have newer modified time because it is expected to ${expectedIsChanged ? "be changed" : "have modified time stamp"}`); } else { - assert.equal(actual[1], old[1], `${actual[0]} expected to not change`); + assert.equal(actual[1], old[1], `${actual[0]} expected to not change or have timestamp modified.`); } } } @@ -85,70 +118,1020 @@ namespace ts.tscWatch { const tests = subProjectFiles(SubProject.tests); const ui = subProjectFiles(SubProject.ui); const allFiles: ReadonlyArray = [libFile, ...core, ...logic, ...tests, ...ui]; - const testProjectExpectedWatchedFiles = [core[0], core[1], core[2], ...logic, ...tests].map(f => f.path); + const testProjectExpectedWatchedFiles = [core[0], core[1], core[2]!, ...logic, ...tests].map(f => f.path.toLowerCase()); // tslint:disable-line no-unnecessary-type-assertion (TODO: type assertion should be necessary) + const testProjectExpectedWatchedDirectoriesRecursive = [projectPath(SubProject.core), projectPath(SubProject.logic)]; - function createSolutionInWatchMode() { - const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); - createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); - checkWatchedFiles(host, testProjectExpectedWatchedFiles); - checkWatchedDirectories(host, emptyArray, /*recursive*/ false); - checkWatchedDirectories(host, emptyArray, /*recursive*/ true); // TODO: #26524 - checkOutputErrorsInitial(host, emptyArray); + function createSolutionInWatchMode(allFiles: ReadonlyArray, defaultOptions?: BuildOptions, disableConsoleClears?: boolean) { + const host = createTsBuildWatchSystem(allFiles, { currentDirectory: projectsLocation }); + createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`], defaultOptions); + verifyWatches(host); + checkOutputErrorsInitial(host, emptyArray, disableConsoleClears); const outputFileStamps = getOutputFileStamps(host); for (const stamp of outputFileStamps) { assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); } return host; } + + function verifyWatches(host: TsBuildWatchSystem) { + checkWatchedFiles(host, testProjectExpectedWatchedFiles); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, testProjectExpectedWatchedDirectoriesRecursive, /*recursive*/ true); + } + it("creates solution in watch mode", () => { - createSolutionInWatchMode(); + createSolutionInWatchMode(allFiles); }); - it("change builds changes and reports found errors message", () => { - const host = createSolutionInWatchMode(); - verifyChange(`${core[1].content} + describe("validates the changes and watched files", () => { + const newFileWithoutExtension = "newFile"; + const newFile: File = { + path: projectFilePath(SubProject.core, `${newFileWithoutExtension}.ts`), + content: `export const newFileConst = 30;` + }; + + function verifyProjectChanges(allFiles: ReadonlyArray) { + function createSolutionInWatchModeToVerifyChanges(additionalFiles?: ReadonlyArray<[SubProject, string]>) { + const host = createSolutionInWatchMode(allFiles); + return { host, verifyChangeWithFile, verifyChangeAfterTimeout, verifyWatches }; + + function verifyChangeWithFile(fileName: string, content: string, local?: boolean) { + const outputFileStamps = getOutputFileStamps(host, additionalFiles); + host.writeFile(fileName, content); + verifyChangeAfterTimeout(outputFileStamps, local); + } + + function verifyChangeAfterTimeout(outputFileStamps: OutputFileStamp[], local?: boolean) { + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles( + changedCore, + outputFileStamps, + additionalFiles ? + getOutputFileNames(SubProject.core, newFileWithoutExtension) : + getOutputFileNames(SubProject.core, "index"), // Written files are new file or core index file thats changed + [ + ...getOutputFileNames(SubProject.core, "anotherModule"), + ...(additionalFiles ? getOutputFileNames(SubProject.core, "index") : emptyArray) + ] + ); + host.checkTimeoutQueueLengthAndRun(1); // Builds logic or updates timestamps + const changedLogic = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles( + changedLogic, + changedCore, + additionalFiles || local ? + emptyArray : + getOutputFileNames(SubProject.logic, "index"), + additionalFiles || local ? + getOutputFileNames(SubProject.logic, "index") : + emptyArray + ); + host.checkTimeoutQueueLengthAndRun(1); // Builds tests + const changedTests = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles( + changedTests, + changedLogic, + additionalFiles || local ? + emptyArray : + getOutputFileNames(SubProject.tests, "index"), + additionalFiles || local ? + getOutputFileNames(SubProject.tests, "index") : + emptyArray + ); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(); + } + + function verifyWatches() { + checkWatchedFiles(host, additionalFiles ? testProjectExpectedWatchedFiles.concat(newFile.path) : testProjectExpectedWatchedFiles); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, testProjectExpectedWatchedDirectoriesRecursive, /*recursive*/ true); + } + } + + it("change builds changes and reports found errors message", () => { + const { host, verifyChangeWithFile, verifyChangeAfterTimeout } = createSolutionInWatchModeToVerifyChanges(); + verifyChange(`${core[1].content} export class someClass { }`); - // Another change requeues and builds it - verifyChange(core[1].content); + // Another change requeues and builds it + verifyChange(core[1].content); - // Two changes together report only single time message: File change detected. Starting incremental compilation... - const outputFileStamps = getOutputFileStamps(host); - const change1 = `${core[1].content} + // Two changes together report only single time message: File change detected. Starting incremental compilation... + const outputFileStamps = getOutputFileStamps(host); + const change1 = `${core[1].content} export class someClass { }`; - host.writeFile(core[1].path, change1); - host.writeFile(core[1].path, `${change1} + host.writeFile(core[1].path, change1); + host.writeFile(core[1].path, `${change1} export class someClass2 { }`); - verifyChangeAfterTimeout(outputFileStamps); + verifyChangeAfterTimeout(outputFileStamps); - function verifyChange(coreContent: string) { - const outputFileStamps = getOutputFileStamps(host); - host.writeFile(core[1].path, coreContent); - verifyChangeAfterTimeout(outputFileStamps); + function verifyChange(coreContent: string) { + verifyChangeWithFile(core[1].path, coreContent); + } + }); + + it("non local change does not start build of referencing projects", () => { + const { verifyChangeWithFile } = createSolutionInWatchModeToVerifyChanges(); + verifyChangeWithFile(core[1].path, `${core[1].content} +function foo() { }`, /*local*/ true); + }); + + it("builds when new file is added, and its subsequent updates", () => { + const additinalFiles: ReadonlyArray<[SubProject, string]> = [[SubProject.core, newFileWithoutExtension]]; + const { verifyChangeWithFile } = createSolutionInWatchModeToVerifyChanges(additinalFiles); + verifyChange(newFile.content); + + // Another change requeues and builds it + verifyChange(`${newFile.content} +export class someClass2 { }`); + + function verifyChange(newFileContent: string) { + verifyChangeWithFile(newFile.path, newFileContent); + } + }); } - function verifyChangeAfterTimeout(outputFileStamps: OutputFileStamp[]) { + describe("with simple project reference graph", () => { + verifyProjectChanges(allFiles); + }); + + describe("with circular project reference", () => { + const [coreTsconfig, ...otherCoreFiles] = core; + const circularCoreConfig: File = { + path: coreTsconfig.path, + content: JSON.stringify({ + compilerOptions: { composite: true, declaration: true }, + references: [{ path: "../tests", circular: true }] + }) + }; + verifyProjectChanges([libFile, circularCoreConfig, ...otherCoreFiles, ...logic, ...tests]); + }); + }); + + it("watches config files that are not present", () => { + const allFiles = [libFile, ...core, logic[1], ...tests]; + const host = createTsBuildWatchSystem(allFiles, { currentDirectory: projectsLocation }); + createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); + checkWatchedFiles(host, [core[0], core[1], core[2]!, logic[0], ...tests].map(f => f.path.toLowerCase())); // tslint:disable-line no-unnecessary-type-assertion (TODO: type assertion should be necessary) + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, [projectPath(SubProject.core)], /*recursive*/ true); + checkOutputErrorsInitial(host, [ + createCompilerDiagnostic(Diagnostics.File_0_not_found, logic[0].path) + ]); + for (const f of [ + ...getOutputFileNames(SubProject.core, "anotherModule"), + ...getOutputFileNames(SubProject.core, "index") + ]) { + assert.isTrue(host.fileExists(f), `${f} expected to be present`); + } + for (const f of [ + ...getOutputFileNames(SubProject.logic, "index"), + ...getOutputFileNames(SubProject.tests, "index") + ]) { + assert.isFalse(host.fileExists(f), `${f} expected to be absent`); + } + + // Create tsconfig file for logic and see that build succeeds + const initial = getOutputFileStamps(host); + host.writeFile(logic[0].path, logic[0].content); + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host); + verifyChangedFiles(changedLogic, initial, getOutputFileNames(SubProject.logic, "index"), emptyArray); + host.checkTimeoutQueueLengthAndRun(1); // Builds tests + const changedTests = getOutputFileStamps(host); + verifyChangedFiles(changedTests, changedLogic, getOutputFileNames(SubProject.tests, "index"), emptyArray); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(host); + }); + + it("when referenced using prepend, builds referencing project even for non local change", () => { + const coreTsConfig: File = { + path: core[0].path, + content: JSON.stringify({ + compilerOptions: { composite: true, declaration: true, outFile: "index.js" } + }) + }; + const coreIndex: File = { + path: core[1].path, + content: `function foo() { return 10; }` + }; + const logicTsConfig: File = { + path: logic[0].path, + content: JSON.stringify({ + compilerOptions: { composite: true, declaration: true, outFile: "index.js" }, + references: [{ path: "../core", prepend: true }] + }) + }; + const logicIndex: File = { + path: logic[1].path, + content: `function bar() { return foo() + 1 };` + }; + + const projectFiles = [coreTsConfig, coreIndex, logicTsConfig, logicIndex]; + const host = createTsBuildWatchSystem([libFile, ...projectFiles], { currentDirectory: projectsLocation }); + createSolutionBuilderWithWatch(host, [`${project}/${SubProject.logic}`]); + verifyWatches(); + checkOutputErrorsInitial(host, emptyArray); + const outputFileStamps = getOutputFileStamps(); + for (const stamp of outputFileStamps) { + assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); + } + + // Make non local change + verifyChangeInCore(`${coreIndex.content} +function myFunc() { return 10; }`); + + // TODO:: local change does not build logic.js because builder doesnt find any changes in input files to generate output + // Make local change to function bar + verifyChangeInCore(`${coreIndex.content} +function myFunc() { return 100; }`); + + function verifyChangeInCore(content: string) { + const outputFileStamps = getOutputFileStamps(); + host.writeFile(coreIndex.path, content); + host.checkTimeoutQueueLengthAndRun(1); // Builds core - const changedCore = getOutputFileStamps(host); - verifyChangedFiles(changedCore, outputFileStamps, [ - ...getOutputFileNames(SubProject.core, "anotherModule"), // This should not be written really - ...getOutputFileNames(SubProject.core, "index") - ]); - host.checkTimeoutQueueLengthAndRun(1); // Builds tests - const changedTests = getOutputFileStamps(host); - verifyChangedFiles(changedTests, changedCore, [ - ...getOutputFileNames(SubProject.tests, "index") // Again these need not be written - ]); + const changedCore = getOutputFileStamps(); + verifyChangedFiles( + changedCore, + outputFileStamps, + getOutputFileNames(SubProject.core, "index"), + emptyArray + ); host.checkTimeoutQueueLengthAndRun(1); // Builds logic - const changedLogic = getOutputFileStamps(host); - verifyChangedFiles(changedLogic, changedTests, [ - ...getOutputFileNames(SubProject.logic, "index") // Again these need not be written - ]); + const changedLogic = getOutputFileStamps(); + verifyChangedFiles( + changedLogic, + changedCore, + getOutputFileNames(SubProject.logic, "index"), + emptyArray + ); host.checkTimeoutQueueLength(0); checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(); + } + + function getOutputFileStamps(): OutputFileStamp[] { + const result = [ + ...getOutputStamps(host, SubProject.core, "index"), + ...getOutputStamps(host, SubProject.logic, "index"), + ]; + host.writtenFiles.clear(); + return result; + } + + function verifyWatches() { + checkWatchedFiles(host, projectFiles.map(f => f.path)); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, testProjectExpectedWatchedDirectoriesRecursive, /*recursive*/ true); } }); - // TODO: write tests reporting errors but that will have more involved work since file + it("when referenced project change introduces error in the down stream project and then fixes it", () => { + const subProjectLibrary = `${projectsLocation}/${project}/Library`; + const libraryTs: File = { + path: `${subProjectLibrary}/library.ts`, + content: ` +interface SomeObject +{ + message: string; +} + +export function createSomeObject(): SomeObject +{ + return { + message: "new Object" + }; +}` + }; + const libraryTsconfig: File = { + path: `${subProjectLibrary}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { composite: true } }) + }; + const subProjectApp = `${projectsLocation}/${project}/App`; + const appTs: File = { + path: `${subProjectApp}/app.ts`, + content: `import { createSomeObject } from "../Library/library"; +createSomeObject().message;` + }; + const appTsconfig: File = { + path: `${subProjectApp}/tsconfig.json`, + content: JSON.stringify({ references: [{ path: "../Library" }] }) + }; + + const files = [libFile, libraryTs, libraryTsconfig, appTs, appTsconfig]; + const host = createTsBuildWatchSystem(files, { currentDirectory: `${projectsLocation}/${project}` }); + createSolutionBuilderWithWatch(host, ["App"]); + checkOutputErrorsInitial(host, emptyArray); + + // Change message in library to message2 + host.writeFile(libraryTs.path, libraryTs.content.replace(/message/g, "message2")); + host.checkTimeoutQueueLengthAndRun(1); // Build library + host.checkTimeoutQueueLengthAndRun(1); // Build App + checkOutputErrorsIncremental(host, [ + "App/app.ts(2,20): error TS2551: Property 'message' does not exist on type 'SomeObject'. Did you mean 'message2'?\n" + ]); + + // Revert library changes + host.writeFile(libraryTs.path, libraryTs.content); + host.checkTimeoutQueueLengthAndRun(1); // Build library + host.checkTimeoutQueueLengthAndRun(1); // Build App + checkOutputErrorsIncremental(host, emptyArray); + }); + + describe("reports errors in all projects on incremental compile", () => { + function verifyIncrementalErrors(defaultBuildOptions?: BuildOptions, disabledConsoleClear?: boolean) { + const host = createSolutionInWatchMode(allFiles, defaultBuildOptions, disabledConsoleClear); + const outputFileStamps = getOutputFileStamps(host); + + host.writeFile(logic[1].path, `${logic[1].content} +let y: string = 10;`); + + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host); + verifyChangedFiles(changedLogic, outputFileStamps, emptyArray, emptyArray); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, [ + `sample1/logic/index.ts(8,5): error TS2322: Type '10' is not assignable to type 'string'.\n` + ], disabledConsoleClear); + + host.writeFile(core[1].path, `${core[1].content} +let x: string = 10;`); + + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host); + verifyChangedFiles(changedCore, changedLogic, emptyArray, emptyArray); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, [ + `sample1/core/index.ts(5,5): error TS2322: Type '10' is not assignable to type 'string'.\n`, + `sample1/logic/index.ts(8,5): error TS2322: Type '10' is not assignable to type 'string'.\n` + ], disabledConsoleClear); + } + + it("when preserveWatchOutput is not used", () => { + verifyIncrementalErrors(); + }); + + it("when preserveWatchOutput is passed on command line", () => { + verifyIncrementalErrors({ preserveWatchOutput: true, watch: true }, /*disabledConsoleClear*/ true); + }); + + describe("when declaration emit errors are present", () => { + const solution = "solution"; + const subProject = "app"; + const subProjectLocation = `${projectsLocation}/${solution}/${subProject}`; + const fileWithError: File = { + path: `${subProjectLocation}/fileWithError.ts`, + content: `export var myClassWithError = class { + tags() { } + private p = 12 + };` + }; + const fileWithFixedError: File = { + path: fileWithError.path, + content: fileWithError.content.replace("private p = 12", "") + }; + const fileWithoutError: File = { + path: `${subProjectLocation}/fileWithoutError.ts`, + content: `export class myClass { }` + }; + const tsconfig: File = { + path: `${subProjectLocation}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { composite: true } }) + }; + const expectedDtsEmitErrors = [ + `${subProject}/fileWithError.ts(1,12): error TS4094: Property 'p' of exported class expression may not be private or protected.\n` + ]; + const outputs = [ + changeExtension(fileWithError.path, Extension.Js), + changeExtension(fileWithError.path, Extension.Dts), + changeExtension(fileWithoutError.path, Extension.Js), + changeExtension(fileWithoutError.path, Extension.Dts) + ]; + + function verifyDtsErrors(host: TsBuildWatchSystem, isIncremental: boolean, expectedErrors: ReadonlyArray) { + (isIncremental ? checkOutputErrorsIncremental : checkOutputErrorsInitial)(host, expectedErrors); + outputs.forEach(f => assert.equal(host.fileExists(f), !expectedErrors.length, `Expected file ${f} to ${!expectedErrors.length ? "exist" : "not exist"}`)); + } + + function createSolutionWithWatch(withFixedError?: true) { + const files = [libFile, withFixedError ? fileWithFixedError : fileWithError, fileWithoutError, tsconfig]; + const host = createTsBuildWatchSystem(files, { currentDirectory: `${projectsLocation}/${solution}` }); + createSolutionBuilderWithWatch(host, [subProject]); + verifyDtsErrors(host, /*isIncremental*/ false, withFixedError ? emptyArray : expectedDtsEmitErrors); + return host; + } + + function incrementalBuild(host: TsBuildWatchSystem) { + host.checkTimeoutQueueLengthAndRun(1); // Build the app + host.checkTimeoutQueueLength(0); + } + + function fixError(host: TsBuildWatchSystem) { + // Fix error + host.writeFile(fileWithError.path, fileWithFixedError.content); + host.writtenFiles.clear(); + incrementalBuild(host); + verifyDtsErrors(host, /*isIncremental*/ true, emptyArray); + } + + it("when fixing error files all files are emitted", () => { + const host = createSolutionWithWatch(); + fixError(host); + }); + + it("when file with no error changes, declaration errors are reported", () => { + const host = createSolutionWithWatch(); + host.writeFile(fileWithoutError.path, fileWithoutError.content.replace(/myClass/g, "myClass2")); + incrementalBuild(host); + verifyDtsErrors(host, /*isIncremental*/ true, expectedDtsEmitErrors); + }); + + describe("when reporting errors on introducing error", () => { + function createSolutionWithIncrementalError() { + const host = createSolutionWithWatch(/*withFixedError*/ true); + host.writeFile(fileWithError.path, fileWithError.content); + host.writtenFiles.clear(); + + incrementalBuild(host); + checkOutputErrorsIncremental(host, expectedDtsEmitErrors); + assert.equal(host.writtenFiles.size, 0, `Expected not to write any files: ${arrayFrom(host.writtenFiles.keys())}`); + return host; + } + + function verifyWrittenFile(host: TsBuildWatchSystem, f: string) { + assert.isTrue(host.writtenFiles.has(host.toFullPath(f)), `Expected to write ${f}: ${arrayFrom(host.writtenFiles.keys())}`); + } + + it("when fixing errors only changed file is emitted", () => { + const host = createSolutionWithIncrementalError(); + fixError(host); + assert.equal(host.writtenFiles.size, 2, `Expected to write only changed files: ${arrayFrom(host.writtenFiles.keys())}`); + verifyWrittenFile(host, outputs[0]); + verifyWrittenFile(host, outputs[1]); + }); + + it("when file with no error changes, declaration errors are reported", () => { + const host = createSolutionWithIncrementalError(); + host.writeFile(fileWithoutError.path, fileWithoutError.content.replace(/myClass/g, "myClass2")); + host.writtenFiles.clear(); + + incrementalBuild(host); + checkOutputErrorsIncremental(host, expectedDtsEmitErrors); + assert.equal(host.writtenFiles.size, 0, `Expected not to write any files: ${arrayFrom(host.writtenFiles.keys())}`); + }); + }); + }); + }); + + describe("tsc-watch and tsserver works with project references", () => { + describe("invoking when references are already built", () => { + function verifyWatchesOfProject(host: TsBuildWatchSystem, expectedWatchedFiles: ReadonlyArray, expectedWatchedDirectoriesRecursive: ReadonlyArray, expectedWatchedDirectories?: ReadonlyArray) { + checkWatchedFilesDetailed(host, expectedWatchedFiles, 1); + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectories || emptyArray, 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true); + } + + function createSolutionOfProject(allFiles: ReadonlyArray, + currentDirectory: string, + solutionBuilderconfig: string, + getOutputFileStamps: (host: TsBuildWatchSystem) => ReadonlyArray) { + // Build the composite project + const host = createTsBuildWatchSystem(allFiles, { currentDirectory }); + const solutionBuilder = createSolutionBuilder(host, [solutionBuilderconfig], {}); + solutionBuilder.buildAllProjects(); + const outputFileStamps = getOutputFileStamps(host); + for (const stamp of outputFileStamps) { + assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); + } + return { host, solutionBuilder }; + } + + function createSolutionAndWatchModeOfProject( + allFiles: ReadonlyArray, + currentDirectory: string, + solutionBuilderconfig: string, + watchConfig: string, + getOutputFileStamps: (host: TsBuildWatchSystem) => ReadonlyArray) { + // Build the composite project + const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps); + + // Build in watch mode + const watch = createWatchOfConfigFile(watchConfig, host); + checkOutputErrorsInitial(host, emptyArray); + + return { host, solutionBuilder, watch }; + } + + function createSolutionAndServiceOfProject(allFiles: ReadonlyArray, + currentDirectory: string, + solutionBuilderconfig: string, + openFileName: string, + getOutputFileStamps: (host: TsBuildWatchSystem) => ReadonlyArray) { + // Build the composite project + const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps); + + // service + const service = projectSystem.createProjectService(host); + service.openClientFile(openFileName); + + return { host, solutionBuilder, service }; + } + + function checkProjectActualFiles(service: projectSystem.TestProjectService, configFile: string, expectedFiles: ReadonlyArray) { + projectSystem.checkNumberOfProjects(service, { configuredProjects: 1 }); + projectSystem.checkProjectActualFiles(service.configuredProjects.get(configFile.toLowerCase())!, expectedFiles); + } + + function verifyDependencies(watch: Watch, filePath: string, expected: ReadonlyArray) { + checkArray(`${filePath} dependencies`, watch.getBuilderProgram().getAllDependencies(watch().getSourceFile(filePath)!), expected); + } + + describe("on sample project", () => { + const coreIndexDts = projectFileName(SubProject.core, "index.d.ts"); + const coreAnotherModuleDts = projectFileName(SubProject.core, "anotherModule.d.ts"); + const logicIndexDts = projectFileName(SubProject.logic, "index.d.ts"); + const expectedWatchedFiles = [core[0], logic[0], ...tests, libFile].map(f => f.path).concat([coreIndexDts, coreAnotherModuleDts, logicIndexDts].map(f => f.toLowerCase())); + const expectedWatchedDirectoriesRecursive = projectSystem.getTypeRootsFromLocation(projectPath(SubProject.tests)); + const expectedProgramFiles = [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]; + + function createSolutionAndWatchMode() { + return createSolutionAndWatchModeOfProject(allFiles, projectsLocation, `${project}/${SubProject.tests}`, tests[0].path, getOutputFileStamps); + } + + function createSolutionAndService() { + return createSolutionAndServiceOfProject(allFiles, projectsLocation, `${project}/${SubProject.tests}`, tests[1].path, getOutputFileStamps); + } + + function verifyWatches(host: TsBuildWatchSystem, withTsserver?: boolean) { + verifyWatchesOfProject(host, withTsserver ? expectedWatchedFiles.filter(f => f !== tests[1].path.toLowerCase()) : expectedWatchedFiles, expectedWatchedDirectoriesRecursive); + } + + function verifyScenario( + edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder) => void, + expectedFilesAfterEdit: ReadonlyArray + ) { + it("with tsc-watch", () => { + const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); + + edit(host, solutionBuilder); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + checkProgramActualFiles(watch(), expectedFilesAfterEdit); + + }); + + it("with tsserver", () => { + const { host, solutionBuilder, service } = createSolutionAndService(); + + edit(host, solutionBuilder); + + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(service, tests[0].path, [tests[0].path, ...expectedFilesAfterEdit]); + }); + } + + describe("verifies dependencies and watches", () => { + it("with tsc-watch", () => { + const { host, watch } = createSolutionAndWatchMode(); + verifyWatches(host); + verifyDependencies(watch, coreIndexDts, [coreIndexDts]); + verifyDependencies(watch, coreAnotherModuleDts, [coreAnotherModuleDts]); + verifyDependencies(watch, logicIndexDts, [logicIndexDts, coreAnotherModuleDts]); + verifyDependencies(watch, tests[1].path, expectedProgramFiles.filter(f => f !== libFile.path)); + }); + + it("with tsserver", () => { + const { host } = createSolutionAndService(); + verifyWatches(host, /*withTsserver*/ true); + }); + }); + + describe("local edit in ts file, result in watch compilation because logic.d.ts is written", () => { + verifyScenario((host, solutionBuilder) => { + host.writeFile(logic[1].path, `${logic[1].content} +function foo() { +}`); + solutionBuilder.invalidateProject(`${project}/${SubProject.logic}`); + solutionBuilder.buildInvalidatedProject(); + + // not ideal, but currently because of d.ts but no new file is written + // There will be timeout queued even though file contents are same + }, expectedProgramFiles); + }); + + describe("non local edit in ts file, rebuilds in watch compilation", () => { + verifyScenario((host, solutionBuilder) => { + host.writeFile(logic[1].path, `${logic[1].content} +export function gfoo() { +}`); + solutionBuilder.invalidateProject(logic[0].path); + solutionBuilder.buildInvalidatedProject(); + }, expectedProgramFiles); + }); + + describe("change in project reference config file builds correctly", () => { + verifyScenario((host, solutionBuilder) => { + host.writeFile(logic[0].path, JSON.stringify({ + compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, + references: [{ path: "../core" }] + })); + solutionBuilder.invalidateProject(logic[0].path, ConfigFileProgramReloadLevel.Full); + solutionBuilder.buildInvalidatedProject(); + }, [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")]); + }); + }); + + describe("on transitive references", () => { + const project = "transitiveReferences"; + const aTsFile = getFileFromProject(project, "a.ts"); + const bTsFile = getFileFromProject(project, "b.ts"); + const cTsFile = getFileFromProject(project, "c.ts"); + const aTsconfigFile = getFileFromProject(project, "tsconfig.a.json"); + const bTsconfigFile = getFileFromProject(project, "tsconfig.b.json"); + const cTsconfigFile = getFileFromProject(project, "tsconfig.c.json"); + const refs = getFileFromProject(project, "refs/a.d.ts"); + + function getRootFile(multiFolder: boolean, fileFromDisk: File, multiFolderPath: string): File { + return multiFolder ? { + path: getFilePathInProject(project, multiFolderPath), + content: fileFromDisk.content + // Replace the relative imports + .replace("./", "../") + } : fileFromDisk; + } + + function dtsFile(extensionLessFile: string) { + return getFilePathInProject(project, `${extensionLessFile}.d.ts`); + } + + function jsFile(extensionLessFile: string) { + return getFilePathInProject(project, `${extensionLessFile}.js`); + } + + function verifyWatchState( + host: TsBuildWatchSystem, + watch: Watch, + expectedProgramFiles: ReadonlyArray, + expectedWatchedFiles: ReadonlyArray, + expectedWatchedDirectoriesRecursive: ReadonlyArray, + dependencies: ReadonlyArray<[string, ReadonlyArray]>, + expectedWatchedDirectories?: ReadonlyArray) { + checkProgramActualFiles(watch(), expectedProgramFiles); + verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); + for (const [file, deps] of dependencies) { + verifyDependencies(watch, file, deps); + } + } + + function getTsConfigFile(multiFolder: boolean, fileFromDisk: File, folder: string): File { + if (!multiFolder) return fileFromDisk; + + return { + path: getFilePathInProject(project, `${folder}/tsconfig.json`), + content: fileFromDisk.content + // Replace files array + .replace(`${folder}.ts`, "index.ts") + // Replace path mappings + .replace("./*", "../*") + .replace("./refs", "../refs") + // Replace references + .replace("tsconfig.a.json", "../a") + .replace("tsconfig.b.json", "../b") + }; + } + + // function writeFile(file: File) { + // Harness.IO.writeFile(file.path.replace(projectsLocation, "c:/temp"), file.content); + // } + + function verifyTransitiveReferences(multiFolder: boolean) { + const aTs = getRootFile(multiFolder, aTsFile, "a/index.ts"); + const bTs = getRootFile(multiFolder, bTsFile, "b/index.ts"); + const cTs = getRootFile(multiFolder, cTsFile, "c/index.ts"); + + const configToBuild = multiFolder ? "c/tsconfig.json" : "tsconfig.c.json"; + const aTsconfig = getTsConfigFile(multiFolder, aTsconfigFile, "a"); + const bTsconfig = getTsConfigFile(multiFolder, bTsconfigFile, "b"); + const cTsconfig = getTsConfigFile(multiFolder, cTsconfigFile, "c"); + + // if (multiFolder) { + // writeFile(aTs); + // writeFile(bTs); + // writeFile(cTs); + // writeFile(aTsconfig); + // writeFile(bTsconfig); + // writeFile(cTsconfig); + // } + + const allFiles = [libFile, aTs, bTs, cTs, aTsconfig, bTsconfig, cTsconfig, refs]; + const aDts = dtsFile(multiFolder ? "a/index" : "a"), bDts = dtsFile(multiFolder ? "b/index" : "b"); + const expectedFiles = [jsFile(multiFolder ? "a/index" : "a"), aDts, jsFile(multiFolder ? "b/index" : "b"), bDts, jsFile(multiFolder ? "c/index" : "c")]; + const expectedProgramFiles = [cTs.path, libFile.path, aDts, refs.path, bDts]; + const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()); + const expectedWatchedDirectories = multiFolder ? [ + getProjectPath(project).toLowerCase() // watches for directories created for resolution of b + ] : emptyArray; + const nrefsPath = multiFolder ? ["../nrefs/*"] : ["./nrefs/*"]; + const expectedWatchedDirectoriesRecursive = [ + ...(multiFolder ? [ + getFilePathInProject(project, "a"), // Failed to package json + getFilePathInProject(project, "b"), // Failed to package json + ] : []), + getFilePathInProject(project, "refs"), // Failed lookup since refs/a.ts does not exist + ...projectSystem.getTypeRootsFromLocation(multiFolder ? getFilePathInProject(project, "c") : getProjectPath(project)) + ].map(s => s.toLowerCase()); + + const defaultDependencies: ReadonlyArray<[string, ReadonlyArray]> = [ + [aDts, [aDts]], + [bDts, [bDts, aDts]], + [refs.path, [refs.path]], + [cTs.path, [cTs.path, refs.path, bDts]] + ]; + + function createSolutionAndWatchMode() { + return createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), configToBuild, configToBuild, getOutputFileStamps); + } + + function createSolutionAndService() { + return createSolutionAndServiceOfProject(allFiles, getProjectPath(project), configToBuild, cTs.path, getOutputFileStamps); + } + + function getOutputFileStamps(host: TsBuildWatchSystem) { + return expectedFiles.map(file => transformOutputToOutputFileStamp(file, host)); + } + + function verifyProgram(host: TsBuildWatchSystem, watch: Watch) { + verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies, expectedWatchedDirectories); + } + + function verifyProject(host: TsBuildWatchSystem, service: projectSystem.TestProjectService, orphanInfos?: ReadonlyArray) { + verifyServerState(host, service, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos); + } + + function verifyServerState( + host: TsBuildWatchSystem, + service: projectSystem.TestProjectService, + expectedProgramFiles: ReadonlyArray, + expectedWatchedFiles: ReadonlyArray, + expectedWatchedDirectoriesRecursive: ReadonlyArray, + orphanInfos?: ReadonlyArray) { + checkProjectActualFiles(service, cTsconfig.path, expectedProgramFiles.concat(cTsconfig.path)); + const watchedFiles = expectedWatchedFiles.filter(f => f !== cTs.path.toLowerCase()); + if (orphanInfos) { + for (const orphan of orphanInfos) { + const info = service.getScriptInfoForPath(orphan as Path); + assert.isDefined(info); + assert.equal(info!.containingProjects.length, 0); + watchedFiles.push(orphan); + } + } + verifyWatchesOfProject(host, watchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); + } + + function verifyScenario( + edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder) => void, + expectedEditErrors: ReadonlyArray, + expectedProgramFiles: ReadonlyArray, + expectedWatchedFiles: ReadonlyArray, + expectedWatchedDirectoriesRecursive: ReadonlyArray, + dependencies: ReadonlyArray<[string, ReadonlyArray]>, + revert?: (host: TsBuildWatchSystem) => void, + orphanInfosAfterEdit?: ReadonlyArray, + orphanInfosAfterRevert?: ReadonlyArray) { + it("with tsc-watch", () => { + const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); + + edit(host, solutionBuilder); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, expectedEditErrors); + verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, dependencies, expectedWatchedDirectories); + + if (revert) { + revert(host); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + } + }); + + if (!multiFolder) return; // With side by side file open is in inferred project without any settings + + it("with tsserver", () => { + const { host, solutionBuilder, service } = createSolutionAndService(); + + edit(host, solutionBuilder); + + host.checkTimeoutQueueLengthAndRun(2); + verifyServerState(host, service, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfosAfterEdit); + + if (revert) { + revert(host); + + host.checkTimeoutQueueLengthAndRun(2); + verifyProject(host, service, orphanInfosAfterRevert); + } + }); + } + + describe("verifies dependencies and watches", () => { + // Initial build + it("with tsc-watch", () => { + const { host, watch } = createSolutionAndWatchMode(); + verifyProgram(host, watch); + }); + if (!multiFolder) return; + it("with tsserver", () => { + const { host, service } = createSolutionAndService(); + verifyProject(host, service); + }); + }); + + describe("non local edit updates the program and watch correctly", () => { + verifyScenario( + (host, solutionBuilder) => { + // edit + host.writeFile(bTs.path, `${bTs.content} +export function gfoo() { +}`); + solutionBuilder.invalidateProject(bTsconfig.path); + solutionBuilder.buildInvalidatedProject(); + }, + emptyArray, + expectedProgramFiles, + expectedWatchedFiles, + expectedWatchedDirectoriesRecursive, + defaultDependencies); + }); + + describe("edit on config file", () => { + const nrefReplacer = (f: string) => f.replace("refs", "nrefs"); + const nrefs: File = { + path: getFilePathInProject(project, "nrefs/a.d.ts"), + content: refs.content + }; + verifyScenario( + host => { + const cTsConfigJson = JSON.parse(cTsconfig.content); + host.ensureFileOrFolder(nrefs); + cTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath }; + host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson)); + }, + emptyArray, + expectedProgramFiles.map(nrefReplacer), + expectedWatchedFiles.map(nrefReplacer), + expectedWatchedDirectoriesRecursive.map(nrefReplacer), + [ + [aDts, [aDts]], + [bDts, [bDts, aDts]], + [nrefs.path, [nrefs.path]], + [cTs.path, [cTs.path, nrefs.path, bDts]] + ], + // revert the update + host => host.writeFile(cTsconfig.path, cTsconfig.content), + // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open + [refs.path.toLowerCase()], + // AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open + [nrefs.path.toLowerCase()] + ); + }); + + describe("edit in referenced config file", () => { + const nrefs: File = { + path: getFilePathInProject(project, "nrefs/a.d.ts"), + content: "export declare class A {}" + }; + const expectedProgramFiles = [cTs.path, bDts, nrefs.path, refs.path, libFile.path]; + const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario + verifyScenario( + host => { + const bTsConfigJson = JSON.parse(bTsconfig.content); + host.ensureFileOrFolder(nrefs); + bTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath }; + host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson)); + }, + emptyArray, + expectedProgramFiles, + expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()), + (multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive).concat(getFilePathInProject(project, "nrefs").toLowerCase()), + [ + [nrefs.path, [nrefs.path]], + [bDts, [bDts, nrefs.path]], + [refs.path, [refs.path]], + [cTs.path, [cTs.path, refs.path, bDts]], + ], + // revert the update + host => host.writeFile(bTsconfig.path, bTsconfig.content), + // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open + [aDts.toLowerCase()], + // AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open + [nrefs.path.toLowerCase()] + ); + }); + + describe("deleting referenced config file", () => { + const expectedProgramFiles = [cTs.path, bTs.path, refs.path, libFile.path]; + const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario + // Resolutions should change now + // Should map to b.ts instead with options from our own config + verifyScenario( + host => host.deleteFile(bTsconfig.path), + [ + `${multiFolder ? "c/tsconfig.json" : "tsconfig.c.json"}(9,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "b" : "tsconfig.b.json"}' not found.\n` + ], + expectedProgramFiles, + expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path).map(s => s.toLowerCase()), + multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive, + [ + [bTs.path, [bTs.path, refs.path]], + [refs.path, [refs.path]], + [cTs.path, [cTs.path, refs.path, bTs.path]], + ], + // revert the update + host => host.writeFile(bTsconfig.path, bTsconfig.content), + // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open + [bDts.toLowerCase(), aDts.toLowerCase(), aTsconfig.path.toLowerCase()], + // AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open + [bTs.path.toLowerCase()] + ); + }); + + describe("deleting transitively referenced config file", () => { + verifyScenario( + host => host.deleteFile(aTsconfig.path), + [ + `${multiFolder ? "b/tsconfig.json" : "tsconfig.b.json"}(10,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "a" : "tsconfig.a.json"}' not found.\n` + ], + expectedProgramFiles.map(s => s.replace(aDts, aTs.path)), + expectedWatchedFiles.map(s => s.replace(aDts.toLowerCase(), aTs.path.toLocaleLowerCase())), + expectedWatchedDirectoriesRecursive, + [ + [aTs.path, [aTs.path]], + [bDts, [bDts, aTs.path]], + [refs.path, [refs.path]], + [cTs.path, [cTs.path, refs.path, bDts]], + ], + // revert the update + host => host.writeFile(aTsconfig.path, aTsconfig.content), + // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open + [aDts.toLowerCase()], + // AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open + [aTs.path.toLowerCase()] + ); + }); + } + + describe("when config files are side by side", () => { + verifyTransitiveReferences(/*multiFolder*/ false); + + it("when referenced project uses different module resolution", () => { + const bTs: File = { + path: bTsFile.path, + content: `import {A} from "a";export const b = new A();` + }; + const bTsconfig: File = { + path: bTsconfigFile.path, + content: JSON.stringify({ + compilerOptions: { composite: true, moduleResolution: "classic" }, + files: ["b.ts"], + references: [{ path: "tsconfig.a.json" }] + }) + }; + const allFiles = [libFile, aTsFile, bTs, cTsFile, aTsconfigFile, bTsconfig, cTsconfigFile, refs]; + const aDts = dtsFile("a"), bDts = dtsFile("b"); + const expectedFiles = [jsFile("a"), aDts, jsFile("b"), bDts, jsFile("c")]; + const expectedProgramFiles = [cTsFile.path, libFile.path, aDts, refs.path, bDts]; + const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfigFile.path, bTsconfigFile.path, aTsconfigFile.path).map(s => s.toLowerCase()); + const expectedWatchedDirectoriesRecursive = [ + getFilePathInProject(project, "refs"), // Failed lookup since refs/a.ts does not exist + ...projectSystem.getTypeRootsFromLocation(getProjectPath(project)) + ].map(s => s.toLowerCase()); + + const defaultDependencies: ReadonlyArray<[string, ReadonlyArray]> = [ + [aDts, [aDts]], + [bDts, [bDts, aDts]], + [refs.path, [refs.path]], + [cTsFile.path, [cTsFile.path, refs.path, bDts]] + ]; + function getOutputFileStamps(host: TsBuildWatchSystem) { + return expectedFiles.map(file => transformOutputToOutputFileStamp(file, host)); + } + const { host, watch } = createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), "tsconfig.c.json", "tsconfig.c.json", getOutputFileStamps); + verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies); + }); + }); + describe("when config files are in side by side folders", () => { + verifyTransitiveReferences(/*multiFolder*/ true); + }); + }); + }); + }); }); } diff --git a/src/testRunner/unittests/tscWatch/consoleClearing.ts b/src/testRunner/unittests/tscWatch/consoleClearing.ts new file mode 100644 index 00000000000..d0669a2327d --- /dev/null +++ b/src/testRunner/unittests/tscWatch/consoleClearing.ts @@ -0,0 +1,97 @@ +namespace ts.tscWatch { + describe("unittests:: tsc-watch:: console clearing", () => { + const currentDirectoryLog = "Current directory: / CaseSensitiveFileNames: false\n"; + const fileWatcherAddedLog = [ + "FileWatcher:: Added:: WatchInfo: /f.ts 250 Source file\n", + "FileWatcher:: Added:: WatchInfo: /a/lib/lib.d.ts 250 Source file\n" + ]; + + const file: File = { + path: "/f.ts", + content: "" + }; + + function getProgramSynchronizingLog(options: CompilerOptions) { + return [ + "Synchronizing program\n", + "CreatingProgramWith::\n", + " roots: [\"/f.ts\"]\n", + ` options: ${JSON.stringify(options)}\n` + ]; + } + + function isConsoleClearDisabled(options: CompilerOptions) { + return options.diagnostics || options.extendedDiagnostics || options.preserveWatchOutput; + } + + function verifyCompilation(host: WatchedSystem, options: CompilerOptions, initialDisableOptions?: CompilerOptions) { + const disableConsoleClear = isConsoleClearDisabled(options); + const hasLog = options.extendedDiagnostics || options.diagnostics; + checkOutputErrorsInitial(host, emptyArray, initialDisableOptions ? isConsoleClearDisabled(initialDisableOptions) : disableConsoleClear, hasLog ? [ + currentDirectoryLog, + ...getProgramSynchronizingLog(options), + ...(options.extendedDiagnostics ? fileWatcherAddedLog : emptyArray) + ] : undefined); + host.modifyFile(file.path, "//"); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, emptyArray, disableConsoleClear, hasLog ? [ + "FileWatcher:: Triggered with /f.ts 1:: WatchInfo: /f.ts 250 Source file\n", + "Scheduling update\n", + "Elapsed:: 0ms FileWatcher:: Triggered with /f.ts 1:: WatchInfo: /f.ts 250 Source file\n" + ] : undefined, hasLog ? getProgramSynchronizingLog(options) : undefined); + } + + function checkConsoleClearingUsingCommandLineOptions(options: CompilerOptions = {}) { + const files = [file, libFile]; + const host = createWatchedSystem(files); + createWatchOfFilesAndCompilerOptions([file.path], host, options); + verifyCompilation(host, options); + } + + it("without --diagnostics or --extendedDiagnostics", () => { + checkConsoleClearingUsingCommandLineOptions(); + }); + it("with --diagnostics", () => { + checkConsoleClearingUsingCommandLineOptions({ + diagnostics: true, + }); + }); + it("with --extendedDiagnostics", () => { + checkConsoleClearingUsingCommandLineOptions({ + extendedDiagnostics: true, + }); + }); + it("with --preserveWatchOutput", () => { + checkConsoleClearingUsingCommandLineOptions({ + preserveWatchOutput: true, + }); + }); + + describe("when preserveWatchOutput is true in config file", () => { + const compilerOptions: CompilerOptions = { + preserveWatchOutput: true + }; + const configFile: File = { + path: "/tsconfig.json", + content: JSON.stringify({ compilerOptions }) + }; + const files = [file, configFile, libFile]; + it("using createWatchOfConfigFile ", () => { + const host = createWatchedSystem(files); + createWatchOfConfigFile(configFile.path, host); + // Initially console is cleared if --preserveOutput is not provided since the config file is yet to be parsed + verifyCompilation(host, compilerOptions, {}); + }); + it("when createWatchProgram is invoked with configFileParseResult on WatchCompilerHostOfConfigFile", () => { + const host = createWatchedSystem(files); + const reportDiagnostic = createDiagnosticReporter(host); + const optionsToExtend: CompilerOptions = {}; + const configParseResult = parseConfigFileWithSystem(configFile.path, optionsToExtend, host, reportDiagnostic)!; + const watchCompilerHost = createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath!, optionsToExtend, host, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(host)); + watchCompilerHost.configFileParsingResult = configParseResult; + createWatchProgram(watchCompilerHost); + verifyCompilation(host, compilerOptions); + }); + }); + }); +} diff --git a/src/testRunner/unittests/tscWatch/emit.ts b/src/testRunner/unittests/tscWatch/emit.ts new file mode 100644 index 00000000000..06aec75f31f --- /dev/null +++ b/src/testRunner/unittests/tscWatch/emit.ts @@ -0,0 +1,718 @@ +namespace ts.tscWatch { + function getEmittedLineForMultiFileOutput(file: File, host: WatchedSystem) { + return `TSFILE: ${file.path.replace(".ts", ".js")}${host.newLine}`; + } + + function getEmittedLineForSingleFileOutput(filename: string, host: WatchedSystem) { + return `TSFILE: ${filename}${host.newLine}`; + } + + interface FileOrFolderEmit extends File { + output?: string; + } + + function getFileOrFolderEmit(file: File, getOutput?: (file: File) => string): FileOrFolderEmit { + const result = file as FileOrFolderEmit; + if (getOutput) { + result.output = getOutput(file); + } + return result; + } + + function getEmittedLines(files: FileOrFolderEmit[]) { + const seen = createMap(); + const result: string[] = []; + for (const { output } of files) { + if (output && !seen.has(output)) { + seen.set(output, true); + result.push(output); + } + } + return result; + } + + function checkAffectedLines(host: WatchedSystem, affectedFiles: FileOrFolderEmit[], allEmittedFiles: string[]) { + const expectedAffectedFiles = getEmittedLines(affectedFiles); + const expectedNonAffectedFiles = mapDefined(allEmittedFiles, line => contains(expectedAffectedFiles, line) ? undefined : line); + checkOutputContains(host, expectedAffectedFiles); + checkOutputDoesNotContain(host, expectedNonAffectedFiles); + } + + describe("unittests:: tsc-watch:: emit with outFile or out setting", () => { + function createWatchForOut(out?: string, outFile?: string) { + const host = createWatchedSystem([]); + const config: FileOrFolderEmit = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions: { listEmittedFiles: true } + }) + }; + + let getOutput: (file: File) => string; + if (out) { + config.content = JSON.stringify({ + compilerOptions: { listEmittedFiles: true, out } + }); + getOutput = __ => getEmittedLineForSingleFileOutput(out, host); + } + else if (outFile) { + config.content = JSON.stringify({ + compilerOptions: { listEmittedFiles: true, outFile } + }); + getOutput = __ => getEmittedLineForSingleFileOutput(outFile, host); + } + else { + getOutput = file => getEmittedLineForMultiFileOutput(file, host); + } + + const f1 = getFileOrFolderEmit({ + path: "/a/a.ts", + content: "let x = 1" + }, getOutput); + const f2 = getFileOrFolderEmit({ + path: "/a/b.ts", + content: "let y = 1" + }, getOutput); + + const files = [f1, f2, config, libFile]; + host.reloadFS(files); + createWatchOfConfigFile(config.path, host); + + const allEmittedLines = getEmittedLines(files); + checkOutputContains(host, allEmittedLines); + host.clearOutput(); + + f1.content = "let x = 11"; + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + checkAffectedLines(host, [f1], allEmittedLines); + } + + it("projectUsesOutFile should not be returned if not set", () => { + createWatchForOut(); + }); + + it("projectUsesOutFile should be true if out is set", () => { + const outJs = "/a/out.js"; + createWatchForOut(outJs); + }); + + it("projectUsesOutFile should be true if outFile is set", () => { + const outJs = "/a/out.js"; + createWatchForOut(/*out*/ undefined, outJs); + }); + + function verifyFilesEmittedOnce(useOutFile: boolean) { + const file1: File = { + path: "/a/b/output/AnotherDependency/file1.d.ts", + content: "declare namespace Common.SomeComponent.DynamicMenu { enum Z { Full = 0, Min = 1, Average = 2, } }" + }; + const file2: File = { + path: "/a/b/dependencies/file2.d.ts", + content: "declare namespace Dependencies.SomeComponent { export class SomeClass { version: string; } }" + }; + const file3: File = { + path: "/a/b/project/src/main.ts", + content: "namespace Main { export function fooBar() {} }" + }; + const file4: File = { + path: "/a/b/project/src/main2.ts", + content: "namespace main.file4 { import DynamicMenu = Common.SomeComponent.DynamicMenu; export function foo(a: DynamicMenu.z) { } }" + }; + const configFile: File = { + path: "/a/b/project/tsconfig.json", + content: JSON.stringify({ + compilerOptions: useOutFile ? + { outFile: "../output/common.js", target: "es5" } : + { outDir: "../output", target: "es5" }, + files: [file1.path, file2.path, file3.path, file4.path] + }) + }; + const files = [file1, file2, file3, file4]; + const allfiles = files.concat(configFile); + const host = createWatchedSystem(allfiles); + const originalWriteFile = host.writeFile.bind(host); + const mapOfFilesWritten = createMap(); + host.writeFile = (p: string, content: string) => { + const count = mapOfFilesWritten.get(p); + mapOfFilesWritten.set(p, count ? count + 1 : 1); + return originalWriteFile(p, content); + }; + createWatchOfConfigFile(configFile.path, host); + if (useOutFile) { + // Only out file + assert.equal(mapOfFilesWritten.size, 1); + } + else { + // main.js and main2.js + assert.equal(mapOfFilesWritten.size, 2); + } + mapOfFilesWritten.forEach((value, key) => { + assert.equal(value, 1, "Key: " + key); + }); + } + + it("with --outFile and multiple declaration files in the program", () => { + verifyFilesEmittedOnce(/*useOutFile*/ true); + }); + + it("without --outFile and multiple declaration files in the program", () => { + verifyFilesEmittedOnce(/*useOutFile*/ false); + }); + }); + + describe("unittests:: tsc-watch:: emit for configured projects", () => { + const file1Consumer1Path = "/a/b/file1Consumer1.ts"; + const moduleFile1Path = "/a/b/moduleFile1.ts"; + const configFilePath = "/a/b/tsconfig.json"; + interface InitialStateParams { + /** custom config file options */ + configObj?: any; + /** list of the files that will be emitted for first compilation */ + firstCompilationEmitFiles?: string[]; + /** get the emit file for file - default is multi file emit line */ + getEmitLine?(file: File, host: WatchedSystem): string; + /** Additional files and folders to add */ + getAdditionalFileOrFolder?(): File[]; + /** initial list of files to emit if not the default list */ + firstReloadFileList?: string[]; + } + function getInitialState({ configObj = {}, firstCompilationEmitFiles, getEmitLine, getAdditionalFileOrFolder, firstReloadFileList }: InitialStateParams = {}) { + const host = createWatchedSystem([]); + const getOutputName = getEmitLine ? (file: File) => getEmitLine(file, host) : + (file: File) => getEmittedLineForMultiFileOutput(file, host); + + const moduleFile1 = getFileOrFolderEmit({ + path: moduleFile1Path, + content: "export function Foo() { };", + }, getOutputName); + + const file1Consumer1 = getFileOrFolderEmit({ + path: file1Consumer1Path, + content: `import {Foo} from "./moduleFile1"; export var y = 10;`, + }, getOutputName); + + const file1Consumer2 = getFileOrFolderEmit({ + path: "/a/b/file1Consumer2.ts", + content: `import {Foo} from "./moduleFile1"; let z = 10;`, + }, getOutputName); + + const moduleFile2 = getFileOrFolderEmit({ + path: "/a/b/moduleFile2.ts", + content: `export var Foo4 = 10;`, + }, getOutputName); + + const globalFile3 = getFileOrFolderEmit({ + path: "/a/b/globalFile3.ts", + content: `interface GlobalFoo { age: number }` + }); + + const additionalFiles = getAdditionalFileOrFolder ? + map(getAdditionalFileOrFolder(), file => getFileOrFolderEmit(file, getOutputName)) : + []; + + (configObj.compilerOptions || (configObj.compilerOptions = {})).listEmittedFiles = true; + const configFile = getFileOrFolderEmit({ + path: configFilePath, + content: JSON.stringify(configObj) + }); + + const files = [moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2, configFile, libFile, ...additionalFiles]; + let allEmittedFiles = getEmittedLines(files); + host.reloadFS(firstReloadFileList ? getFiles(firstReloadFileList) : files); + + // Initial compile + createWatchOfConfigFile(configFile.path, host); + if (firstCompilationEmitFiles) { + checkAffectedLines(host, getFiles(firstCompilationEmitFiles), allEmittedFiles); + } + else { + checkOutputContains(host, allEmittedFiles); + } + host.clearOutput(); + + return { + moduleFile1, file1Consumer1, file1Consumer2, moduleFile2, globalFile3, configFile, + files, + getFile, + verifyAffectedFiles, + verifyAffectedAllFiles, + getOutputName + }; + + function getFiles(filelist: string[]) { + return map(filelist, getFile); + } + + function getFile(fileName: string) { + return find(files, file => file.path === fileName)!; + } + + function verifyAffectedAllFiles() { + host.reloadFS(files); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputContains(host, allEmittedFiles); + host.clearOutput(); + } + + function verifyAffectedFiles(expected: FileOrFolderEmit[], filesToReload?: FileOrFolderEmit[]) { + if (!filesToReload) { + filesToReload = files; + } + else if (filesToReload.length > files.length) { + allEmittedFiles = getEmittedLines(filesToReload); + } + host.reloadFS(filesToReload); + host.checkTimeoutQueueLengthAndRun(1); + checkAffectedLines(host, expected, allEmittedFiles); + host.clearOutput(); + } + } + + it("should contains only itself if a module file's shape didn't change, and all files referencing it if its shape changed", () => { + const { + moduleFile1, file1Consumer1, file1Consumer2, + verifyAffectedFiles + } = getInitialState(); + + // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyAffectedFiles([moduleFile1, file1Consumer1, file1Consumer2]); + + // Change the content of moduleFile1 to `export var T: number;export function Foo() { console.log('hi'); };` + moduleFile1.content = `export var T: number;export function Foo() { console.log('hi'); };`; + verifyAffectedFiles([moduleFile1]); + }); + + it("should be up-to-date with the reference map changes", () => { + const { + moduleFile1, file1Consumer1, file1Consumer2, + verifyAffectedFiles + } = getInitialState(); + + // Change file1Consumer1 content to `export let y = Foo();` + file1Consumer1.content = `export let y = Foo();`; + verifyAffectedFiles([file1Consumer1]); + + // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyAffectedFiles([moduleFile1, file1Consumer2]); + + // Add the import statements back to file1Consumer1 + file1Consumer1.content = `import {Foo} from "./moduleFile1";let y = Foo();`; + verifyAffectedFiles([file1Consumer1]); + + // Change the content of moduleFile1 to `export var T: number;export var T2: string;export function Foo() { };` + moduleFile1.content = `export var T: number;export var T2: string;export function Foo() { };`; + verifyAffectedFiles([moduleFile1, file1Consumer2, file1Consumer1]); + + // Multiple file edits in one go: + + // Change file1Consumer1 content to `export let y = Foo();` + // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` + file1Consumer1.content = `export let y = Foo();`; + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyAffectedFiles([moduleFile1, file1Consumer1, file1Consumer2]); + }); + + it("should be up-to-date with deleted files", () => { + const { + moduleFile1, file1Consumer1, file1Consumer2, + files, + verifyAffectedFiles + } = getInitialState(); + + // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` + moduleFile1.content = `export var T: number;export function Foo() { };`; + + // Delete file1Consumer2 + const filesToLoad = mapDefined(files, file => file === file1Consumer2 ? undefined : file); + verifyAffectedFiles([moduleFile1, file1Consumer1], filesToLoad); + }); + + it("should be up-to-date with newly created files", () => { + const { + moduleFile1, file1Consumer1, file1Consumer2, + files, + verifyAffectedFiles, + getOutputName + } = getInitialState(); + + const file1Consumer3 = getFileOrFolderEmit({ + path: "/a/b/file1Consumer3.ts", + content: `import {Foo} from "./moduleFile1"; let y = Foo();` + }, getOutputName); + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyAffectedFiles([moduleFile1, file1Consumer1, file1Consumer3, file1Consumer2], files.concat(file1Consumer3)); + }); + + it("should detect changes in non-root files", () => { + const { + moduleFile1, file1Consumer1, + verifyAffectedFiles + } = getInitialState({ configObj: { files: [file1Consumer1Path] }, firstCompilationEmitFiles: [file1Consumer1Path, moduleFile1Path] }); + + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyAffectedFiles([moduleFile1, file1Consumer1]); + + // change file1 internal, and verify only file1 is affected + moduleFile1.content += "var T1: number;"; + verifyAffectedFiles([moduleFile1]); + }); + + it("should return all files if a global file changed shape", () => { + const { + globalFile3, verifyAffectedAllFiles + } = getInitialState(); + + globalFile3.content += "var T2: string;"; + verifyAffectedAllFiles(); + }); + + it("should always return the file itself if '--isolatedModules' is specified", () => { + const { + moduleFile1, verifyAffectedFiles + } = getInitialState({ configObj: { compilerOptions: { isolatedModules: true } } }); + + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyAffectedFiles([moduleFile1]); + }); + + it("should always return the file itself if '--out' or '--outFile' is specified", () => { + const outFilePath = "/a/b/out.js"; + const { + moduleFile1, verifyAffectedFiles + } = getInitialState({ + configObj: { compilerOptions: { module: "system", outFile: outFilePath } }, + getEmitLine: (_, host) => getEmittedLineForSingleFileOutput(outFilePath, host) + }); + + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyAffectedFiles([moduleFile1]); + }); + + it("should return cascaded affected file list", () => { + const file1Consumer1Consumer1: File = { + path: "/a/b/file1Consumer1Consumer1.ts", + content: `import {y} from "./file1Consumer1";` + }; + const { + moduleFile1, file1Consumer1, file1Consumer2, verifyAffectedFiles, getFile + } = getInitialState({ + getAdditionalFileOrFolder: () => [file1Consumer1Consumer1] + }); + + const file1Consumer1Consumer1Emit = getFile(file1Consumer1Consumer1.path); + file1Consumer1.content += "export var T: number;"; + verifyAffectedFiles([file1Consumer1, file1Consumer1Consumer1Emit]); + + // Doesnt change the shape of file1Consumer1 + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyAffectedFiles([moduleFile1, file1Consumer1, file1Consumer2]); + + // Change both files before the timeout + file1Consumer1.content += "export var T2: number;"; + moduleFile1.content = `export var T2: number;export function Foo() { };`; + verifyAffectedFiles([moduleFile1, file1Consumer1, file1Consumer2, file1Consumer1Consumer1Emit]); + }); + + it("should work fine for files with circular references", () => { + // TODO: do not exit on such errors? Just continue to watch the files for update in watch mode + + const file1: File = { + path: "/a/b/file1.ts", + content: ` + /// + export var t1 = 10;` + }; + const file2: File = { + path: "/a/b/file2.ts", + content: ` + /// + export var t2 = 10;` + }; + const { + configFile, + getFile, + verifyAffectedFiles + } = getInitialState({ + firstCompilationEmitFiles: [file1.path, file2.path], + getAdditionalFileOrFolder: () => [file1, file2], + firstReloadFileList: [libFile.path, file1.path, file2.path, configFilePath] + }); + const file1Emit = getFile(file1.path), file2Emit = getFile(file2.path); + + file1Emit.content += "export var t3 = 10;"; + verifyAffectedFiles([file1Emit, file2Emit], [file1, file2, libFile, configFile]); + + }); + + it("should detect removed code file", () => { + const referenceFile1: File = { + path: "/a/b/referenceFile1.ts", + content: ` + /// + export var x = Foo();` + }; + const { + configFile, + getFile, + verifyAffectedFiles + } = getInitialState({ + firstCompilationEmitFiles: [referenceFile1.path, moduleFile1Path], + getAdditionalFileOrFolder: () => [referenceFile1], + firstReloadFileList: [libFile.path, referenceFile1.path, moduleFile1Path, configFilePath] + }); + + const referenceFile1Emit = getFile(referenceFile1.path); + verifyAffectedFiles([referenceFile1Emit], [libFile, referenceFile1Emit, configFile]); + }); + + it("should detect non-existing code file", () => { + const referenceFile1: File = { + path: "/a/b/referenceFile1.ts", + content: ` + /// + export var x = Foo();` + }; + const { + configFile, + moduleFile2, + getFile, + verifyAffectedFiles + } = getInitialState({ + firstCompilationEmitFiles: [referenceFile1.path], + getAdditionalFileOrFolder: () => [referenceFile1], + firstReloadFileList: [libFile.path, referenceFile1.path, configFilePath] + }); + + const referenceFile1Emit = getFile(referenceFile1.path); + referenceFile1Emit.content += "export var yy = Foo();"; + verifyAffectedFiles([referenceFile1Emit], [libFile, referenceFile1Emit, configFile]); + + // Create module File2 and see both files are saved + verifyAffectedFiles([referenceFile1Emit, moduleFile2], [libFile, moduleFile2, referenceFile1Emit, configFile]); + }); + }); + + describe("unittests:: tsc-watch:: emit file content", () => { + interface EmittedFile extends File { + shouldBeWritten: boolean; + } + function getEmittedFiles(files: FileOrFolderEmit[], contents: string[]): EmittedFile[] { + return map(contents, (content, index) => { + return { + content, + path: changeExtension(files[index].path, Extension.Js), + shouldBeWritten: true + }; + } + ); + } + function verifyEmittedFiles(host: WatchedSystem, emittedFiles: EmittedFile[]) { + for (const { path, content, shouldBeWritten } of emittedFiles) { + if (shouldBeWritten) { + assert.isTrue(host.fileExists(path), `Expected file ${path} to be present`); + assert.equal(host.readFile(path), content, `Contents of file ${path} do not match`); + } + else { + assert.isNotTrue(host.fileExists(path), `Expected file ${path} to be absent`); + } + } + } + + function verifyEmittedFileContents(newLine: string, inputFiles: File[], initialEmittedFileContents: string[], + modifyFiles: (files: FileOrFolderEmit[], emitedFiles: EmittedFile[]) => FileOrFolderEmit[], configFile?: File) { + const host = createWatchedSystem([], { newLine }); + const files = concatenate( + map(inputFiles, file => getFileOrFolderEmit(file, fileToConvert => getEmittedLineForMultiFileOutput(fileToConvert, host))), + configFile ? [libFile, configFile] : [libFile] + ); + const allEmittedFiles = getEmittedLines(files); + host.reloadFS(files); + + // Initial compile + if (configFile) { + createWatchOfConfigFile(configFile.path, host); + } + else { + // First file as the root + createWatchOfFilesAndCompilerOptions([files[0].path], host, { listEmittedFiles: true }); + } + checkOutputContains(host, allEmittedFiles); + + const emittedFiles = getEmittedFiles(files, initialEmittedFileContents); + verifyEmittedFiles(host, emittedFiles); + host.clearOutput(); + + const affectedFiles = modifyFiles(files, emittedFiles); + host.reloadFS(files); + host.checkTimeoutQueueLengthAndRun(1); + checkAffectedLines(host, affectedFiles, allEmittedFiles); + + verifyEmittedFiles(host, emittedFiles); + } + + function verifyNewLine(newLine: string) { + const lines = ["var x = 1;", "var y = 2;"]; + const fileContent = lines.join(newLine); + const f = { + path: "/a/app.ts", + content: fileContent + }; + + verifyEmittedFileContents(newLine, [f], [fileContent + newLine], modifyFiles); + + function modifyFiles(files: FileOrFolderEmit[], emittedFiles: EmittedFile[]) { + files[0].content = fileContent + newLine + "var z = 3;"; + emittedFiles[0].content = files[0].content + newLine; + return [files[0]]; + } + } + + it("handles new lines: \\n", () => { + verifyNewLine("\n"); + }); + + it("handles new lines: \\r\\n", () => { + verifyNewLine("\r\n"); + }); + + it("should emit specified file", () => { + const file1 = { + path: "/a/b/f1.ts", + content: `export function Foo() { return 10; }` + }; + + const file2 = { + path: "/a/b/f2.ts", + content: `import {Foo} from "./f1"; export let y = Foo();` + }; + + const file3 = { + path: "/a/b/f3.ts", + content: `import {y} from "./f2"; let x = y;` + }; + + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: { listEmittedFiles: true } }) + }; + + verifyEmittedFileContents("\r\n", [file1, file2, file3], [ + `"use strict";\r\nexports.__esModule = true;\r\nfunction Foo() { return 10; }\r\nexports.Foo = Foo;\r\n`, + `"use strict";\r\nexports.__esModule = true;\r\nvar f1_1 = require("./f1");\r\nexports.y = f1_1.Foo();\r\n`, + `"use strict";\r\nexports.__esModule = true;\r\nvar f2_1 = require("./f2");\r\nvar x = f2_1.y;\r\n` + ], modifyFiles, configFile); + + function modifyFiles(files: FileOrFolderEmit[], emittedFiles: EmittedFile[]) { + files[0].content += `export function foo2() { return 2; }`; + emittedFiles[0].content += `function foo2() { return 2; }\r\nexports.foo2 = foo2;\r\n`; + emittedFiles[2].shouldBeWritten = false; + return files.slice(0, 2); + } + }); + + it("Elides const enums correctly in incremental compilation", () => { + const currentDirectory = "/user/someone/projects/myproject"; + const file1: File = { + path: `${currentDirectory}/file1.ts`, + content: "export const enum E1 { V = 1 }" + }; + const file2: File = { + path: `${currentDirectory}/file2.ts`, + content: `import { E1 } from "./file1"; export const enum E2 { V = E1.V }` + }; + const file3: File = { + path: `${currentDirectory}/file3.ts`, + content: `import { E2 } from "./file2"; const v: E2 = E2.V;` + }; + const strictAndEsModule = `"use strict";\nexports.__esModule = true;\n`; + verifyEmittedFileContents("\n", [file3, file2, file1], [ + `${strictAndEsModule}var v = 1 /* V */;\n`, + strictAndEsModule, + strictAndEsModule + ], modifyFiles); + + function modifyFiles(files: FileOrFolderEmit[], emittedFiles: EmittedFile[]) { + files[0].content += `function foo2() { return 2; }`; + emittedFiles[0].content += `function foo2() { return 2; }\n`; + emittedFiles[1].shouldBeWritten = false; + emittedFiles[2].shouldBeWritten = false; + return [files[0]]; + } + }); + + it("file is deleted and created as part of change", () => { + const projectLocation = "/home/username/project"; + const file: File = { + path: `${projectLocation}/app/file.ts`, + content: "var a = 10;" + }; + const fileJs = `${projectLocation}/app/file.js`; + const configFile: File = { + path: `${projectLocation}/tsconfig.json`, + content: JSON.stringify({ + include: [ + "app/**/*.ts" + ] + }) + }; + const files = [file, configFile, libFile]; + const host = createWatchedSystem(files, { currentDirectory: projectLocation, useCaseSensitiveFileNames: true }); + createWatchOfConfigFile("tsconfig.json", host); + verifyProgram(); + + file.content += "\nvar b = 10;"; + + host.reloadFS(files, { invokeFileDeleteCreateAsPartInsteadOfChange: true }); + host.runQueuedTimeoutCallbacks(); + verifyProgram(); + + function verifyProgram() { + assert.isTrue(host.fileExists(fileJs)); + assert.equal(host.readFile(fileJs), file.content + "\n"); + } + }); + }); + + describe("unittests:: tsc-watch:: emit with when module emit is specified as node", () => { + it("when instead of filechanged recursive directory watcher is invoked", () => { + const configFile: File = { + path: "/a/rootFolder/project/tsconfig.json", + content: JSON.stringify({ + compilerOptions: { + module: "none", + allowJs: true, + outDir: "Static/scripts/" + }, + include: [ + "Scripts/**/*" + ], + }) + }; + const outputFolder = "/a/rootFolder/project/Static/scripts/"; + const file1: File = { + path: "/a/rootFolder/project/Scripts/TypeScript.ts", + content: "var z = 10;" + }; + const file2: File = { + path: "/a/rootFolder/project/Scripts/Javascript.js", + content: "var zz = 10;" + }; + const files = [configFile, file1, file2, libFile]; + const host = createWatchedSystem(files); + const watch = createWatchOfConfigFile(configFile.path, host); + + checkProgramActualFiles(watch(), mapDefined(files, f => f === configFile ? undefined : f.path)); + file1.content = "var zz30 = 100;"; + host.reloadFS(files, { invokeDirectoryWatcherInsteadOfFileChanged: true }); + host.runQueuedTimeoutCallbacks(); + + checkProgramActualFiles(watch(), mapDefined(files, f => f === configFile ? undefined : f.path)); + const outputFile1 = changeExtension((outputFolder + getBaseFileName(file1.path)), ".js"); + assert.isTrue(host.fileExists(outputFile1)); + assert.equal(host.readFile(outputFile1), file1.content + host.newLine); + }); + }); +} diff --git a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts new file mode 100644 index 00000000000..b76c9a985d4 --- /dev/null +++ b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts @@ -0,0 +1,307 @@ +namespace ts.tscWatch { + describe("unittests:: tsc-watch:: Emit times and Error updates in builder after program changes", () => { + const currentDirectory = "/user/username/projects/myproject"; + const config: File = { + path: `${currentDirectory}/tsconfig.json`, + content: `{}` + }; + function getOutputFileStampAndError(host: WatchedSystem, watch: Watch, file: File) { + const builderProgram = watch.getBuilderProgram(); + const state = builderProgram.getState(); + return { + file, + fileStamp: host.getModifiedTime(file.path.replace(".ts", ".js")), + errors: builderProgram.getSemanticDiagnostics(watch().getSourceFileByPath(file.path as Path)), + errorsFromOldState: !!state.semanticDiagnosticsFromOldState && state.semanticDiagnosticsFromOldState.has(file.path) + }; + } + + function getOutputFileStampsAndErrors(host: WatchedSystem, watch: Watch, directoryFiles: ReadonlyArray) { + return directoryFiles.map(d => getOutputFileStampAndError(host, watch, d)); + } + + function findStampAndErrors(stampsAndErrors: ReadonlyArray>, file: File) { + return find(stampsAndErrors, info => info.file === file)!; + } + + function verifyOutputFileStampsAndErrors( + file: File, + emitExpected: boolean, + errorRefershExpected: boolean, + beforeChangeFileStampsAndErrors: ReadonlyArray>, + afterChangeFileStampsAndErrors: ReadonlyArray> + ) { + const beforeChange = findStampAndErrors(beforeChangeFileStampsAndErrors, file); + const afterChange = findStampAndErrors(afterChangeFileStampsAndErrors, file); + if (emitExpected) { + assert.notStrictEqual(afterChange.fileStamp, beforeChange.fileStamp, `Expected emit for file ${file.path}`); + } + else { + assert.strictEqual(afterChange.fileStamp, beforeChange.fileStamp, `Did not expect new emit for file ${file.path}`); + } + if (errorRefershExpected) { + if (afterChange.errors !== emptyArray || beforeChange.errors !== emptyArray) { + assert.notStrictEqual(afterChange.errors, beforeChange.errors, `Expected new errors for file ${file.path}`); + } + assert.isFalse(afterChange.errorsFromOldState, `Expected errors to be not copied from old state for file ${file.path}`); + } + else { + assert.strictEqual(afterChange.errors, beforeChange.errors, `Expected errors to not change for file ${file.path}`); + assert.isTrue(afterChange.errorsFromOldState, `Expected errors to be copied from old state for file ${file.path}`); + } + } + + interface VerifyEmitAndErrorUpdates { + change: (host: WatchedSystem) => void; + getInitialErrors: (watch: Watch) => ReadonlyArray | ReadonlyArray; + getIncrementalErrors: (watch: Watch) => ReadonlyArray | ReadonlyArray; + filesWithNewEmit: ReadonlyArray; + filesWithOnlyErrorRefresh: ReadonlyArray; + filesNotTouched: ReadonlyArray; + configFile?: File; + } + + function verifyEmitAndErrorUpdates({ filesWithNewEmit, filesWithOnlyErrorRefresh, filesNotTouched, configFile = config, change, getInitialErrors, getIncrementalErrors }: VerifyEmitAndErrorUpdates) { + const nonLibFiles = [...filesWithNewEmit, ...filesWithOnlyErrorRefresh, ...filesNotTouched]; + const files = [...nonLibFiles, configFile, libFile]; + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfConfigFile("tsconfig.json", host); + checkProgramActualFiles(watch(), [...nonLibFiles.map(f => f.path), libFile.path]); + checkOutputErrorsInitial(host, getInitialErrors(watch)); + const beforeChange = getOutputFileStampsAndErrors(host, watch, nonLibFiles); + change(host); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, getIncrementalErrors(watch)); + const afterChange = getOutputFileStampsAndErrors(host, watch, nonLibFiles); + filesWithNewEmit.forEach(file => verifyOutputFileStampsAndErrors(file, /*emitExpected*/ true, /*errorRefershExpected*/ true, beforeChange, afterChange)); + filesWithOnlyErrorRefresh.forEach(file => verifyOutputFileStampsAndErrors(file, /*emitExpected*/ false, /*errorRefershExpected*/ true, beforeChange, afterChange)); + filesNotTouched.forEach(file => verifyOutputFileStampsAndErrors(file, /*emitExpected*/ false, /*errorRefershExpected*/ false, beforeChange, afterChange)); + } + + describe("deep import changes", () => { + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `import {B} from './b'; +declare var console: any; +let b = new B(); +console.log(b.c.d);` + }; + + function verifyDeepImportChange(bFile: File, cFile: File) { + const filesWithNewEmit: File[] = []; + const filesWithOnlyErrorRefresh = [aFile]; + addImportedModule(bFile); + addImportedModule(cFile); + verifyEmitAndErrorUpdates({ + filesWithNewEmit, + filesWithOnlyErrorRefresh, + filesNotTouched: emptyArray, + change: host => host.writeFile(cFile.path, cFile.content.replace("d", "d2")), + getInitialErrors: () => emptyArray, + getIncrementalErrors: watch => [ + getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.lastIndexOf("d"), 1, Diagnostics.Property_0_does_not_exist_on_type_1, "d", "C") + ] + }); + + function addImportedModule(file: File) { + if (file.path.endsWith(".d.ts")) { + filesWithOnlyErrorRefresh.push(file); + } + else { + filesWithNewEmit.push(file); + } + } + } + + it("updates errors when deep import file changes", () => { + const bFile: File = { + path: `${currentDirectory}/b.ts`, + content: `import {C} from './c'; +export class B +{ + c = new C(); +}` + }; + const cFile: File = { + path: `${currentDirectory}/c.ts`, + content: `export class C +{ + d = 1; +}` + }; + verifyDeepImportChange(bFile, cFile); + }); + + it("updates errors when deep import through declaration file changes", () => { + const bFile: File = { + path: `${currentDirectory}/b.d.ts`, + content: `import {C} from './c'; +export class B +{ + c: C; +}` + }; + const cFile: File = { + path: `${currentDirectory}/c.d.ts`, + content: `export class C +{ + d: number; +}` + }; + verifyDeepImportChange(bFile, cFile); + }); + }); + + it("updates errors in file not exporting a deep multilevel import that changes", () => { + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `export interface Point { + name: string; + c: Coords; +} +export interface Coords { + x2: number; + y: number; +}` + }; + const bFile: File = { + path: `${currentDirectory}/b.ts`, + content: `import { Point } from "./a"; +export interface PointWrapper extends Point { +}` + }; + const cFile: File = { + path: `${currentDirectory}/c.ts`, + content: `import { PointWrapper } from "./b"; +export function getPoint(): PointWrapper { + return { + name: "test", + c: { + x: 1, + y: 2 + } + } +};` + }; + const dFile: File = { + path: `${currentDirectory}/d.ts`, + content: `import { getPoint } from "./c"; +getPoint().c.x;` + }; + const eFile: File = { + path: `${currentDirectory}/e.ts`, + content: `import "./d";` + }; + verifyEmitAndErrorUpdates({ + filesWithNewEmit: [aFile, bFile], + filesWithOnlyErrorRefresh: [cFile, dFile], + filesNotTouched: [eFile], + change: host => host.writeFile(aFile.path, aFile.content.replace("x2", "x")), + getInitialErrors: watch => [ + getDiagnosticOfFileFromProgram(watch(), cFile.path, cFile.content.indexOf("x: 1"), 4, chainDiagnosticMessages( + chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, "x", "Coords"), + Diagnostics.Type_0_is_not_assignable_to_type_1, + "{ x: number; y: number; }", + "Coords" + )), + getDiagnosticOfFileFromProgram(watch(), dFile.path, dFile.content.lastIndexOf("x"), 1, Diagnostics.Property_0_does_not_exist_on_type_1, "x", "Coords") + ], + getIncrementalErrors: () => emptyArray + }); + }); + + describe("updates errors when file transitively exported file changes", () => { + const config: File = { + path: `${currentDirectory}/tsconfig.json`, + content: JSON.stringify({ + files: ["app.ts"], + compilerOptions: { baseUrl: "." } + }) + }; + const app: File = { + path: `${currentDirectory}/app.ts`, + content: `import { Data } from "lib2/public"; +export class App { + public constructor() { + new Data().test(); + } +}` + }; + const lib2Public: File = { + path: `${currentDirectory}/lib2/public.ts`, + content: `export * from "./data";` + }; + const lib2Data: File = { + path: `${currentDirectory}/lib2/data.ts`, + content: `import { ITest } from "lib1/public"; +export class Data { + public test() { + const result: ITest = { + title: "title" + } + return result; + } +}` + }; + const lib1Public: File = { + path: `${currentDirectory}/lib1/public.ts`, + content: `export * from "./tools/public";` + }; + const lib1ToolsPublic: File = { + path: `${currentDirectory}/lib1/tools/public.ts`, + content: `export * from "./tools.interface";` + }; + const lib1ToolsInterface: File = { + path: `${currentDirectory}/lib1/tools/tools.interface.ts`, + content: `export interface ITest { + title: string; +}` + }; + + function verifyTransitiveExports(lib2Data: File, lib2Data2?: File) { + const filesWithNewEmit = [lib1ToolsInterface, lib1ToolsPublic]; + const filesWithOnlyErrorRefresh = [app, lib2Public, lib1Public, lib2Data]; + if (lib2Data2) { + filesWithOnlyErrorRefresh.push(lib2Data2); + } + verifyEmitAndErrorUpdates({ + filesWithNewEmit, + filesWithOnlyErrorRefresh, + filesNotTouched: emptyArray, + configFile: config, + change: host => host.writeFile(lib1ToolsInterface.path, lib1ToolsInterface.content.replace("title", "title2")), + getInitialErrors: () => emptyArray, + getIncrementalErrors: () => [ + "lib2/data.ts(5,13): error TS2322: Type '{ title: string; }' is not assignable to type 'ITest'.\n Object literal may only specify known properties, but 'title' does not exist in type 'ITest'. Did you mean to write 'title2'?\n" + ] + }); + } + it("when there are no circular import and exports", () => { + verifyTransitiveExports(lib2Data); + }); + + it("when there are circular import and exports", () => { + const lib2Data: File = { + path: `${currentDirectory}/lib2/data.ts`, + content: `import { ITest } from "lib1/public"; import { Data2 } from "./data2"; +export class Data { + public dat?: Data2; public test() { + const result: ITest = { + title: "title" + } + return result; + } +}` + }; + const lib2Data2: File = { + path: `${currentDirectory}/lib2/data2.ts`, + content: `import { Data } from "./data"; +export class Data2 { + public dat?: Data; +}` + }; + verifyTransitiveExports(lib2Data, lib2Data2); + }); + }); + }); +} diff --git a/src/testRunner/unittests/tscWatch/helpers.ts b/src/testRunner/unittests/tscWatch/helpers.ts new file mode 100644 index 00000000000..b593cabbec6 --- /dev/null +++ b/src/testRunner/unittests/tscWatch/helpers.ts @@ -0,0 +1,203 @@ +namespace ts.tscWatch { + export import WatchedSystem = TestFSWithWatch.TestServerHost; + export type File = TestFSWithWatch.File; + export type SymLink = TestFSWithWatch.SymLink; + export import libFile = TestFSWithWatch.libFile; + export import createWatchedSystem = TestFSWithWatch.createWatchedSystem; + export import checkArray = TestFSWithWatch.checkArray; + export import checkWatchedFiles = TestFSWithWatch.checkWatchedFiles; + export import checkWatchedFilesDetailed = TestFSWithWatch.checkWatchedFilesDetailed; + export import checkWatchedDirectories = TestFSWithWatch.checkWatchedDirectories; + export import checkWatchedDirectoriesDetailed = TestFSWithWatch.checkWatchedDirectoriesDetailed; + export import checkOutputContains = TestFSWithWatch.checkOutputContains; + export import checkOutputDoesNotContain = TestFSWithWatch.checkOutputDoesNotContain; + + export const commonFile1: File = { + path: "/a/b/commonFile1.ts", + content: "let x = 1" + }; + export const commonFile2: File = { + path: "/a/b/commonFile2.ts", + content: "let y = 1" + }; + + export function checkProgramActualFiles(program: Program, expectedFiles: ReadonlyArray) { + checkArray(`Program actual files`, program.getSourceFiles().map(file => file.fileName), expectedFiles); + } + + export function checkProgramRootFiles(program: Program, expectedFiles: ReadonlyArray) { + checkArray(`Program rootFileNames`, program.getRootFileNames(), expectedFiles); + } + + export interface Watch { + (): Program; + getBuilderProgram(): EmitAndSemanticDiagnosticsBuilderProgram; + } + + export function createWatchOfConfigFile(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { + const compilerHost = createWatchCompilerHostOfConfigFile(configFileName, {}, host); + compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation; + const watch = createWatchProgram(compilerHost); + const result = (() => watch.getCurrentProgram().getProgram()) as Watch; + result.getBuilderProgram = () => watch.getCurrentProgram(); + return result; + } + + export function createWatchOfFilesAndCompilerOptions(rootFiles: string[], host: WatchedSystem, options: CompilerOptions = {}, maxNumberOfFilesToIterateForInvalidation?: number) { + const compilerHost = createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, host); + compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation; + const watch = createWatchProgram(compilerHost); + return () => watch.getCurrentProgram().getProgram(); + } + + const elapsedRegex = /^Elapsed:: [0-9]+ms/; + function checkOutputErrors( + host: WatchedSystem, + logsBeforeWatchDiagnostic: string[] | undefined, + preErrorsWatchDiagnostic: Diagnostic, + logsBeforeErrors: string[] | undefined, + errors: ReadonlyArray | ReadonlyArray, + disableConsoleClears?: boolean | undefined, + ...postErrorsWatchDiagnostics: Diagnostic[] + ) { + let screenClears = 0; + const outputs = host.getOutput(); + const expectedOutputCount = 1 + errors.length + postErrorsWatchDiagnostics.length + + (logsBeforeWatchDiagnostic ? logsBeforeWatchDiagnostic.length : 0) + (logsBeforeErrors ? logsBeforeErrors.length : 0); + assert.equal(outputs.length, expectedOutputCount, JSON.stringify(outputs)); + let index = 0; + forEach(logsBeforeWatchDiagnostic, log => assertLog("logsBeforeWatchDiagnostic", log)); + assertWatchDiagnostic(preErrorsWatchDiagnostic); + forEach(logsBeforeErrors, log => assertLog("logBeforeError", log)); + // Verify errors + forEach(errors, assertDiagnostic); + forEach(postErrorsWatchDiagnostics, assertWatchDiagnostic); + assert.equal(host.screenClears.length, screenClears, "Expected number of screen clears"); + host.clearOutput(); + + function isDiagnostic(diagnostic: Diagnostic | string): diagnostic is Diagnostic { + return !!(diagnostic as Diagnostic).messageText; + } + + function assertDiagnostic(diagnostic: Diagnostic | string) { + const expected = isDiagnostic(diagnostic) ? formatDiagnostic(diagnostic, host) : diagnostic; + assert.equal(outputs[index], expected, getOutputAtFailedMessage("Diagnostic", expected)); + index++; + } + + function assertLog(caption: string, expected: string) { + const actual = outputs[index]; + assert.equal(actual.replace(elapsedRegex, ""), expected.replace(elapsedRegex, ""), getOutputAtFailedMessage(caption, expected)); + index++; + } + + function assertWatchDiagnostic(diagnostic: Diagnostic) { + const expected = getWatchDiagnosticWithoutDate(diagnostic); + if (!disableConsoleClears && contains(screenStartingMessageCodes, diagnostic.code)) { + assert.equal(host.screenClears[screenClears], index, `Expected screen clear at this diagnostic: ${expected}`); + screenClears++; + } + assert.isTrue(endsWith(outputs[index], expected), getOutputAtFailedMessage("Watch diagnostic", expected)); + index++; + } + + function getOutputAtFailedMessage(caption: string, expectedOutput: string) { + return `Expected ${caption}: ${JSON.stringify(expectedOutput)} at ${index} in ${JSON.stringify(outputs)}`; + } + + function getWatchDiagnosticWithoutDate(diagnostic: Diagnostic) { + const newLines = contains(screenStartingMessageCodes, diagnostic.code) + ? `${host.newLine}${host.newLine}` + : host.newLine; + return ` - ${flattenDiagnosticMessageText(diagnostic.messageText, host.newLine)}${newLines}`; + } + } + + function createErrorsFoundCompilerDiagnostic(errors: ReadonlyArray | ReadonlyArray) { + return errors.length === 1 + ? createCompilerDiagnostic(Diagnostics.Found_1_error_Watching_for_file_changes) + : createCompilerDiagnostic(Diagnostics.Found_0_errors_Watching_for_file_changes, errors.length); + } + + export function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { + checkOutputErrors( + host, + /*logsBeforeWatchDiagnostic*/ undefined, + createCompilerDiagnostic(Diagnostics.Starting_compilation_in_watch_mode), + logsBeforeErrors, + errors, + disableConsoleClears, + createErrorsFoundCompilerDiagnostic(errors)); + } + + export function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + checkOutputErrors( + host, + logsBeforeWatchDiagnostic, + createCompilerDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation), + logsBeforeErrors, + errors, + disableConsoleClears, + createErrorsFoundCompilerDiagnostic(errors)); + } + + export function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + checkOutputErrors( + host, + logsBeforeWatchDiagnostic, + createCompilerDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation), + logsBeforeErrors, + errors, + disableConsoleClears); + assert.equal(host.exitCode, expectedExitCode); + } + + function isDiagnosticMessageChain(message: DiagnosticMessage | DiagnosticMessageChain): message is DiagnosticMessageChain { + return !!(message as DiagnosticMessageChain).messageText; + } + + export function getDiagnosticOfFileFrom(file: SourceFile | undefined, start: number | undefined, length: number | undefined, message: DiagnosticMessage | DiagnosticMessageChain, ..._args: (string | number)[]): Diagnostic { + let text: DiagnosticMessageChain | string; + if (isDiagnosticMessageChain(message)) { + text = message; + } + else { + text = getLocaleSpecificMessage(message); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + } + return { + file, + start, + length, + + messageText: text, + category: message.category, + code: message.code, + }; + } + + export function getDiagnosticWithoutFile(message: DiagnosticMessage | DiagnosticMessageChain, ...args: (string | number)[]): Diagnostic { + return getDiagnosticOfFileFrom(/*file*/ undefined, /*start*/ undefined, /*length*/ undefined, message, ...args); + } + + export function getDiagnosticOfFile(file: SourceFile, start: number, length: number, message: DiagnosticMessage | DiagnosticMessageChain, ...args: (string | number)[]): Diagnostic { + return getDiagnosticOfFileFrom(file, start, length, message, ...args); + } + + export function getDiagnosticOfFileFromProgram(program: Program, filePath: string, start: number, length: number, message: DiagnosticMessage | DiagnosticMessageChain, ...args: (string | number)[]): Diagnostic { + return getDiagnosticOfFileFrom(program.getSourceFileByPath(toPath(filePath, program.getCurrentDirectory(), s => s.toLowerCase()))!, + start, length, message, ...args); + } + + export function getUnknownCompilerOption(program: Program, configFile: File, option: string) { + const quotedOption = `"${option}"`; + return getDiagnosticOfFile(program.getCompilerOptions().configFile!, configFile.content.indexOf(quotedOption), quotedOption.length, Diagnostics.Unknown_compiler_option_0, option); + } + + export function getDiagnosticModuleNotFoundOfFile(program: Program, file: File, moduleName: string) { + const quotedModuleName = `"${moduleName}"`; + return getDiagnosticOfFileFromProgram(program, file.path, file.content.indexOf(quotedModuleName), quotedModuleName.length, Diagnostics.Cannot_find_module_0, moduleName); + } +} diff --git a/src/testRunner/unittests/tscWatch/programUpdates.ts b/src/testRunner/unittests/tscWatch/programUpdates.ts new file mode 100644 index 00000000000..b322c08bfe7 --- /dev/null +++ b/src/testRunner/unittests/tscWatch/programUpdates.ts @@ -0,0 +1,1339 @@ +namespace ts.tscWatch { + describe("unittests:: tsc-watch:: program updates", () => { + it("create watch without config file", () => { + const appFile: File = { + path: "/a/b/c/app.ts", + content: ` + import {f} from "./module" + console.log(f) + ` + }; + + const moduleFile: File = { + path: "/a/b/c/module.d.ts", + content: `export let x: number` + }; + const host = createWatchedSystem([appFile, moduleFile, libFile]); + const watch = createWatchOfFilesAndCompilerOptions([appFile.path], host); + + checkProgramActualFiles(watch(), [appFile.path, libFile.path, moduleFile.path]); + + // TODO: Should we watch creation of config files in the root file's file hierarchy? + + // const configFileLocations = ["/a/b/c/", "/a/b/", "/a/", "/"]; + // const configFiles = flatMap(configFileLocations, location => [location + "tsconfig.json", location + "jsconfig.json"]); + // checkWatchedFiles(host, configFiles.concat(libFile.path, moduleFile.path)); + }); + + it("can handle tsconfig file name with difference casing", () => { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1" + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ + include: ["app.ts"] + }) + }; + + const host = createWatchedSystem([f1, config], { useCaseSensitiveFileNames: false }); + const upperCaseConfigFilePath = combinePaths(getDirectoryPath(config.path).toUpperCase(), getBaseFileName(config.path)); + const watch = createWatchOfConfigFile(upperCaseConfigFilePath, host); + checkProgramActualFiles(watch(), [combinePaths(getDirectoryPath(upperCaseConfigFilePath), getBaseFileName(f1.path))]); + }); + + it("create configured project without file list", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: ` + { + "compilerOptions": {}, + "exclude": [ + "e" + ] + }` + }; + const file1: File = { + path: "/a/b/c/f1.ts", + content: "let x = 1" + }; + const file2: File = { + path: "/a/b/d/f2.ts", + content: "let y = 1" + }; + const file3: File = { + path: "/a/b/e/f3.ts", + content: "let z = 1" + }; + + const host = createWatchedSystem([configFile, libFile, file1, file2, file3]); + const watch = createWatchProgram(createWatchCompilerHostOfConfigFile(configFile.path, {}, host, /*createProgram*/ undefined, notImplemented)); + + checkProgramActualFiles(watch.getCurrentProgram().getProgram(), [file1.path, libFile.path, file2.path]); + checkProgramRootFiles(watch.getCurrentProgram().getProgram(), [file1.path, file2.path]); + checkWatchedFiles(host, [configFile.path, file1.path, file2.path, libFile.path]); + const configDir = getDirectoryPath(configFile.path); + checkWatchedDirectories(host, [configDir, combinePaths(configDir, projectSystem.nodeModulesAtTypes)], /*recursive*/ true); + }); + + // TODO: if watching for config file creation + // it("add and then remove a config file in a folder with loose files", () => { + // }); + + it("add new files to a configured program without file list", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{}` + }; + const host = createWatchedSystem([commonFile1, libFile, configFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + const configDir = getDirectoryPath(configFile.path); + checkWatchedDirectories(host, [configDir, combinePaths(configDir, projectSystem.nodeModulesAtTypes)], /*recursive*/ true); + + checkProgramRootFiles(watch(), [commonFile1.path]); + + // add a new ts file + host.reloadFS([commonFile1, commonFile2, libFile, configFile]); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); + }); + + it("should ignore non-existing files specified in the config file", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "files": [ + "commonFile1.ts", + "commonFile3.ts" + ] + }` + }; + const host = createWatchedSystem([commonFile1, commonFile2, configFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + + const commonFile3 = "/a/b/commonFile3.ts"; + checkProgramRootFiles(watch(), [commonFile1.path, commonFile3]); + checkProgramActualFiles(watch(), [commonFile1.path]); + }); + + it("handle recreated files correctly", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{}` + }; + const host = createWatchedSystem([commonFile1, commonFile2, configFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); + + // delete commonFile2 + host.reloadFS([commonFile1, configFile]); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramRootFiles(watch(), [commonFile1.path]); + + // re-add commonFile2 + host.reloadFS([commonFile1, commonFile2, configFile]); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); + }); + + it("handles the missing files - that were added to program because they were added with /// { + const commonFile2Name = "commonFile2.ts"; + const file1: File = { + path: "/a/b/commonFile1.ts", + content: `/// + let x = y` + }; + const host = createWatchedSystem([file1, libFile]); + const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); + + checkProgramRootFiles(watch(), [file1.path]); + checkProgramActualFiles(watch(), [file1.path, libFile.path]); + checkOutputErrorsInitial(host, [ + getDiagnosticOfFileFromProgram(watch(), file1.path, file1.content.indexOf(commonFile2Name), commonFile2Name.length, Diagnostics.File_0_not_found, commonFile2.path), + getDiagnosticOfFileFromProgram(watch(), file1.path, file1.content.indexOf("y"), 1, Diagnostics.Cannot_find_name_0, "y") + ]); + + host.reloadFS([file1, commonFile2, libFile]); + host.runQueuedTimeoutCallbacks(); + checkProgramRootFiles(watch(), [file1.path]); + checkProgramActualFiles(watch(), [file1.path, libFile.path, commonFile2.path]); + checkOutputErrorsIncremental(host, emptyArray); + }); + + it("should reflect change in config file", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "files": ["${commonFile1.path}", "${commonFile2.path}"] + }` + }; + const files = [commonFile1, commonFile2, configFile]; + const host = createWatchedSystem(files); + const watch = createWatchOfConfigFile(configFile.path, host); + + checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); + configFile.content = `{ + "compilerOptions": {}, + "files": ["${commonFile1.path}"] + }`; + + host.reloadFS(files); + host.checkTimeoutQueueLengthAndRun(1); // reload the configured project + checkProgramRootFiles(watch(), [commonFile1.path]); + }); + + it("works correctly when config file is changed but its content havent", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "files": ["${commonFile1.path}", "${commonFile2.path}"] + }` + }; + const files = [libFile, commonFile1, commonFile2, configFile]; + const host = createWatchedSystem(files); + const watch = createWatchOfConfigFile(configFile.path, host); + + checkProgramActualFiles(watch(), [libFile.path, commonFile1.path, commonFile2.path]); + checkOutputErrorsInitial(host, emptyArray); + + host.modifyFile(configFile.path, configFile.content); + host.checkTimeoutQueueLengthAndRun(1); // reload the configured project + + checkProgramActualFiles(watch(), [libFile.path, commonFile1.path, commonFile2.path]); + checkOutputErrorsIncremental(host, emptyArray); + }); + + it("Updates diagnostics when '--noUnusedLabels' changes", () => { + const aTs: File = { path: "/a.ts", content: "label: while (1) {}" }; + const files = [libFile, aTs]; + const paths = files.map(f => f.path); + const options = (allowUnusedLabels: boolean) => `{ "compilerOptions": { "allowUnusedLabels": ${allowUnusedLabels} } }`; + const tsconfig: File = { path: "/tsconfig.json", content: options(/*allowUnusedLabels*/ true) }; + + const host = createWatchedSystem([...files, tsconfig]); + const watch = createWatchOfConfigFile(tsconfig.path, host); + + checkProgramActualFiles(watch(), paths); + checkOutputErrorsInitial(host, emptyArray); + + host.modifyFile(tsconfig.path, options(/*allowUnusedLabels*/ false)); + host.checkTimeoutQueueLengthAndRun(1); // reload the configured project + + checkProgramActualFiles(watch(), paths); + checkOutputErrorsIncremental(host, [ + getDiagnosticOfFileFromProgram(watch(), aTs.path, 0, "label".length, Diagnostics.Unused_label), + ]); + + host.modifyFile(tsconfig.path, options(/*allowUnusedLabels*/ true)); + host.checkTimeoutQueueLengthAndRun(1); // reload the configured project + checkProgramActualFiles(watch(), paths); + checkOutputErrorsIncremental(host, emptyArray); + }); + + it("files explicitly excluded in config file", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "exclude": ["/a/c"] + }` + }; + const excludedFile1: File = { + path: "/a/c/excluedFile1.ts", + content: `let t = 1;` + }; + + const host = createWatchedSystem([commonFile1, commonFile2, excludedFile1, configFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); + }); + + it("should properly handle module resolution changes in config file", () => { + const file1: File = { + path: "/a/b/file1.ts", + content: `import { T } from "module1";` + }; + const nodeModuleFile: File = { + path: "/a/b/node_modules/module1.ts", + content: `export interface T {}` + }; + const classicModuleFile: File = { + path: "/a/module1.ts", + content: `export interface T {}` + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "moduleResolution": "node" + }, + "files": ["${file1.path}"] + }` + }; + const files = [file1, nodeModuleFile, classicModuleFile, configFile]; + const host = createWatchedSystem(files); + const watch = createWatchOfConfigFile(configFile.path, host); + checkProgramRootFiles(watch(), [file1.path]); + checkProgramActualFiles(watch(), [file1.path, nodeModuleFile.path]); + + configFile.content = `{ + "compilerOptions": { + "moduleResolution": "classic" + }, + "files": ["${file1.path}"] + }`; + host.reloadFS(files); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramRootFiles(watch(), [file1.path]); + checkProgramActualFiles(watch(), [file1.path, classicModuleFile.path]); + }); + + it("should tolerate config file errors and still try to build a project", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "target": "es6", + "allowAnything": true + }, + "someOtherProperty": {} + }` + }; + const host = createWatchedSystem([commonFile1, commonFile2, libFile, configFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); + }); + + it("changes in files are reflected in project structure", () => { + const file1 = { + path: "/a/b/f1.ts", + content: `export * from "./f2"` + }; + const file2 = { + path: "/a/b/f2.ts", + content: `export let x = 1` + }; + const file3 = { + path: "/a/c/f3.ts", + content: `export let y = 1;` + }; + const host = createWatchedSystem([file1, file2, file3]); + const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); + checkProgramRootFiles(watch(), [file1.path]); + checkProgramActualFiles(watch(), [file1.path, file2.path]); + + const modifiedFile2 = { + path: file2.path, + content: `export * from "../c/f3"` // now inferred project should inclule file3 + }; + + host.reloadFS([file1, modifiedFile2, file3]); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramRootFiles(watch(), [file1.path]); + checkProgramActualFiles(watch(), [file1.path, modifiedFile2.path, file3.path]); + }); + + it("deleted files affect project structure", () => { + const file1 = { + path: "/a/b/f1.ts", + content: `export * from "./f2"` + }; + const file2 = { + path: "/a/b/f2.ts", + content: `export * from "../c/f3"` + }; + const file3 = { + path: "/a/c/f3.ts", + content: `export let y = 1;` + }; + const host = createWatchedSystem([file1, file2, file3]); + const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); + checkProgramActualFiles(watch(), [file1.path, file2.path, file3.path]); + + host.reloadFS([file1, file3]); + host.checkTimeoutQueueLengthAndRun(1); + + checkProgramActualFiles(watch(), [file1.path]); + }); + + it("deleted files affect project structure - 2", () => { + const file1 = { + path: "/a/b/f1.ts", + content: `export * from "./f2"` + }; + const file2 = { + path: "/a/b/f2.ts", + content: `export * from "../c/f3"` + }; + const file3 = { + path: "/a/c/f3.ts", + content: `export let y = 1;` + }; + const host = createWatchedSystem([file1, file2, file3]); + const watch = createWatchOfFilesAndCompilerOptions([file1.path, file3.path], host); + checkProgramActualFiles(watch(), [file1.path, file2.path, file3.path]); + + host.reloadFS([file1, file3]); + host.checkTimeoutQueueLengthAndRun(1); + + checkProgramActualFiles(watch(), [file1.path, file3.path]); + }); + + it("config file includes the file", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "export let x = 5" + }; + const file2 = { + path: "/a/c/f2.ts", + content: `import {x} from "../b/f1"` + }; + const file3 = { + path: "/a/c/f3.ts", + content: "export let y = 1" + }; + const configFile = { + path: "/a/c/tsconfig.json", + content: JSON.stringify({ compilerOptions: {}, files: ["f2.ts", "f3.ts"] }) + }; + + const host = createWatchedSystem([file1, file2, file3, configFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + + checkProgramRootFiles(watch(), [file2.path, file3.path]); + checkProgramActualFiles(watch(), [file1.path, file2.path, file3.path]); + }); + + it("correctly migrate files between projects", () => { + const file1 = { + path: "/a/b/f1.ts", + content: ` + export * from "../c/f2"; + export * from "../d/f3";` + }; + const file2 = { + path: "/a/c/f2.ts", + content: "export let x = 1;" + }; + const file3 = { + path: "/a/d/f3.ts", + content: "export let y = 1;" + }; + const host = createWatchedSystem([file1, file2, file3]); + const watch = createWatchOfFilesAndCompilerOptions([file2.path, file3.path], host); + checkProgramActualFiles(watch(), [file2.path, file3.path]); + + const watch2 = createWatchOfFilesAndCompilerOptions([file1.path], host); + checkProgramActualFiles(watch2(), [file1.path, file2.path, file3.path]); + + // Previous program shouldnt be updated + checkProgramActualFiles(watch(), [file2.path, file3.path]); + host.checkTimeoutQueueLength(0); + }); + + it("can correctly update configured project when set of root files has changed (new file on disk)", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1" + }; + const file2 = { + path: "/a/b/f2.ts", + content: "let y = 1" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: {} }) + }; + + const host = createWatchedSystem([file1, configFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + checkProgramActualFiles(watch(), [file1.path]); + + host.reloadFS([file1, file2, configFile]); + host.checkTimeoutQueueLengthAndRun(1); + + checkProgramActualFiles(watch(), [file1.path, file2.path]); + checkProgramRootFiles(watch(), [file1.path, file2.path]); + }); + + it("can correctly update configured project when set of root files has changed (new file in list of files)", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1" + }; + const file2 = { + path: "/a/b/f2.ts", + content: "let y = 1" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts"] }) + }; + + const host = createWatchedSystem([file1, file2, configFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + + checkProgramActualFiles(watch(), [file1.path]); + + const modifiedConfigFile = { + path: configFile.path, + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }) + }; + + host.reloadFS([file1, file2, modifiedConfigFile]); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramRootFiles(watch(), [file1.path, file2.path]); + checkProgramActualFiles(watch(), [file1.path, file2.path]); + }); + + it("can update configured project when set of root files was not changed", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1" + }; + const file2 = { + path: "/a/b/f2.ts", + content: "let y = 1" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }) + }; + + const host = createWatchedSystem([file1, file2, configFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + checkProgramActualFiles(watch(), [file1.path, file2.path]); + + const modifiedConfigFile = { + path: configFile.path, + content: JSON.stringify({ compilerOptions: { outFile: "out.js" }, files: ["f1.ts", "f2.ts"] }) + }; + + host.reloadFS([file1, file2, modifiedConfigFile]); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramRootFiles(watch(), [file1.path, file2.path]); + checkProgramActualFiles(watch(), [file1.path, file2.path]); + }); + + it("config file is deleted", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1;" + }; + const file2 = { + path: "/a/b/f2.ts", + content: "let y = 2;" + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: {} }) + }; + const host = createWatchedSystem([file1, file2, libFile, config]); + const watch = createWatchOfConfigFile(config.path, host); + + checkProgramActualFiles(watch(), [file1.path, file2.path, libFile.path]); + checkOutputErrorsInitial(host, emptyArray); + + host.reloadFS([file1, file2, libFile]); + host.checkTimeoutQueueLengthAndRun(1); + + checkOutputErrorsIncrementalWithExit(host, [ + getDiagnosticWithoutFile(Diagnostics.File_0_not_found, config.path) + ], ExitStatus.DiagnosticsPresent_OutputsSkipped); + }); + + it("Proper errors: document is not contained in project", () => { + const file1 = { + path: "/a/b/app.ts", + content: "" + }; + const corruptedConfig = { + path: "/a/b/tsconfig.json", + content: "{" + }; + const host = createWatchedSystem([file1, corruptedConfig]); + const watch = createWatchOfConfigFile(corruptedConfig.path, host); + + checkProgramActualFiles(watch(), [file1.path]); + }); + + it("correctly handles changes in lib section of config file", () => { + const libES5 = { + path: "/compiler/lib.es5.d.ts", + content: "declare const eval: any" + }; + const libES2015Promise = { + path: "/compiler/lib.es2015.promise.d.ts", + content: "declare class Promise {}" + }; + const app = { + path: "/src/app.ts", + content: "var x: Promise;" + }; + const config1 = { + path: "/src/tsconfig.json", + content: JSON.stringify( + { + compilerOptions: { + module: "commonjs", + target: "es5", + noImplicitAny: true, + sourceMap: false, + lib: [ + "es5" + ] + } + }) + }; + const config2 = { + path: config1.path, + content: JSON.stringify( + { + compilerOptions: { + module: "commonjs", + target: "es5", + noImplicitAny: true, + sourceMap: false, + lib: [ + "es5", + "es2015.promise" + ] + } + }) + }; + const host = createWatchedSystem([libES5, libES2015Promise, app, config1], { executingFilePath: "/compiler/tsc.js" }); + const watch = createWatchOfConfigFile(config1.path, host); + + checkProgramActualFiles(watch(), [libES5.path, app.path]); + + host.reloadFS([libES5, libES2015Promise, app, config2]); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramActualFiles(watch(), [libES5.path, libES2015Promise.path, app.path]); + }); + + it("should handle non-existing directories in config file", () => { + const f = { + path: "/a/src/app.ts", + content: "let x = 1;" + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions: {}, + include: [ + "src/**/*", + "notexistingfolder/*" + ] + }) + }; + const host = createWatchedSystem([f, config]); + const watch = createWatchOfConfigFile(config.path, host); + checkProgramActualFiles(watch(), [f.path]); + }); + + it("rename a module file and rename back should restore the states for inferred projects", () => { + const moduleFile = { + path: "/a/b/moduleFile.ts", + content: "export function bar() { };" + }; + const file1 = { + path: "/a/b/file1.ts", + content: 'import * as T from "./moduleFile"; T.bar();' + }; + const host = createWatchedSystem([moduleFile, file1, libFile]); + const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); + checkOutputErrorsInitial(host, emptyArray); + + const moduleFileOldPath = moduleFile.path; + const moduleFileNewPath = "/a/b/moduleFile1.ts"; + moduleFile.path = moduleFileNewPath; + host.reloadFS([moduleFile, file1, libFile]); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, [ + getDiagnosticModuleNotFoundOfFile(watch(), file1, "./moduleFile") + ]); + + moduleFile.path = moduleFileOldPath; + host.reloadFS([moduleFile, file1, libFile]); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, emptyArray); + }); + + it("rename a module file and rename back should restore the states for configured projects", () => { + const moduleFile = { + path: "/a/b/moduleFile.ts", + content: "export function bar() { };" + }; + const file1 = { + path: "/a/b/file1.ts", + content: 'import * as T from "./moduleFile"; T.bar();' + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: `{}` + }; + const host = createWatchedSystem([moduleFile, file1, configFile, libFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + checkOutputErrorsInitial(host, emptyArray); + + const moduleFileOldPath = moduleFile.path; + const moduleFileNewPath = "/a/b/moduleFile1.ts"; + moduleFile.path = moduleFileNewPath; + host.reloadFS([moduleFile, file1, configFile, libFile]); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, [ + getDiagnosticModuleNotFoundOfFile(watch(), file1, "./moduleFile") + ]); + + moduleFile.path = moduleFileOldPath; + host.reloadFS([moduleFile, file1, configFile, libFile]); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, emptyArray); + }); + + it("types should load from config file path if config exists", () => { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1" + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: { types: ["node"], typeRoots: [] } }) + }; + const node = { + path: "/a/b/node_modules/@types/node/index.d.ts", + content: "declare var process: any" + }; + const cwd = { + path: "/a/c" + }; + const host = createWatchedSystem([f1, config, node, cwd], { currentDirectory: cwd.path }); + const watch = createWatchOfConfigFile(config.path, host); + + checkProgramActualFiles(watch(), [f1.path, node.path]); + }); + + it("add the missing module file for inferred project: should remove the `module not found` error", () => { + const moduleFile = { + path: "/a/b/moduleFile.ts", + content: "export function bar() { };" + }; + const file1 = { + path: "/a/b/file1.ts", + content: 'import * as T from "./moduleFile"; T.bar();' + }; + const host = createWatchedSystem([file1, libFile]); + const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); + + checkOutputErrorsInitial(host, [ + getDiagnosticModuleNotFoundOfFile(watch(), file1, "./moduleFile") + ]); + + host.reloadFS([file1, moduleFile, libFile]); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, emptyArray); + }); + + it("Configure file diagnostics events are generated when the config file has errors", () => { + const file = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "foo": "bar", + "allowJS": true + } + }` + }; + + const host = createWatchedSystem([file, configFile, libFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + checkOutputErrorsInitial(host, [ + getUnknownCompilerOption(watch(), configFile, "foo"), + getUnknownCompilerOption(watch(), configFile, "allowJS") + ]); + }); + + it("If config file doesnt have errors, they are not reported", () => { + const file = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {} + }` + }; + + const host = createWatchedSystem([file, configFile, libFile]); + createWatchOfConfigFile(configFile.path, host); + checkOutputErrorsInitial(host, emptyArray); + }); + + it("Reports errors when the config file changes", () => { + const file = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {} + }` + }; + + const host = createWatchedSystem([file, configFile, libFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + checkOutputErrorsInitial(host, emptyArray); + + configFile.content = `{ + "compilerOptions": { + "haha": 123 + } + }`; + host.reloadFS([file, configFile, libFile]); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, [ + getUnknownCompilerOption(watch(), configFile, "haha") + ]); + + configFile.content = `{ + "compilerOptions": {} + }`; + host.reloadFS([file, configFile, libFile]); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, emptyArray); + }); + + it("non-existing directories listed in config file input array should be tolerated without crashing the server", () => { + const configFile = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "include": ["app/*", "test/**/*", "something"] + }` + }; + const file1 = { + path: "/a/b/file1.ts", + content: "let t = 10;" + }; + + const host = createWatchedSystem([file1, configFile, libFile]); + const watch = createWatchOfConfigFile(configFile.path, host); + + checkProgramActualFiles(watch(), emptyArray); + checkOutputErrorsInitial(host, [ + "error TS18003: No inputs were found in config file '/a/b/tsconfig.json'. Specified 'include' paths were '[\"app/*\",\"test/**/*\",\"something\"]' and 'exclude' paths were '[]'.\n" + ]); + }); + + it("non-existing directories listed in config file input array should be able to handle @types if input file list is empty", () => { + const f = { + path: "/a/app.ts", + content: "let x = 1" + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compiler: {}, + files: [] + }) + }; + const t1 = { + path: "/a/node_modules/@types/typings/index.d.ts", + content: `export * from "./lib"` + }; + const t2 = { + path: "/a/node_modules/@types/typings/lib.d.ts", + content: `export const x: number` + }; + const host = createWatchedSystem([f, config, t1, t2], { currentDirectory: getDirectoryPath(f.path) }); + const watch = createWatchOfConfigFile(config.path, host); + + checkProgramActualFiles(watch(), emptyArray); + checkOutputErrorsInitial(host, [ + "tsconfig.json(1,24): error TS18002: The 'files' list in config file '/a/tsconfig.json' is empty.\n" + ]); + }); + + it("should support files without extensions", () => { + const f = { + path: "/a/compile", + content: "let x = 1" + }; + const host = createWatchedSystem([f, libFile]); + const watch = createWatchOfFilesAndCompilerOptions([f.path], host, { allowNonTsExtensions: true }); + checkProgramActualFiles(watch(), [f.path, libFile.path]); + }); + + it("Options Diagnostic locations reported correctly with changes in configFile contents when options change", () => { + const file = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const configFileContentBeforeComment = `{`; + const configFileContentComment = ` + // comment + // More comment`; + const configFileContentAfterComment = ` + "compilerOptions": { + "allowJs": true, + "declaration": true + } + }`; + const configFileContentWithComment = configFileContentBeforeComment + configFileContentComment + configFileContentAfterComment; + const configFileContentWithoutCommentLine = configFileContentBeforeComment + configFileContentAfterComment; + const configFile = { + path: "/a/b/tsconfig.json", + content: configFileContentWithComment + }; + + const files = [file, libFile, configFile]; + const host = createWatchedSystem(files); + const watch = createWatchOfConfigFile(configFile.path, host); + const errors = () => [ + getDiagnosticOfFile(watch().getCompilerOptions().configFile!, configFile.content.indexOf('"allowJs"'), '"allowJs"'.length, Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"), + getDiagnosticOfFile(watch().getCompilerOptions().configFile!, configFile.content.indexOf('"declaration"'), '"declaration"'.length, Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration") + ]; + const intialErrors = errors(); + checkOutputErrorsInitial(host, intialErrors); + + configFile.content = configFileContentWithoutCommentLine; + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + const nowErrors = errors(); + checkOutputErrorsIncremental(host, nowErrors); + assert.equal(nowErrors[0].start, intialErrors[0].start! - configFileContentComment.length); + assert.equal(nowErrors[1].start, intialErrors[1].start! - configFileContentComment.length); + }); + + describe("should not trigger should not trigger recompilation because of program emit", () => { + function verifyWithOptions(options: CompilerOptions, outputFiles: ReadonlyArray) { + const proj = "/user/username/projects/myproject"; + const file1: File = { + path: `${proj}/file1.ts`, + content: "export const c = 30;" + }; + const file2: File = { + path: `${proj}/src/file2.ts`, + content: `import {c} from "file1"; export const d = 30;` + }; + const tsconfig: File = { + path: `${proj}/tsconfig.json`, + content: generateTSConfig(options, emptyArray, "\n") + }; + const host = createWatchedSystem([file1, file2, libFile, tsconfig], { currentDirectory: proj }); + const watch = createWatchOfConfigFile(tsconfig.path, host, /*maxNumberOfFilesToIterateForInvalidation*/1); + checkProgramActualFiles(watch(), [file1.path, file2.path, libFile.path]); + + outputFiles.forEach(f => host.fileExists(f)); + + // This should be 0 + host.checkTimeoutQueueLengthAndRun(0); + } + + it("without outDir or outFile is specified", () => { + verifyWithOptions({ module: ModuleKind.AMD }, ["file1.js", "src/file2.js"]); + }); + + it("with outFile", () => { + verifyWithOptions({ module: ModuleKind.AMD, outFile: "build/outFile.js" }, ["build/outFile.js"]); + }); + + it("when outDir is specified", () => { + verifyWithOptions({ module: ModuleKind.AMD, outDir: "build" }, ["build/file1.js", "build/src/file2.js"]); + }); + + it("when outDir and declarationDir is specified", () => { + verifyWithOptions({ module: ModuleKind.AMD, outDir: "build", declaration: true, declarationDir: "decls" }, + ["build/file1.js", "build/src/file2.js", "decls/file1.d.ts", "decls/src/file2.d.ts"]); + }); + + it("declarationDir is specified", () => { + verifyWithOptions({ module: ModuleKind.AMD, declaration: true, declarationDir: "decls" }, + ["file1.js", "src/file2.js", "decls/file1.d.ts", "decls/src/file2.d.ts"]); + }); + }); + + it("shouldnt report error about unused function incorrectly when file changes from global to module", () => { + const getFileContent = (asModule: boolean) => ` + function one() {} + ${asModule ? "export " : ""}function two() { + return function three() { + one(); + } + }`; + const file: File = { + path: "/a/b/file.ts", + content: getFileContent(/*asModule*/ false) + }; + const files = [file, libFile]; + const host = createWatchedSystem(files); + const watch = createWatchOfFilesAndCompilerOptions([file.path], host, { + noUnusedLocals: true + }); + checkProgramActualFiles(watch(), files.map(file => file.path)); + checkOutputErrorsInitial(host, []); + + file.content = getFileContent(/*asModule*/ true); + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), files.map(file => file.path)); + checkOutputErrorsIncremental(host, emptyArray); + }); + + it("watched files when file is deleted and new file is added as part of change", () => { + const projectLocation = "/home/username/project"; + const file: File = { + path: `${projectLocation}/src/file1.ts`, + content: "var a = 10;" + }; + const configFile: File = { + path: `${projectLocation}/tsconfig.json`, + content: "{}" + }; + const files = [file, libFile, configFile]; + const host = createWatchedSystem(files); + const watch = createWatchOfConfigFile(configFile.path, host); + verifyProgram(); + + file.path = file.path.replace("file1", "file2"); + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + verifyProgram(); + + function verifyProgram() { + checkProgramActualFiles(watch(), mapDefined(files, f => f === configFile ? undefined : f.path)); + checkWatchedDirectories(host, [], /*recursive*/ false); + checkWatchedDirectories(host, [projectLocation, `${projectLocation}/node_modules/@types`], /*recursive*/ true); + checkWatchedFiles(host, files.map(f => f.path)); + } + }); + + it("updates errors correctly when declaration emit is disabled in compiler options", () => { + const currentDirectory = "/user/username/projects/myproject"; + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `import test from './b'; +test(4, 5);` + }; + const bFileContent = `function test(x: number, y: number) { + return x + y / 5; +} +export default test;`; + const bFile: File = { + path: `${currentDirectory}/b.ts`, + content: bFileContent + }; + const tsconfigFile: File = { + path: `${currentDirectory}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "commonjs", + noEmit: true, + strict: true, + } + }) + }; + const files = [aFile, bFile, libFile, tsconfigFile]; + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfConfigFile("tsconfig.json", host); + checkOutputErrorsInitial(host, emptyArray); + + changeParameterType("x", "string", [ + getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.indexOf("4"), 1, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, "4", "string") + ]); + changeParameterType("y", "string", [ + getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.indexOf("5"), 1, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, "5", "string"), + getDiagnosticOfFileFromProgram(watch(), bFile.path, bFile.content.indexOf("y /"), 1, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type) + ]); + + function changeParameterType(parameterName: string, toType: string, expectedErrors: ReadonlyArray) { + const newContent = bFileContent.replace(new RegExp(`${parameterName}\: [a-z]*`), `${parameterName}: ${toType}`); + + verifyErrorsWithBFileContents(newContent, expectedErrors); + verifyErrorsWithBFileContents(bFileContent, emptyArray); + } + + function verifyErrorsWithBFileContents(content: string, expectedErrors: ReadonlyArray) { + host.writeFile(bFile.path, content); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, expectedErrors); + } + }); + + it("updates errors when strictNullChecks changes", () => { + const currentDirectory = "/user/username/projects/myproject"; + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `declare function foo(): null | { hello: any }; +foo().hello` + }; + const config: File = { + path: `${currentDirectory}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: {} }) + }; + const files = [aFile, config, libFile]; + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfConfigFile("tsconfig.json", host); + checkProgramActualFiles(watch(), [aFile.path, libFile.path]); + checkOutputErrorsInitial(host, emptyArray); + const modifiedTimeOfAJs = host.getModifiedTime(`${currentDirectory}/a.js`); + host.writeFile(config.path, JSON.stringify({ compilerOptions: { strictNullChecks: true } })); + host.runQueuedTimeoutCallbacks(); + const expectedStrictNullErrors = [ + getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.lastIndexOf("foo()"), 5, Diagnostics.Object_is_possibly_null) + ]; + checkOutputErrorsIncremental(host, expectedStrictNullErrors); + // File a need not be rewritten + assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); + host.writeFile(config.path, JSON.stringify({ compilerOptions: { strict: true, alwaysStrict: false } })); // Avoid changing 'alwaysStrict' or must re-bind + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, expectedStrictNullErrors); + // File a need not be rewritten + assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); + host.writeFile(config.path, JSON.stringify({ compilerOptions: {} })); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, emptyArray); + // File a need not be rewritten + assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); + }); + + it("updates errors when ambient modules of program changes", () => { + const currentDirectory = "/user/username/projects/myproject"; + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `declare module 'a' { + type foo = number; +}` + }; + const config: File = { + path: `${currentDirectory}/tsconfig.json`, + content: "{}" + }; + const files = [aFile, config, libFile]; + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfConfigFile("tsconfig.json", host); + checkProgramActualFiles(watch(), [aFile.path, libFile.path]); + checkOutputErrorsInitial(host, emptyArray); + + // Create bts with same file contents + const bTsPath = `${currentDirectory}/b.ts`; + host.writeFile(bTsPath, aFile.content); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), [aFile.path, "b.ts", libFile.path]); + checkOutputErrorsIncremental(host, [ + "a.ts(2,8): error TS2300: Duplicate identifier 'foo'.\n", + "b.ts(2,8): error TS2300: Duplicate identifier 'foo'.\n" + ]); + + // Delete bTs + host.deleteFile(bTsPath); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), [aFile.path, libFile.path]); + checkOutputErrorsIncremental(host, emptyArray); + }); + + describe("updates errors in lib file", () => { + const currentDirectory = "/user/username/projects/myproject"; + const field = "fullscreen"; + const fieldWithoutReadonly = `interface Document { + ${field}: boolean; +}`; + + const libFileWithDocument: File = { + path: libFile.path, + content: `${libFile.content} +interface Document { + readonly ${field}: boolean; +}` + }; + + function getDiagnostic(program: Program, file: File) { + return getDiagnosticOfFileFromProgram(program, file.path, file.content.indexOf(field), field.length, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, field); + } + + function verifyLibFileErrorsWith(aFile: File) { + const files = [aFile, libFileWithDocument]; + + function verifyLibErrors(options: CompilerOptions) { + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfFilesAndCompilerOptions([aFile.path], host, options); + checkProgramActualFiles(watch(), [aFile.path, libFile.path]); + checkOutputErrorsInitial(host, getErrors()); + + host.writeFile(aFile.path, aFile.content.replace(fieldWithoutReadonly, "var x: string;")); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), [aFile.path, libFile.path]); + checkOutputErrorsIncremental(host, emptyArray); + + host.writeFile(aFile.path, aFile.content); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), [aFile.path, libFile.path]); + checkOutputErrorsIncremental(host, getErrors()); + + function getErrors() { + return [ + ...(options.skipLibCheck || options.skipDefaultLibCheck ? [] : [getDiagnostic(watch(), libFileWithDocument)]), + getDiagnostic(watch(), aFile) + ]; + } + } + + it("with default options", () => { + verifyLibErrors({}); + }); + it("with skipLibCheck", () => { + verifyLibErrors({ skipLibCheck: true }); + }); + it("with skipDefaultLibCheck", () => { + verifyLibErrors({ skipDefaultLibCheck: true }); + }); + } + + describe("when non module file changes", () => { + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `${fieldWithoutReadonly} +var y: number;` + }; + verifyLibFileErrorsWith(aFile); + }); + + describe("when module file with global definitions changes", () => { + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `export {} +declare global { +${fieldWithoutReadonly} +var y: number; +}` + }; + verifyLibFileErrorsWith(aFile); + }); + }); + + it("when skipLibCheck and skipDefaultLibCheck changes", () => { + const currentDirectory = "/user/username/projects/myproject"; + const field = "fullscreen"; + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `interface Document { + ${field}: boolean; +}` + }; + const bFile: File = { + path: `${currentDirectory}/b.d.ts`, + content: `interface Document { + ${field}: boolean; +}` + }; + const libFileWithDocument: File = { + path: libFile.path, + content: `${libFile.content} +interface Document { + readonly ${field}: boolean; +}` + }; + const configFile: File = { + path: `${currentDirectory}/tsconfig.json`, + content: "{}" + }; + + const files = [aFile, bFile, configFile, libFileWithDocument]; + + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfConfigFile("tsconfig.json", host); + verifyProgramFiles(); + checkOutputErrorsInitial(host, [ + getDiagnostic(libFileWithDocument), + getDiagnostic(aFile), + getDiagnostic(bFile) + ]); + + verifyConfigChange({ skipLibCheck: true }, [aFile]); + verifyConfigChange({ skipDefaultLibCheck: true }, [aFile, bFile]); + verifyConfigChange({}, [libFileWithDocument, aFile, bFile]); + verifyConfigChange({ skipDefaultLibCheck: true }, [aFile, bFile]); + verifyConfigChange({ skipLibCheck: true }, [aFile]); + verifyConfigChange({}, [libFileWithDocument, aFile, bFile]); + + function verifyConfigChange(compilerOptions: CompilerOptions, errorInFiles: ReadonlyArray) { + host.writeFile(configFile.path, JSON.stringify({ compilerOptions })); + host.runQueuedTimeoutCallbacks(); + verifyProgramFiles(); + checkOutputErrorsIncremental(host, errorInFiles.map(getDiagnostic)); + } + + function getDiagnostic(file: File) { + return getDiagnosticOfFileFromProgram(watch(), file.path, file.content.indexOf(field), field.length, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, field); + } + + function verifyProgramFiles() { + checkProgramActualFiles(watch(), [aFile.path, bFile.path, libFile.path]); + } + }); + + it("reports errors correctly with isolatedModules", () => { + const currentDirectory = "/user/username/projects/myproject"; + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `export const a: string = "";` + }; + const bFile: File = { + path: `${currentDirectory}/b.ts`, + content: `import { a } from "./a"; +const b: string = a;` + }; + const configFile: File = { + path: `${currentDirectory}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + isolatedModules: true + } + }) + }; + + const files = [aFile, bFile, libFile, configFile]; + + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfConfigFile("tsconfig.json", host); + verifyProgramFiles(); + checkOutputErrorsInitial(host, emptyArray); + assert.equal(host.readFile(`${currentDirectory}/a.js`), `"use strict"; +exports.__esModule = true; +exports.a = ""; +`, "Contents of a.js"); + assert.equal(host.readFile(`${currentDirectory}/b.js`), `"use strict"; +exports.__esModule = true; +var a_1 = require("./a"); +var b = a_1.a; +`, "Contents of b.js"); + const modifiedTime = host.getModifiedTime(`${currentDirectory}/b.js`); + + host.writeFile(aFile.path, `export const a: number = 1`); + host.runQueuedTimeoutCallbacks(); + verifyProgramFiles(); + checkOutputErrorsIncremental(host, [ + getDiagnosticOfFileFromProgram(watch(), bFile.path, bFile.content.indexOf("b"), 1, Diagnostics.Type_0_is_not_assignable_to_type_1, "number", "string") + ]); + assert.equal(host.readFile(`${currentDirectory}/a.js`), `"use strict"; +exports.__esModule = true; +exports.a = 1; +`, "Contents of a.js"); + assert.equal(host.getModifiedTime(`${currentDirectory}/b.js`), modifiedTime, "Timestamp of b.js"); + + function verifyProgramFiles() { + checkProgramActualFiles(watch(), [aFile.path, bFile.path, libFile.path]); + } + }); + }); +} diff --git a/src/testRunner/unittests/tscWatch/resolutionCache.ts b/src/testRunner/unittests/tscWatch/resolutionCache.ts new file mode 100644 index 00000000000..b29fde85697 --- /dev/null +++ b/src/testRunner/unittests/tscWatch/resolutionCache.ts @@ -0,0 +1,448 @@ +namespace ts.tscWatch { + describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution caching", () => { + it("works", () => { + const root = { + path: "/a/d/f0.ts", + content: `import {x} from "f1"` + }; + const imported = { + path: "/a/f1.ts", + content: `foo()` + }; + + const files = [root, imported, libFile]; + const host = createWatchedSystem(files); + const watch = createWatchOfFilesAndCompilerOptions([root.path], host, { module: ModuleKind.AMD }); + + const f1IsNotModule = getDiagnosticOfFileFromProgram(watch(), root.path, root.content.indexOf('"f1"'), '"f1"'.length, Diagnostics.File_0_is_not_a_module, imported.path); + const cannotFindFoo = getDiagnosticOfFileFromProgram(watch(), imported.path, imported.content.indexOf("foo"), "foo".length, Diagnostics.Cannot_find_name_0, "foo"); + + // ensure that imported file was found + checkOutputErrorsInitial(host, [f1IsNotModule, cannotFindFoo]); + + const originalFileExists = host.fileExists; + { + const newContent = `import {x} from "f1" + var x: string = 1;`; + root.content = newContent; + host.reloadFS(files); + + // patch fileExists to make sure that disk is not touched + host.fileExists = notImplemented; + + // trigger synchronization to make sure that import will be fetched from the cache + host.runQueuedTimeoutCallbacks(); + + // ensure file has correct number of errors after edit + checkOutputErrorsIncremental(host, [ + f1IsNotModule, + getDiagnosticOfFileFromProgram(watch(), root.path, newContent.indexOf("var x") + "var ".length, "x".length, Diagnostics.Type_0_is_not_assignable_to_type_1, 1, "string"), + cannotFindFoo + ]); + } + { + let fileExistsIsCalled = false; + host.fileExists = (fileName): boolean => { + if (fileName === "lib.d.ts") { + return false; + } + fileExistsIsCalled = true; + assert.isTrue(fileName.indexOf("/f2.") !== -1); + return originalFileExists.call(host, fileName); + }; + + root.content = `import {x} from "f2"`; + host.reloadFS(files); + + // trigger synchronization to make sure that LSHost will try to find 'f2' module on disk + host.runQueuedTimeoutCallbacks(); + + // ensure file has correct number of errors after edit + checkOutputErrorsIncremental(host, [ + getDiagnosticModuleNotFoundOfFile(watch(), root, "f2") + ]); + + assert.isTrue(fileExistsIsCalled); + } + { + let fileExistsCalled = false; + host.fileExists = (fileName): boolean => { + if (fileName === "lib.d.ts") { + return false; + } + fileExistsCalled = true; + assert.isTrue(fileName.indexOf("/f1.") !== -1); + return originalFileExists.call(host, fileName); + }; + + const newContent = `import {x} from "f1"`; + root.content = newContent; + + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + + checkOutputErrorsIncremental(host, [f1IsNotModule, cannotFindFoo]); + assert.isTrue(fileExistsCalled); + } + }); + + it("loads missing files from disk", () => { + const root = { + path: `/a/foo.ts`, + content: `import {x} from "bar"` + }; + + const imported = { + path: `/a/bar.d.ts`, + content: `export const y = 1;` + }; + + const files = [root, libFile]; + const host = createWatchedSystem(files); + const originalFileExists = host.fileExists; + + let fileExistsCalledForBar = false; + host.fileExists = fileName => { + if (fileName === "lib.d.ts") { + return false; + } + if (!fileExistsCalledForBar) { + fileExistsCalledForBar = fileName.indexOf("/bar.") !== -1; + } + + return originalFileExists.call(host, fileName); + }; + + const watch = createWatchOfFilesAndCompilerOptions([root.path], host, { module: ModuleKind.AMD }); + + assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called"); + checkOutputErrorsInitial(host, [ + getDiagnosticModuleNotFoundOfFile(watch(), root, "bar") + ]); + + fileExistsCalledForBar = false; + root.content = `import {y} from "bar"`; + host.reloadFS(files.concat(imported)); + + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, emptyArray); + assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called."); + }); + + it("should compile correctly when resolved module goes missing and then comes back (module is not part of the root)", () => { + const root = { + path: `/a/foo.ts`, + content: `import {x} from "bar"` + }; + + const imported = { + path: `/a/bar.d.ts`, + content: `export const y = 1;export const x = 10;` + }; + + const files = [root, libFile]; + const filesWithImported = files.concat(imported); + const host = createWatchedSystem(filesWithImported); + const originalFileExists = host.fileExists; + let fileExistsCalledForBar = false; + host.fileExists = fileName => { + if (fileName === "lib.d.ts") { + return false; + } + if (!fileExistsCalledForBar) { + fileExistsCalledForBar = fileName.indexOf("/bar.") !== -1; + } + return originalFileExists.call(host, fileName); + }; + + const watch = createWatchOfFilesAndCompilerOptions([root.path], host, { module: ModuleKind.AMD }); + + assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called"); + checkOutputErrorsInitial(host, emptyArray); + + fileExistsCalledForBar = false; + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called."); + checkOutputErrorsIncremental(host, [ + getDiagnosticModuleNotFoundOfFile(watch(), root, "bar") + ]); + + fileExistsCalledForBar = false; + host.reloadFS(filesWithImported); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called."); + }); + + it("works when module resolution changes to ambient module", () => { + const root = { + path: "/a/b/foo.ts", + content: `import * as fs from "fs";` + }; + + const packageJson = { + path: "/a/b/node_modules/@types/node/package.json", + content: ` +{ + "main": "" +} +` + }; + + const nodeType = { + path: "/a/b/node_modules/@types/node/index.d.ts", + content: ` +declare module "fs" { + export interface Stats { + isFile(): boolean; + } +}` + }; + + const files = [root, libFile]; + const filesWithNodeType = files.concat(packageJson, nodeType); + const host = createWatchedSystem(files, { currentDirectory: "/a/b" }); + + const watch = createWatchOfFilesAndCompilerOptions([root.path], host, { }); + + checkOutputErrorsInitial(host, [ + getDiagnosticModuleNotFoundOfFile(watch(), root, "fs") + ]); + + host.reloadFS(filesWithNodeType); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, emptyArray); + }); + + it("works when included file with ambient module changes", () => { + const root = { + path: "/a/b/foo.ts", + content: ` +import * as fs from "fs"; +import * as u from "url"; +` + }; + + const file = { + path: "/a/b/bar.d.ts", + content: ` +declare module "url" { + export interface Url { + href?: string; + } +} +` + }; + + const fileContentWithFS = ` +declare module "fs" { + export interface Stats { + isFile(): boolean; + } +} +`; + + const files = [root, file, libFile]; + const host = createWatchedSystem(files, { currentDirectory: "/a/b" }); + + const watch = createWatchOfFilesAndCompilerOptions([root.path, file.path], host, {}); + + checkOutputErrorsInitial(host, [ + getDiagnosticModuleNotFoundOfFile(watch(), root, "fs") + ]); + + file.content += fileContentWithFS; + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, emptyArray); + }); + + it("works when reusing program with files from external library", () => { + interface ExpectedFile { path: string; isExpectedToEmit?: boolean; content?: string; } + const configDir = "/a/b/projects/myProject/src/"; + const file1: File = { + path: configDir + "file1.ts", + content: 'import module1 = require("module1");\nmodule1("hello");' + }; + const file2: File = { + path: configDir + "file2.ts", + content: 'import module11 = require("module1");\nmodule11("hello");' + }; + const module1: File = { + path: "/a/b/projects/myProject/node_modules/module1/index.js", + content: "module.exports = options => { return options.toString(); }" + }; + const configFile: File = { + path: configDir + "tsconfig.json", + content: JSON.stringify({ + compilerOptions: { + allowJs: true, + rootDir: ".", + outDir: "../dist", + moduleResolution: "node", + maxNodeModuleJsDepth: 1 + } + }) + }; + const outDirFolder = "/a/b/projects/myProject/dist/"; + const programFiles = [file1, file2, module1, libFile]; + const host = createWatchedSystem(programFiles.concat(configFile), { currentDirectory: "/a/b/projects/myProject/" }); + const watch = createWatchOfConfigFile(configFile.path, host); + checkProgramActualFiles(watch(), programFiles.map(f => f.path)); + checkOutputErrorsInitial(host, emptyArray); + const expectedFiles: ExpectedFile[] = [ + createExpectedEmittedFile(file1), + createExpectedEmittedFile(file2), + createExpectedToNotEmitFile("index.js"), + createExpectedToNotEmitFile("src/index.js"), + createExpectedToNotEmitFile("src/file1.js"), + createExpectedToNotEmitFile("src/file2.js"), + createExpectedToNotEmitFile("lib.js"), + createExpectedToNotEmitFile("lib.d.ts") + ]; + verifyExpectedFiles(expectedFiles); + + file1.content += "\n;"; + expectedFiles[0].content += ";\n"; // Only emit file1 with this change + expectedFiles[1].isExpectedToEmit = false; + host.reloadFS(programFiles.concat(configFile)); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), programFiles.map(f => f.path)); + checkOutputErrorsIncremental(host, emptyArray); + verifyExpectedFiles(expectedFiles); + + + function verifyExpectedFiles(expectedFiles: ExpectedFile[]) { + forEach(expectedFiles, f => { + assert.equal(!!host.fileExists(f.path), f.isExpectedToEmit, "File " + f.path + " is expected to " + (f.isExpectedToEmit ? "emit" : "not emit")); + if (f.isExpectedToEmit) { + assert.equal(host.readFile(f.path), f.content, "Expected contents of " + f.path); + } + }); + } + + function createExpectedToNotEmitFile(fileName: string): ExpectedFile { + return { + path: outDirFolder + fileName, + isExpectedToEmit: false + }; + } + + function createExpectedEmittedFile(file: File): ExpectedFile { + return { + path: removeFileExtension(file.path.replace(configDir, outDirFolder)) + Extension.Js, + isExpectedToEmit: true, + content: '"use strict";\nexports.__esModule = true;\n' + file.content.replace("import", "var") + "\n" + }; + } + }); + + it("works when renaming node_modules folder that already contains @types folder", () => { + const currentDirectory = "/user/username/projects/myproject"; + const file: File = { + path: `${currentDirectory}/a.ts`, + content: `import * as q from "qqq";` + }; + const module: File = { + path: `${currentDirectory}/node_modules2/@types/qqq/index.d.ts`, + content: "export {}" + }; + const files = [file, module, libFile]; + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfFilesAndCompilerOptions([file.path], host); + + checkProgramActualFiles(watch(), [file.path, libFile.path]); + checkOutputErrorsInitial(host, [getDiagnosticModuleNotFoundOfFile(watch(), file, "qqq")]); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, [`${currentDirectory}/node_modules`, `${currentDirectory}/node_modules/@types`], /*recursive*/ true); + + host.renameFolder(`${currentDirectory}/node_modules2`, `${currentDirectory}/node_modules`); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), [file.path, libFile.path, `${currentDirectory}/node_modules/@types/qqq/index.d.ts`]); + checkOutputErrorsIncremental(host, emptyArray); + }); + + describe("ignores files/folder changes in node_modules that start with '.'", () => { + const projectPath = "/user/username/projects/project"; + const npmCacheFile: File = { + path: `${projectPath}/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.ts`, + content: JSON.stringify({ something: 10 }) + }; + const file1: File = { + path: `${projectPath}/test.ts`, + content: `import { x } from "somemodule";` + }; + const file2: File = { + path: `${projectPath}/node_modules/somemodule/index.d.ts`, + content: `export const x = 10;` + }; + const files = [libFile, file1, file2]; + const expectedFiles = files.map(f => f.path); + it("when watching node_modules in inferred project for failed lookup", () => { + const host = createWatchedSystem(files); + const watch = createWatchOfFilesAndCompilerOptions([file1.path], host, {}, /*maxNumberOfFilesToIterateForInvalidation*/ 1); + checkProgramActualFiles(watch(), expectedFiles); + host.checkTimeoutQueueLength(0); + + host.ensureFileOrFolder(npmCacheFile); + host.checkTimeoutQueueLength(0); + }); + it("when watching node_modules as part of wild card directories in config project", () => { + const config: File = { + path: `${projectPath}/tsconfig.json`, + content: "{}" + }; + const host = createWatchedSystem(files.concat(config)); + const watch = createWatchOfConfigFile(config.path, host); + checkProgramActualFiles(watch(), expectedFiles); + host.checkTimeoutQueueLength(0); + + host.ensureFileOrFolder(npmCacheFile); + host.checkTimeoutQueueLength(0); + }); + }); + }); + + describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch with modules linked to sibling folder", () => { + const projectRoot = "/user/username/projects/project"; + const mainPackageRoot = `${projectRoot}/main`; + const linkedPackageRoot = `${projectRoot}/linked-package`; + const mainFile: File = { + path: `${mainPackageRoot}/index.ts`, + content: "import { Foo } from '@scoped/linked-package'" + }; + const config: File = { + path: `${mainPackageRoot}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { module: "commonjs", moduleResolution: "node", baseUrl: ".", rootDir: "." }, + files: ["index.ts"] + }) + }; + const linkedPackageInMain: SymLink = { + path: `${mainPackageRoot}/node_modules/@scoped/linked-package`, + symLink: `${linkedPackageRoot}` + }; + const linkedPackageJson: File = { + path: `${linkedPackageRoot}/package.json`, + content: JSON.stringify({ name: "@scoped/linked-package", version: "0.0.1", types: "dist/index.d.ts", main: "dist/index.js" }) + }; + const linkedPackageIndex: File = { + path: `${linkedPackageRoot}/dist/index.d.ts`, + content: "export * from './other';" + }; + const linkedPackageOther: File = { + path: `${linkedPackageRoot}/dist/other.d.ts`, + content: 'export declare const Foo = "BAR";' + }; + + it("verify watched directories", () => { + const files = [libFile, mainFile, config, linkedPackageInMain, linkedPackageJson, linkedPackageIndex, linkedPackageOther]; + const host = createWatchedSystem(files, { currentDirectory: mainPackageRoot }); + createWatchOfConfigFile("tsconfig.json", host); + checkWatchedFilesDetailed(host, [libFile.path, mainFile.path, config.path, linkedPackageIndex.path, linkedPackageOther.path], 1); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [`${mainPackageRoot}/@scoped`, `${mainPackageRoot}/node_modules`, linkedPackageRoot, `${mainPackageRoot}/node_modules/@types`, `${projectRoot}/node_modules/@types`], 1, /*recursive*/ true); + }); + }); +} diff --git a/src/testRunner/unittests/tscWatch/watchApi.ts b/src/testRunner/unittests/tscWatch/watchApi.ts new file mode 100644 index 00000000000..35527b73701 --- /dev/null +++ b/src/testRunner/unittests/tscWatch/watchApi.ts @@ -0,0 +1,40 @@ +namespace ts.tscWatch { + describe("unittests:: tsc-watch:: watchAPI:: tsc-watch with custom module resolution", () => { + const projectRoot = "/user/username/projects/project"; + const configFileJson: any = { + compilerOptions: { module: "commonjs", resolveJsonModule: true }, + files: ["index.ts"] + }; + const mainFile: File = { + path: `${projectRoot}/index.ts`, + content: "import settings from './settings.json';" + }; + const config: File = { + path: `${projectRoot}/tsconfig.json`, + content: JSON.stringify(configFileJson) + }; + const settingsJson: File = { + path: `${projectRoot}/settings.json`, + content: JSON.stringify({ content: "Print this" }) + }; + + it("verify that module resolution with json extension works when returned without extension", () => { + const files = [libFile, mainFile, config, settingsJson]; + const host = createWatchedSystem(files, { currentDirectory: projectRoot }); + const compilerHost = createWatchCompilerHostOfConfigFile(config.path, {}, host); + const parsedCommandResult = parseJsonConfigFileContent(configFileJson, host, config.path); + compilerHost.resolveModuleNames = (moduleNames, containingFile) => moduleNames.map(m => { + const result = resolveModuleName(m, containingFile, parsedCommandResult.options, compilerHost); + const resolvedModule = result.resolvedModule!; + return { + resolvedFileName: resolvedModule.resolvedFileName, + isExternalLibraryImport: resolvedModule.isExternalLibraryImport, + originalFileName: resolvedModule.originalPath, + }; + }); + const watch = createWatchProgram(compilerHost); + const program = watch.getCurrentProgram().getProgram(); + checkProgramActualFiles(program, [mainFile.path, libFile.path, settingsJson.path]); + }); + }); +} diff --git a/src/testRunner/unittests/tscWatch/watchEnvironment.ts b/src/testRunner/unittests/tscWatch/watchEnvironment.ts new file mode 100644 index 00000000000..d30e5854652 --- /dev/null +++ b/src/testRunner/unittests/tscWatch/watchEnvironment.ts @@ -0,0 +1,178 @@ +namespace ts.tscWatch { + import Tsc_WatchDirectory = TestFSWithWatch.Tsc_WatchDirectory; + describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different polling/non polling options", () => { + it("watchFile using dynamic priority polling", () => { + const projectFolder = "/a/username/project"; + const file1: File = { + path: `${projectFolder}/typescript.ts`, + content: "var z = 10;" + }; + const files = [file1, libFile]; + const environmentVariables = createMap(); + environmentVariables.set("TSC_WATCHFILE", "DynamicPriorityPolling"); + const host = createWatchedSystem(files, { environmentVariables }); + const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); + + const initialProgram = watch(); + verifyProgram(); + + const mediumPollingIntervalThreshold = unchangedPollThresholds[PollingInterval.Medium]; + for (let index = 0; index < mediumPollingIntervalThreshold; index++) { + // Transition libFile and file1 to low priority queue + host.checkTimeoutQueueLengthAndRun(1); + assert.deepEqual(watch(), initialProgram); + } + + // Make a change to file + file1.content = "var zz30 = 100;"; + host.reloadFS(files); + + // This should detect change in the file + host.checkTimeoutQueueLengthAndRun(1); + assert.deepEqual(watch(), initialProgram); + + // Callbacks: medium priority + high priority queue and scheduled program update + host.checkTimeoutQueueLengthAndRun(3); + // During this timeout the file would be detected as unchanged + let fileUnchangeDetected = 1; + const newProgram = watch(); + assert.notStrictEqual(newProgram, initialProgram); + + verifyProgram(); + const outputFile1 = changeExtension(file1.path, ".js"); + assert.isTrue(host.fileExists(outputFile1)); + assert.equal(host.readFile(outputFile1), file1.content + host.newLine); + + const newThreshold = unchangedPollThresholds[PollingInterval.Low] + mediumPollingIntervalThreshold; + for (; fileUnchangeDetected < newThreshold; fileUnchangeDetected++) { + // For high + Medium/low polling interval + host.checkTimeoutQueueLengthAndRun(2); + assert.deepEqual(watch(), newProgram); + } + + // Everything goes in high polling interval queue + host.checkTimeoutQueueLengthAndRun(1); + assert.deepEqual(watch(), newProgram); + + function verifyProgram() { + checkProgramActualFiles(watch(), files.map(f => f.path)); + checkWatchedFiles(host, []); + checkWatchedDirectories(host, [], /*recursive*/ false); + checkWatchedDirectories(host, [], /*recursive*/ true); + } + }); + + describe("tsc-watch when watchDirectories implementation", () => { + function verifyRenamingFileInSubFolder(tscWatchDirectory: Tsc_WatchDirectory) { + const projectFolder = "/a/username/project"; + const projectSrcFolder = `${projectFolder}/src`; + const configFile: File = { + path: `${projectFolder}/tsconfig.json`, + content: "{}" + }; + const file: File = { + path: `${projectSrcFolder}/file1.ts`, + content: "" + }; + const programFiles = [file, libFile]; + const files = [file, configFile, libFile]; + const environmentVariables = createMap(); + environmentVariables.set("TSC_WATCHDIRECTORY", tscWatchDirectory); + const host = createWatchedSystem(files, { environmentVariables }); + const watch = createWatchOfConfigFile(configFile.path, host); + const projectFolders = [projectFolder, projectSrcFolder, `${projectFolder}/node_modules/@types`]; + // Watching files config file, file, lib file + const expectedWatchedFiles = files.map(f => f.path); + const expectedWatchedDirectories = tscWatchDirectory === Tsc_WatchDirectory.NonRecursiveWatchDirectory ? projectFolders : emptyArray; + if (tscWatchDirectory === Tsc_WatchDirectory.WatchFile) { + expectedWatchedFiles.push(...projectFolders); + } + + verifyProgram(checkOutputErrorsInitial); + + // Rename the file: + file.path = file.path.replace("file1.ts", "file2.ts"); + expectedWatchedFiles[0] = file.path; + host.reloadFS(files); + if (tscWatchDirectory === Tsc_WatchDirectory.DynamicPolling) { + // With dynamic polling the fs change would be detected only by running timeouts + host.runQueuedTimeoutCallbacks(); + } + // Delayed update program + host.runQueuedTimeoutCallbacks(); + verifyProgram(checkOutputErrorsIncremental); + + function verifyProgram(checkOutputErrors: (host: WatchedSystem, errors: ReadonlyArray) => void) { + checkProgramActualFiles(watch(), programFiles.map(f => f.path)); + checkOutputErrors(host, emptyArray); + + const outputFile = changeExtension(file.path, ".js"); + assert(host.fileExists(outputFile)); + assert.equal(host.readFile(outputFile), file.content); + + checkWatchedDirectories(host, emptyArray, /*recursive*/ true); + + // Watching config file, file, lib file and directories + checkWatchedFilesDetailed(host, expectedWatchedFiles, 1); + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectories, 1, /*recursive*/ false); + } + } + + it("uses watchFile when renaming file in subfolder", () => { + verifyRenamingFileInSubFolder(Tsc_WatchDirectory.WatchFile); + }); + + it("uses non recursive watchDirectory when renaming file in subfolder", () => { + verifyRenamingFileInSubFolder(Tsc_WatchDirectory.NonRecursiveWatchDirectory); + }); + + it("uses non recursive dynamic polling when renaming file in subfolder", () => { + verifyRenamingFileInSubFolder(Tsc_WatchDirectory.DynamicPolling); + }); + + it("when there are symlinks to folders in recursive folders", () => { + const cwd = "/home/user/projects/myproject"; + const file1: File = { + path: `${cwd}/src/file.ts`, + content: `import * as a from "a"` + }; + const tsconfig: File = { + path: `${cwd}/tsconfig.json`, + content: `{ "compilerOptions": { "extendedDiagnostics": true, "traceResolution": true }}` + }; + const realA: File = { + path: `${cwd}/node_modules/reala/index.d.ts`, + content: `export {}` + }; + const realB: File = { + path: `${cwd}/node_modules/realb/index.d.ts`, + content: `export {}` + }; + const symLinkA: SymLink = { + path: `${cwd}/node_modules/a`, + symLink: `${cwd}/node_modules/reala` + }; + const symLinkB: SymLink = { + path: `${cwd}/node_modules/b`, + symLink: `${cwd}/node_modules/realb` + }; + const symLinkBInA: SymLink = { + path: `${cwd}/node_modules/reala/node_modules/b`, + symLink: `${cwd}/node_modules/b` + }; + const symLinkAInB: SymLink = { + path: `${cwd}/node_modules/realb/node_modules/a`, + symLink: `${cwd}/node_modules/a` + }; + const files = [file1, tsconfig, realA, realB, symLinkA, symLinkB, symLinkBInA, symLinkAInB]; + const environmentVariables = createMap(); + environmentVariables.set("TSC_WATCHDIRECTORY", Tsc_WatchDirectory.NonRecursiveWatchDirectory); + const host = createWatchedSystem(files, { environmentVariables, currentDirectory: cwd }); + createWatchOfConfigFile("tsconfig.json", host); + checkWatchedDirectories(host, emptyArray, /*recursive*/ true); + checkWatchedDirectories(host, [cwd, `${cwd}/node_modules`, `${cwd}/node_modules/@types`, `${cwd}/node_modules/reala`, `${cwd}/node_modules/realb`, + `${cwd}/node_modules/reala/node_modules`, `${cwd}/node_modules/realb/node_modules`, `${cwd}/src`], /*recursive*/ false); + }); + }); + }); +} diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts deleted file mode 100644 index da1c4fd0d70..00000000000 --- a/src/testRunner/unittests/tscWatchMode.ts +++ /dev/null @@ -1,2754 +0,0 @@ -namespace ts.tscWatch { - export import WatchedSystem = TestFSWithWatch.TestServerHost; - export type File = TestFSWithWatch.File; - export type SymLink = TestFSWithWatch.SymLink; - export import createWatchedSystem = TestFSWithWatch.createWatchedSystem; - export import checkArray = TestFSWithWatch.checkArray; - export import checkWatchedFiles = TestFSWithWatch.checkWatchedFiles; - export import checkWatchedFilesDetailed = TestFSWithWatch.checkWatchedFilesDetailed; - export import checkWatchedDirectories = TestFSWithWatch.checkWatchedDirectories; - export import checkWatchedDirectoriesDetailed = TestFSWithWatch.checkWatchedDirectoriesDetailed; - export import checkOutputContains = TestFSWithWatch.checkOutputContains; - export import checkOutputDoesNotContain = TestFSWithWatch.checkOutputDoesNotContain; - export import Tsc_WatchDirectory = TestFSWithWatch.Tsc_WatchDirectory; - - export function checkProgramActualFiles(program: Program, expectedFiles: string[]) { - checkArray(`Program actual files`, program.getSourceFiles().map(file => file.fileName), expectedFiles); - } - - export function checkProgramRootFiles(program: Program, expectedFiles: string[]) { - checkArray(`Program rootFileNames`, program.getRootFileNames(), expectedFiles); - } - - function createWatchOfConfigFile(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { - const compilerHost = createWatchCompilerHostOfConfigFile(configFileName, {}, host); - compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation; - const watch = createWatchProgram(compilerHost); - return () => watch.getCurrentProgram().getProgram(); - } - - function createWatchOfFilesAndCompilerOptions(rootFiles: string[], host: WatchedSystem, options: CompilerOptions = {}) { - const watch = createWatchProgram(createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, host)); - return () => watch.getCurrentProgram().getProgram(); - } - - function getEmittedLineForMultiFileOutput(file: File, host: WatchedSystem) { - return `TSFILE: ${file.path.replace(".ts", ".js")}${host.newLine}`; - } - - function getEmittedLineForSingleFileOutput(filename: string, host: WatchedSystem) { - return `TSFILE: ${filename}${host.newLine}`; - } - - interface FileOrFolderEmit extends File { - output?: string; - } - - function getFileOrFolderEmit(file: File, getOutput?: (file: File) => string): FileOrFolderEmit { - const result = file as FileOrFolderEmit; - if (getOutput) { - result.output = getOutput(file); - } - return result; - } - - function getEmittedLines(files: FileOrFolderEmit[]) { - const seen = createMap(); - const result: string[] = []; - for (const { output } of files) { - if (output && !seen.has(output)) { - seen.set(output, true); - result.push(output); - } - } - return result; - } - - function checkAffectedLines(host: WatchedSystem, affectedFiles: FileOrFolderEmit[], allEmittedFiles: string[]) { - const expectedAffectedFiles = getEmittedLines(affectedFiles); - const expectedNonAffectedFiles = mapDefined(allEmittedFiles, line => contains(expectedAffectedFiles, line) ? undefined : line); - checkOutputContains(host, expectedAffectedFiles); - checkOutputDoesNotContain(host, expectedNonAffectedFiles); - } - - const elapsedRegex = /^Elapsed:: [0-9]+ms/; - function checkOutputErrors( - host: WatchedSystem, - logsBeforeWatchDiagnostic: string[] | undefined, - preErrorsWatchDiagnostic: Diagnostic, - logsBeforeErrors: string[] | undefined, - errors: ReadonlyArray, - disableConsoleClears?: boolean | undefined, - ...postErrorsWatchDiagnostics: Diagnostic[] - ) { - let screenClears = 0; - const outputs = host.getOutput(); - const expectedOutputCount = 1 + errors.length + postErrorsWatchDiagnostics.length + - (logsBeforeWatchDiagnostic ? logsBeforeWatchDiagnostic.length : 0) + (logsBeforeErrors ? logsBeforeErrors.length : 0); - assert.equal(outputs.length, expectedOutputCount, JSON.stringify(outputs)); - let index = 0; - forEach(logsBeforeWatchDiagnostic, log => assertLog("logsBeforeWatchDiagnostic", log)); - assertWatchDiagnostic(preErrorsWatchDiagnostic); - forEach(logsBeforeErrors, log => assertLog("logBeforeError", log)); - // Verify errors - forEach(errors, assertDiagnostic); - forEach(postErrorsWatchDiagnostics, assertWatchDiagnostic); - assert.equal(host.screenClears.length, screenClears, "Expected number of screen clears"); - host.clearOutput(); - - function assertDiagnostic(diagnostic: Diagnostic) { - const expected = formatDiagnostic(diagnostic, host); - assert.equal(outputs[index], expected, getOutputAtFailedMessage("Diagnostic", expected)); - index++; - } - - function assertLog(caption: string, expected: string) { - const actual = outputs[index]; - assert.equal(actual.replace(elapsedRegex, ""), expected.replace(elapsedRegex, ""), getOutputAtFailedMessage(caption, expected)); - index++; - } - - function assertWatchDiagnostic(diagnostic: Diagnostic) { - const expected = getWatchDiagnosticWithoutDate(diagnostic); - if (!disableConsoleClears && contains(screenStartingMessageCodes, diagnostic.code)) { - assert.equal(host.screenClears[screenClears], index, `Expected screen clear at this diagnostic: ${expected}`); - screenClears++; - } - assert.isTrue(endsWith(outputs[index], expected), getOutputAtFailedMessage("Watch diagnostic", expected)); - index++; - } - - function getOutputAtFailedMessage(caption: string, expectedOutput: string) { - return `Expected ${caption}: ${JSON.stringify(expectedOutput)} at ${index} in ${JSON.stringify(outputs)}`; - } - - function getWatchDiagnosticWithoutDate(diagnostic: Diagnostic) { - const newLines = contains(screenStartingMessageCodes, diagnostic.code) - ? `${host.newLine}${host.newLine}` - : host.newLine; - return ` - ${flattenDiagnosticMessageText(diagnostic.messageText, host.newLine)}${newLines}`; - } - } - - function createErrorsFoundCompilerDiagnostic(errors: ReadonlyArray) { - return errors.length === 1 - ? createCompilerDiagnostic(Diagnostics.Found_1_error_Watching_for_file_changes) - : createCompilerDiagnostic(Diagnostics.Found_0_errors_Watching_for_file_changes, errors.length); - } - - export function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { - checkOutputErrors( - host, - /*logsBeforeWatchDiagnostic*/ undefined, - createCompilerDiagnostic(Diagnostics.Starting_compilation_in_watch_mode), - logsBeforeErrors, - errors, - disableConsoleClears, - createErrorsFoundCompilerDiagnostic(errors)); - } - - export function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { - checkOutputErrors( - host, - logsBeforeWatchDiagnostic, - createCompilerDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation), - logsBeforeErrors, - errors, - disableConsoleClears, - createErrorsFoundCompilerDiagnostic(errors)); - } - - function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { - checkOutputErrors( - host, - logsBeforeWatchDiagnostic, - createCompilerDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation), - logsBeforeErrors, - errors, - disableConsoleClears); - assert.equal(host.exitCode, expectedExitCode); - } - - function getDiagnosticOfFileFrom(file: SourceFile | undefined, text: string, start: number | undefined, length: number | undefined, message: DiagnosticMessage): Diagnostic { - return { - file, - start, - length, - - messageText: text, - category: message.category, - code: message.code, - }; - } - - function getDiagnosticWithoutFile(message: DiagnosticMessage, ..._args: (string | number)[]): Diagnostic { - let text = getLocaleSpecificMessage(message); - - if (arguments.length > 1) { - text = formatStringFromArgs(text, arguments, 1); - } - - return getDiagnosticOfFileFrom(/*file*/ undefined, text, /*start*/ undefined, /*length*/ undefined, message); - } - - function getDiagnosticOfFile(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ..._args: (string | number)[]): Diagnostic { - let text = getLocaleSpecificMessage(message); - - if (arguments.length > 4) { - text = formatStringFromArgs(text, arguments, 4); - } - - return getDiagnosticOfFileFrom(file, text, start, length, message); - } - - function getUnknownCompilerOption(program: Program, configFile: File, option: string) { - const quotedOption = `"${option}"`; - return getDiagnosticOfFile(program.getCompilerOptions().configFile!, configFile.content.indexOf(quotedOption), quotedOption.length, Diagnostics.Unknown_compiler_option_0, option); - } - - function getDiagnosticOfFileFromProgram(program: Program, filePath: string, start: number, length: number, message: DiagnosticMessage, ..._args: (string | number)[]): Diagnostic { - let text = getLocaleSpecificMessage(message); - - if (arguments.length > 5) { - text = formatStringFromArgs(text, arguments, 5); - } - - return getDiagnosticOfFileFrom(program.getSourceFileByPath(toPath(filePath, program.getCurrentDirectory(), s => s.toLowerCase()))!, - text, start, length, message); - } - - function getDiagnosticModuleNotFoundOfFile(program: Program, file: File, moduleName: string) { - const quotedModuleName = `"${moduleName}"`; - return getDiagnosticOfFileFromProgram(program, file.path, file.content.indexOf(quotedModuleName), quotedModuleName.length, Diagnostics.Cannot_find_module_0, moduleName); - } - - describe("tsc-watch program updates", () => { - const commonFile1: File = { - path: "/a/b/commonFile1.ts", - content: "let x = 1" - }; - const commonFile2: File = { - path: "/a/b/commonFile2.ts", - content: "let y = 1" - }; - - it("create watch without config file", () => { - const appFile: File = { - path: "/a/b/c/app.ts", - content: ` - import {f} from "./module" - console.log(f) - ` - }; - - const moduleFile: File = { - path: "/a/b/c/module.d.ts", - content: `export let x: number` - }; - const host = createWatchedSystem([appFile, moduleFile, libFile]); - const watch = createWatchOfFilesAndCompilerOptions([appFile.path], host); - - checkProgramActualFiles(watch(), [appFile.path, libFile.path, moduleFile.path]); - - // TODO: Should we watch creation of config files in the root file's file hierarchy? - - // const configFileLocations = ["/a/b/c/", "/a/b/", "/a/", "/"]; - // const configFiles = flatMap(configFileLocations, location => [location + "tsconfig.json", location + "jsconfig.json"]); - // checkWatchedFiles(host, configFiles.concat(libFile.path, moduleFile.path)); - }); - - it("can handle tsconfig file name with difference casing", () => { - const f1 = { - path: "/a/b/app.ts", - content: "let x = 1" - }; - const config = { - path: "/a/b/tsconfig.json", - content: JSON.stringify({ - include: ["app.ts"] - }) - }; - - const host = createWatchedSystem([f1, config], { useCaseSensitiveFileNames: false }); - const upperCaseConfigFilePath = combinePaths(getDirectoryPath(config.path).toUpperCase(), getBaseFileName(config.path)); - const watch = createWatchOfConfigFile(upperCaseConfigFilePath, host); - checkProgramActualFiles(watch(), [combinePaths(getDirectoryPath(upperCaseConfigFilePath), getBaseFileName(f1.path))]); - }); - - it("create configured project without file list", () => { - const configFile: File = { - path: "/a/b/tsconfig.json", - content: ` - { - "compilerOptions": {}, - "exclude": [ - "e" - ] - }` - }; - const file1: File = { - path: "/a/b/c/f1.ts", - content: "let x = 1" - }; - const file2: File = { - path: "/a/b/d/f2.ts", - content: "let y = 1" - }; - const file3: File = { - path: "/a/b/e/f3.ts", - content: "let z = 1" - }; - - const host = createWatchedSystem([configFile, libFile, file1, file2, file3]); - const watch = createWatchProgram(createWatchCompilerHostOfConfigFile(configFile.path, {}, host, /*createProgram*/ undefined, notImplemented)); - - checkProgramActualFiles(watch.getCurrentProgram().getProgram(), [file1.path, libFile.path, file2.path]); - checkProgramRootFiles(watch.getCurrentProgram().getProgram(), [file1.path, file2.path]); - checkWatchedFiles(host, [configFile.path, file1.path, file2.path, libFile.path]); - const configDir = getDirectoryPath(configFile.path); - checkWatchedDirectories(host, [configDir, combinePaths(configDir, projectSystem.nodeModulesAtTypes)], /*recursive*/ true); - }); - - // TODO: if watching for config file creation - // it("add and then remove a config file in a folder with loose files", () => { - // }); - - it("add new files to a configured program without file list", () => { - const configFile: File = { - path: "/a/b/tsconfig.json", - content: `{}` - }; - const host = createWatchedSystem([commonFile1, libFile, configFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - const configDir = getDirectoryPath(configFile.path); - checkWatchedDirectories(host, [configDir, combinePaths(configDir, projectSystem.nodeModulesAtTypes)], /*recursive*/ true); - - checkProgramRootFiles(watch(), [commonFile1.path]); - - // add a new ts file - host.reloadFS([commonFile1, commonFile2, libFile, configFile]); - host.checkTimeoutQueueLengthAndRun(1); - checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); - }); - - it("should ignore non-existing files specified in the config file", () => { - const configFile: File = { - path: "/a/b/tsconfig.json", - content: `{ - "compilerOptions": {}, - "files": [ - "commonFile1.ts", - "commonFile3.ts" - ] - }` - }; - const host = createWatchedSystem([commonFile1, commonFile2, configFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - - const commonFile3 = "/a/b/commonFile3.ts"; - checkProgramRootFiles(watch(), [commonFile1.path, commonFile3]); - checkProgramActualFiles(watch(), [commonFile1.path]); - }); - - it("handle recreated files correctly", () => { - const configFile: File = { - path: "/a/b/tsconfig.json", - content: `{}` - }; - const host = createWatchedSystem([commonFile1, commonFile2, configFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); - - // delete commonFile2 - host.reloadFS([commonFile1, configFile]); - host.checkTimeoutQueueLengthAndRun(1); - checkProgramRootFiles(watch(), [commonFile1.path]); - - // re-add commonFile2 - host.reloadFS([commonFile1, commonFile2, configFile]); - host.checkTimeoutQueueLengthAndRun(1); - checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); - }); - - it("handles the missing files - that were added to program because they were added with /// { - const commonFile2Name = "commonFile2.ts"; - const file1: File = { - path: "/a/b/commonFile1.ts", - content: `/// - let x = y` - }; - const host = createWatchedSystem([file1, libFile]); - const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); - - checkProgramRootFiles(watch(), [file1.path]); - checkProgramActualFiles(watch(), [file1.path, libFile.path]); - checkOutputErrorsInitial(host, [ - getDiagnosticOfFileFromProgram(watch(), file1.path, file1.content.indexOf(commonFile2Name), commonFile2Name.length, Diagnostics.File_0_not_found, commonFile2.path), - getDiagnosticOfFileFromProgram(watch(), file1.path, file1.content.indexOf("y"), 1, Diagnostics.Cannot_find_name_0, "y") - ]); - - host.reloadFS([file1, commonFile2, libFile]); - host.runQueuedTimeoutCallbacks(); - checkProgramRootFiles(watch(), [file1.path]); - checkProgramActualFiles(watch(), [file1.path, libFile.path, commonFile2.path]); - checkOutputErrorsIncremental(host, emptyArray); - }); - - it("should reflect change in config file", () => { - const configFile: File = { - path: "/a/b/tsconfig.json", - content: `{ - "compilerOptions": {}, - "files": ["${commonFile1.path}", "${commonFile2.path}"] - }` - }; - const files = [commonFile1, commonFile2, configFile]; - const host = createWatchedSystem(files); - const watch = createWatchOfConfigFile(configFile.path, host); - - checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); - configFile.content = `{ - "compilerOptions": {}, - "files": ["${commonFile1.path}"] - }`; - - host.reloadFS(files); - host.checkTimeoutQueueLengthAndRun(1); // reload the configured project - checkProgramRootFiles(watch(), [commonFile1.path]); - }); - - it("works correctly when config file is changed but its content havent", () => { - const configFile: File = { - path: "/a/b/tsconfig.json", - content: `{ - "compilerOptions": {}, - "files": ["${commonFile1.path}", "${commonFile2.path}"] - }` - }; - const files = [libFile, commonFile1, commonFile2, configFile]; - const host = createWatchedSystem(files); - const watch = createWatchOfConfigFile(configFile.path, host); - - checkProgramActualFiles(watch(), [libFile.path, commonFile1.path, commonFile2.path]); - checkOutputErrorsInitial(host, emptyArray); - - host.modifyFile(configFile.path, configFile.content); - host.checkTimeoutQueueLengthAndRun(1); // reload the configured project - - checkProgramActualFiles(watch(), [libFile.path, commonFile1.path, commonFile2.path]); - checkOutputErrorsIncremental(host, emptyArray); - }); - - it("files explicitly excluded in config file", () => { - const configFile: File = { - path: "/a/b/tsconfig.json", - content: `{ - "compilerOptions": {}, - "exclude": ["/a/c"] - }` - }; - const excludedFile1: File = { - path: "/a/c/excluedFile1.ts", - content: `let t = 1;` - }; - - const host = createWatchedSystem([commonFile1, commonFile2, excludedFile1, configFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); - }); - - it("should properly handle module resolution changes in config file", () => { - const file1: File = { - path: "/a/b/file1.ts", - content: `import { T } from "module1";` - }; - const nodeModuleFile: File = { - path: "/a/b/node_modules/module1.ts", - content: `export interface T {}` - }; - const classicModuleFile: File = { - path: "/a/module1.ts", - content: `export interface T {}` - }; - const configFile: File = { - path: "/a/b/tsconfig.json", - content: `{ - "compilerOptions": { - "moduleResolution": "node" - }, - "files": ["${file1.path}"] - }` - }; - const files = [file1, nodeModuleFile, classicModuleFile, configFile]; - const host = createWatchedSystem(files); - const watch = createWatchOfConfigFile(configFile.path, host); - checkProgramRootFiles(watch(), [file1.path]); - checkProgramActualFiles(watch(), [file1.path, nodeModuleFile.path]); - - configFile.content = `{ - "compilerOptions": { - "moduleResolution": "classic" - }, - "files": ["${file1.path}"] - }`; - host.reloadFS(files); - host.checkTimeoutQueueLengthAndRun(1); - checkProgramRootFiles(watch(), [file1.path]); - checkProgramActualFiles(watch(), [file1.path, classicModuleFile.path]); - }); - - it("should tolerate config file errors and still try to build a project", () => { - const configFile: File = { - path: "/a/b/tsconfig.json", - content: `{ - "compilerOptions": { - "target": "es6", - "allowAnything": true - }, - "someOtherProperty": {} - }` - }; - const host = createWatchedSystem([commonFile1, commonFile2, libFile, configFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - checkProgramRootFiles(watch(), [commonFile1.path, commonFile2.path]); - }); - - it("changes in files are reflected in project structure", () => { - const file1 = { - path: "/a/b/f1.ts", - content: `export * from "./f2"` - }; - const file2 = { - path: "/a/b/f2.ts", - content: `export let x = 1` - }; - const file3 = { - path: "/a/c/f3.ts", - content: `export let y = 1;` - }; - const host = createWatchedSystem([file1, file2, file3]); - const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); - checkProgramRootFiles(watch(), [file1.path]); - checkProgramActualFiles(watch(), [file1.path, file2.path]); - - const modifiedFile2 = { - path: file2.path, - content: `export * from "../c/f3"` // now inferred project should inclule file3 - }; - - host.reloadFS([file1, modifiedFile2, file3]); - host.checkTimeoutQueueLengthAndRun(1); - checkProgramRootFiles(watch(), [file1.path]); - checkProgramActualFiles(watch(), [file1.path, modifiedFile2.path, file3.path]); - }); - - it("deleted files affect project structure", () => { - const file1 = { - path: "/a/b/f1.ts", - content: `export * from "./f2"` - }; - const file2 = { - path: "/a/b/f2.ts", - content: `export * from "../c/f3"` - }; - const file3 = { - path: "/a/c/f3.ts", - content: `export let y = 1;` - }; - const host = createWatchedSystem([file1, file2, file3]); - const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); - checkProgramActualFiles(watch(), [file1.path, file2.path, file3.path]); - - host.reloadFS([file1, file3]); - host.checkTimeoutQueueLengthAndRun(1); - - checkProgramActualFiles(watch(), [file1.path]); - }); - - it("deleted files affect project structure - 2", () => { - const file1 = { - path: "/a/b/f1.ts", - content: `export * from "./f2"` - }; - const file2 = { - path: "/a/b/f2.ts", - content: `export * from "../c/f3"` - }; - const file3 = { - path: "/a/c/f3.ts", - content: `export let y = 1;` - }; - const host = createWatchedSystem([file1, file2, file3]); - const watch = createWatchOfFilesAndCompilerOptions([file1.path, file3.path], host); - checkProgramActualFiles(watch(), [file1.path, file2.path, file3.path]); - - host.reloadFS([file1, file3]); - host.checkTimeoutQueueLengthAndRun(1); - - checkProgramActualFiles(watch(), [file1.path, file3.path]); - }); - - it("config file includes the file", () => { - const file1 = { - path: "/a/b/f1.ts", - content: "export let x = 5" - }; - const file2 = { - path: "/a/c/f2.ts", - content: `import {x} from "../b/f1"` - }; - const file3 = { - path: "/a/c/f3.ts", - content: "export let y = 1" - }; - const configFile = { - path: "/a/c/tsconfig.json", - content: JSON.stringify({ compilerOptions: {}, files: ["f2.ts", "f3.ts"] }) - }; - - const host = createWatchedSystem([file1, file2, file3, configFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - - checkProgramRootFiles(watch(), [file2.path, file3.path]); - checkProgramActualFiles(watch(), [file1.path, file2.path, file3.path]); - }); - - it("correctly migrate files between projects", () => { - const file1 = { - path: "/a/b/f1.ts", - content: ` - export * from "../c/f2"; - export * from "../d/f3";` - }; - const file2 = { - path: "/a/c/f2.ts", - content: "export let x = 1;" - }; - const file3 = { - path: "/a/d/f3.ts", - content: "export let y = 1;" - }; - const host = createWatchedSystem([file1, file2, file3]); - const watch = createWatchOfFilesAndCompilerOptions([file2.path, file3.path], host); - checkProgramActualFiles(watch(), [file2.path, file3.path]); - - const watch2 = createWatchOfFilesAndCompilerOptions([file1.path], host); - checkProgramActualFiles(watch2(), [file1.path, file2.path, file3.path]); - - // Previous program shouldnt be updated - checkProgramActualFiles(watch(), [file2.path, file3.path]); - host.checkTimeoutQueueLength(0); - }); - - it("can correctly update configured project when set of root files has changed (new file on disk)", () => { - const file1 = { - path: "/a/b/f1.ts", - content: "let x = 1" - }; - const file2 = { - path: "/a/b/f2.ts", - content: "let y = 1" - }; - const configFile = { - path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: {} }) - }; - - const host = createWatchedSystem([file1, configFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - checkProgramActualFiles(watch(), [file1.path]); - - host.reloadFS([file1, file2, configFile]); - host.checkTimeoutQueueLengthAndRun(1); - - checkProgramActualFiles(watch(), [file1.path, file2.path]); - checkProgramRootFiles(watch(), [file1.path, file2.path]); - }); - - it("can correctly update configured project when set of root files has changed (new file in list of files)", () => { - const file1 = { - path: "/a/b/f1.ts", - content: "let x = 1" - }; - const file2 = { - path: "/a/b/f2.ts", - content: "let y = 1" - }; - const configFile = { - path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts"] }) - }; - - const host = createWatchedSystem([file1, file2, configFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - - checkProgramActualFiles(watch(), [file1.path]); - - const modifiedConfigFile = { - path: configFile.path, - content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }) - }; - - host.reloadFS([file1, file2, modifiedConfigFile]); - host.checkTimeoutQueueLengthAndRun(1); - checkProgramRootFiles(watch(), [file1.path, file2.path]); - checkProgramActualFiles(watch(), [file1.path, file2.path]); - }); - - it("can update configured project when set of root files was not changed", () => { - const file1 = { - path: "/a/b/f1.ts", - content: "let x = 1" - }; - const file2 = { - path: "/a/b/f2.ts", - content: "let y = 1" - }; - const configFile = { - path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }) - }; - - const host = createWatchedSystem([file1, file2, configFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - checkProgramActualFiles(watch(), [file1.path, file2.path]); - - const modifiedConfigFile = { - path: configFile.path, - content: JSON.stringify({ compilerOptions: { outFile: "out.js" }, files: ["f1.ts", "f2.ts"] }) - }; - - host.reloadFS([file1, file2, modifiedConfigFile]); - host.checkTimeoutQueueLengthAndRun(1); - checkProgramRootFiles(watch(), [file1.path, file2.path]); - checkProgramActualFiles(watch(), [file1.path, file2.path]); - }); - - it("config file is deleted", () => { - const file1 = { - path: "/a/b/f1.ts", - content: "let x = 1;" - }; - const file2 = { - path: "/a/b/f2.ts", - content: "let y = 2;" - }; - const config = { - path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: {} }) - }; - const host = createWatchedSystem([file1, file2, libFile, config]); - const watch = createWatchOfConfigFile(config.path, host); - - checkProgramActualFiles(watch(), [file1.path, file2.path, libFile.path]); - checkOutputErrorsInitial(host, emptyArray); - - host.reloadFS([file1, file2, libFile]); - host.checkTimeoutQueueLengthAndRun(1); - - checkOutputErrorsIncrementalWithExit(host, [ - getDiagnosticWithoutFile(Diagnostics.File_0_not_found, config.path) - ], ExitStatus.DiagnosticsPresent_OutputsSkipped); - }); - - it("Proper errors: document is not contained in project", () => { - const file1 = { - path: "/a/b/app.ts", - content: "" - }; - const corruptedConfig = { - path: "/a/b/tsconfig.json", - content: "{" - }; - const host = createWatchedSystem([file1, corruptedConfig]); - const watch = createWatchOfConfigFile(corruptedConfig.path, host); - - checkProgramActualFiles(watch(), [file1.path]); - }); - - it("correctly handles changes in lib section of config file", () => { - const libES5 = { - path: "/compiler/lib.es5.d.ts", - content: "declare const eval: any" - }; - const libES2015Promise = { - path: "/compiler/lib.es2015.promise.d.ts", - content: "declare class Promise {}" - }; - const app = { - path: "/src/app.ts", - content: "var x: Promise;" - }; - const config1 = { - path: "/src/tsconfig.json", - content: JSON.stringify( - { - compilerOptions: { - module: "commonjs", - target: "es5", - noImplicitAny: true, - sourceMap: false, - lib: [ - "es5" - ] - } - }) - }; - const config2 = { - path: config1.path, - content: JSON.stringify( - { - compilerOptions: { - module: "commonjs", - target: "es5", - noImplicitAny: true, - sourceMap: false, - lib: [ - "es5", - "es2015.promise" - ] - } - }) - }; - const host = createWatchedSystem([libES5, libES2015Promise, app, config1], { executingFilePath: "/compiler/tsc.js" }); - const watch = createWatchOfConfigFile(config1.path, host); - - checkProgramActualFiles(watch(), [libES5.path, app.path]); - - host.reloadFS([libES5, libES2015Promise, app, config2]); - host.checkTimeoutQueueLengthAndRun(1); - checkProgramActualFiles(watch(), [libES5.path, libES2015Promise.path, app.path]); - }); - - it("should handle non-existing directories in config file", () => { - const f = { - path: "/a/src/app.ts", - content: "let x = 1;" - }; - const config = { - path: "/a/tsconfig.json", - content: JSON.stringify({ - compilerOptions: {}, - include: [ - "src/**/*", - "notexistingfolder/*" - ] - }) - }; - const host = createWatchedSystem([f, config]); - const watch = createWatchOfConfigFile(config.path, host); - checkProgramActualFiles(watch(), [f.path]); - }); - - it("rename a module file and rename back should restore the states for inferred projects", () => { - const moduleFile = { - path: "/a/b/moduleFile.ts", - content: "export function bar() { };" - }; - const file1 = { - path: "/a/b/file1.ts", - content: 'import * as T from "./moduleFile"; T.bar();' - }; - const host = createWatchedSystem([moduleFile, file1, libFile]); - const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); - checkOutputErrorsInitial(host, emptyArray); - - const moduleFileOldPath = moduleFile.path; - const moduleFileNewPath = "/a/b/moduleFile1.ts"; - moduleFile.path = moduleFileNewPath; - host.reloadFS([moduleFile, file1, libFile]); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, [ - getDiagnosticModuleNotFoundOfFile(watch(), file1, "./moduleFile") - ]); - - moduleFile.path = moduleFileOldPath; - host.reloadFS([moduleFile, file1, libFile]); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, emptyArray); - }); - - it("rename a module file and rename back should restore the states for configured projects", () => { - const moduleFile = { - path: "/a/b/moduleFile.ts", - content: "export function bar() { };" - }; - const file1 = { - path: "/a/b/file1.ts", - content: 'import * as T from "./moduleFile"; T.bar();' - }; - const configFile = { - path: "/a/b/tsconfig.json", - content: `{}` - }; - const host = createWatchedSystem([moduleFile, file1, configFile, libFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - checkOutputErrorsInitial(host, emptyArray); - - const moduleFileOldPath = moduleFile.path; - const moduleFileNewPath = "/a/b/moduleFile1.ts"; - moduleFile.path = moduleFileNewPath; - host.reloadFS([moduleFile, file1, configFile, libFile]); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, [ - getDiagnosticModuleNotFoundOfFile(watch(), file1, "./moduleFile") - ]); - - moduleFile.path = moduleFileOldPath; - host.reloadFS([moduleFile, file1, configFile, libFile]); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, emptyArray); - }); - - it("types should load from config file path if config exists", () => { - const f1 = { - path: "/a/b/app.ts", - content: "let x = 1" - }; - const config = { - path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: { types: ["node"], typeRoots: [] } }) - }; - const node = { - path: "/a/b/node_modules/@types/node/index.d.ts", - content: "declare var process: any" - }; - const cwd = { - path: "/a/c" - }; - const host = createWatchedSystem([f1, config, node, cwd], { currentDirectory: cwd.path }); - const watch = createWatchOfConfigFile(config.path, host); - - checkProgramActualFiles(watch(), [f1.path, node.path]); - }); - - it("add the missing module file for inferred project: should remove the `module not found` error", () => { - const moduleFile = { - path: "/a/b/moduleFile.ts", - content: "export function bar() { };" - }; - const file1 = { - path: "/a/b/file1.ts", - content: 'import * as T from "./moduleFile"; T.bar();' - }; - const host = createWatchedSystem([file1, libFile]); - const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); - - checkOutputErrorsInitial(host, [ - getDiagnosticModuleNotFoundOfFile(watch(), file1, "./moduleFile") - ]); - - host.reloadFS([file1, moduleFile, libFile]); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, emptyArray); - }); - - it("Configure file diagnostics events are generated when the config file has errors", () => { - const file = { - path: "/a/b/app.ts", - content: "let x = 10" - }; - const configFile = { - path: "/a/b/tsconfig.json", - content: `{ - "compilerOptions": { - "foo": "bar", - "allowJS": true - } - }` - }; - - const host = createWatchedSystem([file, configFile, libFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - checkOutputErrorsInitial(host, [ - getUnknownCompilerOption(watch(), configFile, "foo"), - getUnknownCompilerOption(watch(), configFile, "allowJS") - ]); - }); - - it("If config file doesnt have errors, they are not reported", () => { - const file = { - path: "/a/b/app.ts", - content: "let x = 10" - }; - const configFile = { - path: "/a/b/tsconfig.json", - content: `{ - "compilerOptions": {} - }` - }; - - const host = createWatchedSystem([file, configFile, libFile]); - createWatchOfConfigFile(configFile.path, host); - checkOutputErrorsInitial(host, emptyArray); - }); - - it("Reports errors when the config file changes", () => { - const file = { - path: "/a/b/app.ts", - content: "let x = 10" - }; - const configFile = { - path: "/a/b/tsconfig.json", - content: `{ - "compilerOptions": {} - }` - }; - - const host = createWatchedSystem([file, configFile, libFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - checkOutputErrorsInitial(host, emptyArray); - - configFile.content = `{ - "compilerOptions": { - "haha": 123 - } - }`; - host.reloadFS([file, configFile, libFile]); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, [ - getUnknownCompilerOption(watch(), configFile, "haha") - ]); - - configFile.content = `{ - "compilerOptions": {} - }`; - host.reloadFS([file, configFile, libFile]); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, emptyArray); - }); - - it("non-existing directories listed in config file input array should be tolerated without crashing the server", () => { - const configFile = { - path: "/a/b/tsconfig.json", - content: `{ - "compilerOptions": {}, - "include": ["app/*", "test/**/*", "something"] - }` - }; - const file1 = { - path: "/a/b/file1.ts", - content: "let t = 10;" - }; - - const host = createWatchedSystem([file1, configFile, libFile]); - const watch = createWatchOfConfigFile(configFile.path, host); - - checkProgramActualFiles(watch(), [libFile.path]); - }); - - it("non-existing directories listed in config file input array should be able to handle @types if input file list is empty", () => { - const f = { - path: "/a/app.ts", - content: "let x = 1" - }; - const config = { - path: "/a/tsconfig.json", - content: JSON.stringify({ - compiler: {}, - files: [] - }) - }; - const t1 = { - path: "/a/node_modules/@types/typings/index.d.ts", - content: `export * from "./lib"` - }; - const t2 = { - path: "/a/node_modules/@types/typings/lib.d.ts", - content: `export const x: number` - }; - const host = createWatchedSystem([f, config, t1, t2], { currentDirectory: getDirectoryPath(f.path) }); - const watch = createWatchOfConfigFile(config.path, host); - - checkProgramActualFiles(watch(), [t1.path, t2.path]); - }); - - it("should support files without extensions", () => { - const f = { - path: "/a/compile", - content: "let x = 1" - }; - const host = createWatchedSystem([f, libFile]); - const watch = createWatchOfFilesAndCompilerOptions([f.path], host, { allowNonTsExtensions: true }); - checkProgramActualFiles(watch(), [f.path, libFile.path]); - }); - - it("Options Diagnostic locations reported correctly with changes in configFile contents when options change", () => { - const file = { - path: "/a/b/app.ts", - content: "let x = 10" - }; - const configFileContentBeforeComment = `{`; - const configFileContentComment = ` - // comment - // More comment`; - const configFileContentAfterComment = ` - "compilerOptions": { - "allowJs": true, - "declaration": true - } - }`; - const configFileContentWithComment = configFileContentBeforeComment + configFileContentComment + configFileContentAfterComment; - const configFileContentWithoutCommentLine = configFileContentBeforeComment + configFileContentAfterComment; - const configFile = { - path: "/a/b/tsconfig.json", - content: configFileContentWithComment - }; - - const files = [file, libFile, configFile]; - const host = createWatchedSystem(files); - const watch = createWatchOfConfigFile(configFile.path, host); - const errors = () => [ - getDiagnosticOfFile(watch().getCompilerOptions().configFile!, configFile.content.indexOf('"allowJs"'), '"allowJs"'.length, Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"), - getDiagnosticOfFile(watch().getCompilerOptions().configFile!, configFile.content.indexOf('"declaration"'), '"declaration"'.length, Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration") - ]; - const intialErrors = errors(); - checkOutputErrorsInitial(host, intialErrors); - - configFile.content = configFileContentWithoutCommentLine; - host.reloadFS(files); - host.runQueuedTimeoutCallbacks(); - const nowErrors = errors(); - checkOutputErrorsIncremental(host, nowErrors); - assert.equal(nowErrors[0].start, intialErrors[0].start! - configFileContentComment.length); - assert.equal(nowErrors[1].start, intialErrors[1].start! - configFileContentComment.length); - }); - - describe("should not trigger should not trigger recompilation because of program emit", () => { - function verifyWithOptions(options: CompilerOptions, outputFiles: ReadonlyArray) { - const proj = "/user/username/projects/myproject"; - const file1: File = { - path: `${proj}/file1.ts`, - content: "export const c = 30;" - }; - const file2: File = { - path: `${proj}/src/file2.ts`, - content: `import {c} from "file1"; export const d = 30;` - }; - const tsconfig: File = { - path: `${proj}/tsconfig.json`, - content: generateTSConfig(options, emptyArray, "\n") - }; - const host = createWatchedSystem([file1, file2, libFile, tsconfig], { currentDirectory: proj }); - const watch = createWatchOfConfigFile(tsconfig.path, host, /*maxNumberOfFilesToIterateForInvalidation*/1); - checkProgramActualFiles(watch(), [file1.path, file2.path, libFile.path]); - - outputFiles.forEach(f => host.fileExists(f)); - - // This should be 0 - host.checkTimeoutQueueLengthAndRun(0); - } - - it("without outDir or outFile is specified", () => { - verifyWithOptions({ module: ModuleKind.AMD }, ["file1.js", "src/file2.js"]); - }); - - it("with outFile", () => { - verifyWithOptions({ module: ModuleKind.AMD, outFile: "build/outFile.js" }, ["build/outFile.js"]); - }); - - it("when outDir is specified", () => { - verifyWithOptions({ module: ModuleKind.AMD, outDir: "build" }, ["build/file1.js", "build/src/file2.js"]); - }); - - it("when outDir and declarationDir is specified", () => { - verifyWithOptions({ module: ModuleKind.AMD, outDir: "build", declaration: true, declarationDir: "decls" }, - ["build/file1.js", "build/src/file2.js", "decls/file1.d.ts", "decls/src/file2.d.ts"]); - }); - - it("declarationDir is specified", () => { - verifyWithOptions({ module: ModuleKind.AMD, declaration: true, declarationDir: "decls" }, - ["file1.js", "src/file2.js", "decls/file1.d.ts", "decls/src/file2.d.ts"]); - }); - }); - - it("shouldnt report error about unused function incorrectly when file changes from global to module", () => { - const getFileContent = (asModule: boolean) => ` - function one() {} - ${asModule ? "export " : ""}function two() { - return function three() { - one(); - } - }`; - const file: File = { - path: "/a/b/file.ts", - content: getFileContent(/*asModule*/ false) - }; - const files = [file, libFile]; - const host = createWatchedSystem(files); - const watch = createWatchOfFilesAndCompilerOptions([file.path], host, { - noUnusedLocals: true - }); - checkProgramActualFiles(watch(), files.map(file => file.path)); - checkOutputErrorsInitial(host, []); - - file.content = getFileContent(/*asModule*/ true); - host.reloadFS(files); - host.runQueuedTimeoutCallbacks(); - checkProgramActualFiles(watch(), files.map(file => file.path)); - checkOutputErrorsIncremental(host, []); - }); - - it("watched files when file is deleted and new file is added as part of change", () => { - const projectLocation = "/home/username/project"; - const file: File = { - path: `${projectLocation}/src/file1.ts`, - content: "var a = 10;" - }; - const configFile: File = { - path: `${projectLocation}/tsconfig.json`, - content: "{}" - }; - const files = [file, libFile, configFile]; - const host = createWatchedSystem(files); - const watch = createWatchOfConfigFile(configFile.path, host); - verifyProgram(); - - file.path = file.path.replace("file1", "file2"); - host.reloadFS(files); - host.runQueuedTimeoutCallbacks(); - verifyProgram(); - - function verifyProgram() { - checkProgramActualFiles(watch(), mapDefined(files, f => f === configFile ? undefined : f.path)); - checkWatchedDirectories(host, [], /*recursive*/ false); - checkWatchedDirectories(host, [projectLocation, `${projectLocation}/node_modules/@types`], /*recursive*/ true); - checkWatchedFiles(host, files.map(f => f.path)); - } - }); - - it("updates errors correctly when declaration emit is disabled in compiler options", () => { - const currentDirectory = "/user/username/projects/myproject"; - const aFile: File = { - path: `${currentDirectory}/a.ts`, - content: `import test from './b'; -test(4, 5);` - }; - const bFileContent = `function test(x: number, y: number) { - return x + y / 5; -} -export default test;`; - const bFile: File = { - path: `${currentDirectory}/b.ts`, - content: bFileContent - }; - const tsconfigFile: File = { - path: `${currentDirectory}/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { - module: "commonjs", - noEmit: true, - strict: true, - } - }) - }; - const files = [aFile, bFile, libFile, tsconfigFile]; - const host = createWatchedSystem(files, { currentDirectory }); - const watch = createWatchOfConfigFile("tsconfig.json", host); - checkOutputErrorsInitial(host, emptyArray); - - changeParameterType("x", "string", [ - getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.indexOf("4"), 1, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, "4", "string") - ]); - changeParameterType("y", "string", [ - getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.indexOf("5"), 1, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, "5", "string"), - getDiagnosticOfFileFromProgram(watch(), bFile.path, bFile.content.indexOf("y /"), 1, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type) - ]); - - function changeParameterType(parameterName: string, toType: string, expectedErrors: ReadonlyArray) { - const newContent = bFileContent.replace(new RegExp(`${parameterName}\: [a-z]*`), `${parameterName}: ${toType}`); - - verifyErrorsWithBFileContents(newContent, expectedErrors); - verifyErrorsWithBFileContents(bFileContent, emptyArray); - } - - function verifyErrorsWithBFileContents(content: string, expectedErrors: ReadonlyArray) { - host.writeFile(bFile.path, content); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, expectedErrors); - } - }); - - it("updates errors when deep import file changes", () => { - const currentDirectory = "/user/username/projects/myproject"; - const aFile: File = { - path: `${currentDirectory}/a.ts`, - content: `import {B} from './b'; -declare var console: any; -let b = new B(); -console.log(b.c.d);` - }; - const bFile: File = { - path: `${currentDirectory}/b.ts`, - content: `import {C} from './c'; -export class B -{ - c = new C(); -}` - }; - const cFile: File = { - path: `${currentDirectory}/c.ts`, - content: `export class C -{ - d = 1; -}` - }; - const config: File = { - path: `${currentDirectory}/tsconfig.json`, - content: `{}` - }; - const files = [aFile, bFile, cFile, config, libFile]; - const host = createWatchedSystem(files, { currentDirectory }); - const watch = createWatchOfConfigFile("tsconfig.json", host); - checkProgramActualFiles(watch(), [aFile.path, bFile.path, cFile.path, libFile.path]); - checkOutputErrorsInitial(host, emptyArray); - const modifiedTimeOfAJs = host.getModifiedTime(`${currentDirectory}/a.js`); - host.writeFile(cFile.path, cFile.content.replace("d", "d2")); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, [ - getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.lastIndexOf("d"), 1, Diagnostics.Property_0_does_not_exist_on_type_1, "d", "C") - ]); - // File a need not be rewritten - assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); - }); - - it("updates errors when strictNullChecks changes", () => { - const currentDirectory = "/user/username/projects/myproject"; - const aFile: File = { - path: `${currentDirectory}/a.ts`, - content: `declare function foo(): null | { hello: any }; -foo().hello` - }; - const compilerOptions: CompilerOptions = { - }; - const config: File = { - path: `${currentDirectory}/tsconfig.json`, - content: JSON.stringify({ compilerOptions }) - }; - const files = [aFile, config, libFile]; - const host = createWatchedSystem(files, { currentDirectory }); - const watch = createWatchOfConfigFile("tsconfig.json", host); - checkProgramActualFiles(watch(), [aFile.path, libFile.path]); - checkOutputErrorsInitial(host, emptyArray); - const modifiedTimeOfAJs = host.getModifiedTime(`${currentDirectory}/a.js`); - compilerOptions.strictNullChecks = true; - host.writeFile(config.path, JSON.stringify({ compilerOptions })); - host.runQueuedTimeoutCallbacks(); - const expectedStrictNullErrors = [ - getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.lastIndexOf("foo()"), 5, Diagnostics.Object_is_possibly_null) - ]; - checkOutputErrorsIncremental(host, expectedStrictNullErrors); - // File a need not be rewritten - assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); - compilerOptions.strict = true; - delete (compilerOptions.strictNullChecks); - host.writeFile(config.path, JSON.stringify({ compilerOptions })); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, expectedStrictNullErrors); - // File a need not be rewritten - assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); - delete (compilerOptions.strict); - host.writeFile(config.path, JSON.stringify({ compilerOptions })); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, emptyArray); - // File a need not be rewritten - assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); - }); - }); - - describe("tsc-watch emit with outFile or out setting", () => { - function createWatchForOut(out?: string, outFile?: string) { - const host = createWatchedSystem([]); - const config: FileOrFolderEmit = { - path: "/a/tsconfig.json", - content: JSON.stringify({ - compilerOptions: { listEmittedFiles: true } - }) - }; - - let getOutput: (file: File) => string; - if (out) { - config.content = JSON.stringify({ - compilerOptions: { listEmittedFiles: true, out } - }); - getOutput = __ => getEmittedLineForSingleFileOutput(out, host); - } - else if (outFile) { - config.content = JSON.stringify({ - compilerOptions: { listEmittedFiles: true, outFile } - }); - getOutput = __ => getEmittedLineForSingleFileOutput(outFile, host); - } - else { - getOutput = file => getEmittedLineForMultiFileOutput(file, host); - } - - const f1 = getFileOrFolderEmit({ - path: "/a/a.ts", - content: "let x = 1" - }, getOutput); - const f2 = getFileOrFolderEmit({ - path: "/a/b.ts", - content: "let y = 1" - }, getOutput); - - const files = [f1, f2, config, libFile]; - host.reloadFS(files); - createWatchOfConfigFile(config.path, host); - - const allEmittedLines = getEmittedLines(files); - checkOutputContains(host, allEmittedLines); - host.clearOutput(); - - f1.content = "let x = 11"; - host.reloadFS(files); - host.runQueuedTimeoutCallbacks(); - checkAffectedLines(host, [f1], allEmittedLines); - } - - it("projectUsesOutFile should not be returned if not set", () => { - createWatchForOut(); - }); - - it("projectUsesOutFile should be true if out is set", () => { - const outJs = "/a/out.js"; - createWatchForOut(outJs); - }); - - it("projectUsesOutFile should be true if outFile is set", () => { - const outJs = "/a/out.js"; - createWatchForOut(/*out*/ undefined, outJs); - }); - - function verifyFilesEmittedOnce(useOutFile: boolean) { - const file1: File = { - path: "/a/b/output/AnotherDependency/file1.d.ts", - content: "declare namespace Common.SomeComponent.DynamicMenu { enum Z { Full = 0, Min = 1, Average = 2, } }" - }; - const file2: File = { - path: "/a/b/dependencies/file2.d.ts", - content: "declare namespace Dependencies.SomeComponent { export class SomeClass { version: string; } }" - }; - const file3: File = { - path: "/a/b/project/src/main.ts", - content: "namespace Main { export function fooBar() {} }" - }; - const file4: File = { - path: "/a/b/project/src/main2.ts", - content: "namespace main.file4 { import DynamicMenu = Common.SomeComponent.DynamicMenu; export function foo(a: DynamicMenu.z) { } }" - }; - const configFile: File = { - path: "/a/b/project/tsconfig.json", - content: JSON.stringify({ - compilerOptions: useOutFile ? - { outFile: "../output/common.js", target: "es5" } : - { outDir: "../output", target: "es5" }, - files: [file1.path, file2.path, file3.path, file4.path] - }) - }; - const files = [file1, file2, file3, file4]; - const allfiles = files.concat(configFile); - const host = createWatchedSystem(allfiles); - const originalWriteFile = host.writeFile.bind(host); - const mapOfFilesWritten = createMap(); - host.writeFile = (p: string, content: string) => { - const count = mapOfFilesWritten.get(p); - mapOfFilesWritten.set(p, count ? count + 1 : 1); - return originalWriteFile(p, content); - }; - createWatchOfConfigFile(configFile.path, host); - if (useOutFile) { - // Only out file - assert.equal(mapOfFilesWritten.size, 1); - } - else { - // main.js and main2.js - assert.equal(mapOfFilesWritten.size, 2); - } - mapOfFilesWritten.forEach((value, key) => { - assert.equal(value, 1, "Key: " + key); - }); - } - - it("with --outFile and multiple declaration files in the program", () => { - verifyFilesEmittedOnce(/*useOutFile*/ true); - }); - - it("without --outFile and multiple declaration files in the program", () => { - verifyFilesEmittedOnce(/*useOutFile*/ false); - }); - }); - - describe("tsc-watch emit for configured projects", () => { - const file1Consumer1Path = "/a/b/file1Consumer1.ts"; - const moduleFile1Path = "/a/b/moduleFile1.ts"; - const configFilePath = "/a/b/tsconfig.json"; - interface InitialStateParams { - /** custom config file options */ - configObj?: any; - /** list of the files that will be emitted for first compilation */ - firstCompilationEmitFiles?: string[]; - /** get the emit file for file - default is multi file emit line */ - getEmitLine?(file: File, host: WatchedSystem): string; - /** Additional files and folders to add */ - getAdditionalFileOrFolder?(): File[]; - /** initial list of files to emit if not the default list */ - firstReloadFileList?: string[]; - } - function getInitialState({ configObj = {}, firstCompilationEmitFiles, getEmitLine, getAdditionalFileOrFolder, firstReloadFileList }: InitialStateParams = {}) { - const host = createWatchedSystem([]); - const getOutputName = getEmitLine ? (file: File) => getEmitLine(file, host) : - (file: File) => getEmittedLineForMultiFileOutput(file, host); - - const moduleFile1 = getFileOrFolderEmit({ - path: moduleFile1Path, - content: "export function Foo() { };", - }, getOutputName); - - const file1Consumer1 = getFileOrFolderEmit({ - path: file1Consumer1Path, - content: `import {Foo} from "./moduleFile1"; export var y = 10;`, - }, getOutputName); - - const file1Consumer2 = getFileOrFolderEmit({ - path: "/a/b/file1Consumer2.ts", - content: `import {Foo} from "./moduleFile1"; let z = 10;`, - }, getOutputName); - - const moduleFile2 = getFileOrFolderEmit({ - path: "/a/b/moduleFile2.ts", - content: `export var Foo4 = 10;`, - }, getOutputName); - - const globalFile3 = getFileOrFolderEmit({ - path: "/a/b/globalFile3.ts", - content: `interface GlobalFoo { age: number }` - }); - - const additionalFiles = getAdditionalFileOrFolder ? - map(getAdditionalFileOrFolder(), file => getFileOrFolderEmit(file, getOutputName)) : - []; - - (configObj.compilerOptions || (configObj.compilerOptions = {})).listEmittedFiles = true; - const configFile = getFileOrFolderEmit({ - path: configFilePath, - content: JSON.stringify(configObj) - }); - - const files = [moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2, configFile, libFile, ...additionalFiles]; - let allEmittedFiles = getEmittedLines(files); - host.reloadFS(firstReloadFileList ? getFiles(firstReloadFileList) : files); - - // Initial compile - createWatchOfConfigFile(configFile.path, host); - if (firstCompilationEmitFiles) { - checkAffectedLines(host, getFiles(firstCompilationEmitFiles), allEmittedFiles); - } - else { - checkOutputContains(host, allEmittedFiles); - } - host.clearOutput(); - - return { - moduleFile1, file1Consumer1, file1Consumer2, moduleFile2, globalFile3, configFile, - files, - getFile, - verifyAffectedFiles, - verifyAffectedAllFiles, - getOutputName - }; - - function getFiles(filelist: string[]) { - return map(filelist, getFile); - } - - function getFile(fileName: string) { - return find(files, file => file.path === fileName)!; - } - - function verifyAffectedAllFiles() { - host.reloadFS(files); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputContains(host, allEmittedFiles); - host.clearOutput(); - } - - function verifyAffectedFiles(expected: FileOrFolderEmit[], filesToReload?: FileOrFolderEmit[]) { - if (!filesToReload) { - filesToReload = files; - } - else if (filesToReload.length > files.length) { - allEmittedFiles = getEmittedLines(filesToReload); - } - host.reloadFS(filesToReload); - host.checkTimeoutQueueLengthAndRun(1); - checkAffectedLines(host, expected, allEmittedFiles); - host.clearOutput(); - } - } - - it("should contains only itself if a module file's shape didn't change, and all files referencing it if its shape changed", () => { - const { - moduleFile1, file1Consumer1, file1Consumer2, - verifyAffectedFiles - } = getInitialState(); - - // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` - moduleFile1.content = `export var T: number;export function Foo() { };`; - verifyAffectedFiles([moduleFile1, file1Consumer1, file1Consumer2]); - - // Change the content of moduleFile1 to `export var T: number;export function Foo() { console.log('hi'); };` - moduleFile1.content = `export var T: number;export function Foo() { console.log('hi'); };`; - verifyAffectedFiles([moduleFile1]); - }); - - it("should be up-to-date with the reference map changes", () => { - const { - moduleFile1, file1Consumer1, file1Consumer2, - verifyAffectedFiles - } = getInitialState(); - - // Change file1Consumer1 content to `export let y = Foo();` - file1Consumer1.content = `export let y = Foo();`; - verifyAffectedFiles([file1Consumer1]); - - // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` - moduleFile1.content = `export var T: number;export function Foo() { };`; - verifyAffectedFiles([moduleFile1, file1Consumer2]); - - // Add the import statements back to file1Consumer1 - file1Consumer1.content = `import {Foo} from "./moduleFile1";let y = Foo();`; - verifyAffectedFiles([file1Consumer1]); - - // Change the content of moduleFile1 to `export var T: number;export var T2: string;export function Foo() { };` - moduleFile1.content = `export var T: number;export var T2: string;export function Foo() { };`; - verifyAffectedFiles([moduleFile1, file1Consumer2, file1Consumer1]); - - // Multiple file edits in one go: - - // Change file1Consumer1 content to `export let y = Foo();` - // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` - file1Consumer1.content = `export let y = Foo();`; - moduleFile1.content = `export var T: number;export function Foo() { };`; - verifyAffectedFiles([moduleFile1, file1Consumer1, file1Consumer2]); - }); - - it("should be up-to-date with deleted files", () => { - const { - moduleFile1, file1Consumer1, file1Consumer2, - files, - verifyAffectedFiles - } = getInitialState(); - - // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` - moduleFile1.content = `export var T: number;export function Foo() { };`; - - // Delete file1Consumer2 - const filesToLoad = mapDefined(files, file => file === file1Consumer2 ? undefined : file); - verifyAffectedFiles([moduleFile1, file1Consumer1], filesToLoad); - }); - - it("should be up-to-date with newly created files", () => { - const { - moduleFile1, file1Consumer1, file1Consumer2, - files, - verifyAffectedFiles, - getOutputName - } = getInitialState(); - - const file1Consumer3 = getFileOrFolderEmit({ - path: "/a/b/file1Consumer3.ts", - content: `import {Foo} from "./moduleFile1"; let y = Foo();` - }, getOutputName); - moduleFile1.content = `export var T: number;export function Foo() { };`; - verifyAffectedFiles([moduleFile1, file1Consumer1, file1Consumer3, file1Consumer2], files.concat(file1Consumer3)); - }); - - it("should detect changes in non-root files", () => { - const { - moduleFile1, file1Consumer1, - verifyAffectedFiles - } = getInitialState({ configObj: { files: [file1Consumer1Path] }, firstCompilationEmitFiles: [file1Consumer1Path, moduleFile1Path] }); - - moduleFile1.content = `export var T: number;export function Foo() { };`; - verifyAffectedFiles([moduleFile1, file1Consumer1]); - - // change file1 internal, and verify only file1 is affected - moduleFile1.content += "var T1: number;"; - verifyAffectedFiles([moduleFile1]); - }); - - it("should return all files if a global file changed shape", () => { - const { - globalFile3, verifyAffectedAllFiles - } = getInitialState(); - - globalFile3.content += "var T2: string;"; - verifyAffectedAllFiles(); - }); - - it("should always return the file itself if '--isolatedModules' is specified", () => { - const { - moduleFile1, verifyAffectedFiles - } = getInitialState({ configObj: { compilerOptions: { isolatedModules: true } } }); - - moduleFile1.content = `export var T: number;export function Foo() { };`; - verifyAffectedFiles([moduleFile1]); - }); - - it("should always return the file itself if '--out' or '--outFile' is specified", () => { - const outFilePath = "/a/b/out.js"; - const { - moduleFile1, verifyAffectedFiles - } = getInitialState({ - configObj: { compilerOptions: { module: "system", outFile: outFilePath } }, - getEmitLine: (_, host) => getEmittedLineForSingleFileOutput(outFilePath, host) - }); - - moduleFile1.content = `export var T: number;export function Foo() { };`; - verifyAffectedFiles([moduleFile1]); - }); - - it("should return cascaded affected file list", () => { - const file1Consumer1Consumer1: File = { - path: "/a/b/file1Consumer1Consumer1.ts", - content: `import {y} from "./file1Consumer1";` - }; - const { - moduleFile1, file1Consumer1, file1Consumer2, verifyAffectedFiles, getFile - } = getInitialState({ - getAdditionalFileOrFolder: () => [file1Consumer1Consumer1] - }); - - const file1Consumer1Consumer1Emit = getFile(file1Consumer1Consumer1.path); - file1Consumer1.content += "export var T: number;"; - verifyAffectedFiles([file1Consumer1, file1Consumer1Consumer1Emit]); - - // Doesnt change the shape of file1Consumer1 - moduleFile1.content = `export var T: number;export function Foo() { };`; - verifyAffectedFiles([moduleFile1, file1Consumer1, file1Consumer2]); - - // Change both files before the timeout - file1Consumer1.content += "export var T2: number;"; - moduleFile1.content = `export var T2: number;export function Foo() { };`; - verifyAffectedFiles([moduleFile1, file1Consumer1, file1Consumer2, file1Consumer1Consumer1Emit]); - }); - - it("should work fine for files with circular references", () => { - // TODO: do not exit on such errors? Just continue to watch the files for update in watch mode - - const file1: File = { - path: "/a/b/file1.ts", - content: ` - /// - export var t1 = 10;` - }; - const file2: File = { - path: "/a/b/file2.ts", - content: ` - /// - export var t2 = 10;` - }; - const { - configFile, - getFile, - verifyAffectedFiles - } = getInitialState({ - firstCompilationEmitFiles: [file1.path, file2.path], - getAdditionalFileOrFolder: () => [file1, file2], - firstReloadFileList: [libFile.path, file1.path, file2.path, configFilePath] - }); - const file1Emit = getFile(file1.path), file2Emit = getFile(file2.path); - - file1Emit.content += "export var t3 = 10;"; - verifyAffectedFiles([file1Emit, file2Emit], [file1, file2, libFile, configFile]); - - }); - - it("should detect removed code file", () => { - const referenceFile1: File = { - path: "/a/b/referenceFile1.ts", - content: ` - /// - export var x = Foo();` - }; - const { - configFile, - getFile, - verifyAffectedFiles - } = getInitialState({ - firstCompilationEmitFiles: [referenceFile1.path, moduleFile1Path], - getAdditionalFileOrFolder: () => [referenceFile1], - firstReloadFileList: [libFile.path, referenceFile1.path, moduleFile1Path, configFilePath] - }); - - const referenceFile1Emit = getFile(referenceFile1.path); - verifyAffectedFiles([referenceFile1Emit], [libFile, referenceFile1Emit, configFile]); - }); - - it("should detect non-existing code file", () => { - const referenceFile1: File = { - path: "/a/b/referenceFile1.ts", - content: ` - /// - export var x = Foo();` - }; - const { - configFile, - moduleFile2, - getFile, - verifyAffectedFiles - } = getInitialState({ - firstCompilationEmitFiles: [referenceFile1.path], - getAdditionalFileOrFolder: () => [referenceFile1], - firstReloadFileList: [libFile.path, referenceFile1.path, configFilePath] - }); - - const referenceFile1Emit = getFile(referenceFile1.path); - referenceFile1Emit.content += "export var yy = Foo();"; - verifyAffectedFiles([referenceFile1Emit], [libFile, referenceFile1Emit, configFile]); - - // Create module File2 and see both files are saved - verifyAffectedFiles([referenceFile1Emit, moduleFile2], [libFile, moduleFile2, referenceFile1Emit, configFile]); - }); - }); - - describe("tsc-watch emit file content", () => { - interface EmittedFile extends File { - shouldBeWritten: boolean; - } - function getEmittedFiles(files: FileOrFolderEmit[], contents: string[]): EmittedFile[] { - return map(contents, (content, index) => { - return { - content, - path: changeExtension(files[index].path, Extension.Js), - shouldBeWritten: true - }; - } - ); - } - function verifyEmittedFiles(host: WatchedSystem, emittedFiles: EmittedFile[]) { - for (const { path, content, shouldBeWritten } of emittedFiles) { - if (shouldBeWritten) { - assert.isTrue(host.fileExists(path), `Expected file ${path} to be present`); - assert.equal(host.readFile(path), content, `Contents of file ${path} do not match`); - } - else { - assert.isNotTrue(host.fileExists(path), `Expected file ${path} to be absent`); - } - } - } - - function verifyEmittedFileContents(newLine: string, inputFiles: File[], initialEmittedFileContents: string[], - modifyFiles: (files: FileOrFolderEmit[], emitedFiles: EmittedFile[]) => FileOrFolderEmit[], configFile?: File) { - const host = createWatchedSystem([], { newLine }); - const files = concatenate( - map(inputFiles, file => getFileOrFolderEmit(file, fileToConvert => getEmittedLineForMultiFileOutput(fileToConvert, host))), - configFile ? [libFile, configFile] : [libFile] - ); - const allEmittedFiles = getEmittedLines(files); - host.reloadFS(files); - - // Initial compile - if (configFile) { - createWatchOfConfigFile(configFile.path, host); - } - else { - // First file as the root - createWatchOfFilesAndCompilerOptions([files[0].path], host, { listEmittedFiles: true }); - } - checkOutputContains(host, allEmittedFiles); - - const emittedFiles = getEmittedFiles(files, initialEmittedFileContents); - verifyEmittedFiles(host, emittedFiles); - host.clearOutput(); - - const affectedFiles = modifyFiles(files, emittedFiles); - host.reloadFS(files); - host.checkTimeoutQueueLengthAndRun(1); - checkAffectedLines(host, affectedFiles, allEmittedFiles); - - verifyEmittedFiles(host, emittedFiles); - } - - function verifyNewLine(newLine: string) { - const lines = ["var x = 1;", "var y = 2;"]; - const fileContent = lines.join(newLine); - const f = { - path: "/a/app.ts", - content: fileContent - }; - - verifyEmittedFileContents(newLine, [f], [fileContent + newLine], modifyFiles); - - function modifyFiles(files: FileOrFolderEmit[], emittedFiles: EmittedFile[]) { - files[0].content = fileContent + newLine + "var z = 3;"; - emittedFiles[0].content = files[0].content + newLine; - return [files[0]]; - } - } - - it("handles new lines: \\n", () => { - verifyNewLine("\n"); - }); - - it("handles new lines: \\r\\n", () => { - verifyNewLine("\r\n"); - }); - - it("should emit specified file", () => { - const file1 = { - path: "/a/b/f1.ts", - content: `export function Foo() { return 10; }` - }; - - const file2 = { - path: "/a/b/f2.ts", - content: `import {Foo} from "./f1"; export let y = Foo();` - }; - - const file3 = { - path: "/a/b/f3.ts", - content: `import {y} from "./f2"; let x = y;` - }; - - const configFile = { - path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: { listEmittedFiles: true } }) - }; - - verifyEmittedFileContents("\r\n", [file1, file2, file3], [ - `"use strict";\r\nexports.__esModule = true;\r\nfunction Foo() { return 10; }\r\nexports.Foo = Foo;\r\n`, - `"use strict";\r\nexports.__esModule = true;\r\nvar f1_1 = require("./f1");\r\nexports.y = f1_1.Foo();\r\n`, - `"use strict";\r\nexports.__esModule = true;\r\nvar f2_1 = require("./f2");\r\nvar x = f2_1.y;\r\n` - ], modifyFiles, configFile); - - function modifyFiles(files: FileOrFolderEmit[], emittedFiles: EmittedFile[]) { - files[0].content += `export function foo2() { return 2; }`; - emittedFiles[0].content += `function foo2() { return 2; }\r\nexports.foo2 = foo2;\r\n`; - emittedFiles[2].shouldBeWritten = false; - return files.slice(0, 2); - } - }); - - it("Elides const enums correctly in incremental compilation", () => { - const currentDirectory = "/user/someone/projects/myproject"; - const file1: File = { - path: `${currentDirectory}/file1.ts`, - content: "export const enum E1 { V = 1 }" - }; - const file2: File = { - path: `${currentDirectory}/file2.ts`, - content: `import { E1 } from "./file1"; export const enum E2 { V = E1.V }` - }; - const file3: File = { - path: `${currentDirectory}/file3.ts`, - content: `import { E2 } from "./file2"; const v: E2 = E2.V;` - }; - const strictAndEsModule = `"use strict";\nexports.__esModule = true;\n`; - verifyEmittedFileContents("\n", [file3, file2, file1], [ - `${strictAndEsModule}var v = 1 /* V */;\n`, - strictAndEsModule, - strictAndEsModule - ], modifyFiles); - - function modifyFiles(files: FileOrFolderEmit[], emittedFiles: EmittedFile[]) { - files[0].content += `function foo2() { return 2; }`; - emittedFiles[0].content += `function foo2() { return 2; }\n`; - emittedFiles[1].shouldBeWritten = false; - emittedFiles[2].shouldBeWritten = false; - return [files[0]]; - } - }); - - it("file is deleted and created as part of change", () => { - const projectLocation = "/home/username/project"; - const file: File = { - path: `${projectLocation}/app/file.ts`, - content: "var a = 10;" - }; - const fileJs = `${projectLocation}/app/file.js`; - const configFile: File = { - path: `${projectLocation}/tsconfig.json`, - content: JSON.stringify({ - include: [ - "app/**/*.ts" - ] - }) - }; - const files = [file, configFile, libFile]; - const host = createWatchedSystem(files, { currentDirectory: projectLocation, useCaseSensitiveFileNames: true }); - createWatchOfConfigFile("tsconfig.json", host); - verifyProgram(); - - file.content += "\nvar b = 10;"; - - host.reloadFS(files, { invokeFileDeleteCreateAsPartInsteadOfChange: true }); - host.runQueuedTimeoutCallbacks(); - verifyProgram(); - - function verifyProgram() { - assert.isTrue(host.fileExists(fileJs)); - assert.equal(host.readFile(fileJs), file.content + "\n"); - } - }); - }); - - describe("tsc-watch module resolution caching", () => { - it("works", () => { - const root = { - path: "/a/d/f0.ts", - content: `import {x} from "f1"` - }; - const imported = { - path: "/a/f1.ts", - content: `foo()` - }; - - const files = [root, imported, libFile]; - const host = createWatchedSystem(files); - const watch = createWatchOfFilesAndCompilerOptions([root.path], host, { module: ModuleKind.AMD }); - - const f1IsNotModule = getDiagnosticOfFileFromProgram(watch(), root.path, root.content.indexOf('"f1"'), '"f1"'.length, Diagnostics.File_0_is_not_a_module, imported.path); - const cannotFindFoo = getDiagnosticOfFileFromProgram(watch(), imported.path, imported.content.indexOf("foo"), "foo".length, Diagnostics.Cannot_find_name_0, "foo"); - - // ensure that imported file was found - checkOutputErrorsInitial(host, [f1IsNotModule, cannotFindFoo]); - - const originalFileExists = host.fileExists; - { - const newContent = `import {x} from "f1" - var x: string = 1;`; - root.content = newContent; - host.reloadFS(files); - - // patch fileExists to make sure that disk is not touched - host.fileExists = notImplemented; - - // trigger synchronization to make sure that import will be fetched from the cache - host.runQueuedTimeoutCallbacks(); - - // ensure file has correct number of errors after edit - checkOutputErrorsIncremental(host, [ - f1IsNotModule, - getDiagnosticOfFileFromProgram(watch(), root.path, newContent.indexOf("var x") + "var ".length, "x".length, Diagnostics.Type_0_is_not_assignable_to_type_1, 1, "string"), - cannotFindFoo - ]); - } - { - let fileExistsIsCalled = false; - host.fileExists = (fileName): boolean => { - if (fileName === "lib.d.ts") { - return false; - } - fileExistsIsCalled = true; - assert.isTrue(fileName.indexOf("/f2.") !== -1); - return originalFileExists.call(host, fileName); - }; - - root.content = `import {x} from "f2"`; - host.reloadFS(files); - - // trigger synchronization to make sure that LSHost will try to find 'f2' module on disk - host.runQueuedTimeoutCallbacks(); - - // ensure file has correct number of errors after edit - checkOutputErrorsIncremental(host, [ - getDiagnosticModuleNotFoundOfFile(watch(), root, "f2") - ]); - - assert.isTrue(fileExistsIsCalled); - } - { - let fileExistsCalled = false; - host.fileExists = (fileName): boolean => { - if (fileName === "lib.d.ts") { - return false; - } - fileExistsCalled = true; - assert.isTrue(fileName.indexOf("/f1.") !== -1); - return originalFileExists.call(host, fileName); - }; - - const newContent = `import {x} from "f1"`; - root.content = newContent; - - host.reloadFS(files); - host.runQueuedTimeoutCallbacks(); - - checkOutputErrorsIncremental(host, [f1IsNotModule, cannotFindFoo]); - assert.isTrue(fileExistsCalled); - } - }); - - it("loads missing files from disk", () => { - const root = { - path: `/a/foo.ts`, - content: `import {x} from "bar"` - }; - - const imported = { - path: `/a/bar.d.ts`, - content: `export const y = 1;` - }; - - const files = [root, libFile]; - const host = createWatchedSystem(files); - const originalFileExists = host.fileExists; - - let fileExistsCalledForBar = false; - host.fileExists = fileName => { - if (fileName === "lib.d.ts") { - return false; - } - if (!fileExistsCalledForBar) { - fileExistsCalledForBar = fileName.indexOf("/bar.") !== -1; - } - - return originalFileExists.call(host, fileName); - }; - - const watch = createWatchOfFilesAndCompilerOptions([root.path], host, { module: ModuleKind.AMD }); - - assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called"); - checkOutputErrorsInitial(host, [ - getDiagnosticModuleNotFoundOfFile(watch(), root, "bar") - ]); - - fileExistsCalledForBar = false; - root.content = `import {y} from "bar"`; - host.reloadFS(files.concat(imported)); - - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, emptyArray); - assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called."); - }); - - it("should compile correctly when resolved module goes missing and then comes back (module is not part of the root)", () => { - const root = { - path: `/a/foo.ts`, - content: `import {x} from "bar"` - }; - - const imported = { - path: `/a/bar.d.ts`, - content: `export const y = 1;export const x = 10;` - }; - - const files = [root, libFile]; - const filesWithImported = files.concat(imported); - const host = createWatchedSystem(filesWithImported); - const originalFileExists = host.fileExists; - let fileExistsCalledForBar = false; - host.fileExists = fileName => { - if (fileName === "lib.d.ts") { - return false; - } - if (!fileExistsCalledForBar) { - fileExistsCalledForBar = fileName.indexOf("/bar.") !== -1; - } - return originalFileExists.call(host, fileName); - }; - - const watch = createWatchOfFilesAndCompilerOptions([root.path], host, { module: ModuleKind.AMD }); - - assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called"); - checkOutputErrorsInitial(host, emptyArray); - - fileExistsCalledForBar = false; - host.reloadFS(files); - host.runQueuedTimeoutCallbacks(); - assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called."); - checkOutputErrorsIncremental(host, [ - getDiagnosticModuleNotFoundOfFile(watch(), root, "bar") - ]); - - fileExistsCalledForBar = false; - host.reloadFS(filesWithImported); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called."); - }); - - it("works when module resolution changes to ambient module", () => { - const root = { - path: "/a/b/foo.ts", - content: `import * as fs from "fs";` - }; - - const packageJson = { - path: "/a/b/node_modules/@types/node/package.json", - content: ` -{ - "main": "" -} -` - }; - - const nodeType = { - path: "/a/b/node_modules/@types/node/index.d.ts", - content: ` -declare module "fs" { - export interface Stats { - isFile(): boolean; - } -}` - }; - - const files = [root, libFile]; - const filesWithNodeType = files.concat(packageJson, nodeType); - const host = createWatchedSystem(files, { currentDirectory: "/a/b" }); - - const watch = createWatchOfFilesAndCompilerOptions([root.path], host, { }); - - checkOutputErrorsInitial(host, [ - getDiagnosticModuleNotFoundOfFile(watch(), root, "fs") - ]); - - host.reloadFS(filesWithNodeType); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, emptyArray); - }); - - it("works when included file with ambient module changes", () => { - const root = { - path: "/a/b/foo.ts", - content: ` -import * as fs from "fs"; -import * as u from "url"; -` - }; - - const file = { - path: "/a/b/bar.d.ts", - content: ` -declare module "url" { - export interface Url { - href?: string; - } -} -` - }; - - const fileContentWithFS = ` -declare module "fs" { - export interface Stats { - isFile(): boolean; - } -} -`; - - const files = [root, file, libFile]; - const host = createWatchedSystem(files, { currentDirectory: "/a/b" }); - - const watch = createWatchOfFilesAndCompilerOptions([root.path, file.path], host, {}); - - checkOutputErrorsInitial(host, [ - getDiagnosticModuleNotFoundOfFile(watch(), root, "fs") - ]); - - file.content += fileContentWithFS; - host.reloadFS(files); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, emptyArray); - }); - - it("works when reusing program with files from external library", () => { - interface ExpectedFile { path: string; isExpectedToEmit?: boolean; content?: string; } - const configDir = "/a/b/projects/myProject/src/"; - const file1: File = { - path: configDir + "file1.ts", - content: 'import module1 = require("module1");\nmodule1("hello");' - }; - const file2: File = { - path: configDir + "file2.ts", - content: 'import module11 = require("module1");\nmodule11("hello");' - }; - const module1: File = { - path: "/a/b/projects/myProject/node_modules/module1/index.js", - content: "module.exports = options => { return options.toString(); }" - }; - const configFile: File = { - path: configDir + "tsconfig.json", - content: JSON.stringify({ - compilerOptions: { - allowJs: true, - rootDir: ".", - outDir: "../dist", - moduleResolution: "node", - maxNodeModuleJsDepth: 1 - } - }) - }; - const outDirFolder = "/a/b/projects/myProject/dist/"; - const programFiles = [file1, file2, module1, libFile]; - const host = createWatchedSystem(programFiles.concat(configFile), { currentDirectory: "/a/b/projects/myProject/" }); - const watch = createWatchOfConfigFile(configFile.path, host); - checkProgramActualFiles(watch(), programFiles.map(f => f.path)); - checkOutputErrorsInitial(host, emptyArray); - const expectedFiles: ExpectedFile[] = [ - createExpectedEmittedFile(file1), - createExpectedEmittedFile(file2), - createExpectedToNotEmitFile("index.js"), - createExpectedToNotEmitFile("src/index.js"), - createExpectedToNotEmitFile("src/file1.js"), - createExpectedToNotEmitFile("src/file2.js"), - createExpectedToNotEmitFile("lib.js"), - createExpectedToNotEmitFile("lib.d.ts") - ]; - verifyExpectedFiles(expectedFiles); - - file1.content += "\n;"; - expectedFiles[0].content += ";\n"; // Only emit file1 with this change - expectedFiles[1].isExpectedToEmit = false; - host.reloadFS(programFiles.concat(configFile)); - host.runQueuedTimeoutCallbacks(); - checkProgramActualFiles(watch(), programFiles.map(f => f.path)); - checkOutputErrorsIncremental(host, emptyArray); - verifyExpectedFiles(expectedFiles); - - - function verifyExpectedFiles(expectedFiles: ExpectedFile[]) { - forEach(expectedFiles, f => { - assert.equal(!!host.fileExists(f.path), f.isExpectedToEmit, "File " + f.path + " is expected to " + (f.isExpectedToEmit ? "emit" : "not emit")); - if (f.isExpectedToEmit) { - assert.equal(host.readFile(f.path), f.content, "Expected contents of " + f.path); - } - }); - } - - function createExpectedToNotEmitFile(fileName: string): ExpectedFile { - return { - path: outDirFolder + fileName, - isExpectedToEmit: false - }; - } - - function createExpectedEmittedFile(file: File): ExpectedFile { - return { - path: removeFileExtension(file.path.replace(configDir, outDirFolder)) + Extension.Js, - isExpectedToEmit: true, - content: '"use strict";\nexports.__esModule = true;\n' + file.content.replace("import", "var") + "\n" - }; - } - }); - - it("works when renaming node_modules folder that already contains @types folder", () => { - const currentDirectory = "/user/username/projects/myproject"; - const file: File = { - path: `${currentDirectory}/a.ts`, - content: `import * as q from "qqq";` - }; - const module: File = { - path: `${currentDirectory}/node_modules2/@types/qqq/index.d.ts`, - content: "export {}" - }; - const files = [file, module, libFile]; - const host = createWatchedSystem(files, { currentDirectory }); - const watch = createWatchOfFilesAndCompilerOptions([file.path], host); - - checkProgramActualFiles(watch(), [file.path, libFile.path]); - checkOutputErrorsInitial(host, [getDiagnosticModuleNotFoundOfFile(watch(), file, "qqq")]); - checkWatchedDirectories(host, emptyArray, /*recursive*/ false); - checkWatchedDirectories(host, [`${currentDirectory}/node_modules`, `${currentDirectory}/node_modules/@types`], /*recursive*/ true); - - host.renameFolder(`${currentDirectory}/node_modules2`, `${currentDirectory}/node_modules`); - host.runQueuedTimeoutCallbacks(); - checkProgramActualFiles(watch(), [file.path, libFile.path, `${currentDirectory}/node_modules/@types/qqq/index.d.ts`]); - checkOutputErrorsIncremental(host, emptyArray); - }); - }); - - describe("tsc-watch with when module emit is specified as node", () => { - it("when instead of filechanged recursive directory watcher is invoked", () => { - const configFile: File = { - path: "/a/rootFolder/project/tsconfig.json", - content: JSON.stringify({ - compilerOptions: { - module: "none", - allowJs: true, - outDir: "Static/scripts/" - }, - include: [ - "Scripts/**/*" - ], - }) - }; - const outputFolder = "/a/rootFolder/project/Static/scripts/"; - const file1: File = { - path: "/a/rootFolder/project/Scripts/TypeScript.ts", - content: "var z = 10;" - }; - const file2: File = { - path: "/a/rootFolder/project/Scripts/Javascript.js", - content: "var zz = 10;" - }; - const files = [configFile, file1, file2, libFile]; - const host = createWatchedSystem(files); - const watch = createWatchOfConfigFile(configFile.path, host); - - checkProgramActualFiles(watch(), mapDefined(files, f => f === configFile ? undefined : f.path)); - file1.content = "var zz30 = 100;"; - host.reloadFS(files, { invokeDirectoryWatcherInsteadOfFileChanged: true }); - host.runQueuedTimeoutCallbacks(); - - checkProgramActualFiles(watch(), mapDefined(files, f => f === configFile ? undefined : f.path)); - const outputFile1 = changeExtension((outputFolder + getBaseFileName(file1.path)), ".js"); - assert.isTrue(host.fileExists(outputFile1)); - assert.equal(host.readFile(outputFile1), file1.content + host.newLine); - }); - }); - - describe("tsc-watch console clearing", () => { - const currentDirectoryLog = "Current directory: / CaseSensitiveFileNames: false\n"; - const fileWatcherAddedLog = [ - "FileWatcher:: Added:: WatchInfo: /f.ts 250 Source file\n", - "FileWatcher:: Added:: WatchInfo: /a/lib/lib.d.ts 250 Source file\n" - ]; - - const file: File = { - path: "/f.ts", - content: "" - }; - - function getProgramSynchronizingLog(options: CompilerOptions) { - return [ - "Synchronizing program\n", - "CreatingProgramWith::\n", - " roots: [\"/f.ts\"]\n", - ` options: ${JSON.stringify(options)}\n` - ]; - } - - function isConsoleClearDisabled(options: CompilerOptions) { - return options.diagnostics || options.extendedDiagnostics || options.preserveWatchOutput; - } - - function verifyCompilation(host: WatchedSystem, options: CompilerOptions, initialDisableOptions?: CompilerOptions) { - const disableConsoleClear = isConsoleClearDisabled(options); - const hasLog = options.extendedDiagnostics || options.diagnostics; - checkOutputErrorsInitial(host, emptyArray, initialDisableOptions ? isConsoleClearDisabled(initialDisableOptions) : disableConsoleClear, hasLog ? [ - currentDirectoryLog, - ...getProgramSynchronizingLog(options), - ...(options.extendedDiagnostics ? fileWatcherAddedLog : emptyArray) - ] : undefined); - host.modifyFile(file.path, "//"); - host.runQueuedTimeoutCallbacks(); - checkOutputErrorsIncremental(host, emptyArray, disableConsoleClear, hasLog ? [ - "FileWatcher:: Triggered with /f.ts 1:: WatchInfo: /f.ts 250 Source file\n", - "Scheduling update\n", - "Elapsed:: 0ms FileWatcher:: Triggered with /f.ts 1:: WatchInfo: /f.ts 250 Source file\n" - ] : undefined, hasLog ? getProgramSynchronizingLog(options) : undefined); - } - - function checkConsoleClearingUsingCommandLineOptions(options: CompilerOptions = {}) { - const files = [file, libFile]; - const host = createWatchedSystem(files); - createWatchOfFilesAndCompilerOptions([file.path], host, options); - verifyCompilation(host, options); - } - - it("without --diagnostics or --extendedDiagnostics", () => { - checkConsoleClearingUsingCommandLineOptions(); - }); - it("with --diagnostics", () => { - checkConsoleClearingUsingCommandLineOptions({ - diagnostics: true, - }); - }); - it("with --extendedDiagnostics", () => { - checkConsoleClearingUsingCommandLineOptions({ - extendedDiagnostics: true, - }); - }); - it("with --preserveWatchOutput", () => { - checkConsoleClearingUsingCommandLineOptions({ - preserveWatchOutput: true, - }); - }); - - describe("when preserveWatchOutput is true in config file", () => { - const compilerOptions: CompilerOptions = { - preserveWatchOutput: true - }; - const configFile: File = { - path: "/tsconfig.json", - content: JSON.stringify({ compilerOptions }) - }; - const files = [file, configFile, libFile]; - it("using createWatchOfConfigFile ", () => { - const host = createWatchedSystem(files); - createWatchOfConfigFile(configFile.path, host); - // Initially console is cleared if --preserveOutput is not provided since the config file is yet to be parsed - verifyCompilation(host, compilerOptions, {}); - }); - it("when createWatchProgram is invoked with configFileParseResult on WatchCompilerHostOfConfigFile", () => { - const host = createWatchedSystem(files); - const reportDiagnostic = createDiagnosticReporter(host); - const optionsToExtend: CompilerOptions = {}; - const configParseResult = parseConfigFileWithSystem(configFile.path, optionsToExtend, host, reportDiagnostic)!; - const watchCompilerHost = createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath!, optionsToExtend, host, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(host)); - watchCompilerHost.configFileParsingResult = configParseResult; - createWatchProgram(watchCompilerHost); - verifyCompilation(host, compilerOptions); - }); - }); - }); - - describe("tsc-watch with different polling/non polling options", () => { - it("watchFile using dynamic priority polling", () => { - const projectFolder = "/a/username/project"; - const file1: File = { - path: `${projectFolder}/typescript.ts`, - content: "var z = 10;" - }; - const files = [file1, libFile]; - const environmentVariables = createMap(); - environmentVariables.set("TSC_WATCHFILE", "DynamicPriorityPolling"); - const host = createWatchedSystem(files, { environmentVariables }); - const watch = createWatchOfFilesAndCompilerOptions([file1.path], host); - - const initialProgram = watch(); - verifyProgram(); - - const mediumPollingIntervalThreshold = unchangedPollThresholds[PollingInterval.Medium]; - for (let index = 0; index < mediumPollingIntervalThreshold; index++) { - // Transition libFile and file1 to low priority queue - host.checkTimeoutQueueLengthAndRun(1); - assert.deepEqual(watch(), initialProgram); - } - - // Make a change to file - file1.content = "var zz30 = 100;"; - host.reloadFS(files); - - // This should detect change in the file - host.checkTimeoutQueueLengthAndRun(1); - assert.deepEqual(watch(), initialProgram); - - // Callbacks: medium priority + high priority queue and scheduled program update - host.checkTimeoutQueueLengthAndRun(3); - // During this timeout the file would be detected as unchanged - let fileUnchangeDetected = 1; - const newProgram = watch(); - assert.notStrictEqual(newProgram, initialProgram); - - verifyProgram(); - const outputFile1 = changeExtension(file1.path, ".js"); - assert.isTrue(host.fileExists(outputFile1)); - assert.equal(host.readFile(outputFile1), file1.content + host.newLine); - - const newThreshold = unchangedPollThresholds[PollingInterval.Low] + mediumPollingIntervalThreshold; - for (; fileUnchangeDetected < newThreshold; fileUnchangeDetected++) { - // For high + Medium/low polling interval - host.checkTimeoutQueueLengthAndRun(2); - assert.deepEqual(watch(), newProgram); - } - - // Everything goes in high polling interval queue - host.checkTimeoutQueueLengthAndRun(1); - assert.deepEqual(watch(), newProgram); - - function verifyProgram() { - checkProgramActualFiles(watch(), files.map(f => f.path)); - checkWatchedFiles(host, []); - checkWatchedDirectories(host, [], /*recursive*/ false); - checkWatchedDirectories(host, [], /*recursive*/ true); - } - }); - - describe("tsc-watch when watchDirectories implementation", () => { - function verifyRenamingFileInSubFolder(tscWatchDirectory: Tsc_WatchDirectory) { - const projectFolder = "/a/username/project"; - const projectSrcFolder = `${projectFolder}/src`; - const configFile: File = { - path: `${projectFolder}/tsconfig.json`, - content: "{}" - }; - const file: File = { - path: `${projectSrcFolder}/file1.ts`, - content: "" - }; - const programFiles = [file, libFile]; - const files = [file, configFile, libFile]; - const environmentVariables = createMap(); - environmentVariables.set("TSC_WATCHDIRECTORY", tscWatchDirectory); - const host = createWatchedSystem(files, { environmentVariables }); - const watch = createWatchOfConfigFile(configFile.path, host); - const projectFolders = [projectFolder, projectSrcFolder, `${projectFolder}/node_modules/@types`]; - // Watching files config file, file, lib file - const expectedWatchedFiles = files.map(f => f.path); - const expectedWatchedDirectories = tscWatchDirectory === Tsc_WatchDirectory.NonRecursiveWatchDirectory ? projectFolders : emptyArray; - if (tscWatchDirectory === Tsc_WatchDirectory.WatchFile) { - expectedWatchedFiles.push(...projectFolders); - } - - verifyProgram(checkOutputErrorsInitial); - - // Rename the file: - file.path = file.path.replace("file1.ts", "file2.ts"); - expectedWatchedFiles[0] = file.path; - host.reloadFS(files); - if (tscWatchDirectory === Tsc_WatchDirectory.DynamicPolling) { - // With dynamic polling the fs change would be detected only by running timeouts - host.runQueuedTimeoutCallbacks(); - } - // Delayed update program - host.runQueuedTimeoutCallbacks(); - verifyProgram(checkOutputErrorsIncremental); - - function verifyProgram(checkOutputErrors: (host: WatchedSystem, errors: ReadonlyArray) => void) { - checkProgramActualFiles(watch(), programFiles.map(f => f.path)); - checkOutputErrors(host, emptyArray); - - const outputFile = changeExtension(file.path, ".js"); - assert(host.fileExists(outputFile)); - assert.equal(host.readFile(outputFile), file.content); - - checkWatchedDirectories(host, emptyArray, /*recursive*/ true); - - // Watching config file, file, lib file and directories - checkWatchedFilesDetailed(host, expectedWatchedFiles, 1); - checkWatchedDirectoriesDetailed(host, expectedWatchedDirectories, 1, /*recursive*/ false); - } - } - - it("uses watchFile when renaming file in subfolder", () => { - verifyRenamingFileInSubFolder(Tsc_WatchDirectory.WatchFile); - }); - - it("uses non recursive watchDirectory when renaming file in subfolder", () => { - verifyRenamingFileInSubFolder(Tsc_WatchDirectory.NonRecursiveWatchDirectory); - }); - - it("uses non recursive dynamic polling when renaming file in subfolder", () => { - verifyRenamingFileInSubFolder(Tsc_WatchDirectory.DynamicPolling); - }); - - it("when there are symlinks to folders in recursive folders", () => { - const cwd = "/home/user/projects/myproject"; - const file1: File = { - path: `${cwd}/src/file.ts`, - content: `import * as a from "a"` - }; - const tsconfig: File = { - path: `${cwd}/tsconfig.json`, - content: `{ "compilerOptions": { "extendedDiagnostics": true, "traceResolution": true }}` - }; - const realA: File = { - path: `${cwd}/node_modules/reala/index.d.ts`, - content: `export {}` - }; - const realB: File = { - path: `${cwd}/node_modules/realb/index.d.ts`, - content: `export {}` - }; - const symLinkA: SymLink = { - path: `${cwd}/node_modules/a`, - symLink: `${cwd}/node_modules/reala` - }; - const symLinkB: SymLink = { - path: `${cwd}/node_modules/b`, - symLink: `${cwd}/node_modules/realb` - }; - const symLinkBInA: SymLink = { - path: `${cwd}/node_modules/reala/node_modules/b`, - symLink: `${cwd}/node_modules/b` - }; - const symLinkAInB: SymLink = { - path: `${cwd}/node_modules/realb/node_modules/a`, - symLink: `${cwd}/node_modules/a` - }; - const files = [file1, tsconfig, realA, realB, symLinkA, symLinkB, symLinkBInA, symLinkAInB]; - const environmentVariables = createMap(); - environmentVariables.set("TSC_WATCHDIRECTORY", Tsc_WatchDirectory.NonRecursiveWatchDirectory); - const host = createWatchedSystem(files, { environmentVariables, currentDirectory: cwd }); - createWatchOfConfigFile("tsconfig.json", host); - checkWatchedDirectories(host, emptyArray, /*recursive*/ true); - checkWatchedDirectories(host, [cwd, `${cwd}/node_modules`, `${cwd}/node_modules/@types`, `${cwd}/node_modules/reala`, `${cwd}/node_modules/realb`, - `${cwd}/node_modules/reala/node_modules`, `${cwd}/node_modules/realb/node_modules`, `${cwd}/src`], /*recursive*/ false); - }); - }); - }); - - describe("tsc-watch with modules linked to sibling folder", () => { - const projectRoot = "/user/username/projects/project"; - const mainPackageRoot = `${projectRoot}/main`; - const linkedPackageRoot = `${projectRoot}/linked-package`; - const mainFile: File = { - path: `${mainPackageRoot}/index.ts`, - content: "import { Foo } from '@scoped/linked-package'" - }; - const config: File = { - path: `${mainPackageRoot}/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { module: "commonjs", moduleResolution: "node", baseUrl: ".", rootDir: "." }, - files: ["index.ts"] - }) - }; - const linkedPackageInMain: SymLink = { - path: `${mainPackageRoot}/node_modules/@scoped/linked-package`, - symLink: `${linkedPackageRoot}` - }; - const linkedPackageJson: File = { - path: `${linkedPackageRoot}/package.json`, - content: JSON.stringify({ name: "@scoped/linked-package", version: "0.0.1", types: "dist/index.d.ts", main: "dist/index.js" }) - }; - const linkedPackageIndex: File = { - path: `${linkedPackageRoot}/dist/index.d.ts`, - content: "export * from './other';" - }; - const linkedPackageOther: File = { - path: `${linkedPackageRoot}/dist/other.d.ts`, - content: 'export declare const Foo = "BAR";' - }; - - it("verify watched directories", () => { - const files = [libFile, mainFile, config, linkedPackageInMain, linkedPackageJson, linkedPackageIndex, linkedPackageOther]; - const host = createWatchedSystem(files, { currentDirectory: mainPackageRoot }); - createWatchOfConfigFile("tsconfig.json", host); - checkWatchedFilesDetailed(host, [libFile.path, mainFile.path, config.path, linkedPackageIndex.path, linkedPackageOther.path], 1); - checkWatchedDirectories(host, emptyArray, /*recursive*/ false); - checkWatchedDirectoriesDetailed(host, [`${mainPackageRoot}/@scoped`, `${mainPackageRoot}/node_modules`, linkedPackageRoot, `${mainPackageRoot}/node_modules/@types`, `${projectRoot}/node_modules/@types`], 1, /*recursive*/ true); - }); - }); - - describe("tsc-watch with custom module resolution", () => { - const projectRoot = "/user/username/projects/project"; - const configFileJson: any = { - compilerOptions: { module: "commonjs", resolveJsonModule: true }, - files: ["index.ts"] - }; - const mainFile: File = { - path: `${projectRoot}/index.ts`, - content: "import settings from './settings.json';" - }; - const config: File = { - path: `${projectRoot}/tsconfig.json`, - content: JSON.stringify(configFileJson) - }; - const settingsJson: File = { - path: `${projectRoot}/settings.json`, - content: JSON.stringify({ content: "Print this" }) - }; - - it("verify that module resolution with json extension works when returned without extension", () => { - const files = [libFile, mainFile, config, settingsJson]; - const host = createWatchedSystem(files, { currentDirectory: projectRoot }); - const compilerHost = createWatchCompilerHostOfConfigFile(config.path, {}, host); - const parsedCommandResult = parseJsonConfigFileContent(configFileJson, host, config.path); - compilerHost.resolveModuleNames = (moduleNames, containingFile) => moduleNames.map(m => { - const result = resolveModuleName(m, containingFile, parsedCommandResult.options, compilerHost); - const resolvedModule = result.resolvedModule!; - return { - resolvedFileName: resolvedModule.resolvedFileName, - isExternalLibraryImport: resolvedModule.isExternalLibraryImport, - originalFileName: resolvedModule.originalPath, - }; - }); - const watch = createWatchProgram(compilerHost); - const program = watch.getCurrentProgram().getProgram(); - checkProgramActualFiles(program, [mainFile.path, libFile.path, settingsJson.path]); - }); - }); -} diff --git a/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts b/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts new file mode 100644 index 00000000000..26b7857347a --- /dev/null +++ b/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts @@ -0,0 +1,704 @@ +namespace ts.projectSystem { + function getNumberOfWatchesInvokedForRecursiveWatches(recursiveWatchedDirs: string[], file: string) { + return countWhere(recursiveWatchedDirs, dir => file.length > dir.length && startsWith(file, dir) && file[dir.length] === directorySeparator); + } + + describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectSystem CachingFileSystemInformation", () => { + enum CalledMapsWithSingleArg { + fileExists = "fileExists", + directoryExists = "directoryExists", + getDirectories = "getDirectories", + readFile = "readFile" + } + enum CalledMapsWithFiveArgs { + readDirectory = "readDirectory" + } + type CalledMaps = CalledMapsWithSingleArg | CalledMapsWithFiveArgs; + function createCallsTrackingHost(host: TestServerHost) { + const calledMaps: Record> & Record, ReadonlyArray, ReadonlyArray, number]>> = { + fileExists: setCallsTrackingWithSingleArgFn(CalledMapsWithSingleArg.fileExists), + directoryExists: setCallsTrackingWithSingleArgFn(CalledMapsWithSingleArg.directoryExists), + getDirectories: setCallsTrackingWithSingleArgFn(CalledMapsWithSingleArg.getDirectories), + readFile: setCallsTrackingWithSingleArgFn(CalledMapsWithSingleArg.readFile), + readDirectory: setCallsTrackingWithFiveArgFn(CalledMapsWithFiveArgs.readDirectory) + }; + + return { + verifyNoCall, + verifyCalledOnEachEntryNTimes, + verifyCalledOnEachEntry, + verifyNoHostCalls, + verifyNoHostCallsExceptFileExistsOnce, + verifyCalledOn, + clear + }; + + function setCallsTrackingWithSingleArgFn(prop: CalledMapsWithSingleArg) { + const calledMap = createMultiMap(); + const cb = (host)[prop].bind(host); + (host)[prop] = (f: string) => { + calledMap.add(f, /*value*/ true); + return cb(f); + }; + return calledMap; + } + + function setCallsTrackingWithFiveArgFn(prop: CalledMapsWithFiveArgs) { + const calledMap = createMultiMap<[U, V, W, X]>(); + const cb = (host)[prop].bind(host); + (host)[prop] = (f: string, arg1?: U, arg2?: V, arg3?: W, arg4?: X) => { + calledMap.add(f, [arg1!, arg2!, arg3!, arg4!]); // TODO: GH#18217 + return cb(f, arg1, arg2, arg3, arg4); + }; + return calledMap; + } + + function verifyCalledOn(callback: CalledMaps, name: string) { + const calledMap = calledMaps[callback]; + const result = calledMap.get(name); + assert.isTrue(result && !!result.length, `${callback} should be called with name: ${name}: ${arrayFrom(calledMap.keys())}`); + } + + function verifyNoCall(callback: CalledMaps) { + const calledMap = calledMaps[callback]; + assert.equal(calledMap.size, 0, `${callback} shouldn't be called: ${arrayFrom(calledMap.keys())}`); + } + + function verifyCalledOnEachEntry(callback: CalledMaps, expectedKeys: Map) { + TestFSWithWatch.checkMultiMapKeyCount(callback, calledMaps[callback], expectedKeys); + } + + function verifyCalledOnEachEntryNTimes(callback: CalledMaps, expectedKeys: ReadonlyArray, nTimes: number) { + TestFSWithWatch.checkMultiMapKeyCount(callback, calledMaps[callback], expectedKeys, nTimes); + } + + function verifyNoHostCalls() { + iterateOnCalledMaps(key => verifyNoCall(key)); + } + + function verifyNoHostCallsExceptFileExistsOnce(expectedKeys: ReadonlyArray) { + verifyCalledOnEachEntryNTimes(CalledMapsWithSingleArg.fileExists, expectedKeys, 1); + verifyNoCall(CalledMapsWithSingleArg.directoryExists); + verifyNoCall(CalledMapsWithSingleArg.getDirectories); + verifyNoCall(CalledMapsWithSingleArg.readFile); + verifyNoCall(CalledMapsWithFiveArgs.readDirectory); + } + + function clear() { + iterateOnCalledMaps(key => calledMaps[key].clear()); + } + + function iterateOnCalledMaps(cb: (key: CalledMaps) => void) { + for (const key in CalledMapsWithSingleArg) { + cb(key as CalledMapsWithSingleArg); + } + for (const key in CalledMapsWithFiveArgs) { + cb(key as CalledMapsWithFiveArgs); + } + } + } + + it("works using legacy resolution logic", () => { + let rootContent = `import {x} from "f1"`; + const root: File = { + path: "/c/d/f0.ts", + content: rootContent + }; + + const imported: File = { + path: "/c/f1.ts", + content: `foo()` + }; + + const host = createServerHost([root, imported]); + const projectService = createProjectService(host); + projectService.setCompilerOptionsForInferredProjects({ module: ModuleKind.AMD, noLib: true }); + projectService.openClientFile(root.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + const project = projectService.inferredProjects[0]; + const rootScriptInfo = project.getRootScriptInfos()[0]; + assert.equal(rootScriptInfo.fileName, root.path); + + // ensure that imported file was found + verifyImportedDiagnostics(); + + const callsTrackingHost = createCallsTrackingHost(host); + + // trigger synchronization to make sure that import will be fetched from the cache + // ensure file has correct number of errors after edit + editContent(`import {x} from "f1"; + var x: string = 1;`); + verifyImportedDiagnostics(); + callsTrackingHost.verifyNoHostCalls(); + + // trigger synchronization to make sure that LSHost will try to find 'f2' module on disk + editContent(`import {x} from "f2"`); + try { + // trigger synchronization to make sure that LSHost will try to find 'f2' module on disk + verifyImportedDiagnostics(); + assert.isTrue(false, `should not find file '${imported.path}'`); + } + catch (e) { + assert.isTrue(e.message.indexOf(`Could not find file: '${imported.path}'.`) === 0); + } + const f2Lookups = getLocationsForModuleLookup("f2"); + callsTrackingHost.verifyCalledOnEachEntryNTimes(CalledMapsWithSingleArg.fileExists, f2Lookups, 1); + const f2DirLookups = getLocationsForDirectoryLookup(); + callsTrackingHost.verifyCalledOnEachEntry(CalledMapsWithSingleArg.directoryExists, f2DirLookups); + callsTrackingHost.verifyNoCall(CalledMapsWithSingleArg.getDirectories); + callsTrackingHost.verifyNoCall(CalledMapsWithSingleArg.readFile); + callsTrackingHost.verifyNoCall(CalledMapsWithFiveArgs.readDirectory); + + editContent(`import {x} from "f1"`); + verifyImportedDiagnostics(); + const f1Lookups = f2Lookups.map(s => s.replace("f2", "f1")); + f1Lookups.length = f1Lookups.indexOf(imported.path) + 1; + const f1DirLookups = ["/c/d", "/c", ...mapCombinedPathsInAncestor(getDirectoryPath(root.path), nodeModulesAtTypes, returnTrue)]; + vertifyF1Lookups(); + + // setting compiler options discards module resolution cache + callsTrackingHost.clear(); + projectService.setCompilerOptionsForInferredProjects({ module: ModuleKind.AMD, noLib: true, target: ScriptTarget.ES5 }); + verifyImportedDiagnostics(); + vertifyF1Lookups(); + + function vertifyF1Lookups() { + callsTrackingHost.verifyCalledOnEachEntryNTimes(CalledMapsWithSingleArg.fileExists, f1Lookups, 1); + callsTrackingHost.verifyCalledOnEachEntryNTimes(CalledMapsWithSingleArg.directoryExists, f1DirLookups, 1); + callsTrackingHost.verifyNoCall(CalledMapsWithSingleArg.getDirectories); + callsTrackingHost.verifyNoCall(CalledMapsWithSingleArg.readFile); + callsTrackingHost.verifyNoCall(CalledMapsWithFiveArgs.readDirectory); + } + + function editContent(newContent: string) { + callsTrackingHost.clear(); + rootScriptInfo.editContent(0, rootContent.length, newContent); + rootContent = newContent; + } + + function verifyImportedDiagnostics() { + const diags = project.getLanguageService().getSemanticDiagnostics(imported.path); + assert.equal(diags.length, 1); + const diag = diags[0]; + assert.equal(diag.code, Diagnostics.Cannot_find_name_0.code); + assert.equal(flattenDiagnosticMessageText(diag.messageText, "\n"), "Cannot find name 'foo'."); + } + + function getLocationsForModuleLookup(module: string) { + const locations: string[] = []; + forEachAncestorDirectory(getDirectoryPath(root.path), ancestor => { + locations.push( + combinePaths(ancestor, `${module}.ts`), + combinePaths(ancestor, `${module}.tsx`), + combinePaths(ancestor, `${module}.d.ts`) + ); + }); + forEachAncestorDirectory(getDirectoryPath(root.path), ancestor => { + locations.push( + combinePaths(ancestor, `${module}.js`), + combinePaths(ancestor, `${module}.jsx`) + ); + }); + return locations; + } + + function getLocationsForDirectoryLookup() { + const result = createMap(); + forEachAncestorDirectory(getDirectoryPath(root.path), ancestor => { + // To resolve modules + result.set(ancestor, 2); + // for type roots + result.set(combinePaths(ancestor, nodeModules), 1); + result.set(combinePaths(ancestor, nodeModulesAtTypes), 1); + }); + return result; + } + }); + + it("loads missing files from disk", () => { + const root: File = { + path: "/c/foo.ts", + content: `import {y} from "bar"` + }; + + const imported: File = { + path: "/c/bar.d.ts", + content: `export var y = 1` + }; + + const host = createServerHost([root]); + const projectService = createProjectService(host); + projectService.setCompilerOptionsForInferredProjects({ module: ModuleKind.AMD, noLib: true }); + const callsTrackingHost = createCallsTrackingHost(host); + projectService.openClientFile(root.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + const project = projectService.inferredProjects[0]; + const rootScriptInfo = project.getRootScriptInfos()[0]; + assert.equal(rootScriptInfo.fileName, root.path); + + let diags = project.getLanguageService().getSemanticDiagnostics(root.path); + assert.equal(diags.length, 1); + const diag = diags[0]; + assert.equal(diag.code, Diagnostics.Cannot_find_module_0.code); + assert.equal(flattenDiagnosticMessageText(diag.messageText, "\n"), "Cannot find module 'bar'."); + callsTrackingHost.verifyCalledOn(CalledMapsWithSingleArg.fileExists, imported.path); + + + callsTrackingHost.clear(); + host.reloadFS([root, imported]); + host.runQueuedTimeoutCallbacks(); + diags = project.getLanguageService().getSemanticDiagnostics(root.path); + assert.equal(diags.length, 0); + callsTrackingHost.verifyCalledOn(CalledMapsWithSingleArg.fileExists, imported.path); + }); + + it("when calling goto definition of module", () => { + const clientFile: File = { + path: "/a/b/controllers/vessels/client.ts", + content: ` + import { Vessel } from '~/models/vessel'; + const v = new Vessel(); + ` + }; + const anotherModuleFile: File = { + path: "/a/b/utils/db.ts", + content: "export class Bookshelf { }" + }; + const moduleFile: File = { + path: "/a/b/models/vessel.ts", + content: ` + import { Bookshelf } from '~/utils/db'; + export class Vessel extends Bookshelf {} + ` + }; + const tsconfigFile: File = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ + compilerOptions: { + target: "es6", + module: "es6", + baseUrl: "./", // all paths are relative to the baseUrl + paths: { + "~/*": ["*"] // resolve any `~/foo/bar` to `/foo/bar` + } + }, + exclude: [ + "api", + "build", + "node_modules", + "public", + "seeds", + "sql_updates", + "tests.build" + ] + }) + }; + const projectFiles = [clientFile, anotherModuleFile, moduleFile, tsconfigFile]; + const host = createServerHost(projectFiles); + const session = createSession(host); + const projectService = session.getProjectService(); + const { configFileName } = projectService.openClientFile(clientFile.path); + + assert.isDefined(configFileName, `should find config`); + checkNumberOfConfiguredProjects(projectService, 1); + + const project = projectService.configuredProjects.get(tsconfigFile.path)!; + checkProjectActualFiles(project, map(projectFiles, f => f.path)); + + const callsTrackingHost = createCallsTrackingHost(host); + + // Get definitions shouldnt make host requests + const getDefinitionRequest = makeSessionRequest(protocol.CommandTypes.Definition, { + file: clientFile.path, + position: clientFile.content.indexOf("/vessel") + 1, + line: undefined!, // TODO: GH#18217 + offset: undefined! // TODO: GH#18217 + }); + const response = session.executeCommand(getDefinitionRequest).response as server.protocol.FileSpan[]; + assert.equal(response[0].file, moduleFile.path, "Should go to definition of vessel: response: " + JSON.stringify(response)); + callsTrackingHost.verifyNoHostCalls(); + + // Open the file should call only file exists on module directory and use cached value for parental directory + const { configFileName: config2 } = projectService.openClientFile(moduleFile.path); + assert.equal(config2, configFileName); + callsTrackingHost.verifyNoHostCallsExceptFileExistsOnce(["/a/b/models/tsconfig.json", "/a/b/models/jsconfig.json"]); + + checkNumberOfConfiguredProjects(projectService, 1); + assert.strictEqual(projectService.configuredProjects.get(tsconfigFile.path), project); + }); + + describe("WatchDirectories for config file with", () => { + function verifyWatchDirectoriesCaseSensitivity(useCaseSensitiveFileNames: boolean) { + const frontendDir = "/Users/someuser/work/applications/frontend"; + const toCanonical: (s: string) => Path = useCaseSensitiveFileNames ? s => s as Path : s => s.toLowerCase() as Path; + const canonicalFrontendDir = toCanonical(frontendDir); + const file1: File = { + path: `${frontendDir}/src/app/utils/Analytic.ts`, + content: "export class SomeClass { };" + }; + const file2: File = { + path: `${frontendDir}/src/app/redux/configureStore.ts`, + content: "export class configureStore { }" + }; + const file3: File = { + path: `${frontendDir}/src/app/utils/Cookie.ts`, + content: "export class Cookie { }" + }; + const es2016LibFile: File = { + path: "/a/lib/lib.es2016.full.d.ts", + content: libFile.content + }; + const typeRoots = ["types", "node_modules/@types"]; + const types = ["node", "jest"]; + const tsconfigFile: File = { + path: `${frontendDir}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + strict: true, + strictNullChecks: true, + target: "es2016", + module: "commonjs", + moduleResolution: "node", + sourceMap: true, + noEmitOnError: true, + experimentalDecorators: true, + emitDecoratorMetadata: true, + types, + noUnusedLocals: true, + outDir: "./compiled", + typeRoots, + baseUrl: ".", + paths: { + "*": [ + "types/*" + ] + } + }, + include: [ + "src/**/*" + ], + exclude: [ + "node_modules", + "compiled" + ] + }) + }; + const projectFiles = [file1, file2, es2016LibFile, tsconfigFile]; + const host = createServerHost(projectFiles, { useCaseSensitiveFileNames }); + const projectService = createProjectService(host); + const canonicalConfigPath = toCanonical(tsconfigFile.path); + const { configFileName } = projectService.openClientFile(file1.path); + assert.equal(configFileName, tsconfigFile.path as server.NormalizedPath, `should find config`); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) + checkNumberOfConfiguredProjects(projectService, 1); + const watchingRecursiveDirectories = [`${canonicalFrontendDir}/src`, `${canonicalFrontendDir}/types`, `${canonicalFrontendDir}/node_modules`].concat(getNodeModuleDirectories(getDirectoryPath(canonicalFrontendDir))); + + const project = projectService.configuredProjects.get(canonicalConfigPath)!; + verifyProjectAndWatchedDirectories(); + + const callsTrackingHost = createCallsTrackingHost(host); + + // Create file cookie.ts + projectFiles.push(file3); + host.reloadFS(projectFiles); + host.runQueuedTimeoutCallbacks(); + + const canonicalFile3Path = useCaseSensitiveFileNames ? file3.path : file3.path.toLocaleLowerCase(); + const numberOfTimesWatchInvoked = getNumberOfWatchesInvokedForRecursiveWatches(watchingRecursiveDirectories, canonicalFile3Path); + callsTrackingHost.verifyCalledOnEachEntryNTimes(CalledMapsWithSingleArg.fileExists, [canonicalFile3Path], numberOfTimesWatchInvoked); + callsTrackingHost.verifyCalledOnEachEntryNTimes(CalledMapsWithSingleArg.directoryExists, [canonicalFile3Path], numberOfTimesWatchInvoked); + callsTrackingHost.verifyNoCall(CalledMapsWithSingleArg.getDirectories); + callsTrackingHost.verifyCalledOnEachEntryNTimes(CalledMapsWithSingleArg.readFile, [file3.path], 1); + callsTrackingHost.verifyNoCall(CalledMapsWithFiveArgs.readDirectory); + + checkNumberOfConfiguredProjects(projectService, 1); + assert.strictEqual(projectService.configuredProjects.get(canonicalConfigPath), project); + verifyProjectAndWatchedDirectories(); + + callsTrackingHost.clear(); + + const { configFileName: configFile2 } = projectService.openClientFile(file3.path); + assert.equal(configFile2, configFileName); + + checkNumberOfConfiguredProjects(projectService, 1); + assert.strictEqual(projectService.configuredProjects.get(canonicalConfigPath), project); + verifyProjectAndWatchedDirectories(); + callsTrackingHost.verifyNoHostCalls(); + + function getFilePathIfNotOpen(f: File) { + const path = toCanonical(f.path); + const info = projectService.getScriptInfoForPath(toCanonical(f.path)); + return info && info.isScriptOpen() ? undefined : path; + } + + function verifyProjectAndWatchedDirectories() { + checkProjectActualFiles(project, map(projectFiles, f => f.path)); + checkWatchedFiles(host, mapDefined(projectFiles, getFilePathIfNotOpen)); + checkWatchedDirectories(host, watchingRecursiveDirectories, /*recursive*/ true); + checkWatchedDirectories(host, [], /*recursive*/ false); + } + } + + it("case insensitive file system", () => { + verifyWatchDirectoriesCaseSensitivity(/*useCaseSensitiveFileNames*/ false); + }); + + it("case sensitive file system", () => { + verifyWatchDirectoriesCaseSensitivity(/*useCaseSensitiveFileNames*/ true); + }); + }); + + describe("Subfolder invalidations correctly include parent folder failed lookup locations", () => { + function runFailedLookupTest(resolution: "Node" | "Classic") { + const projectLocation = "/proj"; + const file1: File = { + path: `${projectLocation}/foo/boo/app.ts`, + content: `import * as debug from "debug"` + }; + const file2: File = { + path: `${projectLocation}/foo/boo/moo/app.ts`, + content: `import * as debug from "debug"` + }; + const tsconfig: File = { + path: `${projectLocation}/tsconfig.json`, + content: JSON.stringify({ + files: ["foo/boo/app.ts", "foo/boo/moo/app.ts"], + moduleResolution: resolution + }) + }; + + const files = [file1, file2, tsconfig, libFile]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(file1.path); + + const project = service.configuredProjects.get(tsconfig.path)!; + checkProjectActualFiles(project, files.map(f => f.path)); + assert.deepEqual(project.getLanguageService().getSemanticDiagnostics(file1.path).map(diag => diag.messageText), ["Cannot find module 'debug'."]); + assert.deepEqual(project.getLanguageService().getSemanticDiagnostics(file2.path).map(diag => diag.messageText), ["Cannot find module 'debug'."]); + + const debugTypesFile: File = { + path: `${projectLocation}/node_modules/debug/index.d.ts`, + content: "export {}" + }; + files.push(debugTypesFile); + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + checkProjectActualFiles(project, files.map(f => f.path)); + assert.deepEqual(project.getLanguageService().getSemanticDiagnostics(file1.path).map(diag => diag.messageText), []); + assert.deepEqual(project.getLanguageService().getSemanticDiagnostics(file2.path).map(diag => diag.messageText), []); + } + + it("Includes the parent folder FLLs in node module resolution mode", () => { + runFailedLookupTest("Node"); + }); + it("Includes the parent folder FLLs in classic module resolution mode", () => { + runFailedLookupTest("Classic"); + }); + }); + + describe("Verify npm install in directory with tsconfig file works when", () => { + function verifyNpmInstall(timeoutDuringPartialInstallation: boolean) { + const root = "/user/username/rootfolder/otherfolder"; + const getRootedFileOrFolder = (fileOrFolder: File) => { + fileOrFolder.path = root + fileOrFolder.path; + return fileOrFolder; + }; + const app: File = getRootedFileOrFolder({ + path: "/a/b/app.ts", + content: "import _ from 'lodash';" + }); + const tsconfigJson: File = getRootedFileOrFolder({ + path: "/a/b/tsconfig.json", + content: '{ "compilerOptions": { } }' + }); + const packageJson: File = getRootedFileOrFolder({ + path: "/a/b/package.json", + content: ` +{ + "name": "test", + "version": "1.0.0", + "description": "", + "main": "index.js", + "dependencies": { + "lodash", + "rxjs" + }, + "devDependencies": { + "@types/lodash", + "typescript" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC" +} +` + }); + const appFolder = getDirectoryPath(app.path); + const projectFiles = [app, libFile, tsconfigJson]; + const typeRootDirectories = getTypeRootsFromLocation(getDirectoryPath(tsconfigJson.path)); + const otherFiles = [packageJson]; + const host = createServerHost(projectFiles.concat(otherFiles)); + const projectService = createProjectService(host); + const { configFileName } = projectService.openClientFile(app.path); + assert.equal(configFileName, tsconfigJson.path as server.NormalizedPath, `should find config`); // TODO: GH#18217 + const recursiveWatchedDirectories: string[] = [`${appFolder}`, `${appFolder}/node_modules`].concat(getNodeModuleDirectories(getDirectoryPath(appFolder))); + verifyProject(); + + let npmInstallComplete = false; + + // Simulate npm install + const filesAndFoldersToAdd: File[] = [ + { path: "/a/b/node_modules" }, + { path: "/a/b/node_modules/.staging/@types" }, + { path: "/a/b/node_modules/.staging/lodash-b0733faa" }, + { path: "/a/b/node_modules/.staging/@types/lodash-e56c4fe7" }, + { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff" }, + { path: "/a/b/node_modules/.staging/rxjs-22375c61" }, + { path: "/a/b/node_modules/.staging/typescript-8493ea5d" }, + { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff/package.json", content: "{\n \"name\": \"symbol-observable\",\n \"version\": \"1.0.4\",\n \"description\": \"Symbol.observable ponyfill\",\n \"license\": \"MIT\",\n \"repository\": \"blesh/symbol-observable\",\n \"author\": {\n \"name\": \"Ben Lesh\",\n \"email\": \"ben@benlesh.com\"\n },\n \"engines\": {\n \"node\": \">=0.10.0\"\n },\n \"scripts\": {\n \"test\": \"npm run build && mocha && tsc ./ts-test/test.ts && node ./ts-test/test.js && check-es3-syntax -p lib/ --kill\",\n \"build\": \"babel es --out-dir lib\",\n \"prepublish\": \"npm test\"\n },\n \"files\": [\n \"" }, + { path: "/a/b/node_modules/.staging/lodash-b0733faa/package.json", content: "{\n \"name\": \"lodash\",\n \"version\": \"4.17.4\",\n \"description\": \"Lodash modular utilities.\",\n \"keywords\": \"modules, stdlib, util\",\n \"homepage\": \"https://lodash.com/\",\n \"repository\": \"lodash/lodash\",\n \"icon\": \"https://lodash.com/icon.svg\",\n \"license\": \"MIT\",\n \"main\": \"lodash.js\",\n \"author\": \"John-David Dalton (http://allyoucanleet.com/)\",\n \"contributors\": [\n \"John-David Dalton (http://allyoucanleet.com/)\",\n \"Mathias Bynens \",\n \"contributors\": [\n {\n \"name\": \"Ben Lesh\",\n \"email\": \"ben@benlesh.com\"\n },\n {\n \"name\": \"Paul Taylor\",\n \"email\": \"paul.e.taylor@me.com\"\n },\n {\n \"name\": \"Jeff Cross\",\n \"email\": \"crossj@google.com\"\n },\n {\n \"name\": \"Matthew Podwysocki\",\n \"email\": \"matthewp@microsoft.com\"\n },\n {\n \"name\": \"OJ Kwon\",\n \"email\": \"kwon.ohjoong@gmail.com\"\n },\n {\n \"name\": \"Andre Staltz\",\n \"email\": \"andre@staltz.com\"\n }\n ],\n \"license\": \"Apache-2.0\",\n \"bugs\": {\n \"url\": \"https://github.com/ReactiveX/RxJS/issues\"\n },\n \"homepage\": \"https://github.com/ReactiveX/RxJS\",\n \"devDependencies\": {\n \"babel-polyfill\": \"^6.23.0\",\n \"benchmark\": \"^2.1.0\",\n \"benchpress\": \"2.0.0-beta.1\",\n \"chai\": \"^3.5.0\",\n \"color\": \"^0.11.1\",\n \"colors\": \"1.1.2\",\n \"commitizen\": \"^2.8.6\",\n \"coveralls\": \"^2.11.13\",\n \"cz-conventional-changelog\": \"^1.2.0\",\n \"danger\": \"^1.1.0\",\n \"doctoc\": \"^1.0.0\",\n \"escape-string-regexp\": \"^1.0.5 \",\n \"esdoc\": \"^0.4.7\",\n \"eslint\": \"^3.8.0\",\n \"fs-extra\": \"^2.1.2\",\n \"get-folder-size\": \"^1.0.0\",\n \"glob\": \"^7.0.3\",\n \"gm\": \"^1.22.0\",\n \"google-closure-compiler-js\": \"^20170218.0.0\",\n \"gzip-size\": \"^3.0.0\",\n \"http-server\": \"^0.9.0\",\n \"husky\": \"^0.13.3\",\n \"lint-staged\": \"3.2.5\",\n \"lodash\": \"^4.15.0\",\n \"madge\": \"^1.4.3\",\n \"markdown-doctest\": \"^0.9.1\",\n \"minimist\": \"^1.2.0\",\n \"mkdirp\": \"^0.5.1\",\n \"mocha\": \"^3.0.2\",\n \"mocha-in-sauce\": \"0.0.1\",\n \"npm-run-all\": \"^4.0.2\",\n \"npm-scripts-info\": \"^0.3.4\",\n \"nyc\": \"^10.2.0\",\n \"opn-cli\": \"^3.1.0\",\n \"platform\": \"^1.3.1\",\n \"promise\": \"^7.1.1\",\n \"protractor\": \"^3.1.1\",\n \"rollup\": \"0.36.3\",\n \"rollup-plugin-inject\": \"^2.0.0\",\n \"rollup-plugin-node-resolve\": \"^2.0.0\",\n \"rx\": \"latest\",\n \"rxjs\": \"latest\",\n \"shx\": \"^0.2.2\",\n \"sinon\": \"^2.1.0\",\n \"sinon-chai\": \"^2.9.0\",\n \"source-map-support\": \"^0.4.0\",\n \"tslib\": \"^1.5.0\",\n \"tslint\": \"^4.4.2\",\n \"typescript\": \"~2.0.6\",\n \"typings\": \"^2.0.0\",\n \"validate-commit-msg\": \"^2.14.0\",\n \"watch\": \"^1.0.1\",\n \"webpack\": \"^1.13.1\",\n \"xmlhttprequest\": \"1.8.0\"\n },\n \"engines\": {\n \"npm\": \">=2.0.0\"\n },\n \"typings\": \"Rx.d.ts\",\n \"dependencies\": {\n \"symbol-observable\": \"^1.0.1\"\n }\n}" }, + { path: "/a/b/node_modules/.staging/typescript-8493ea5d/package.json", content: "{\n \"name\": \"typescript\",\n \"author\": \"Microsoft Corp.\",\n \"homepage\": \"http://typescriptlang.org/\",\n \"version\": \"2.4.2\",\n \"license\": \"Apache-2.0\",\n \"description\": \"TypeScript is a language for application scale JavaScript development\",\n \"keywords\": [\n \"TypeScript\",\n \"Microsoft\",\n \"compiler\",\n \"language\",\n \"javascript\"\n ],\n \"bugs\": {\n \"url\": \"https://github.com/Microsoft/TypeScript/issues\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Microsoft/TypeScript.git\"\n },\n \"main\": \"./lib/typescript.js\",\n \"typings\": \"./lib/typescript.d.ts\",\n \"bin\": {\n \"tsc\": \"./bin/tsc\",\n \"tsserver\": \"./bin/tsserver\"\n },\n \"engines\": {\n \"node\": \">=4.2.0\"\n },\n \"devDependencies\": {\n \"@types/browserify\": \"latest\",\n \"@types/chai\": \"latest\",\n \"@types/convert-source-map\": \"latest\",\n \"@types/del\": \"latest\",\n \"@types/glob\": \"latest\",\n \"@types/gulp\": \"latest\",\n \"@types/gulp-concat\": \"latest\",\n \"@types/gulp-help\": \"latest\",\n \"@types/gulp-newer\": \"latest\",\n \"@types/gulp-sourcemaps\": \"latest\",\n \"@types/merge2\": \"latest\",\n \"@types/minimatch\": \"latest\",\n \"@types/minimist\": \"latest\",\n \"@types/mkdirp\": \"latest\",\n \"@types/mocha\": \"latest\",\n \"@types/node\": \"latest\",\n \"@types/q\": \"latest\",\n \"@types/run-sequence\": \"latest\",\n \"@types/through2\": \"latest\",\n \"browserify\": \"latest\",\n \"chai\": \"latest\",\n \"convert-source-map\": \"latest\",\n \"del\": \"latest\",\n \"gulp\": \"latest\",\n \"gulp-clone\": \"latest\",\n \"gulp-concat\": \"latest\",\n \"gulp-help\": \"latest\",\n \"gulp-insert\": \"latest\",\n \"gulp-newer\": \"latest\",\n \"gulp-sourcemaps\": \"latest\",\n \"gulp-typescript\": \"latest\",\n \"into-stream\": \"latest\",\n \"istanbul\": \"latest\",\n \"jake\": \"latest\",\n \"merge2\": \"latest\",\n \"minimist\": \"latest\",\n \"mkdirp\": \"latest\",\n \"mocha\": \"latest\",\n \"mocha-fivemat-progress-reporter\": \"latest\",\n \"q\": \"latest\",\n \"run-sequence\": \"latest\",\n \"sorcery\": \"latest\",\n \"through2\": \"latest\",\n \"travis-fold\": \"latest\",\n \"ts-node\": \"latest\",\n \"tslint\": \"latest\",\n \"typescript\": \"^2.4\"\n },\n \"scripts\": {\n \"pretest\": \"jake tests\",\n \"test\": \"jake runtests-parallel\",\n \"build\": \"npm run build:compiler && npm run build:tests\",\n \"build:compiler\": \"jake local\",\n \"build:tests\": \"jake tests\",\n \"start\": \"node lib/tsc\",\n \"clean\": \"jake clean\",\n \"gulp\": \"gulp\",\n \"jake\": \"jake\",\n \"lint\": \"jake lint\",\n \"setup-hooks\": \"node scripts/link-hooks.js\"\n },\n \"browser\": {\n \"buffer\": false,\n \"fs\": false,\n \"os\": false,\n \"path\": false\n }\n}" }, + { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff/index.js", content: "module.exports = require('./lib/index');\n" }, + { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff/index.d.ts", content: "declare const observableSymbol: symbol;\nexport default observableSymbol;\n" }, + { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff/lib" }, + { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff/lib/index.js", content: "'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _ponyfill = require('./ponyfill');\n\nvar _ponyfill2 = _interopRequireDefault(_ponyfill);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nvar root; /* global window */\n\n\nif (typeof self !== 'undefined') {\n root = self;\n} else if (typeof window !== 'undefined') {\n root = window;\n} else if (typeof global !== 'undefined') {\n root = global;\n} else if (typeof module !== 'undefined') {\n root = module;\n} else {\n root = Function('return this')();\n}\n\nvar result = (0, _ponyfill2['default'])(root);\nexports['default'] = result;" }, + ].map(getRootedFileOrFolder); + verifyAfterPartialOrCompleteNpmInstall(2); + + filesAndFoldersToAdd.push(...[ + { path: "/a/b/node_modules/.staging/typescript-8493ea5d/lib" }, + { path: "/a/b/node_modules/.staging/rxjs-22375c61/add/operator" }, + { path: "/a/b/node_modules/.staging/@types/lodash-e56c4fe7/package.json", content: "{\n \"name\": \"@types/lodash\",\n \"version\": \"4.14.74\",\n \"description\": \"TypeScript definitions for Lo-Dash\",\n \"license\": \"MIT\",\n \"contributors\": [\n {\n \"name\": \"Brian Zengel\",\n \"url\": \"https://github.com/bczengel\"\n },\n {\n \"name\": \"Ilya Mochalov\",\n \"url\": \"https://github.com/chrootsu\"\n },\n {\n \"name\": \"Stepan Mikhaylyuk\",\n \"url\": \"https://github.com/stepancar\"\n },\n {\n \"name\": \"Eric L Anderson\",\n \"url\": \"https://github.com/ericanderson\"\n },\n {\n \"name\": \"AJ Richardson\",\n \"url\": \"https://github.com/aj-r\"\n },\n {\n \"name\": \"Junyoung Clare Jang\",\n \"url\": \"https://github.com/ailrun\"\n }\n ],\n \"main\": \"\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://www.github.com/DefinitelyTyped/DefinitelyTyped.git\"\n },\n \"scripts\": {},\n \"dependencies\": {},\n \"typesPublisherContentHash\": \"12af578ffaf8d86d2df37e591857906a86b983fa9258414326544a0fe6af0de8\",\n \"typeScriptVersion\": \"2.2\"\n}" }, + { path: "/a/b/node_modules/.staging/lodash-b0733faa/index.js", content: "module.exports = require('./lodash');" }, + { path: "/a/b/node_modules/.staging/typescript-8493ea5d/package.json.3017591594" } + ].map(getRootedFileOrFolder)); + // Since we added/removed in .staging no timeout + verifyAfterPartialOrCompleteNpmInstall(0); + + // Remove file "/a/b/node_modules/.staging/typescript-8493ea5d/package.json.3017591594" + filesAndFoldersToAdd.length--; + verifyAfterPartialOrCompleteNpmInstall(0); + + filesAndFoldersToAdd.push(...[ + { path: "/a/b/node_modules/.staging/rxjs-22375c61/bundles" }, + { path: "/a/b/node_modules/.staging/rxjs-22375c61/operator" }, + { path: "/a/b/node_modules/.staging/rxjs-22375c61/src/add/observable/dom" }, + { path: "/a/b/node_modules/.staging/@types/lodash-e56c4fe7/index.d.ts", content: "\n// Stub for lodash\nexport = _;\nexport as namespace _;\ndeclare var _: _.LoDashStatic;\ndeclare namespace _ {\n interface LoDashStatic {\n someProp: string;\n }\n class SomeClass {\n someMethod(): void;\n }\n}" } + ].map(getRootedFileOrFolder)); + verifyAfterPartialOrCompleteNpmInstall(0); + + filesAndFoldersToAdd.push(...[ + { path: "/a/b/node_modules/.staging/rxjs-22375c61/src/scheduler" }, + { path: "/a/b/node_modules/.staging/rxjs-22375c61/src/util" }, + { path: "/a/b/node_modules/.staging/rxjs-22375c61/symbol" }, + { path: "/a/b/node_modules/.staging/rxjs-22375c61/testing" }, + { path: "/a/b/node_modules/.staging/rxjs-22375c61/package.json.2252192041", content: "{\n \"_args\": [\n [\n {\n \"raw\": \"rxjs@^5.4.2\",\n \"scope\": null,\n \"escapedName\": \"rxjs\",\n \"name\": \"rxjs\",\n \"rawSpec\": \"^5.4.2\",\n \"spec\": \">=5.4.2 <6.0.0\",\n \"type\": \"range\"\n },\n \"C:\\\\Users\\\\shkamat\\\\Desktop\\\\app\"\n ]\n ],\n \"_from\": \"rxjs@>=5.4.2 <6.0.0\",\n \"_id\": \"rxjs@5.4.3\",\n \"_inCache\": true,\n \"_location\": \"/rxjs\",\n \"_nodeVersion\": \"7.7.2\",\n \"_npmOperationalInternal\": {\n \"host\": \"s3://npm-registry-packages\",\n \"tmp\": \"tmp/rxjs-5.4.3.tgz_1502407898166_0.6800217325799167\"\n },\n \"_npmUser\": {\n \"name\": \"blesh\",\n \"email\": \"ben@benlesh.com\"\n },\n \"_npmVersion\": \"5.3.0\",\n \"_phantomChildren\": {},\n \"_requested\": {\n \"raw\": \"rxjs@^5.4.2\",\n \"scope\": null,\n \"escapedName\": \"rxjs\",\n \"name\": \"rxjs\",\n \"rawSpec\": \"^5.4.2\",\n \"spec\": \">=5.4.2 <6.0.0\",\n \"type\": \"range\"\n },\n \"_requiredBy\": [\n \"/\"\n ],\n \"_resolved\": \"https://registry.npmjs.org/rxjs/-/rxjs-5.4.3.tgz\",\n \"_shasum\": \"0758cddee6033d68e0fd53676f0f3596ce3d483f\",\n \"_shrinkwrap\": null,\n \"_spec\": \"rxjs@^5.4.2\",\n \"_where\": \"C:\\\\Users\\\\shkamat\\\\Desktop\\\\app\",\n \"author\": {\n \"name\": \"Ben Lesh\",\n \"email\": \"ben@benlesh.com\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/ReactiveX/RxJS/issues\"\n },\n \"config\": {\n \"commitizen\": {\n \"path\": \"cz-conventional-changelog\"\n }\n },\n \"contributors\": [\n {\n \"name\": \"Ben Lesh\",\n \"email\": \"ben@benlesh.com\"\n },\n {\n \"name\": \"Paul Taylor\",\n \"email\": \"paul.e.taylor@me.com\"\n },\n {\n \"name\": \"Jeff Cross\",\n \"email\": \"crossj@google.com\"\n },\n {\n \"name\": \"Matthew Podwysocki\",\n \"email\": \"matthewp@microsoft.com\"\n },\n {\n \"name\": \"OJ Kwon\",\n \"email\": \"kwon.ohjoong@gmail.com\"\n },\n {\n \"name\": \"Andre Staltz\",\n \"email\": \"andre@staltz.com\"\n }\n ],\n \"dependencies\": {\n \"symbol-observable\": \"^1.0.1\"\n },\n \"description\": \"Reactive Extensions for modern JavaScript\",\n \"devDependencies\": {\n \"babel-polyfill\": \"^6.23.0\",\n \"benchmark\": \"^2.1.0\",\n \"benchpress\": \"2.0.0-beta.1\",\n \"chai\": \"^3.5.0\",\n \"color\": \"^0.11.1\",\n \"colors\": \"1.1.2\",\n \"commitizen\": \"^2.8.6\",\n \"coveralls\": \"^2.11.13\",\n \"cz-conventional-changelog\": \"^1.2.0\",\n \"danger\": \"^1.1.0\",\n \"doctoc\": \"^1.0.0\",\n \"escape-string-regexp\": \"^1.0.5 \",\n \"esdoc\": \"^0.4.7\",\n \"eslint\": \"^3.8.0\",\n \"fs-extra\": \"^2.1.2\",\n \"get-folder-size\": \"^1.0.0\",\n \"glob\": \"^7.0.3\",\n \"gm\": \"^1.22.0\",\n \"google-closure-compiler-js\": \"^20170218.0.0\",\n \"gzip-size\": \"^3.0.0\",\n \"http-server\": \"^0.9.0\",\n \"husky\": \"^0.13.3\",\n \"lint-staged\": \"3.2.5\",\n \"lodash\": \"^4.15.0\",\n \"madge\": \"^1.4.3\",\n \"markdown-doctest\": \"^0.9.1\",\n \"minimist\": \"^1.2.0\",\n \"mkdirp\": \"^0.5.1\",\n \"mocha\": \"^3.0.2\",\n \"mocha-in-sauce\": \"0.0.1\",\n \"npm-run-all\": \"^4.0.2\",\n \"npm-scripts-info\": \"^0.3.4\",\n \"nyc\": \"^10.2.0\",\n \"opn-cli\": \"^3.1.0\",\n \"platform\": \"^1.3.1\",\n \"promise\": \"^7.1.1\",\n \"protractor\": \"^3.1.1\",\n \"rollup\": \"0.36.3\",\n \"rollup-plugin-inject\": \"^2.0.0\",\n \"rollup-plugin-node-resolve\": \"^2.0.0\",\n \"rx\": \"latest\",\n \"rxjs\": \"latest\",\n \"shx\": \"^0.2.2\",\n \"sinon\": \"^2.1.0\",\n \"sinon-chai\": \"^2.9.0\",\n \"source-map-support\": \"^0.4.0\",\n \"tslib\": \"^1.5.0\",\n \"tslint\": \"^4.4.2\",\n \"typescript\": \"~2.0.6\",\n \"typings\": \"^2.0.0\",\n \"validate-commit-msg\": \"^2.14.0\",\n \"watch\": \"^1.0.1\",\n \"webpack\": \"^1.13.1\",\n \"xmlhttprequest\": \"1.8.0\"\n },\n \"directories\": {},\n \"dist\": {\n \"integrity\": \"sha512-fSNi+y+P9ss+EZuV0GcIIqPUK07DEaMRUtLJvdcvMyFjc9dizuDjere+A4V7JrLGnm9iCc+nagV/4QdMTkqC4A==\",\n \"shasum\": \"0758cddee6033d68e0fd53676f0f3596ce3d483f\",\n \"tarball\": \"https://registry.npmjs.org/rxjs/-/rxjs-5.4.3.tgz\"\n },\n \"engines\": {\n \"npm\": \">=2.0.0\"\n },\n \"homepage\": \"https://github.com/ReactiveX/RxJS\",\n \"keywords\": [\n \"Rx\",\n \"RxJS\",\n \"ReactiveX\",\n \"ReactiveExtensions\",\n \"Streams\",\n \"Observables\",\n \"Observable\",\n \"Stream\",\n \"ES6\",\n \"ES2015\"\n ],\n \"license\": \"Apache-2.0\",\n \"lint-staged\": {\n \"*.@(js)\": [\n \"eslint --fix\",\n \"git add\"\n ],\n \"*.@(ts)\": [\n \"tslint --fix\",\n \"git add\"\n ]\n },\n \"main\": \"Rx.js\",\n \"maintainers\": [\n {\n \"name\": \"blesh\",\n \"email\": \"ben@benlesh.com\"\n }\n ],\n \"name\": \"rxjs\",\n \"optionalDependencies\": {},\n \"readme\": \"ERROR: No README data found!\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+ssh://git@github.com/ReactiveX/RxJS.git\"\n },\n \"scripts-info\": {\n \"info\": \"List available script\",\n \"build_all\": \"Build all packages (ES6, CJS, UMD) and generate packages\",\n \"build_cjs\": \"Build CJS package with clean up existing build, copy source into dist\",\n \"build_es6\": \"Build ES6 package with clean up existing build, copy source into dist\",\n \"build_closure_core\": \"Minify Global core build using closure compiler\",\n \"build_global\": \"Build Global package, then minify build\",\n \"build_perf\": \"Build CJS & Global build, run macro performance test\",\n \"build_test\": \"Build CJS package & test spec, execute mocha test runner\",\n \"build_cover\": \"Run lint to current code, build CJS & test spec, execute test coverage\",\n \"build_docs\": \"Build ES6 & global package, create documentation using it\",\n \"build_spec\": \"Build test specs\",\n \"check_circular_dependencies\": \"Check codebase has circular dependencies\",\n \"clean_spec\": \"Clean up existing test spec build output\",\n \"clean_dist_cjs\": \"Clean up existing CJS package output\",\n \"clean_dist_es6\": \"Clean up existing ES6 package output\",\n \"clean_dist_global\": \"Clean up existing Global package output\",\n \"commit\": \"Run git commit wizard\",\n \"compile_dist_cjs\": \"Compile codebase into CJS module\",\n \"compile_module_es6\": \"Compile codebase into ES6\",\n \"cover\": \"Execute test coverage\",\n \"lint_perf\": \"Run lint against performance test suite\",\n \"lint_spec\": \"Run lint against test spec\",\n \"lint_src\": \"Run lint against source\",\n \"lint\": \"Run lint against everything\",\n \"perf\": \"Run macro performance benchmark\",\n \"perf_micro\": \"Run micro performance benchmark\",\n \"test_mocha\": \"Execute mocha test runner against existing test spec build\",\n \"test_browser\": \"Execute mocha test runner on browser against existing test spec build\",\n \"test\": \"Clean up existing test spec build, build test spec and execute mocha test runner\",\n \"tests2png\": \"Generate marble diagram image from test spec\",\n \"watch\": \"Watch codebase, trigger compile when source code changes\"\n },\n \"typings\": \"Rx.d.ts\",\n \"version\": \"5.4.3\"\n}\n" } + ].map(getRootedFileOrFolder)); + verifyAfterPartialOrCompleteNpmInstall(0); + + // remove /a/b/node_modules/.staging/rxjs-22375c61/package.json.2252192041 + filesAndFoldersToAdd.length--; + // and add few more folders/files + filesAndFoldersToAdd.push(...[ + { path: "/a/b/node_modules/symbol-observable" }, + { path: "/a/b/node_modules/@types" }, + { path: "/a/b/node_modules/@types/lodash" }, + { path: "/a/b/node_modules/lodash" }, + { path: "/a/b/node_modules/rxjs" }, + { path: "/a/b/node_modules/typescript" }, + { path: "/a/b/node_modules/.bin" } + ].map(getRootedFileOrFolder)); + // From the type root update + verifyAfterPartialOrCompleteNpmInstall(2); + + forEach(filesAndFoldersToAdd, f => { + f.path = f.path + .replace("/a/b/node_modules/.staging", "/a/b/node_modules") + .replace(/[\-\.][\d\w][\d\w][\d\w][\d\w][\d\w][\d\w][\d\w][\d\w]/g, ""); + }); + + const lodashIndexPath = root + "/a/b/node_modules/@types/lodash/index.d.ts"; + projectFiles.push(find(filesAndFoldersToAdd, f => f.path === lodashIndexPath)!); + // we would now not have failed lookup in the parent of appFolder since lodash is available + recursiveWatchedDirectories.length = 2; + // npm installation complete, timeout after reload fs + npmInstallComplete = true; + verifyAfterPartialOrCompleteNpmInstall(2); + + function verifyAfterPartialOrCompleteNpmInstall(timeoutQueueLengthWhenRunningTimeouts: number) { + host.reloadFS(projectFiles.concat(otherFiles, filesAndFoldersToAdd)); + if (npmInstallComplete || timeoutDuringPartialInstallation) { + host.checkTimeoutQueueLengthAndRun(timeoutQueueLengthWhenRunningTimeouts); + } + else { + host.checkTimeoutQueueLength(2); + } + verifyProject(); + } + + function verifyProject() { + checkNumberOfConfiguredProjects(projectService, 1); + + const project = projectService.configuredProjects.get(tsconfigJson.path)!; + const projectFilePaths = map(projectFiles, f => f.path); + checkProjectActualFiles(project, projectFilePaths); + + const filesWatched = filter(projectFilePaths, p => p !== app.path && p.indexOf("/a/b/node_modules") === -1); + checkWatchedFiles(host, filesWatched); + checkWatchedDirectories(host, typeRootDirectories.concat(recursiveWatchedDirectories), /*recursive*/ true); + checkWatchedDirectories(host, [], /*recursive*/ false); + } + } + + it("timeouts occur inbetween installation", () => { + verifyNpmInstall(/*timeoutDuringPartialInstallation*/ true); + }); + + it("timeout occurs after installation", () => { + verifyNpmInstall(/*timeoutDuringPartialInstallation*/ false); + }); + }); + + it("when node_modules dont receive event for the @types file addition", () => { + const projectLocation = "/user/username/folder/myproject"; + const app: File = { + path: `${projectLocation}/app.ts`, + content: `import * as debug from "debug"` + }; + const tsconfig: File = { + path: `${projectLocation}/tsconfig.json`, + content: "" + }; + + const files = [app, tsconfig, libFile]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(app.path); + + const project = service.configuredProjects.get(tsconfig.path)!; + checkProjectActualFiles(project, files.map(f => f.path)); + assert.deepEqual(project.getLanguageService().getSemanticDiagnostics(app.path).map(diag => diag.messageText), ["Cannot find module 'debug'."]); + + const debugTypesFile: File = { + path: `${projectLocation}/node_modules/@types/debug/index.d.ts`, + content: "export {}" + }; + files.push(debugTypesFile); + // Do not invoke recursive directory watcher for anything other than node_module/@types + const invoker = host.invokeWatchedDirectoriesRecursiveCallback; + host.invokeWatchedDirectoriesRecursiveCallback = (fullPath, relativePath) => { + if (fullPath.endsWith("@types")) { + invoker.call(host, fullPath, relativePath); + } + }; + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + checkProjectActualFiles(project, files.map(f => f.path)); + assert.deepEqual(project.getLanguageService().getSemanticDiagnostics(app.path).map(diag => diag.messageText), []); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/cancellationToken.ts b/src/testRunner/unittests/tsserver/cancellationToken.ts new file mode 100644 index 00000000000..71fb4bb4b22 --- /dev/null +++ b/src/testRunner/unittests/tsserver/cancellationToken.ts @@ -0,0 +1,271 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: cancellationToken", () => { + // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test + let oldPrepare: AnyFunction; + before(() => { + oldPrepare = (Error as any).prepareStackTrace; + delete (Error as any).prepareStackTrace; + }); + + after(() => { + (Error as any).prepareStackTrace = oldPrepare; + }); + + it("is attached to request", () => { + const f1 = { + path: "/a/b/app.ts", + content: "let xyz = 1;" + }; + const host = createServerHost([f1]); + let expectedRequestId: number; + const cancellationToken: server.ServerCancellationToken = { + isCancellationRequested: () => false, + setRequest: requestId => { + if (expectedRequestId === undefined) { + assert.isTrue(false, "unexpected call"); + } + assert.equal(requestId, expectedRequestId); + }, + resetRequest: noop + }; + + const session = createSession(host, { cancellationToken }); + + expectedRequestId = session.getNextSeq(); + session.executeCommandSeq({ + command: "open", + arguments: { file: f1.path } + }); + + expectedRequestId = session.getNextSeq(); + session.executeCommandSeq({ + command: "geterr", + arguments: { files: [f1.path] } + }); + + expectedRequestId = session.getNextSeq(); + session.executeCommandSeq({ + command: "occurrences", + arguments: { file: f1.path, line: 1, offset: 6 } + }); + + expectedRequestId = 2; + host.runQueuedImmediateCallbacks(); + expectedRequestId = 2; + host.runQueuedImmediateCallbacks(); + }); + + it("Geterr is cancellable", () => { + const f1 = { + path: "/a/app.ts", + content: "let x = 1" + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions: {} + }) + }; + + const cancellationToken = new TestServerCancellationToken(); + const host = createServerHost([f1, config]); + const session = createSession(host, { + canUseEvents: true, + eventHandler: noop, + cancellationToken + }); + { + session.executeCommandSeq({ + command: "open", + arguments: { file: f1.path } + }); + // send geterr for missing file + session.executeCommandSeq({ + command: "geterr", + arguments: { files: ["/a/missing"] } + }); + // no files - expect 'completed' event + assert.equal(host.getOutput().length, 1, "expect 1 message"); + verifyRequestCompleted(session.getSeq(), 0); + } + { + const getErrId = session.getNextSeq(); + // send geterr for a valid file + session.executeCommandSeq({ + command: "geterr", + arguments: { files: [f1.path] } + }); + + assert.equal(host.getOutput().length, 0, "expect 0 messages"); + + // run new request + session.executeCommandSeq({ + command: "projectInfo", + arguments: { file: f1.path } + }); + session.clearMessages(); + + // cancel previously issued Geterr + cancellationToken.setRequestToCancel(getErrId); + host.runQueuedTimeoutCallbacks(); + + assert.equal(host.getOutput().length, 1, "expect 1 message"); + verifyRequestCompleted(getErrId, 0); + + cancellationToken.resetToken(); + } + { + const getErrId = session.getNextSeq(); + session.executeCommandSeq({ + command: "geterr", + arguments: { files: [f1.path] } + }); + assert.equal(host.getOutput().length, 0, "expect 0 messages"); + + // run first step + host.runQueuedTimeoutCallbacks(); + assert.equal(host.getOutput().length, 1, "expect 1 message"); + const e1 = getMessage(0); + assert.equal(e1.event, "syntaxDiag"); + session.clearMessages(); + + cancellationToken.setRequestToCancel(getErrId); + host.runQueuedImmediateCallbacks(); + assert.equal(host.getOutput().length, 1, "expect 1 message"); + verifyRequestCompleted(getErrId, 0); + + cancellationToken.resetToken(); + } + { + const getErrId = session.getNextSeq(); + session.executeCommandSeq({ + command: "geterr", + arguments: { files: [f1.path] } + }); + assert.equal(host.getOutput().length, 0, "expect 0 messages"); + + // run first step + host.runQueuedTimeoutCallbacks(); + assert.equal(host.getOutput().length, 1, "expect 1 message"); + const e1 = getMessage(0); + assert.equal(e1.event, "syntaxDiag"); + session.clearMessages(); + + // the semanticDiag message + host.runQueuedImmediateCallbacks(); + assert.equal(host.getOutput().length, 1); + const e2 = getMessage(0); + assert.equal(e2.event, "semanticDiag"); + session.clearMessages(); + + host.runQueuedImmediateCallbacks(1); + assert.equal(host.getOutput().length, 2); + const e3 = getMessage(0); + assert.equal(e3.event, "suggestionDiag"); + verifyRequestCompleted(getErrId, 1); + + cancellationToken.resetToken(); + } + { + const getErr1 = session.getNextSeq(); + session.executeCommandSeq({ + command: "geterr", + arguments: { files: [f1.path] } + }); + assert.equal(host.getOutput().length, 0, "expect 0 messages"); + // run first step + host.runQueuedTimeoutCallbacks(); + assert.equal(host.getOutput().length, 1, "expect 1 message"); + const e1 = getMessage(0); + assert.equal(e1.event, "syntaxDiag"); + session.clearMessages(); + + session.executeCommandSeq({ + command: "geterr", + arguments: { files: [f1.path] } + }); + // make sure that getErr1 is completed + verifyRequestCompleted(getErr1, 0); + } + + function verifyRequestCompleted(expectedSeq: number, n: number) { + const event = getMessage(n); + assert.equal(event.event, "requestCompleted"); + assert.equal(event.body.request_seq, expectedSeq, "expectedSeq"); + session.clearMessages(); + } + + function getMessage(n: number) { + return JSON.parse(server.extractMessage(host.getOutput()[n])); + } + }); + + it("Lower priority tasks are cancellable", () => { + const f1 = { + path: "/a/app.ts", + content: `{ let x = 1; } var foo = "foo"; var bar = "bar"; var fooBar = "fooBar";` + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions: {} + }) + }; + const cancellationToken = new TestServerCancellationToken(/*cancelAfterRequest*/ 3); + const host = createServerHost([f1, config]); + const session = createSession(host, { + canUseEvents: true, + eventHandler: noop, + cancellationToken, + throttleWaitMilliseconds: 0 + }); + { + session.executeCommandSeq({ + command: "open", + arguments: { file: f1.path } + }); + + // send navbar request (normal priority) + session.executeCommandSeq({ + command: "navbar", + arguments: { file: f1.path } + }); + + // ensure the nav bar request can be canceled + verifyExecuteCommandSeqIsCancellable({ + command: "navbar", + arguments: { file: f1.path } + }); + + // send outlining spans request (normal priority) + session.executeCommandSeq({ + command: "outliningSpans", + arguments: { file: f1.path } + }); + + // ensure the outlining spans request can be canceled + verifyExecuteCommandSeqIsCancellable({ + command: "outliningSpans", + arguments: { file: f1.path } + }); + } + + function verifyExecuteCommandSeqIsCancellable(request: Partial) { + // Set the next request to be cancellable + // The cancellation token will cancel the request the third time + // isCancellationRequested() is called. + cancellationToken.setRequestToCancel(session.getNextSeq()); + let operationCanceledExceptionThrown = false; + + try { + session.executeCommandSeq(request); + } + catch (e) { + assert(e instanceof OperationCanceledException); + operationCanceledExceptionThrown = true; + } + assert(operationCanceledExceptionThrown, "Operation Canceled Exception not thrown for request: " + JSON.stringify(request)); + } + }); + }); +} diff --git a/src/testRunner/unittests/compileOnSave.ts b/src/testRunner/unittests/tsserver/compileOnSave.ts similarity index 81% rename from src/testRunner/unittests/compileOnSave.ts rename to src/testRunner/unittests/tsserver/compileOnSave.ts index 49d1659deec..7dc9ea0497c 100644 --- a/src/testRunner/unittests/compileOnSave.ts +++ b/src/testRunner/unittests/tsserver/compileOnSave.ts @@ -6,7 +6,7 @@ namespace ts.projectSystem { return new TestTypingsInstaller("/a/data/", /*throttleLimit*/5, host); } - describe("CompileOnSave affected list", () => { + describe("unittests:: tsserver:: compileOnSave:: affected list", () => { function sendAffectedFileRequestAndCheckResult(session: server.Session, request: server.protocol.Request, expectedFileList: { projectFileName: string, files: File[] }[]) { const response = session.executeCommand(request).response as server.protocol.CompileOnSaveAffectedFileListSingleProject[]; const actualResult = response.sort((list1, list2) => compareStringsCaseSensitive(list1.projectFileName, list2.projectFileName)); @@ -36,7 +36,7 @@ namespace ts.projectSystem { typingsInstaller: typingsInstaller || server.nullTypingsInstaller, byteLength: Utils.byteLength, hrtime: process.hrtime, - logger: nullLogger, + logger: createHasErrorMessageLogger().logger, canUseEvents: false }; return new server.Session(opts); @@ -502,9 +502,57 @@ namespace ts.projectSystem { ]); }); }); + + describe("tsserverProjectSystem emit with outFile or out setting", () => { + function test(opts: CompilerOptions, expectedUsesOutFile: boolean) { + const f1 = { + path: "/a/a.ts", + content: "let x = 1" + }; + const f2 = { + path: "/a/b.ts", + content: "let y = 1" + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions: opts, + compileOnSave: true + }) + }; + const host = createServerHost([f1, f2, config]); + const session = projectSystem.createSession(host); + session.executeCommand({ + seq: 1, + type: "request", + command: "open", + arguments: { file: f1.path } + }); + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 1 }); + const { response } = session.executeCommand({ + seq: 2, + type: "request", + command: "compileOnSaveAffectedFileList", + arguments: { file: f1.path } + }); + assert.equal((response).length, 1, "expected output for 1 project"); + assert.equal((response)[0].fileNames.length, 2, "expected output for 1 project"); + assert.equal((response)[0].projectUsesOutFile, expectedUsesOutFile, "usesOutFile"); + } + + it("projectUsesOutFile should not be returned if not set", () => { + test({}, /*expectedUsesOutFile*/ false); + }); + it("projectUsesOutFile should be true if outFile is set", () => { + test({ outFile: "/a/out.js" }, /*expectedUsesOutFile*/ true); + }); + it("projectUsesOutFile should be true if out is set", () => { + test({ out: "/a/out.js" }, /*expectedUsesOutFile*/ true); + }); + }); }); - describe("EmitFile test", () => { + describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { it("should respect line endings", () => { test("\n"); test("\r\n"); @@ -646,4 +694,100 @@ namespace ts.projectSystem { } }); }); + + describe("unittests:: tsserver:: compileOnSave:: CompileOnSaveAffectedFileListRequest with and without projectFileName in request", () => { + const projectRoot = "/user/username/projects/myproject"; + const core: File = { + path: `${projectRoot}/core/core.ts`, + content: "let z = 10;" + }; + const app1: File = { + path: `${projectRoot}/app1/app.ts`, + content: "let x = 10;" + }; + const app2: File = { + path: `${projectRoot}/app2/app.ts`, + content: "let y = 10;" + }; + const app1Config: File = { + path: `${projectRoot}/app1/tsconfig.json`, + content: JSON.stringify({ + files: ["app.ts", "../core/core.ts"], + compilerOptions: { outFile: "build/output.js" }, + compileOnSave: true + }) + }; + const app2Config: File = { + path: `${projectRoot}/app2/tsconfig.json`, + content: JSON.stringify({ + files: ["app.ts", "../core/core.ts"], + compilerOptions: { outFile: "build/output.js" }, + compileOnSave: true + }) + }; + const files = [libFile, core, app1, app2, app1Config, app2Config]; + + function insertString(session: TestSession, file: File) { + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: file.path, + line: 1, + offset: 1, + endLine: 1, + endOffset: 1, + insertString: "let k = 1" + } + }); + } + + function getSession() { + const host = createServerHost(files); + const session = createSession(host); + openFilesForSession([app1, app2, core], session); + const service = session.getProjectService(); + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 }); + const project1 = service.configuredProjects.get(app1Config.path)!; + const project2 = service.configuredProjects.get(app2Config.path)!; + checkProjectActualFiles(project1, [libFile.path, app1.path, core.path, app1Config.path]); + checkProjectActualFiles(project2, [libFile.path, app2.path, core.path, app2Config.path]); + insertString(session, app1); + insertString(session, app2); + assert.equal(project1.dirty, true); + assert.equal(project2.dirty, true); + return session; + } + + it("when projectFile is specified", () => { + const session = getSession(); + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { + file: core.path, + projectFileName: app1Config.path + } + }).response; + assert.deepEqual(response, [ + { projectFileName: app1Config.path, fileNames: [core.path, app1.path], projectUsesOutFile: true } + ]); + assert.equal(session.getProjectService().configuredProjects.get(app1Config.path)!.dirty, false); + assert.equal(session.getProjectService().configuredProjects.get(app2Config.path)!.dirty, true); + }); + + it("when projectFile is not specified", () => { + const session = getSession(); + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { + file: core.path + } + }).response; + assert.deepEqual(response, [ + { projectFileName: app1Config.path, fileNames: [core.path, app1.path], projectUsesOutFile: true }, + { projectFileName: app2Config.path, fileNames: [core.path, app2.path], projectUsesOutFile: true } + ]); + assert.equal(session.getProjectService().configuredProjects.get(app1Config.path)!.dirty, false); + assert.equal(session.getProjectService().configuredProjects.get(app2Config.path)!.dirty, false); + }); + }); } diff --git a/src/testRunner/unittests/tsserver/completions.ts b/src/testRunner/unittests/tsserver/completions.ts new file mode 100644 index 00000000000..0a62f74dc7d --- /dev/null +++ b/src/testRunner/unittests/tsserver/completions.ts @@ -0,0 +1,122 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: completions", () => { + it("works", () => { + const aTs: File = { + path: "/a.ts", + content: "export const foo = 0;", + }; + const bTs: File = { + path: "/b.ts", + content: "foo", + }; + const tsconfig: File = { + path: "/tsconfig.json", + content: "{}", + }; + + const session = createSession(createServerHost([aTs, bTs, tsconfig])); + openFilesForSession([aTs, bTs], session); + + const requestLocation: protocol.FileLocationRequestArgs = { + file: bTs.path, + line: 1, + offset: 3, + }; + + const response = executeSessionRequest(session, protocol.CommandTypes.CompletionInfo, { + ...requestLocation, + includeExternalModuleExports: true, + prefix: "foo", + }); + const entry: protocol.CompletionEntry = { + hasAction: true, + insertText: undefined, + isRecommended: undefined, + kind: ScriptElementKind.constElement, + kindModifiers: ScriptElementKindModifier.exportedModifier, + name: "foo", + replacementSpan: undefined, + sortText: "0", + source: "/a", + }; + assert.deepEqual(response, { + isGlobalCompletion: true, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries: [entry], + }); + + const detailsRequestArgs: protocol.CompletionDetailsRequestArgs = { + ...requestLocation, + entryNames: [{ name: "foo", source: "/a" }], + }; + + const detailsResponse = executeSessionRequest(session, protocol.CommandTypes.CompletionDetails, detailsRequestArgs); + const detailsCommon: protocol.CompletionEntryDetails & CompletionEntryDetails = { + displayParts: [ + keywordPart(SyntaxKind.ConstKeyword), + spacePart(), + displayPart("foo", SymbolDisplayPartKind.localName), + punctuationPart(SyntaxKind.ColonToken), + spacePart(), + displayPart("0", SymbolDisplayPartKind.stringLiteral), + ], + documentation: emptyArray, + kind: ScriptElementKind.constElement, + kindModifiers: ScriptElementKindModifier.exportedModifier, + name: "foo", + source: [{ text: "./a", kind: "text" }], + tags: undefined, + }; + assert.deepEqual | undefined>(detailsResponse, [ + { + codeActions: [ + { + description: `Import 'foo' from module "./a"`, + changes: [ + { + fileName: "/b.ts", + textChanges: [ + { + start: { line: 1, offset: 1 }, + end: { line: 1, offset: 1 }, + newText: 'import { foo } from "./a";\n\n', + }, + ], + }, + ], + commands: undefined, + }, + ], + ...detailsCommon, + }, + ]); + + interface CompletionDetailsFullRequest extends protocol.FileLocationRequest { + readonly command: protocol.CommandTypes.CompletionDetailsFull; + readonly arguments: protocol.CompletionDetailsRequestArgs; + } + interface CompletionDetailsFullResponse extends protocol.Response { + readonly body?: ReadonlyArray; + } + const detailsFullResponse = executeSessionRequest(session, protocol.CommandTypes.CompletionDetailsFull, detailsRequestArgs); + assert.deepEqual | undefined>(detailsFullResponse, [ + { + codeActions: [ + { + description: `Import 'foo' from module "./a"`, + changes: [ + { + fileName: "/b.ts", + textChanges: [createTextChange(createTextSpan(0, 0), 'import { foo } from "./a";\n\n')], + }, + ], + commands: undefined, + } + ], + ...detailsCommon, + } + ]); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/configFileSearch.ts b/src/testRunner/unittests/tsserver/configFileSearch.ts new file mode 100644 index 00000000000..c9e02b8bd06 --- /dev/null +++ b/src/testRunner/unittests/tsserver/configFileSearch.ts @@ -0,0 +1,174 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: searching for config file", () => { + it("should stop at projectRootPath if given", () => { + const f1 = { + path: "/a/file1.ts", + content: "" + }; + const configFile = { + path: "/tsconfig.json", + content: "{}" + }; + const host = createServerHost([f1, configFile]); + const service = createProjectService(host); + service.openClientFile(f1.path, /*fileContent*/ undefined, /*scriptKind*/ undefined, "/a"); + + checkNumberOfConfiguredProjects(service, 0); + checkNumberOfInferredProjects(service, 1); + + service.closeClientFile(f1.path); + service.openClientFile(f1.path); + checkNumberOfConfiguredProjects(service, 1); + checkNumberOfInferredProjects(service, 0); + }); + + it("should use projectRootPath when searching for inferred project again", () => { + const projectDir = "/a/b/projects/project"; + const configFileLocation = `${projectDir}/src`; + const f1 = { + path: `${configFileLocation}/file1.ts`, + content: "" + }; + const configFile = { + path: `${configFileLocation}/tsconfig.json`, + content: "{}" + }; + const configFile2 = { + path: "/a/b/projects/tsconfig.json", + content: "{}" + }; + const host = createServerHost([f1, libFile, configFile, configFile2]); + const service = createProjectService(host); + service.openClientFile(f1.path, /*fileContent*/ undefined, /*scriptKind*/ undefined, projectDir); + checkNumberOfProjects(service, { configuredProjects: 1 }); + assert.isDefined(service.configuredProjects.get(configFile.path)); + checkWatchedFiles(host, [libFile.path, configFile.path]); + checkWatchedDirectories(host, [], /*recursive*/ false); + const typeRootLocations = getTypeRootsFromLocation(configFileLocation); + checkWatchedDirectories(host, typeRootLocations.concat(configFileLocation), /*recursive*/ true); + + // Delete config file - should create inferred project and not configured project + host.reloadFS([f1, libFile, configFile2]); + host.runQueuedTimeoutCallbacks(); + checkNumberOfProjects(service, { inferredProjects: 1 }); + checkWatchedFiles(host, [libFile.path, configFile.path, `${configFileLocation}/jsconfig.json`, `${projectDir}/tsconfig.json`, `${projectDir}/jsconfig.json`]); + checkWatchedDirectories(host, [], /*recursive*/ false); + checkWatchedDirectories(host, typeRootLocations, /*recursive*/ true); + }); + + it("should use projectRootPath when searching for inferred project again 2", () => { + const projectDir = "/a/b/projects/project"; + const configFileLocation = `${projectDir}/src`; + const f1 = { + path: `${configFileLocation}/file1.ts`, + content: "" + }; + const configFile = { + path: `${configFileLocation}/tsconfig.json`, + content: "{}" + }; + const configFile2 = { + path: "/a/b/projects/tsconfig.json", + content: "{}" + }; + const host = createServerHost([f1, libFile, configFile, configFile2]); + const service = createProjectService(host, { useSingleInferredProject: true }, { useInferredProjectPerProjectRoot: true }); + service.openClientFile(f1.path, /*fileContent*/ undefined, /*scriptKind*/ undefined, projectDir); + checkNumberOfProjects(service, { configuredProjects: 1 }); + assert.isDefined(service.configuredProjects.get(configFile.path)); + checkWatchedFiles(host, [libFile.path, configFile.path]); + checkWatchedDirectories(host, [], /*recursive*/ false); + checkWatchedDirectories(host, getTypeRootsFromLocation(configFileLocation).concat(configFileLocation), /*recursive*/ true); + + // Delete config file - should create inferred project with project root path set + host.reloadFS([f1, libFile, configFile2]); + host.runQueuedTimeoutCallbacks(); + checkNumberOfProjects(service, { inferredProjects: 1 }); + assert.equal(service.inferredProjects[0].projectRootPath, projectDir); + checkWatchedFiles(host, [libFile.path, configFile.path, `${configFileLocation}/jsconfig.json`, `${projectDir}/tsconfig.json`, `${projectDir}/jsconfig.json`]); + checkWatchedDirectories(host, [], /*recursive*/ false); + checkWatchedDirectories(host, getTypeRootsFromLocation(projectDir), /*recursive*/ true); + }); + + describe("when the opened file is not from project root", () => { + const projectRoot = "/a/b/projects/project"; + const file: File = { + path: `${projectRoot}/src/index.ts`, + content: "let y = 10" + }; + const tsconfig: File = { + path: `${projectRoot}/tsconfig.json`, + content: "{}" + }; + const files = [file, libFile]; + const filesWithConfig = files.concat(tsconfig); + const dirOfFile = getDirectoryPath(file.path); + + function openClientFile(files: File[]) { + const host = createServerHost(files); + const projectService = createProjectService(host); + + projectService.openClientFile(file.path, /*fileContent*/ undefined, /*scriptKind*/ undefined, "/a/b/projects/proj"); + return { host, projectService }; + } + + function verifyConfiguredProject(host: TestServerHost, projectService: TestProjectService, orphanInferredProject?: boolean) { + projectService.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: orphanInferredProject ? 1 : 0 }); + const project = Debug.assertDefined(projectService.configuredProjects.get(tsconfig.path)); + + if (orphanInferredProject) { + const inferredProject = projectService.inferredProjects[0]; + assert.isTrue(inferredProject.isOrphan()); + } + + checkProjectActualFiles(project, [file.path, libFile.path, tsconfig.path]); + checkWatchedFiles(host, [libFile.path, tsconfig.path]); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, (orphanInferredProject ? [projectRoot, `${dirOfFile}/node_modules/@types`] : [projectRoot]).concat(getTypeRootsFromLocation(projectRoot)), /*recursive*/ true); + } + + function verifyInferredProject(host: TestServerHost, projectService: TestProjectService) { + projectService.checkNumberOfProjects({ inferredProjects: 1 }); + const project = projectService.inferredProjects[0]; + assert.isDefined(project); + + const filesToWatch = [libFile.path]; + forEachAncestorDirectory(dirOfFile, ancestor => { + filesToWatch.push(combinePaths(ancestor, "tsconfig.json")); + filesToWatch.push(combinePaths(ancestor, "jsconfig.json")); + }); + + checkProjectActualFiles(project, [file.path, libFile.path]); + checkWatchedFiles(host, filesToWatch); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, getTypeRootsFromLocation(dirOfFile), /*recursive*/ true); + } + + it("tsconfig for the file exists", () => { + const { host, projectService } = openClientFile(filesWithConfig); + verifyConfiguredProject(host, projectService); + + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + verifyInferredProject(host, projectService); + + host.reloadFS(filesWithConfig); + host.runQueuedTimeoutCallbacks(); + verifyConfiguredProject(host, projectService, /*orphanInferredProject*/ true); + }); + + it("tsconfig for the file does not exist", () => { + const { host, projectService } = openClientFile(files); + verifyInferredProject(host, projectService); + + host.reloadFS(filesWithConfig); + host.runQueuedTimeoutCallbacks(); + verifyConfiguredProject(host, projectService, /*orphanInferredProject*/ true); + + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + verifyInferredProject(host, projectService); + }); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/configuredProjects.ts b/src/testRunner/unittests/tsserver/configuredProjects.ts new file mode 100644 index 00000000000..d1525f8dbeb --- /dev/null +++ b/src/testRunner/unittests/tsserver/configuredProjects.ts @@ -0,0 +1,1010 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: ConfiguredProjects", () => { + it("create configured project without file list", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: ` + { + "compilerOptions": {}, + "exclude": [ + "e" + ] + }` + }; + const file1: File = { + path: "/a/b/c/f1.ts", + content: "let x = 1" + }; + const file2: File = { + path: "/a/b/d/f2.ts", + content: "let y = 1" + }; + const file3: File = { + path: "/a/b/e/f3.ts", + content: "let z = 1" + }; + + const host = createServerHost([configFile, libFile, file1, file2, file3]); + const projectService = createProjectService(host); + const { configFileName, configFileErrors } = projectService.openClientFile(file1.path); + + assert(configFileName, "should find config file"); + assert.isTrue(!configFileErrors || configFileErrors.length === 0, `expect no errors in config file, got ${JSON.stringify(configFileErrors)}`); + checkNumberOfInferredProjects(projectService, 0); + checkNumberOfConfiguredProjects(projectService, 1); + + const project = configuredProjectAt(projectService, 0); + checkProjectActualFiles(project, [file1.path, libFile.path, file2.path, configFile.path]); + checkProjectRootFiles(project, [file1.path, file2.path]); + // watching all files except one that was open + checkWatchedFiles(host, [configFile.path, file2.path, libFile.path]); + const configFileDirectory = getDirectoryPath(configFile.path); + checkWatchedDirectories(host, [configFileDirectory, combinePaths(configFileDirectory, nodeModulesAtTypes)], /*recursive*/ true); + }); + + it("create configured project with the file list", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: ` + { + "compilerOptions": {}, + "include": ["*.ts"] + }` + }; + const file1: File = { + path: "/a/b/f1.ts", + content: "let x = 1" + }; + const file2: File = { + path: "/a/b/f2.ts", + content: "let y = 1" + }; + const file3: File = { + path: "/a/b/c/f3.ts", + content: "let z = 1" + }; + + const host = createServerHost([configFile, libFile, file1, file2, file3]); + const projectService = createProjectService(host); + const { configFileName, configFileErrors } = projectService.openClientFile(file1.path); + + assert(configFileName, "should find config file"); + assert.isTrue(!configFileErrors || configFileErrors.length === 0, `expect no errors in config file, got ${JSON.stringify(configFileErrors)}`); + checkNumberOfInferredProjects(projectService, 0); + checkNumberOfConfiguredProjects(projectService, 1); + + const project = configuredProjectAt(projectService, 0); + checkProjectActualFiles(project, [file1.path, libFile.path, file2.path, configFile.path]); + checkProjectRootFiles(project, [file1.path, file2.path]); + // watching all files except one that was open + checkWatchedFiles(host, [configFile.path, file2.path, libFile.path]); + checkWatchedDirectories(host, [getDirectoryPath(configFile.path)], /*recursive*/ false); + }); + + it("add and then remove a config file in a folder with loose files", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "files": ["commonFile1.ts"] + }` + }; + const filesWithoutConfig = [libFile, commonFile1, commonFile2]; + const host = createServerHost(filesWithoutConfig); + + const filesWithConfig = [libFile, commonFile1, commonFile2, configFile]; + const projectService = createProjectService(host); + projectService.openClientFile(commonFile1.path); + projectService.openClientFile(commonFile2.path); + + projectService.checkNumberOfProjects({ inferredProjects: 2 }); + checkProjectActualFiles(projectService.inferredProjects[0], [commonFile1.path, libFile.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [commonFile2.path, libFile.path]); + + const configFileLocations = ["/", "/a/", "/a/b/"]; + const watchedFiles = flatMap(configFileLocations, location => [location + "tsconfig.json", location + "jsconfig.json"]).concat(libFile.path); + checkWatchedFiles(host, watchedFiles); + + // Add a tsconfig file + host.reloadFS(filesWithConfig); + host.checkTimeoutQueueLengthAndRun(2); // load configured project from disk + ensureProjectsForOpenFiles + + projectService.checkNumberOfProjects({ inferredProjects: 2, configuredProjects: 1 }); + assert.isTrue(projectService.inferredProjects[0].isOrphan()); + checkProjectActualFiles(projectService.inferredProjects[1], [commonFile2.path, libFile.path]); + checkProjectActualFiles(projectService.configuredProjects.get(configFile.path)!, [libFile.path, commonFile1.path, configFile.path]); + + checkWatchedFiles(host, watchedFiles); + + // remove the tsconfig file + host.reloadFS(filesWithoutConfig); + + projectService.checkNumberOfProjects({ inferredProjects: 2 }); + assert.isTrue(projectService.inferredProjects[0].isOrphan()); + checkProjectActualFiles(projectService.inferredProjects[1], [commonFile2.path, libFile.path]); + + host.checkTimeoutQueueLengthAndRun(1); // Refresh inferred projects + + projectService.checkNumberOfProjects({ inferredProjects: 2 }); + checkProjectActualFiles(projectService.inferredProjects[0], [commonFile1.path, libFile.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [commonFile2.path, libFile.path]); + checkWatchedFiles(host, watchedFiles); + }); + + it("add new files to a configured project without file list", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{}` + }; + const host = createServerHost([commonFile1, libFile, configFile]); + const projectService = createProjectService(host); + projectService.openClientFile(commonFile1.path); + const configFileDir = getDirectoryPath(configFile.path); + checkWatchedDirectories(host, [configFileDir, combinePaths(configFileDir, nodeModulesAtTypes)], /*recursive*/ true); + checkNumberOfConfiguredProjects(projectService, 1); + + const project = configuredProjectAt(projectService, 0); + checkProjectRootFiles(project, [commonFile1.path]); + + // add a new ts file + host.reloadFS([commonFile1, commonFile2, libFile, configFile]); + host.checkTimeoutQueueLengthAndRun(2); + // project service waits for 250ms to update the project structure, therefore the assertion needs to wait longer. + checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]); + }); + + it("should ignore non-existing files specified in the config file", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "files": [ + "commonFile1.ts", + "commonFile3.ts" + ] + }` + }; + const host = createServerHost([commonFile1, commonFile2, configFile]); + const projectService = createProjectService(host); + projectService.openClientFile(commonFile1.path); + projectService.openClientFile(commonFile2.path); + + checkNumberOfConfiguredProjects(projectService, 1); + const project = configuredProjectAt(projectService, 0); + checkProjectRootFiles(project, [commonFile1.path]); + checkNumberOfInferredProjects(projectService, 1); + }); + + it("handle recreated files correctly", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{}` + }; + const host = createServerHost([commonFile1, commonFile2, configFile]); + const projectService = createProjectService(host); + projectService.openClientFile(commonFile1.path); + + checkNumberOfConfiguredProjects(projectService, 1); + const project = configuredProjectAt(projectService, 0); + checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]); + + // delete commonFile2 + host.reloadFS([commonFile1, configFile]); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectRootFiles(project, [commonFile1.path]); + + // re-add commonFile2 + host.reloadFS([commonFile1, commonFile2, configFile]); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]); + }); + + it("files explicitly excluded in config file", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "exclude": ["/a/c"] + }` + }; + const excludedFile1: File = { + path: "/a/c/excluedFile1.ts", + content: `let t = 1;` + }; + + const host = createServerHost([commonFile1, commonFile2, excludedFile1, configFile]); + const projectService = createProjectService(host); + + projectService.openClientFile(commonFile1.path); + checkNumberOfConfiguredProjects(projectService, 1); + const project = configuredProjectAt(projectService, 0); + checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]); + projectService.openClientFile(excludedFile1.path); + checkNumberOfInferredProjects(projectService, 1); + }); + + it("should properly handle module resolution changes in config file", () => { + const file1: File = { + path: "/a/b/file1.ts", + content: `import { T } from "module1";` + }; + const nodeModuleFile: File = { + path: "/a/b/node_modules/module1.ts", + content: `export interface T {}` + }; + const classicModuleFile: File = { + path: "/a/module1.ts", + content: `export interface T {}` + }; + const randomFile: File = { + path: "/a/file1.ts", + content: `export interface T {}` + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "moduleResolution": "node" + }, + "files": ["${file1.path}"] + }` + }; + const files = [file1, nodeModuleFile, classicModuleFile, configFile, randomFile]; + const host = createServerHost(files); + const projectService = createProjectService(host); + projectService.openClientFile(file1.path); + projectService.openClientFile(nodeModuleFile.path); + projectService.openClientFile(classicModuleFile.path); + + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 1 }); + const project = configuredProjectAt(projectService, 0); + const inferredProject0 = projectService.inferredProjects[0]; + checkProjectActualFiles(project, [file1.path, nodeModuleFile.path, configFile.path]); + checkProjectActualFiles(projectService.inferredProjects[0], [classicModuleFile.path]); + + configFile.content = `{ + "compilerOptions": { + "moduleResolution": "classic" + }, + "files": ["${file1.path}"] + }`; + host.reloadFS(files); + host.checkTimeoutQueueLengthAndRun(2); + + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 2 }); // will not remove project 1 + checkProjectActualFiles(project, [file1.path, classicModuleFile.path, configFile.path]); + assert.strictEqual(projectService.inferredProjects[0], inferredProject0); + assert.isTrue(projectService.inferredProjects[0].isOrphan()); + const inferredProject1 = projectService.inferredProjects[1]; + checkProjectActualFiles(projectService.inferredProjects[1], [nodeModuleFile.path]); + + // Open random file and it will reuse first inferred project + projectService.openClientFile(randomFile.path); + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 2 }); + checkProjectActualFiles(project, [file1.path, classicModuleFile.path, configFile.path]); + assert.strictEqual(projectService.inferredProjects[0], inferredProject0); + checkProjectActualFiles(projectService.inferredProjects[0], [randomFile.path]); // Reuses first inferred project + assert.strictEqual(projectService.inferredProjects[1], inferredProject1); + checkProjectActualFiles(projectService.inferredProjects[1], [nodeModuleFile.path]); + }); + + it("should keep the configured project when the opened file is referenced by the project but not its root", () => { + const file1: File = { + path: "/a/b/main.ts", + content: "import { objA } from './obj-a';" + }; + const file2: File = { + path: "/a/b/obj-a.ts", + content: `export const objA = Object.assign({foo: "bar"}, {bar: "baz"});` + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "target": "es6" + }, + "files": [ "main.ts" ] + }` + }; + const host = createServerHost([file1, file2, configFile]); + const projectService = createProjectService(host); + projectService.openClientFile(file1.path); + projectService.closeClientFile(file1.path); + projectService.openClientFile(file2.path); + checkNumberOfConfiguredProjects(projectService, 1); + checkNumberOfInferredProjects(projectService, 0); + }); + + it("should keep the configured project when the opened file is referenced by the project but not its root", () => { + const file1: File = { + path: "/a/b/main.ts", + content: "import { objA } from './obj-a';" + }; + const file2: File = { + path: "/a/b/obj-a.ts", + content: `export const objA = Object.assign({foo: "bar"}, {bar: "baz"});` + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "target": "es6" + }, + "files": [ "main.ts" ] + }` + }; + const host = createServerHost([file1, file2, configFile]); + const projectService = createProjectService(host); + projectService.openClientFile(file1.path); + projectService.closeClientFile(file1.path); + projectService.openClientFile(file2.path); + checkNumberOfConfiguredProjects(projectService, 1); + checkNumberOfInferredProjects(projectService, 0); + }); + + it("should tolerate config file errors and still try to build a project", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "target": "es6", + "allowAnything": true + }, + "someOtherProperty": {} + }` + }; + const host = createServerHost([commonFile1, commonFile2, libFile, configFile]); + const projectService = createProjectService(host); + projectService.openClientFile(commonFile1.path); + checkNumberOfConfiguredProjects(projectService, 1); + checkProjectRootFiles(configuredProjectAt(projectService, 0), [commonFile1.path, commonFile2.path]); + }); + + it("should reuse same project if file is opened from the configured project that has no open files", () => { + const file1 = { + path: "/a/b/main.ts", + content: "let x =1;" + }; + const file2 = { + path: "/a/b/main2.ts", + content: "let y =1;" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "target": "es6" + }, + "files": [ "main.ts", "main2.ts" ] + }` + }; + const host = createServerHost([file1, file2, configFile, libFile]); + const projectService = createProjectService(host, { useSingleInferredProject: true }); + projectService.openClientFile(file1.path); + checkNumberOfConfiguredProjects(projectService, 1); + const project = projectService.configuredProjects.get(configFile.path)!; + assert.isTrue(project.hasOpenRef()); // file1 + + projectService.closeClientFile(file1.path); + checkNumberOfConfiguredProjects(projectService, 1); + assert.strictEqual(projectService.configuredProjects.get(configFile.path), project); + assert.isFalse(project.hasOpenRef()); // No open files + assert.isFalse(project.isClosed()); + + projectService.openClientFile(file2.path); + checkNumberOfConfiguredProjects(projectService, 1); + assert.strictEqual(projectService.configuredProjects.get(configFile.path), project); + assert.isTrue(project.hasOpenRef()); // file2 + assert.isFalse(project.isClosed()); + }); + + it("should not close configured project after closing last open file, but should be closed on next file open if its not the file from same project", () => { + const file1 = { + path: "/a/b/main.ts", + content: "let x =1;" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "target": "es6" + }, + "files": [ "main.ts" ] + }` + }; + const host = createServerHost([file1, configFile, libFile]); + const projectService = createProjectService(host, { useSingleInferredProject: true }); + projectService.openClientFile(file1.path); + checkNumberOfConfiguredProjects(projectService, 1); + const project = projectService.configuredProjects.get(configFile.path)!; + assert.isTrue(project.hasOpenRef()); // file1 + + projectService.closeClientFile(file1.path); + checkNumberOfConfiguredProjects(projectService, 1); + assert.strictEqual(projectService.configuredProjects.get(configFile.path), project); + assert.isFalse(project.hasOpenRef()); // No files + assert.isFalse(project.isClosed()); + + projectService.openClientFile(libFile.path); + checkNumberOfConfiguredProjects(projectService, 0); + assert.isFalse(project.hasOpenRef()); // No files + project closed + assert.isTrue(project.isClosed()); + }); + + it("open file become a part of configured project if it is referenced from root file", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "export let x = 5" + }; + const file2 = { + path: "/a/c/f2.ts", + content: `import {x} from "../b/f1"` + }; + const file3 = { + path: "/a/c/f3.ts", + content: "export let y = 1" + }; + const configFile = { + path: "/a/c/tsconfig.json", + content: JSON.stringify({ compilerOptions: {}, files: ["f2.ts", "f3.ts"] }) + }; + + const host = createServerHost([file1, file2, file3]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkProjectActualFiles(projectService.inferredProjects[0], [file1.path]); + + projectService.openClientFile(file3.path); + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + checkProjectActualFiles(projectService.inferredProjects[0], [file1.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [file3.path]); + + host.reloadFS([file1, file2, file3, configFile]); + host.checkTimeoutQueueLengthAndRun(2); // load configured project from disk + ensureProjectsForOpenFiles + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 2 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path, file3.path, configFile.path]); + assert.isTrue(projectService.inferredProjects[0].isOrphan()); + assert.isTrue(projectService.inferredProjects[1].isOrphan()); + }); + + it("can correctly update configured project when set of root files has changed (new file on disk)", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1" + }; + const file2 = { + path: "/a/b/f2.ts", + content: "let y = 1" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: {} }) + }; + + const host = createServerHost([file1, configFile]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, configFile.path]); + + host.reloadFS([file1, file2, configFile]); + + host.checkTimeoutQueueLengthAndRun(2); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectRootFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path]); + }); + + it("can correctly update configured project when set of root files has changed (new file in list of files)", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1" + }; + const file2 = { + path: "/a/b/f2.ts", + content: "let y = 1" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts"] }) + }; + + const host = createServerHost([file1, file2, configFile]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, configFile.path]); + + const modifiedConfigFile = { + path: configFile.path, + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }) + }; + + host.reloadFS([file1, file2, modifiedConfigFile]); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectRootFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path]); + }); + + it("can update configured project when set of root files was not changed", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1" + }; + const file2 = { + path: "/a/b/f2.ts", + content: "let y = 1" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }) + }; + + const host = createServerHost([file1, file2, configFile]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path, configFile.path]); + + const modifiedConfigFile = { + path: configFile.path, + content: JSON.stringify({ compilerOptions: { outFile: "out.js" }, files: ["f1.ts", "f2.ts"] }) + }; + + host.reloadFS([file1, file2, modifiedConfigFile]); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectRootFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path]); + }); + + it("Open ref of configured project when open file gets added to the project as part of configured file update", () => { + const file1: File = { + path: "/a/b/src/file1.ts", + content: "let x = 1;" + }; + const file2: File = { + path: "/a/b/src/file2.ts", + content: "let y = 1;" + }; + const file3: File = { + path: "/a/b/file3.ts", + content: "let z = 1;" + }; + const file4: File = { + path: "/a/file4.ts", + content: "let z = 1;" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ files: ["src/file1.ts", "file3.ts"] }) + }; + + const files = [file1, file2, file3, file4]; + const host = createServerHost(files.concat(configFile)); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + projectService.openClientFile(file2.path); + projectService.openClientFile(file3.path); + projectService.openClientFile(file4.path); + + const infos = files.map(file => projectService.getScriptInfoForPath(file.path as Path)!); + checkOpenFiles(projectService, files); + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 2 }); + const configProject1 = projectService.configuredProjects.get(configFile.path)!; + assert.isTrue(configProject1.hasOpenRef()); // file1 and file3 + checkProjectActualFiles(configProject1, [file1.path, file3.path, configFile.path]); + const inferredProject1 = projectService.inferredProjects[0]; + checkProjectActualFiles(inferredProject1, [file2.path]); + const inferredProject2 = projectService.inferredProjects[1]; + checkProjectActualFiles(inferredProject2, [file4.path]); + + configFile.content = "{}"; + host.reloadFS(files.concat(configFile)); + host.runQueuedTimeoutCallbacks(); + + verifyScriptInfos(); + checkOpenFiles(projectService, files); + verifyConfiguredProjectStateAfterUpdate(/*hasOpenRef*/ true, 2); // file1, file2, file3 + assert.isTrue(projectService.inferredProjects[0].isOrphan()); + const inferredProject3 = projectService.inferredProjects[1]; + checkProjectActualFiles(inferredProject3, [file4.path]); + assert.strictEqual(inferredProject3, inferredProject2); + + projectService.closeClientFile(file1.path); + projectService.closeClientFile(file2.path); + projectService.closeClientFile(file4.path); + + verifyScriptInfos(); + checkOpenFiles(projectService, [file3]); + verifyConfiguredProjectStateAfterUpdate(/*hasOpenRef*/ true, 2); // file3 + assert.isTrue(projectService.inferredProjects[0].isOrphan()); + assert.isTrue(projectService.inferredProjects[1].isOrphan()); + + projectService.openClientFile(file4.path); + verifyScriptInfos(); + checkOpenFiles(projectService, [file3, file4]); + verifyConfiguredProjectStateAfterUpdate(/*hasOpenRef*/ true, 1); // file3 + const inferredProject4 = projectService.inferredProjects[0]; + checkProjectActualFiles(inferredProject4, [file4.path]); + + projectService.closeClientFile(file3.path); + verifyScriptInfos(); + checkOpenFiles(projectService, [file4]); + verifyConfiguredProjectStateAfterUpdate(/*hasOpenRef*/ false, 1); // No open files + const inferredProject5 = projectService.inferredProjects[0]; + checkProjectActualFiles(inferredProject4, [file4.path]); + assert.strictEqual(inferredProject5, inferredProject4); + + const file5: File = { + path: "/file5.ts", + content: "let zz = 1;" + }; + host.reloadFS(files.concat(configFile, file5)); + projectService.openClientFile(file5.path); + verifyScriptInfosAreUndefined([file1, file2, file3]); + assert.strictEqual(projectService.getScriptInfoForPath(file4.path as Path), find(infos, info => info.path === file4.path)); + assert.isDefined(projectService.getScriptInfoForPath(file5.path as Path)); + checkOpenFiles(projectService, [file4, file5]); + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + checkProjectActualFiles(projectService.inferredProjects[0], [file4.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [file5.path]); + + function verifyScriptInfos() { + infos.forEach(info => assert.strictEqual(projectService.getScriptInfoForPath(info.path), info)); + } + + function verifyScriptInfosAreUndefined(files: File[]) { + for (const file of files) { + assert.isUndefined(projectService.getScriptInfoForPath(file.path as Path)); + } + } + + function verifyConfiguredProjectStateAfterUpdate(hasOpenRef: boolean, inferredProjects: number) { + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects }); + const configProject2 = projectService.configuredProjects.get(configFile.path)!; + assert.strictEqual(configProject2, configProject1); + checkProjectActualFiles(configProject2, [file1.path, file2.path, file3.path, configFile.path]); + assert.equal(configProject2.hasOpenRef(), hasOpenRef); + } + }); + + it("Open ref of configured project when open file gets added to the project as part of configured file update buts its open file references are all closed when the update happens", () => { + const file1: File = { + path: "/a/b/src/file1.ts", + content: "let x = 1;" + }; + const file2: File = { + path: "/a/b/src/file2.ts", + content: "let y = 1;" + }; + const file3: File = { + path: "/a/b/file3.ts", + content: "let z = 1;" + }; + const file4: File = { + path: "/a/file4.ts", + content: "let z = 1;" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ files: ["src/file1.ts", "file3.ts"] }) + }; + + const files = [file1, file2, file3]; + const hostFiles = files.concat(file4, configFile); + const host = createServerHost(hostFiles); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + projectService.openClientFile(file2.path); + projectService.openClientFile(file3.path); + + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 1 }); + const configuredProject = projectService.configuredProjects.get(configFile.path)!; + assert.isTrue(configuredProject.hasOpenRef()); // file1 and file3 + checkProjectActualFiles(configuredProject, [file1.path, file3.path, configFile.path]); + const inferredProject1 = projectService.inferredProjects[0]; + checkProjectActualFiles(inferredProject1, [file2.path]); + + projectService.closeClientFile(file1.path); + projectService.closeClientFile(file3.path); + assert.isFalse(configuredProject.hasOpenRef()); // No files + + configFile.content = "{}"; + host.reloadFS(files.concat(configFile)); + // Time out is not yet run so there is project update pending + assert.isTrue(configuredProject.hasOpenRef()); // Pending update and file2 might get into the project + + projectService.openClientFile(file4.path); + + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 2 }); + assert.strictEqual(projectService.configuredProjects.get(configFile.path), configuredProject); + assert.isTrue(configuredProject.hasOpenRef()); // Pending update and F2 might get into the project + assert.strictEqual(projectService.inferredProjects[0], inferredProject1); + const inferredProject2 = projectService.inferredProjects[1]; + checkProjectActualFiles(inferredProject2, [file4.path]); + + host.runQueuedTimeoutCallbacks(); + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 2 }); + assert.strictEqual(projectService.configuredProjects.get(configFile.path), configuredProject); + assert.isTrue(configuredProject.hasOpenRef()); // file2 + checkProjectActualFiles(configuredProject, [file1.path, file2.path, file3.path, configFile.path]); + assert.strictEqual(projectService.inferredProjects[0], inferredProject1); + assert.isTrue(inferredProject1.isOrphan()); + assert.strictEqual(projectService.inferredProjects[1], inferredProject2); + checkProjectActualFiles(inferredProject2, [file4.path]); + }); + + it("files are properly detached when language service is disabled", () => { + const f1 = { + path: "/a/app.js", + content: "var x = 1" + }; + const f2 = { + path: "/a/largefile.js", + content: "" + }; + const f3 = { + path: "/a/lib.js", + content: "var x = 1" + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ compilerOptions: { allowJs: true } }) + }; + const host = createServerHost([f1, f2, f3, config]); + const originalGetFileSize = host.getFileSize; + host.getFileSize = (filePath: string) => + filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + + const projectService = createProjectService(host); + projectService.openClientFile(f1.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + const project = projectService.configuredProjects.get(config.path)!; + assert.isTrue(project.hasOpenRef()); // f1 + assert.isFalse(project.isClosed()); + + projectService.closeClientFile(f1.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(config.path), project); + assert.isFalse(project.hasOpenRef()); // No files + assert.isFalse(project.isClosed()); + + for (const f of [f1, f2, f3]) { + // All the script infos should be present and contain the project since it is still alive. + const scriptInfo = projectService.getScriptInfoForNormalizedPath(server.toNormalizedPath(f.path))!; + assert.equal(scriptInfo.containingProjects.length, 1, `expect 1 containing projects for '${f.path}'`); + assert.equal(scriptInfo.containingProjects[0], project, `expect configured project to be the only containing project for '${f.path}'`); + } + + const f4 = { + path: "/aa.js", + content: "var x = 1" + }; + host.reloadFS([f1, f2, f3, config, f4]); + projectService.openClientFile(f4.path); + projectService.checkNumberOfProjects({ inferredProjects: 1 }); + assert.isFalse(project.hasOpenRef()); // No files + assert.isTrue(project.isClosed()); + + for (const f of [f1, f2, f3]) { + // All the script infos should not be present since the project is closed and orphan script infos are collected + assert.isUndefined(projectService.getScriptInfoForNormalizedPath(server.toNormalizedPath(f.path))); + } + }); + + it("syntactic features work even if language service is disabled", () => { + const f1 = { + path: "/a/app.js", + content: "let x = 1;" + }; + const f2 = { + path: "/a/largefile.js", + content: "" + }; + const config = { + path: "/a/jsconfig.json", + content: "{}" + }; + const host = createServerHost([f1, f2, config]); + const originalGetFileSize = host.getFileSize; + host.getFileSize = (filePath: string) => + filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + const { session, events } = createSessionWithEventTracking(host, server.ProjectLanguageServiceStateEvent); + session.executeCommand({ + seq: 0, + type: "request", + command: "open", + arguments: { file: f1.path } + }); + + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const project = configuredProjectAt(projectService, 0); + assert.isFalse(project.languageServiceEnabled, "Language service enabled"); + assert.equal(events.length, 1, "should receive event"); + assert.equal(events[0].data.project, project, "project name"); + assert.isFalse(events[0].data.languageServiceEnabled, "Language service state"); + + const options = projectService.getFormatCodeOptions(f1.path as server.NormalizedPath); + const edits = project.getLanguageService().getFormattingEditsForDocument(f1.path, options); + assert.deepEqual(edits, [{ span: createTextSpan(/*start*/ 7, /*length*/ 3), newText: " " }]); + }); + }); + + describe("unittests:: tsserver:: ConfiguredProjects:: non-existing directories listed in config file input array", () => { + it("should be tolerated without crashing the server", () => { + const configFile = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "include": ["app/*", "test/**/*", "something"] + }` + }; + const file1 = { + path: "/a/b/file1.ts", + content: "let t = 10;" + }; + + const host = createServerHost([file1, configFile]); + const projectService = createProjectService(host); + projectService.openClientFile(file1.path); + host.runQueuedTimeoutCallbacks(); + // Since there is no file open from configFile it would be closed + checkNumberOfConfiguredProjects(projectService, 0); + checkNumberOfInferredProjects(projectService, 1); + + const inferredProject = projectService.inferredProjects[0]; + assert.isTrue(inferredProject.containsFile(file1.path)); + }); + + it("should be able to handle @types if input file list is empty", () => { + const f = { + path: "/a/app.ts", + content: "let x = 1" + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compiler: {}, + files: [] + }) + }; + const t1 = { + path: "/a/node_modules/@types/typings/index.d.ts", + content: `export * from "./lib"` + }; + const t2 = { + path: "/a/node_modules/@types/typings/lib.d.ts", + content: `export const x: number` + }; + const host = createServerHost([f, config, t1, t2], { currentDirectory: getDirectoryPath(f.path) }); + const projectService = createProjectService(host); + + projectService.openClientFile(f.path); + // Since no file from the configured project is open, it would be closed immediately + projectService.checkNumberOfProjects({ configuredProjects: 0, inferredProjects: 1 }); + }); + + it("should tolerate invalid include files that start in subDirectory", () => { + const projectFolder = "/user/username/projects/myproject"; + const f = { + path: `${projectFolder}/src/server/index.ts`, + content: "let x = 1" + }; + const config = { + path: `${projectFolder}/src/server/tsconfig.json`, + content: JSON.stringify({ + compiler: { + module: "commonjs", + outDir: "../../build" + }, + include: [ + "../src/**/*.ts" + ] + }) + }; + const host = createServerHost([f, config, libFile], { useCaseSensitiveFileNames: true }); + const projectService = createProjectService(host); + + projectService.openClientFile(f.path); + // Since no file from the configured project is open, it would be closed immediately + projectService.checkNumberOfProjects({ configuredProjects: 0, inferredProjects: 1 }); + }); + + it("Changed module resolution reflected when specifying files list", () => { + const file1: File = { + path: "/a/b/file1.ts", + content: 'import classc from "file2"' + }; + const file2a: File = { + path: "/a/file2.ts", + content: "export classc { method2a() { return 10; } }" + }; + const file2: File = { + path: "/a/b/file2.ts", + content: "export classc { method2() { return 10; } }" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ files: [file1.path], compilerOptions: { module: "amd" } }) + }; + const files = [file1, file2a, configFile, libFile]; + const host = createServerHost(files); + const projectService = createProjectService(host); + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const project = projectService.configuredProjects.get(configFile.path)!; + assert.isDefined(project); + checkProjectActualFiles(project, map(files, file => file.path)); + checkWatchedFiles(host, mapDefined(files, file => file === file1 ? undefined : file.path)); + checkWatchedDirectoriesDetailed(host, ["/a/b"], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, ["/a/b/node_modules/@types"], 1, /*recursive*/ true); + + files.push(file2); + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(configFile.path), project); + checkProjectActualFiles(project, mapDefined(files, file => file === file2a ? undefined : file.path)); + checkWatchedFiles(host, mapDefined(files, file => file === file1 ? undefined : file.path)); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, ["/a/b/node_modules/@types"], 1, /*recursive*/ true); + + // On next file open the files file2a should be closed and not watched any more + projectService.openClientFile(file2.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(configFile.path), project); + checkProjectActualFiles(project, mapDefined(files, file => file === file2a ? undefined : file.path)); + checkWatchedFiles(host, [libFile.path, configFile.path]); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, ["/a/b/node_modules/@types"], 1, /*recursive*/ true); + }); + + it("Failed lookup locations uses parent most node_modules directory", () => { + const root = "/user/username/rootfolder"; + const file1: File = { + path: "/a/b/src/file1.ts", + content: 'import { classc } from "module1"' + }; + const module1: File = { + path: "/a/b/node_modules/module1/index.d.ts", + content: `import { class2 } from "module2"; + export classc { method2a(): class2; }` + }; + const module2: File = { + path: "/a/b/node_modules/module2/index.d.ts", + content: "export class2 { method2() { return 10; } }" + }; + const module3: File = { + path: "/a/b/node_modules/module/node_modules/module3/index.d.ts", + content: "export class3 { method2() { return 10; } }" + }; + const configFile: File = { + path: "/a/b/src/tsconfig.json", + content: JSON.stringify({ files: ["file1.ts"] }) + }; + const nonLibFiles = [file1, module1, module2, module3, configFile]; + nonLibFiles.forEach(f => f.path = root + f.path); + const files = nonLibFiles.concat(libFile); + const host = createServerHost(files); + const projectService = createProjectService(host); + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const project = projectService.configuredProjects.get(configFile.path)!; + assert.isDefined(project); + checkProjectActualFiles(project, [file1.path, libFile.path, module1.path, module2.path, configFile.path]); + checkWatchedFiles(host, [libFile.path, configFile.path]); + checkWatchedDirectories(host, [], /*recursive*/ false); + const watchedRecursiveDirectories = getTypeRootsFromLocation(root + "/a/b/src"); + watchedRecursiveDirectories.push(`${root}/a/b/src/node_modules`, `${root}/a/b/node_modules`); + checkWatchedDirectories(host, watchedRecursiveDirectories, /*recursive*/ true); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/declarationFileMaps.ts b/src/testRunner/unittests/tsserver/declarationFileMaps.ts new file mode 100644 index 00000000000..200d7af0240 --- /dev/null +++ b/src/testRunner/unittests/tsserver/declarationFileMaps.ts @@ -0,0 +1,566 @@ +namespace ts.projectSystem { + function protocolFileSpanFromSubstring(file: File, substring: string, options?: SpanFromSubstringOptions): protocol.FileSpan { + return { file: file.path, ...protocolTextSpanFromSubstring(file.content, substring, options) }; + } + + function documentSpanFromSubstring(file: File, substring: string, options?: SpanFromSubstringOptions): DocumentSpan { + return { fileName: file.path, textSpan: textSpanFromSubstring(file.content, substring, options) }; + } + + function renameLocation(file: File, substring: string, options?: SpanFromSubstringOptions): RenameLocation { + return documentSpanFromSubstring(file, substring, options); + } + + function makeReferenceItem(file: File, isDefinition: boolean, text: string, lineText: string, options?: SpanFromSubstringOptions): protocol.ReferencesResponseItem { + return { + ...protocolFileSpanFromSubstring(file, text, options), + isDefinition, + isWriteAccess: isDefinition, + lineText, + }; + } + + function makeReferenceEntry(file: File, isDefinition: boolean, text: string, options?: SpanFromSubstringOptions): ReferenceEntry { + return { + ...documentSpanFromSubstring(file, text, options), + isDefinition, + isWriteAccess: isDefinition, + isInString: undefined, + }; + } + + function checkDeclarationFiles(file: File, session: TestSession, expectedFiles: ReadonlyArray): void { + openFilesForSession([file], session); + const project = Debug.assertDefined(session.getProjectService().getDefaultProjectForFile(file.path as server.NormalizedPath, /*ensureProject*/ false)); + const program = project.getCurrentProgram()!; + const output = getFileEmitOutput(program, Debug.assertDefined(program.getSourceFile(file.path)), /*emitOnlyDtsFiles*/ true); + closeFilesForSession([file], session); + + Debug.assert(!output.emitSkipped); + assert.deepEqual(output.outputFiles, expectedFiles.map((e): OutputFile => ({ name: e.path, text: e.content, writeByteOrderMark: false }))); + } + + describe("unittests:: tsserver:: with declaration file maps:: project references", () => { + const aTs: File = { + path: "/a/a.ts", + content: "export function fnA() {}\nexport interface IfaceA {}\nexport const instanceA: IfaceA = {};", + }; + const compilerOptions: CompilerOptions = { + outDir: "bin", + declaration: true, + declarationMap: true, + composite: true, + }; + const configContent = JSON.stringify({ compilerOptions }); + const aTsconfig: File = { path: "/a/tsconfig.json", content: configContent }; + + const aDtsMapContent: RawSourceMap = { + version: 3, + file: "a.d.ts", + sourceRoot: "", + sources: ["../a.ts"], + names: [], + mappings: "AAAA,wBAAgB,GAAG,SAAK;AACxB,MAAM,WAAW,MAAM;CAAG;AAC1B,eAAO,MAAM,SAAS,EAAE,MAAW,CAAC" + }; + const aDtsMap: File = { + path: "/a/bin/a.d.ts.map", + content: JSON.stringify(aDtsMapContent), + }; + const aDts: File = { + path: "/a/bin/a.d.ts", + // Need to mangle the sourceMappingURL part or it breaks the build + content: `export declare function fnA(): void;\nexport interface IfaceA {\n}\nexport declare const instanceA: IfaceA;\n//# source${""}MappingURL=a.d.ts.map`, + }; + + const bTs: File = { + path: "/b/b.ts", + content: "export function fnB() {}", + }; + const bTsconfig: File = { path: "/b/tsconfig.json", content: configContent }; + + const bDtsMapContent: RawSourceMap = { + version: 3, + file: "b.d.ts", + sourceRoot: "", + sources: ["../b.ts"], + names: [], + mappings: "AAAA,wBAAgB,GAAG,SAAK", + }; + const bDtsMap: File = { + path: "/b/bin/b.d.ts.map", + content: JSON.stringify(bDtsMapContent), + }; + const bDts: File = { + // Need to mangle the sourceMappingURL part or it breaks the build + path: "/b/bin/b.d.ts", + content: `export declare function fnB(): void;\n//# source${""}MappingURL=b.d.ts.map`, + }; + + const dummyFile: File = { + path: "/dummy/dummy.ts", + content: "let a = 10;" + }; + + const userTs: File = { + path: "/user/user.ts", + content: 'import * as a from "../a/bin/a";\nimport * as b from "../b/bin/b";\nexport function fnUser() { a.fnA(); b.fnB(); a.instanceA; }', + }; + + const userTsForConfigProject: File = { + path: "/user/user.ts", + content: 'import * as a from "../a/a";\nimport * as b from "../b/b";\nexport function fnUser() { a.fnA(); b.fnB(); a.instanceA; }', + }; + + const userTsconfig: File = { + path: "/user/tsconfig.json", + content: JSON.stringify({ + file: ["user.ts"], + references: [{ path: "../a" }, { path: "../b" }] + }) + }; + + function makeSampleProjects(addUserTsConfig?: boolean) { + const host = createServerHost([aTs, aTsconfig, aDtsMap, aDts, bTsconfig, bTs, bDtsMap, bDts, ...(addUserTsConfig ? [userTsForConfigProject, userTsconfig] : [userTs]), dummyFile]); + const session = createSession(host); + + checkDeclarationFiles(aTs, session, [aDtsMap, aDts]); + checkDeclarationFiles(bTs, session, [bDtsMap, bDts]); + + // Testing what happens if we delete the original sources. + host.deleteFile(bTs.path); + + openFilesForSession([userTs], session); + const service = session.getProjectService(); + checkNumberOfProjects(service, addUserTsConfig ? { configuredProjects: 1 } : { inferredProjects: 1 }); + return session; + } + + function verifyInferredProjectUnchanged(session: TestSession) { + checkProjectActualFiles(session.getProjectService().inferredProjects[0], [userTs.path, aDts.path, bDts.path]); + } + + function verifyDummyProject(session: TestSession) { + checkProjectActualFiles(session.getProjectService().inferredProjects[0], [dummyFile.path]); + } + + function verifyOnlyOrphanInferredProject(session: TestSession) { + openFilesForSession([dummyFile], session); + checkNumberOfProjects(session.getProjectService(), { inferredProjects: 1 }); + verifyDummyProject(session); + } + + function verifySingleInferredProject(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { inferredProjects: 1 }); + verifyInferredProjectUnchanged(session); + + // Close user file should close all the projects after opening dummy file + closeFilesForSession([userTs], session); + verifyOnlyOrphanInferredProject(session); + } + + function verifyATsConfigProject(session: TestSession) { + checkProjectActualFiles(session.getProjectService().configuredProjects.get(aTsconfig.path)!, [aTs.path, aTsconfig.path]); + } + + function verifyATsConfigOriginalProject(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { inferredProjects: 1, configuredProjects: 1 }); + verifyInferredProjectUnchanged(session); + verifyATsConfigProject(session); + // Close user file should close all the projects + closeFilesForSession([userTs], session); + verifyOnlyOrphanInferredProject(session); + } + + function verifyATsConfigWhenOpened(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { inferredProjects: 1, configuredProjects: 1 }); + verifyInferredProjectUnchanged(session); + verifyATsConfigProject(session); + + closeFilesForSession([userTs], session); + openFilesForSession([dummyFile], session); + checkNumberOfProjects(session.getProjectService(), { inferredProjects: 1, configuredProjects: 1 }); + verifyDummyProject(session); + verifyATsConfigProject(session); // ATsConfig should still be alive + } + + function verifyUserTsConfigProject(session: TestSession) { + checkProjectActualFiles(session.getProjectService().configuredProjects.get(userTsconfig.path)!, [userTs.path, aDts.path, userTsconfig.path]); + } + + it("goToDefinition", () => { + const session = makeSampleProjects(); + const response = executeSessionRequest(session, protocol.CommandTypes.Definition, protocolFileLocationFromSubstring(userTs, "fnA()")); + assert.deepEqual(response, [protocolFileSpanFromSubstring(aTs, "fnA")]); + verifySingleInferredProject(session); + }); + + it("getDefinitionAndBoundSpan", () => { + const session = makeSampleProjects(); + const response = executeSessionRequest(session, protocol.CommandTypes.DefinitionAndBoundSpan, protocolFileLocationFromSubstring(userTs, "fnA()")); + assert.deepEqual(response, { + textSpan: protocolTextSpanFromSubstring(userTs.content, "fnA"), + definitions: [protocolFileSpanFromSubstring(aTs, "fnA")], + }); + verifySingleInferredProject(session); + }); + + it("getDefinitionAndBoundSpan with file navigation", () => { + const session = makeSampleProjects(/*addUserTsConfig*/ true); + const response = executeSessionRequest(session, protocol.CommandTypes.DefinitionAndBoundSpan, protocolFileLocationFromSubstring(userTs, "fnA()")); + assert.deepEqual(response, { + textSpan: protocolTextSpanFromSubstring(userTs.content, "fnA"), + definitions: [protocolFileSpanFromSubstring(aTs, "fnA")], + }); + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 1 }); + verifyUserTsConfigProject(session); + + // Navigate to the definition + closeFilesForSession([userTs], session); + openFilesForSession([aTs], session); + + // UserTs configured project should be alive + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 }); + verifyUserTsConfigProject(session); + verifyATsConfigProject(session); + + closeFilesForSession([aTs], session); + verifyOnlyOrphanInferredProject(session); + }); + + it("goToType", () => { + const session = makeSampleProjects(); + const response = executeSessionRequest(session, protocol.CommandTypes.TypeDefinition, protocolFileLocationFromSubstring(userTs, "instanceA")); + assert.deepEqual(response, [protocolFileSpanFromSubstring(aTs, "IfaceA")]); + verifySingleInferredProject(session); + }); + + it("goToImplementation", () => { + const session = makeSampleProjects(); + const response = executeSessionRequest(session, protocol.CommandTypes.Implementation, protocolFileLocationFromSubstring(userTs, "fnA()")); + assert.deepEqual(response, [protocolFileSpanFromSubstring(aTs, "fnA")]); + verifySingleInferredProject(session); + }); + + it("goToDefinition -- target does not exist", () => { + const session = makeSampleProjects(); + const response = executeSessionRequest(session, CommandNames.Definition, protocolFileLocationFromSubstring(userTs, "fnB()")); + // bTs does not exist, so stick with bDts + assert.deepEqual(response, [protocolFileSpanFromSubstring(bDts, "fnB")]); + verifySingleInferredProject(session); + }); + + it("navigateTo", () => { + const session = makeSampleProjects(); + const response = executeSessionRequest(session, CommandNames.Navto, { file: userTs.path, searchValue: "fn" }); + assert.deepEqual | undefined>(response, [ + { + ...protocolFileSpanFromSubstring(bDts, "export declare function fnB(): void;"), + name: "fnB", + matchKind: "prefix", + isCaseSensitive: true, + kind: ScriptElementKind.functionElement, + kindModifiers: "export,declare", + }, + { + ...protocolFileSpanFromSubstring(userTs, "export function fnUser() { a.fnA(); b.fnB(); a.instanceA; }"), + name: "fnUser", + matchKind: "prefix", + isCaseSensitive: true, + kind: ScriptElementKind.functionElement, + kindModifiers: "export", + }, + { + ...protocolFileSpanFromSubstring(aTs, "export function fnA() {}"), + name: "fnA", + matchKind: "prefix", + isCaseSensitive: true, + kind: ScriptElementKind.functionElement, + kindModifiers: "export", + }, + ]); + + verifyATsConfigOriginalProject(session); + }); + + const referenceATs = (aTs: File): protocol.ReferencesResponseItem => makeReferenceItem(aTs, /*isDefinition*/ true, "fnA", "export function fnA() {}"); + const referencesUserTs = (userTs: File): ReadonlyArray => [ + makeReferenceItem(userTs, /*isDefinition*/ false, "fnA", "export function fnUser() { a.fnA(); b.fnB(); a.instanceA; }"), + ]; + + it("findAllReferences", () => { + const session = makeSampleProjects(); + + const response = executeSessionRequest(session, protocol.CommandTypes.References, protocolFileLocationFromSubstring(userTs, "fnA()")); + assert.deepEqual(response, { + refs: [...referencesUserTs(userTs), referenceATs(aTs)], + symbolName: "fnA", + symbolStartOffset: protocolLocationFromSubstring(userTs.content, "fnA()").offset, + symbolDisplayString: "function fnA(): void", + }); + + verifyATsConfigOriginalProject(session); + }); + + it("findAllReferences -- starting at definition", () => { + const session = makeSampleProjects(); + openFilesForSession([aTs], session); // If it's not opened, the reference isn't found. + const response = executeSessionRequest(session, protocol.CommandTypes.References, protocolFileLocationFromSubstring(aTs, "fnA")); + assert.deepEqual(response, { + refs: [referenceATs(aTs), ...referencesUserTs(userTs)], + symbolName: "fnA", + symbolStartOffset: protocolLocationFromSubstring(aTs.content, "fnA").offset, + symbolDisplayString: "function fnA(): void", + }); + verifyATsConfigWhenOpened(session); + }); + + interface ReferencesFullRequest extends protocol.FileLocationRequest { readonly command: protocol.CommandTypes.ReferencesFull; } + interface ReferencesFullResponse extends protocol.Response { readonly body: ReadonlyArray; } + + it("findAllReferencesFull", () => { + const session = makeSampleProjects(); + + const responseFull = executeSessionRequest(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(userTs, "fnA()")); + + assert.deepEqual>(responseFull, [ + { + definition: { + ...documentSpanFromSubstring(aTs, "fnA"), + kind: ScriptElementKind.functionElement, + name: "function fnA(): void", + containerKind: ScriptElementKind.unknown, + containerName: "", + displayParts: [ + keywordPart(SyntaxKind.FunctionKeyword), + spacePart(), + displayPart("fnA", SymbolDisplayPartKind.functionName), + punctuationPart(SyntaxKind.OpenParenToken), + punctuationPart(SyntaxKind.CloseParenToken), + punctuationPart(SyntaxKind.ColonToken), + spacePart(), + keywordPart(SyntaxKind.VoidKeyword), + ], + }, + references: [ + makeReferenceEntry(userTs, /*isDefinition*/ false, "fnA"), + makeReferenceEntry(aTs, /*isDefinition*/ true, "fnA"), + ], + }, + ]); + verifyATsConfigOriginalProject(session); + }); + + it("findAllReferencesFull definition is in mapped file", () => { + const aTs: File = { path: "/a/a.ts", content: `function f() {}` }; + const aTsconfig: File = { + path: "/a/tsconfig.json", + content: JSON.stringify({ compilerOptions: { declaration: true, declarationMap: true, outFile: "../bin/a.js" } }), + }; + const bTs: File = { path: "/b/b.ts", content: `f();` }; + const bTsconfig: File = { path: "/b/tsconfig.json", content: JSON.stringify({ references: [{ path: "../a" }] }) }; + const aDts: File = { path: "/bin/a.d.ts", content: `declare function f(): void;\n//# sourceMappingURL=a.d.ts.map` }; + const aDtsMap: File = { + path: "/bin/a.d.ts.map", + content: JSON.stringify({ version: 3, file: "a.d.ts", sourceRoot: "", sources: ["../a/a.ts"], names: [], mappings: "AAAA,iBAAS,CAAC,SAAK" }), + }; + + const session = createSession(createServerHost([aTs, aTsconfig, bTs, bTsconfig, aDts, aDtsMap])); + checkDeclarationFiles(aTs, session, [aDtsMap, aDts]); + openFilesForSession([bTs], session); + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 1 }); + + const responseFull = executeSessionRequest(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(bTs, "f()")); + + assert.deepEqual>(responseFull, [ + { + definition: { + containerKind: ScriptElementKind.unknown, + containerName: "", + displayParts: [ + keywordPart(SyntaxKind.FunctionKeyword), + spacePart(), + displayPart("f", SymbolDisplayPartKind.functionName), + punctuationPart(SyntaxKind.OpenParenToken), + punctuationPart(SyntaxKind.CloseParenToken), + punctuationPart(SyntaxKind.ColonToken), + spacePart(), + keywordPart(SyntaxKind.VoidKeyword), + ], + fileName: aTs.path, + kind: ScriptElementKind.functionElement, + name: "function f(): void", + textSpan: { start: 9, length: 1 }, + }, + references: [ + { + fileName: bTs.path, + isDefinition: false, + isInString: undefined, + isWriteAccess: false, + textSpan: { start: 0, length: 1 }, + }, + { + fileName: aTs.path, + isDefinition: true, + isInString: undefined, + isWriteAccess: true, + textSpan: { start: 9, length: 1 }, + }, + ], + } + ]); + }); + + it("findAllReferences -- target does not exist", () => { + const session = makeSampleProjects(); + + const response = executeSessionRequest(session, protocol.CommandTypes.References, protocolFileLocationFromSubstring(userTs, "fnB()")); + assert.deepEqual(response, { + refs: [ + makeReferenceItem(bDts, /*isDefinition*/ true, "fnB", "export declare function fnB(): void;"), + makeReferenceItem(userTs, /*isDefinition*/ false, "fnB", "export function fnUser() { a.fnA(); b.fnB(); a.instanceA; }"), + ], + symbolName: "fnB", + symbolStartOffset: protocolLocationFromSubstring(userTs.content, "fnB()").offset, + symbolDisplayString: "function fnB(): void", + }); + verifySingleInferredProject(session); + }); + + const renameATs = (aTs: File): protocol.SpanGroup => ({ + file: aTs.path, + locs: [protocolRenameSpanFromSubstring(aTs.content, "fnA")], + }); + const renameUserTs = (userTs: File): protocol.SpanGroup => ({ + file: userTs.path, + locs: [protocolRenameSpanFromSubstring(userTs.content, "fnA")], + }); + + it("renameLocations", () => { + const session = makeSampleProjects(); + const response = executeSessionRequest(session, protocol.CommandTypes.Rename, protocolFileLocationFromSubstring(userTs, "fnA()")); + assert.deepEqual(response, { + info: { + canRename: true, + displayName: "fnA", + fileToRename: undefined, + fullDisplayName: '"/a/bin/a".fnA', // Ideally this would use the original source's path instead of the declaration file's path. + kind: ScriptElementKind.functionElement, + kindModifiers: [ScriptElementKindModifier.exportedModifier, ScriptElementKindModifier.ambientModifier].join(","), + triggerSpan: protocolTextSpanFromSubstring(userTs.content, "fnA"), + }, + locs: [renameUserTs(userTs), renameATs(aTs)], + }); + verifyATsConfigOriginalProject(session); + }); + + it("renameLocations -- starting at definition", () => { + const session = makeSampleProjects(); + openFilesForSession([aTs], session); // If it's not opened, the reference isn't found. + const response = executeSessionRequest(session, protocol.CommandTypes.Rename, protocolFileLocationFromSubstring(aTs, "fnA")); + assert.deepEqual(response, { + info: { + canRename: true, + displayName: "fnA", + fileToRename: undefined, + fullDisplayName: '"/a/a".fnA', + kind: ScriptElementKind.functionElement, + kindModifiers: ScriptElementKindModifier.exportedModifier, + triggerSpan: protocolTextSpanFromSubstring(aTs.content, "fnA"), + }, + locs: [renameATs(aTs), renameUserTs(userTs)], + }); + verifyATsConfigWhenOpened(session); + }); + + it("renameLocationsFull", () => { + const session = makeSampleProjects(); + const response = executeSessionRequest(session, protocol.CommandTypes.RenameLocationsFull, protocolFileLocationFromSubstring(userTs, "fnA()")); + assert.deepEqual>(response, [ + renameLocation(userTs, "fnA"), + renameLocation(aTs, "fnA"), + ]); + verifyATsConfigOriginalProject(session); + }); + + it("renameLocations -- target does not exist", () => { + const session = makeSampleProjects(); + const response = executeSessionRequest(session, protocol.CommandTypes.Rename, protocolFileLocationFromSubstring(userTs, "fnB()")); + assert.deepEqual(response, { + info: { + canRename: true, + displayName: "fnB", + fileToRename: undefined, + fullDisplayName: '"/b/bin/b".fnB', + kind: ScriptElementKind.functionElement, + kindModifiers: [ScriptElementKindModifier.exportedModifier, ScriptElementKindModifier.ambientModifier].join(","), + triggerSpan: protocolTextSpanFromSubstring(userTs.content, "fnB"), + }, + locs: [ + { + file: bDts.path, + locs: [protocolRenameSpanFromSubstring(bDts.content, "fnB")], + }, + { + file: userTs.path, + locs: [protocolRenameSpanFromSubstring(userTs.content, "fnB")], + }, + ], + }); + verifySingleInferredProject(session); + }); + + it("getEditsForFileRename", () => { + const session = makeSampleProjects(); + const response = executeSessionRequest(session, protocol.CommandTypes.GetEditsForFileRename, { + oldFilePath: aTs.path, + newFilePath: "/a/aNew.ts", + }); + assert.deepEqual>(response, [ + { + fileName: userTs.path, + textChanges: [ + { ...protocolTextSpanFromSubstring(userTs.content, "../a/bin/a"), newText: "../a/bin/aNew" }, + ], + }, + ]); + verifySingleInferredProject(session); + }); + + it("getEditsForFileRename when referencing project doesnt include file and its renamed", () => { + const aTs: File = { path: "/a/src/a.ts", content: "" }; + const aTsconfig: File = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions: { + composite: true, + declaration: true, + declarationMap: true, + outDir: "./build", + } + }), + }; + const bTs: File = { path: "/b/src/b.ts", content: "" }; + const bTsconfig: File = { + path: "/b/tsconfig.json", + content: JSON.stringify({ + compilerOptions: { + composite: true, + outDir: "./build", + }, + include: ["./src"], + references: [{ path: "../a" }], + }), + }; + + const host = createServerHost([aTs, aTsconfig, bTs, bTsconfig]); + const session = createSession(host); + openFilesForSession([aTs, bTs], session); + const response = executeSessionRequest(session, CommandNames.GetEditsForFileRename, { + oldFilePath: aTs.path, + newFilePath: "/a/src/a1.ts", + }); + assert.deepEqual>(response, []); // Should not change anything + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/documentRegistry.ts b/src/testRunner/unittests/tsserver/documentRegistry.ts new file mode 100644 index 00000000000..1761e413833 --- /dev/null +++ b/src/testRunner/unittests/tsserver/documentRegistry.ts @@ -0,0 +1,94 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: document registry in project service", () => { + const projectRootPath = "/user/username/projects/project"; + const importModuleContent = `import {a} from "./module1"`; + const file: File = { + path: `${projectRootPath}/index.ts`, + content: importModuleContent + }; + const moduleFile: File = { + path: `${projectRootPath}/module1.d.ts`, + content: "export const a: number;" + }; + const configFile: File = { + path: `${projectRootPath}/tsconfig.json`, + content: JSON.stringify({ files: ["index.ts"] }) + }; + + function getProject(service: TestProjectService) { + return service.configuredProjects.get(configFile.path)!; + } + + function checkProject(service: TestProjectService, moduleIsOrphan: boolean) { + // Update the project + const project = getProject(service); + project.getLanguageService(); + checkProjectActualFiles(project, [file.path, libFile.path, configFile.path, ...(moduleIsOrphan ? [] : [moduleFile.path])]); + const moduleInfo = service.getScriptInfo(moduleFile.path)!; + assert.isDefined(moduleInfo); + assert.equal(moduleInfo.isOrphan(), moduleIsOrphan); + const key = service.documentRegistry.getKeyForCompilationSettings(project.getCompilationSettings()); + assert.deepEqual(service.documentRegistry.getLanguageServiceRefCounts(moduleInfo.path), [[key, moduleIsOrphan ? undefined : 1]]); + } + + function createServiceAndHost() { + const host = createServerHost([file, moduleFile, libFile, configFile]); + const service = createProjectService(host); + service.openClientFile(file.path); + checkProject(service, /*moduleIsOrphan*/ false); + return { host, service }; + } + + function changeFileToNotImportModule(service: TestProjectService) { + const info = service.getScriptInfo(file.path)!; + service.applyChangesToFile(info, [{ span: { start: 0, length: importModuleContent.length }, newText: "" }]); + checkProject(service, /*moduleIsOrphan*/ true); + } + + function changeFileToImportModule(service: TestProjectService) { + const info = service.getScriptInfo(file.path)!; + service.applyChangesToFile(info, [{ span: { start: 0, length: 0 }, newText: importModuleContent }]); + checkProject(service, /*moduleIsOrphan*/ false); + } + + it("Caches the source file if script info is orphan", () => { + const { service } = createServiceAndHost(); + const project = getProject(service); + + const moduleInfo = service.getScriptInfo(moduleFile.path)!; + const sourceFile = moduleInfo.cacheSourceFile!.sourceFile; + assert.equal(project.getSourceFile(moduleInfo.path), sourceFile); + + // edit file + changeFileToNotImportModule(service); + assert.equal(moduleInfo.cacheSourceFile!.sourceFile, sourceFile); + + // write content back + changeFileToImportModule(service); + assert.equal(moduleInfo.cacheSourceFile!.sourceFile, sourceFile); + assert.equal(project.getSourceFile(moduleInfo.path), sourceFile); + }); + + it("Caches the source file if script info is orphan, and orphan script info changes", () => { + const { host, service } = createServiceAndHost(); + const project = getProject(service); + + const moduleInfo = service.getScriptInfo(moduleFile.path)!; + const sourceFile = moduleInfo.cacheSourceFile!.sourceFile; + assert.equal(project.getSourceFile(moduleInfo.path), sourceFile); + + // edit file + changeFileToNotImportModule(service); + assert.equal(moduleInfo.cacheSourceFile!.sourceFile, sourceFile); + + const updatedModuleContent = moduleFile.content + "\nexport const b: number;"; + host.writeFile(moduleFile.path, updatedModuleContent); + + // write content back + changeFileToImportModule(service); + assert.notEqual(moduleInfo.cacheSourceFile!.sourceFile, sourceFile); + assert.equal(project.getSourceFile(moduleInfo.path), moduleInfo.cacheSourceFile!.sourceFile); + assert.equal(moduleInfo.cacheSourceFile!.sourceFile.text, updatedModuleContent); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/duplicatePackages.ts b/src/testRunner/unittests/tsserver/duplicatePackages.ts new file mode 100644 index 00000000000..ec85eb6a82f --- /dev/null +++ b/src/testRunner/unittests/tsserver/duplicatePackages.ts @@ -0,0 +1,54 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: duplicate packages", () => { + // Tests that 'moduleSpecifiers.ts' will import from the redirecting file, and not from the file it redirects to, if that can provide a global module specifier. + it("works with import fixes", () => { + const packageContent = "export const foo: number;"; + const packageJsonContent = JSON.stringify({ name: "foo", version: "1.2.3" }); + const aFooIndex: File = { path: "/a/node_modules/foo/index.d.ts", content: packageContent }; + const aFooPackage: File = { path: "/a/node_modules/foo/package.json", content: packageJsonContent }; + const bFooIndex: File = { path: "/b/node_modules/foo/index.d.ts", content: packageContent }; + const bFooPackage: File = { path: "/b/node_modules/foo/package.json", content: packageJsonContent }; + + const userContent = 'import("foo");\nfoo'; + const aUser: File = { path: "/a/user.ts", content: userContent }; + const bUser: File = { path: "/b/user.ts", content: userContent }; + const tsconfig: File = { + path: "/tsconfig.json", + content: "{}", + }; + + const host = createServerHost([aFooIndex, aFooPackage, bFooIndex, bFooPackage, aUser, bUser, tsconfig]); + const session = createSession(host); + + openFilesForSession([aUser, bUser], session); + + for (const user of [aUser, bUser]) { + const response = executeSessionRequest(session, protocol.CommandTypes.GetCodeFixes, { + file: user.path, + startLine: 2, + startOffset: 1, + endLine: 2, + endOffset: 4, + errorCodes: [Diagnostics.Cannot_find_name_0.code], + }); + assert.deepEqual | undefined>(response, [ + { + description: `Import 'foo' from module "foo"`, + fixName: "import", + fixId: "fixMissingImport", + fixAllDescription: "Add all missing imports", + changes: [{ + fileName: user.path, + textChanges: [{ + start: { line: 1, offset: 1 }, + end: { line: 1, offset: 1 }, + newText: 'import { foo } from "foo";\n\n', + }], + }], + commands: undefined, + }, + ]); + } + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts b/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts new file mode 100644 index 00000000000..ff69a7e6568 --- /dev/null +++ b/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts @@ -0,0 +1,76 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: events:: LargeFileReferencedEvent with large file", () => { + const projectRoot = "/user/username/projects/project"; + + function getLargeFile(useLargeTsFile: boolean) { + return `src/large.${useLargeTsFile ? "ts" : "js"}`; + } + + function createSessionWithEventHandler(files: File[], useLargeTsFile: boolean) { + const largeFile: File = { + path: `${projectRoot}/${getLargeFile(useLargeTsFile)}`, + content: "export var x = 10;", + fileSize: server.maxFileSize + 1 + }; + files.push(largeFile); + const host = createServerHost(files); + const { session, events: largeFileReferencedEvents } = createSessionWithEventTracking(host, server.LargeFileReferencedEvent); + + return { session, verifyLargeFile }; + + function verifyLargeFile(project: server.Project) { + checkProjectActualFiles(project, files.map(f => f.path)); + + // large file for non ts file should be empty and for ts file should have content + const service = session.getProjectService(); + const info = service.getScriptInfo(largeFile.path)!; + assert.equal(info.cacheSourceFile!.sourceFile.text, useLargeTsFile ? largeFile.content : ""); + + assert.deepEqual(largeFileReferencedEvents, useLargeTsFile ? emptyArray : [{ + eventName: server.LargeFileReferencedEvent, + data: { file: largeFile.path, fileSize: largeFile.fileSize, maxFileSize: server.maxFileSize } + }]); + } + } + + function verifyLargeFile(useLargeTsFile: boolean) { + it("when large file is included by tsconfig", () => { + const file: File = { + path: `${projectRoot}/src/file.ts`, + content: "export var y = 10;" + }; + const tsconfig: File = { + path: `${projectRoot}/tsconfig.json`, + content: JSON.stringify({ files: ["src/file.ts", getLargeFile(useLargeTsFile)], compilerOptions: { target: 1, allowJs: true } }) + }; + const files = [file, libFile, tsconfig]; + const { session, verifyLargeFile } = createSessionWithEventHandler(files, useLargeTsFile); + const service = session.getProjectService(); + openFilesForSession([file], session); + checkNumberOfProjects(service, { configuredProjects: 1 }); + verifyLargeFile(service.configuredProjects.get(tsconfig.path)!); + }); + + it("when large file is included by module resolution", () => { + const file: File = { + path: `${projectRoot}/src/file.ts`, + content: `export var y = 10;import {x} from "./large"` + }; + const files = [file, libFile]; + const { session, verifyLargeFile } = createSessionWithEventHandler(files, useLargeTsFile); + const service = session.getProjectService(); + openFilesForSession([file], session); + checkNumberOfProjects(service, { inferredProjects: 1 }); + verifyLargeFile(service.inferredProjects[0]); + }); + } + + describe("large file is ts file", () => { + verifyLargeFile(/*useLargeTsFile*/ true); + }); + + describe("large file is js file", () => { + verifyLargeFile(/*useLargeTsFile*/ false); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts b/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts new file mode 100644 index 00000000000..231c46c350b --- /dev/null +++ b/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts @@ -0,0 +1,51 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: events:: ProjectLanguageServiceStateEvent", () => { + it("language service disabled events are triggered", () => { + const f1 = { + path: "/a/app.js", + content: "let x = 1;" + }; + const f2 = { + path: "/a/largefile.js", + content: "" + }; + const config = { + path: "/a/jsconfig.json", + content: "{}" + }; + const configWithExclude = { + path: config.path, + content: JSON.stringify({ exclude: ["largefile.js"] }) + }; + const host = createServerHost([f1, f2, config]); + const originalGetFileSize = host.getFileSize; + host.getFileSize = (filePath: string) => + filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + + const { session, events } = createSessionWithEventTracking(host, server.ProjectLanguageServiceStateEvent); + session.executeCommand({ + seq: 0, + type: "request", + command: "open", + arguments: { file: f1.path } + }); + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const project = configuredProjectAt(projectService, 0); + assert.isFalse(project.languageServiceEnabled, "Language service enabled"); + assert.equal(events.length, 1, "should receive event"); + assert.equal(events[0].data.project, project, "project name"); + assert.equal(events[0].data.project.getProjectName(), config.path, "config path"); + assert.isFalse(events[0].data.languageServiceEnabled, "Language service state"); + + host.reloadFS([f1, f2, configWithExclude]); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + assert.isTrue(project.languageServiceEnabled, "Language service enabled"); + assert.equal(events.length, 2, "should receive event"); + assert.equal(events[1].data.project, project, "project"); + assert.equal(events[1].data.project.getProjectName(), config.path, "config path"); + assert.isTrue(events[1].data.languageServiceEnabled, "Language service state"); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/events/projectLoading.ts b/src/testRunner/unittests/tsserver/events/projectLoading.ts new file mode 100644 index 00000000000..7a881ff1380 --- /dev/null +++ b/src/testRunner/unittests/tsserver/events/projectLoading.ts @@ -0,0 +1,193 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoadingFinish events", () => { + const projectRoot = "/user/username/projects"; + const aTs: File = { + path: `${projectRoot}/a/a.ts`, + content: "export class A { }" + }; + const configA: File = { + path: `${projectRoot}/a/tsconfig.json`, + content: "{}" + }; + const bTsPath = `${projectRoot}/b/b.ts`; + const configBPath = `${projectRoot}/b/tsconfig.json`; + const files = [libFile, aTs, configA]; + + function verifyProjectLoadingStartAndFinish(createSession: (host: TestServerHost) => { + session: TestSession; + getNumberOfEvents: () => number; + clearEvents: () => void; + verifyProjectLoadEvents: (expected: [server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent]) => void; + }) { + function createSessionToVerifyEvent(files: ReadonlyArray) { + const host = createServerHost(files); + const originalReadFile = host.readFile; + const { session, getNumberOfEvents, clearEvents, verifyProjectLoadEvents } = createSession(host); + host.readFile = file => { + if (file === configA.path || file === configBPath) { + assert.equal(getNumberOfEvents(), 1, "Event for loading is sent before reading config file"); + } + return originalReadFile.call(host, file); + }; + const service = session.getProjectService(); + return { host, session, verifyEvent, verifyEventWithOpenTs, service, getNumberOfEvents }; + + function verifyEvent(project: server.Project, reason: string) { + verifyProjectLoadEvents([ + { eventName: server.ProjectLoadingStartEvent, data: { project, reason } }, + { eventName: server.ProjectLoadingFinishEvent, data: { project } } + ]); + clearEvents(); + } + + function verifyEventWithOpenTs(file: File, configPath: string, configuredProjects: number) { + openFilesForSession([file], session); + checkNumberOfProjects(service, { configuredProjects }); + const project = service.configuredProjects.get(configPath)!; + assert.isDefined(project); + verifyEvent(project, `Creating possible configured project for ${file.path} to open`); + } + } + + it("when project is created by open file", () => { + const bTs: File = { + path: bTsPath, + content: "export class B {}" + }; + const configB: File = { + path: configBPath, + content: "{}" + }; + const { verifyEventWithOpenTs } = createSessionToVerifyEvent(files.concat(bTs, configB)); + verifyEventWithOpenTs(aTs, configA.path, 1); + verifyEventWithOpenTs(bTs, configB.path, 2); + }); + + it("when change is detected in the config file", () => { + const { host, verifyEvent, verifyEventWithOpenTs, service } = createSessionToVerifyEvent(files); + verifyEventWithOpenTs(aTs, configA.path, 1); + + host.writeFile(configA.path, configA.content); + host.checkTimeoutQueueLengthAndRun(2); + const project = service.configuredProjects.get(configA.path)!; + verifyEvent(project, `Change in config file detected`); + }); + + it("when opening original location project", () => { + const aDTs: File = { + path: `${projectRoot}/a/a.d.ts`, + content: `export declare class A { +} +//# sourceMappingURL=a.d.ts.map +` + }; + const aDTsMap: File = { + path: `${projectRoot}/a/a.d.ts.map`, + content: `{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["./a.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;CAAI"}` + }; + const bTs: File = { + path: bTsPath, + content: `import {A} from "../a/a"; new A();` + }; + const configB: File = { + path: configBPath, + content: JSON.stringify({ + references: [{ path: "../a" }] + }) + }; + + const { service, session, verifyEventWithOpenTs, verifyEvent } = createSessionToVerifyEvent(files.concat(aDTs, aDTsMap, bTs, configB)); + verifyEventWithOpenTs(bTs, configB.path, 1); + + session.executeCommandSeq({ + command: protocol.CommandTypes.References, + arguments: { + file: bTs.path, + ...protocolLocationFromSubstring(bTs.content, "A()") + } + }); + + checkNumberOfProjects(service, { configuredProjects: 2 }); + const project = service.configuredProjects.get(configA.path)!; + assert.isDefined(project); + verifyEvent(project, `Creating project for original file: ${aTs.path} for location: ${aDTs.path}`); + }); + + describe("with external projects and config files ", () => { + const projectFileName = `${projectRoot}/a/project.csproj`; + + function createSession(lazyConfiguredProjectsFromExternalProject: boolean) { + const { session, service, verifyEvent: verifyEventWorker, getNumberOfEvents } = createSessionToVerifyEvent(files); + service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } }); + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([aTs.path, configA.path]), + options: {} + }); + checkNumberOfProjects(service, { configuredProjects: 1 }); + return { session, service, verifyEvent, getNumberOfEvents }; + + function verifyEvent() { + const projectA = service.configuredProjects.get(configA.path)!; + assert.isDefined(projectA); + verifyEventWorker(projectA, `Creating configured project in external project: ${projectFileName}`); + } + } + + it("when lazyConfiguredProjectsFromExternalProject is false", () => { + const { verifyEvent } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ false); + verifyEvent(); + }); + + it("when lazyConfiguredProjectsFromExternalProject is true and file is opened", () => { + const { verifyEvent, getNumberOfEvents, session } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ true); + assert.equal(getNumberOfEvents(), 0); + + openFilesForSession([aTs], session); + verifyEvent(); + }); + + it("when lazyConfiguredProjectsFromExternalProject is disabled", () => { + const { verifyEvent, getNumberOfEvents, service } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ true); + assert.equal(getNumberOfEvents(), 0); + + service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject: false } }); + verifyEvent(); + }); + }); + } + + describe("when using event handler", () => { + verifyProjectLoadingStartAndFinish(host => { + const { session, events } = createSessionWithEventTracking(host, server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent); + return { + session, + getNumberOfEvents: () => events.length, + clearEvents: () => events.length = 0, + verifyProjectLoadEvents: expected => assert.deepEqual(events, expected) + }; + }); + }); + + describe("when using default event handler", () => { + verifyProjectLoadingStartAndFinish(host => { + const { session, getEvents, clearEvents } = createSessionWithDefaultEventHandler(host, [server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent]); + return { + session, + getNumberOfEvents: () => getEvents().length, + clearEvents, + verifyProjectLoadEvents + }; + + function verifyProjectLoadEvents(expected: [server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent]) { + const actual = getEvents().map(e => ({ eventName: e.event, data: e.body })); + const mappedExpected = expected.map(e => { + const { project, ...rest } = e.data; + return { eventName: e.eventName, data: { projectName: project.getProjectName(), ...rest } }; + }); + assert.deepEqual(actual, mappedExpected); + } + }); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts b/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts new file mode 100644 index 00000000000..05a43cb4a15 --- /dev/null +++ b/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts @@ -0,0 +1,591 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { + function verifyFiles(caption: string, actual: ReadonlyArray, expected: ReadonlyArray) { + assert.equal(actual.length, expected.length, `Incorrect number of ${caption}. Actual: ${actual} Expected: ${expected}`); + const seen = createMap(); + forEach(actual, f => { + assert.isFalse(seen.has(f), `${caption}: Found duplicate ${f}. Actual: ${actual} Expected: ${expected}`); + seen.set(f, true); + assert.isTrue(contains(expected, f), `${caption}: Expected not to contain ${f}. Actual: ${actual} Expected: ${expected}`); + }); + } + + function createVerifyInitialOpen(session: TestSession, verifyProjectsUpdatedInBackgroundEventHandler: (events: server.ProjectsUpdatedInBackgroundEvent[]) => void) { + return (file: File) => { + session.executeCommandSeq({ + command: server.CommandNames.Open, + arguments: { + file: file.path + } + }); + verifyProjectsUpdatedInBackgroundEventHandler([]); + }; + } + + interface ProjectsUpdatedInBackgroundEventVerifier { + session: TestSession; + verifyProjectsUpdatedInBackgroundEventHandler(events: server.ProjectsUpdatedInBackgroundEvent[]): void; + verifyInitialOpen(file: File): void; + } + + function verifyProjectsUpdatedInBackgroundEvent(createSession: (host: TestServerHost) => ProjectsUpdatedInBackgroundEventVerifier) { + it("when adding new file", () => { + const commonFile1: File = { + path: "/a/b/file1.ts", + content: "export var x = 10;" + }; + const commonFile2: File = { + path: "/a/b/file2.ts", + content: "export var y = 10;" + }; + const commonFile3: File = { + path: "/a/b/file3.ts", + content: "export var z = 10;" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{}` + }; + const openFiles = [commonFile1.path]; + const host = createServerHost([commonFile1, libFile, configFile]); + const { verifyProjectsUpdatedInBackgroundEventHandler, verifyInitialOpen } = createSession(host); + verifyInitialOpen(commonFile1); + + host.reloadFS([commonFile1, libFile, configFile, commonFile2]); + host.runQueuedTimeoutCallbacks(); + verifyProjectsUpdatedInBackgroundEventHandler([{ + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles + } + }]); + + host.reloadFS([commonFile1, commonFile2, libFile, configFile, commonFile3]); + host.runQueuedTimeoutCallbacks(); + verifyProjectsUpdatedInBackgroundEventHandler([{ + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles + } + }]); + }); + + describe("with --out or --outFile setting", () => { + function verifyEventWithOutSettings(compilerOptions: CompilerOptions = {}) { + const config: File = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions + }) + }; + + const f1: File = { + path: "/a/a.ts", + content: "export let x = 1" + }; + const f2: File = { + path: "/a/b.ts", + content: "export let y = 1" + }; + + const openFiles = [f1.path]; + const files = [f1, config, libFile]; + const host = createServerHost(files); + const { verifyInitialOpen, verifyProjectsUpdatedInBackgroundEventHandler } = createSession(host); + verifyInitialOpen(f1); + + files.push(f2); + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + + verifyProjectsUpdatedInBackgroundEventHandler([{ + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles + } + }]); + + f2.content = "export let x = 11"; + host.reloadFS(files); + host.runQueuedTimeoutCallbacks(); + verifyProjectsUpdatedInBackgroundEventHandler([{ + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles + } + }]); + } + + it("when both options are not set", () => { + verifyEventWithOutSettings(); + }); + + it("when --out is set", () => { + const outJs = "/a/out.js"; + verifyEventWithOutSettings({ out: outJs }); + }); + + it("when --outFile is set", () => { + const outJs = "/a/out.js"; + verifyEventWithOutSettings({ outFile: outJs }); + }); + }); + + describe("with modules and configured project", () => { + const file1Consumer1Path = "/a/b/file1Consumer1.ts"; + const moduleFile1Path = "/a/b/moduleFile1.ts"; + const configFilePath = "/a/b/tsconfig.json"; + interface InitialStateParams { + /** custom config file options */ + configObj?: any; + /** Additional files and folders to add */ + getAdditionalFileOrFolder?(): File[]; + /** initial list of files to reload in fs and first file in this list being the file to open */ + firstReloadFileList?: string[]; + } + function getInitialState({ configObj = {}, getAdditionalFileOrFolder, firstReloadFileList }: InitialStateParams = {}) { + const moduleFile1: File = { + path: moduleFile1Path, + content: "export function Foo() { };", + }; + + const file1Consumer1: File = { + path: file1Consumer1Path, + content: `import {Foo} from "./moduleFile1"; export var y = 10;`, + }; + + const file1Consumer2: File = { + path: "/a/b/file1Consumer2.ts", + content: `import {Foo} from "./moduleFile1"; let z = 10;`, + }; + + const moduleFile2: File = { + path: "/a/b/moduleFile2.ts", + content: `export var Foo4 = 10;`, + }; + + const globalFile3: File = { + path: "/a/b/globalFile3.ts", + content: `interface GlobalFoo { age: number }` + }; + + const additionalFiles = getAdditionalFileOrFolder ? getAdditionalFileOrFolder() : []; + const configFile = { + path: configFilePath, + content: JSON.stringify(configObj || { compilerOptions: {} }) + }; + + const files: File[] = [file1Consumer1, moduleFile1, file1Consumer2, moduleFile2, ...additionalFiles, globalFile3, libFile, configFile]; + + const filesToReload = firstReloadFileList && getFiles(firstReloadFileList) || files; + const host = createServerHost([filesToReload[0], configFile]); + + // Initial project creation + const { session, verifyProjectsUpdatedInBackgroundEventHandler, verifyInitialOpen } = createSession(host); + const openFiles = [filesToReload[0].path]; + verifyInitialOpen(filesToReload[0]); + + // Since this is first event, it will have all the files + verifyProjectsUpdatedInBackgroundEvent(filesToReload); + + return { + moduleFile1, file1Consumer1, file1Consumer2, moduleFile2, globalFile3, configFile, + files, + updateContentOfOpenFile, + verifyNoProjectsUpdatedInBackgroundEvent, + verifyProjectsUpdatedInBackgroundEvent + }; + + function getFiles(filelist: string[]) { + return map(filelist, getFile); + } + + function getFile(fileName: string) { + return find(files, file => file.path === fileName)!; + } + + function verifyNoProjectsUpdatedInBackgroundEvent(filesToReload?: File[]) { + host.reloadFS(filesToReload || files); + host.runQueuedTimeoutCallbacks(); + verifyProjectsUpdatedInBackgroundEventHandler([]); + } + + function verifyProjectsUpdatedInBackgroundEvent(filesToReload?: File[]) { + host.reloadFS(filesToReload || files); + host.runQueuedTimeoutCallbacks(); + verifyProjectsUpdatedInBackgroundEventHandler([{ + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles + } + }]); + } + + function updateContentOfOpenFile(file: File, newContent: string) { + session.executeCommandSeq({ + command: server.CommandNames.Change, + arguments: { + file: file.path, + insertString: newContent, + endLine: 1, + endOffset: file.content.length, + line: 1, + offset: 1 + } + }); + file.content = newContent; + } + } + + it("should contains only itself if a module file's shape didn't change, and all files referencing it if its shape changed", () => { + const { moduleFile1, verifyProjectsUpdatedInBackgroundEvent } = getInitialState(); + + // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyProjectsUpdatedInBackgroundEvent(); + + // Change the content of moduleFile1 to `export var T: number;export function Foo() { console.log('hi'); };` + moduleFile1.content = `export var T: number;export function Foo() { console.log('hi'); };`; + verifyProjectsUpdatedInBackgroundEvent(); + }); + + it("should be up-to-date with the reference map changes", () => { + const { moduleFile1, file1Consumer1, updateContentOfOpenFile, verifyProjectsUpdatedInBackgroundEvent, verifyNoProjectsUpdatedInBackgroundEvent } = getInitialState(); + + // Change file1Consumer1 content to `export let y = Foo();` + updateContentOfOpenFile(file1Consumer1, "export let y = Foo();"); + verifyNoProjectsUpdatedInBackgroundEvent(); + + // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyProjectsUpdatedInBackgroundEvent(); + + // Add the import statements back to file1Consumer1 + updateContentOfOpenFile(file1Consumer1, `import {Foo} from "./moduleFile1";let y = Foo();`); + verifyNoProjectsUpdatedInBackgroundEvent(); + + // Change the content of moduleFile1 to `export var T: number;export var T2: string;export function Foo() { };` + moduleFile1.content = `export var T: number;export var T2: string;export function Foo() { };`; + verifyProjectsUpdatedInBackgroundEvent(); + + // Multiple file edits in one go: + + // Change file1Consumer1 content to `export let y = Foo();` + // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` + updateContentOfOpenFile(file1Consumer1, `export let y = Foo();`); + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyProjectsUpdatedInBackgroundEvent(); + }); + + it("should be up-to-date with deleted files", () => { + const { moduleFile1, file1Consumer2, files, verifyProjectsUpdatedInBackgroundEvent } = getInitialState(); + + // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` + moduleFile1.content = `export var T: number;export function Foo() { };`; + + // Delete file1Consumer2 + const filesToLoad = filter(files, file => file !== file1Consumer2); + verifyProjectsUpdatedInBackgroundEvent(filesToLoad); + }); + + it("should be up-to-date with newly created files", () => { + const { moduleFile1, files, verifyProjectsUpdatedInBackgroundEvent, } = getInitialState(); + + const file1Consumer3: File = { + path: "/a/b/file1Consumer3.ts", + content: `import {Foo} from "./moduleFile1"; let y = Foo();` + }; + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyProjectsUpdatedInBackgroundEvent(files.concat(file1Consumer3)); + }); + + it("should detect changes in non-root files", () => { + const { moduleFile1, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ + configObj: { files: [file1Consumer1Path] }, + }); + + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyProjectsUpdatedInBackgroundEvent(); + + // change file1 internal, and verify only file1 is affected + moduleFile1.content += "var T1: number;"; + verifyProjectsUpdatedInBackgroundEvent(); + }); + + it("should return all files if a global file changed shape", () => { + const { globalFile3, verifyProjectsUpdatedInBackgroundEvent } = getInitialState(); + + globalFile3.content += "var T2: string;"; + verifyProjectsUpdatedInBackgroundEvent(); + }); + + it("should always return the file itself if '--isolatedModules' is specified", () => { + const { moduleFile1, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ + configObj: { compilerOptions: { isolatedModules: true } } + }); + + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyProjectsUpdatedInBackgroundEvent(); + }); + + it("should always return the file itself if '--out' or '--outFile' is specified", () => { + const outFilePath = "/a/b/out.js"; + const { moduleFile1, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ + configObj: { compilerOptions: { module: "system", outFile: outFilePath } } + }); + + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyProjectsUpdatedInBackgroundEvent(); + }); + + it("should return cascaded affected file list", () => { + const file1Consumer1Consumer1: File = { + path: "/a/b/file1Consumer1Consumer1.ts", + content: `import {y} from "./file1Consumer1";` + }; + const { moduleFile1, file1Consumer1, updateContentOfOpenFile, verifyNoProjectsUpdatedInBackgroundEvent, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ + getAdditionalFileOrFolder: () => [file1Consumer1Consumer1] + }); + + updateContentOfOpenFile(file1Consumer1, file1Consumer1.content + "export var T: number;"); + verifyNoProjectsUpdatedInBackgroundEvent(); + + // Doesnt change the shape of file1Consumer1 + moduleFile1.content = `export var T: number;export function Foo() { };`; + verifyProjectsUpdatedInBackgroundEvent(); + + // Change both files before the timeout + updateContentOfOpenFile(file1Consumer1, file1Consumer1.content + "export var T2: number;"); + moduleFile1.content = `export var T2: number;export function Foo() { };`; + verifyProjectsUpdatedInBackgroundEvent(); + }); + + it("should work fine for files with circular references", () => { + const file1: File = { + path: "/a/b/file1.ts", + content: ` + /// + export var t1 = 10;` + }; + const file2: File = { + path: "/a/b/file2.ts", + content: ` + /// + export var t2 = 10;` + }; + const { configFile, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ + getAdditionalFileOrFolder: () => [file1, file2], + firstReloadFileList: [file1.path, libFile.path, file2.path, configFilePath] + }); + + file2.content += "export var t3 = 10;"; + verifyProjectsUpdatedInBackgroundEvent([file1, file2, libFile, configFile]); + }); + + it("should detect removed code file", () => { + const referenceFile1: File = { + path: "/a/b/referenceFile1.ts", + content: ` + /// + export var x = Foo();` + }; + const { configFile, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ + getAdditionalFileOrFolder: () => [referenceFile1], + firstReloadFileList: [referenceFile1.path, libFile.path, moduleFile1Path, configFilePath] + }); + + verifyProjectsUpdatedInBackgroundEvent([libFile, referenceFile1, configFile]); + }); + + it("should detect non-existing code file", () => { + const referenceFile1: File = { + path: "/a/b/referenceFile1.ts", + content: ` + /// + export var x = Foo();` + }; + const { configFile, moduleFile2, updateContentOfOpenFile, verifyNoProjectsUpdatedInBackgroundEvent, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ + getAdditionalFileOrFolder: () => [referenceFile1], + firstReloadFileList: [referenceFile1.path, libFile.path, configFilePath] + }); + + updateContentOfOpenFile(referenceFile1, referenceFile1.content + "export var yy = Foo();"); + verifyNoProjectsUpdatedInBackgroundEvent([libFile, referenceFile1, configFile]); + + // Create module File2 and see both files are saved + verifyProjectsUpdatedInBackgroundEvent([libFile, moduleFile2, referenceFile1, configFile]); + }); + }); + + describe("resolution when resolution cache size", () => { + function verifyWithMaxCacheLimit(limitHit: boolean, useSlashRootAsSomeNotRootFolderInUserDirectory: boolean) { + const rootFolder = useSlashRootAsSomeNotRootFolderInUserDirectory ? "/user/username/rootfolder/otherfolder/" : "/"; + const file1: File = { + path: rootFolder + "a/b/project/file1.ts", + content: 'import a from "file2"' + }; + const file2: File = { + path: rootFolder + "a/b/node_modules/file2.d.ts", + content: "export class a { }" + }; + const file3: File = { + path: rootFolder + "a/b/project/file3.ts", + content: "export class c { }" + }; + const configFile: File = { + path: rootFolder + "a/b/project/tsconfig.json", + content: JSON.stringify({ compilerOptions: { typeRoots: [] } }) + }; + + const projectFiles = [file1, file3, libFile, configFile]; + const openFiles = [file1.path]; + const watchedRecursiveDirectories = useSlashRootAsSomeNotRootFolderInUserDirectory ? + // Folders of node_modules lookup not in changedRoot + ["a/b/project", "a/b/project/node_modules", "a/b/node_modules", "a/node_modules", "node_modules"].map(v => rootFolder + v) : + // Folder of tsconfig + ["/a/b/project", "/a/b/project/node_modules"]; + const host = createServerHost(projectFiles); + const { session, verifyInitialOpen, verifyProjectsUpdatedInBackgroundEventHandler } = createSession(host); + const projectService = session.getProjectService(); + verifyInitialOpen(file1); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const project = projectService.configuredProjects.get(configFile.path)!; + verifyProject(); + if (limitHit) { + (project as ResolutionCacheHost).maxNumberOfFilesToIterateForInvalidation = 1; + } + + file3.content += "export class d {}"; + host.reloadFS(projectFiles); + host.checkTimeoutQueueLengthAndRun(2); + + // Since this is first event + verifyProject(); + verifyProjectsUpdatedInBackgroundEventHandler([{ + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles + } + }]); + + projectFiles.push(file2); + host.reloadFS(projectFiles); + host.runQueuedTimeoutCallbacks(); + if (useSlashRootAsSomeNotRootFolderInUserDirectory) { + watchedRecursiveDirectories.length = 3; + } + else { + // file2 addition wont be detected + projectFiles.pop(); + assert.isTrue(host.fileExists(file2.path)); + } + verifyProject(); + + verifyProjectsUpdatedInBackgroundEventHandler(useSlashRootAsSomeNotRootFolderInUserDirectory ? [{ + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles + } + }] : []); + + function verifyProject() { + checkProjectActualFiles(project, map(projectFiles, file => file.path)); + checkWatchedDirectories(host, [], /*recursive*/ false); + checkWatchedDirectories(host, watchedRecursiveDirectories, /*recursive*/ true); + } + } + + it("limit not hit and project is not at root level", () => { + verifyWithMaxCacheLimit(/*limitHit*/ false, /*useSlashRootAsSomeNotRootFolderInUserDirectory*/ true); + }); + + it("limit hit and project is not at root level", () => { + verifyWithMaxCacheLimit(/*limitHit*/ true, /*useSlashRootAsSomeNotRootFolderInUserDirectory*/ true); + }); + + it("limit not hit and project is at root level", () => { + verifyWithMaxCacheLimit(/*limitHit*/ false, /*useSlashRootAsSomeNotRootFolderInUserDirectory*/ false); + }); + + it("limit hit and project is at root level", () => { + verifyWithMaxCacheLimit(/*limitHit*/ true, /*useSlashRootAsSomeNotRootFolderInUserDirectory*/ false); + }); + }); + } + + describe("when event handler is set in the session", () => { + verifyProjectsUpdatedInBackgroundEvent(createSessionWithProjectChangedEventHandler); + + function createSessionWithProjectChangedEventHandler(host: TestServerHost): ProjectsUpdatedInBackgroundEventVerifier { + const { session, events: projectChangedEvents } = createSessionWithEventTracking(host, server.ProjectsUpdatedInBackgroundEvent); + return { + session, + verifyProjectsUpdatedInBackgroundEventHandler, + verifyInitialOpen: createVerifyInitialOpen(session, verifyProjectsUpdatedInBackgroundEventHandler) + }; + + function eventToString(event: server.ProjectsUpdatedInBackgroundEvent) { + return JSON.stringify(event && { eventName: event.eventName, data: event.data }); + } + + function eventsToString(events: ReadonlyArray) { + return "[" + map(events, eventToString).join(",") + "]"; + } + + function verifyProjectsUpdatedInBackgroundEventHandler(expectedEvents: ReadonlyArray) { + assert.equal(projectChangedEvents.length, expectedEvents.length, `Incorrect number of events Actual: ${eventsToString(projectChangedEvents)} Expected: ${eventsToString(expectedEvents)}`); + forEach(projectChangedEvents, (actualEvent, i) => { + const expectedEvent = expectedEvents[i]; + assert.strictEqual(actualEvent.eventName, expectedEvent.eventName); + verifyFiles("openFiles", actualEvent.data.openFiles, expectedEvent.data.openFiles); + }); + + // Verified the events, reset them + projectChangedEvents.length = 0; + } + } + }); + + describe("when event handler is not set but session is created with canUseEvents = true", () => { + describe("without noGetErrOnBackgroundUpdate, diagnostics for open files are queued", () => { + verifyProjectsUpdatedInBackgroundEvent(createSessionThatUsesEvents); + }); + + describe("with noGetErrOnBackgroundUpdate, diagnostics for open file are not queued", () => { + verifyProjectsUpdatedInBackgroundEvent(host => createSessionThatUsesEvents(host, /*noGetErrOnBackgroundUpdate*/ true)); + }); + + + function createSessionThatUsesEvents(host: TestServerHost, noGetErrOnBackgroundUpdate?: boolean): ProjectsUpdatedInBackgroundEventVerifier { + const { session, getEvents, clearEvents } = createSessionWithDefaultEventHandler(host, server.ProjectsUpdatedInBackgroundEvent, { noGetErrOnBackgroundUpdate }); + + return { + session, + verifyProjectsUpdatedInBackgroundEventHandler, + verifyInitialOpen: createVerifyInitialOpen(session, verifyProjectsUpdatedInBackgroundEventHandler) + }; + + function verifyProjectsUpdatedInBackgroundEventHandler(expected: ReadonlyArray) { + const expectedEvents: protocol.ProjectsUpdatedInBackgroundEventBody[] = map(expected, e => { + return { + openFiles: e.data.openFiles + }; + }); + const events = getEvents(); + assert.equal(events.length, expectedEvents.length, `Incorrect number of events Actual: ${map(events, e => e.body)} Expected: ${expectedEvents}`); + forEach(events, (actualEvent, i) => { + const expectedEvent = expectedEvents[i]; + verifyFiles("openFiles", actualEvent.body.openFiles, expectedEvent.openFiles); + }); + + // Verified the events, reset them + clearEvents(); + + if (events.length) { + host.checkTimeoutQueueLength(noGetErrOnBackgroundUpdate ? 0 : 1); // Error checking queued only if not noGetErrOnBackgroundUpdate + } + } + } + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/events/surveyReady.ts b/src/testRunner/unittests/tsserver/events/surveyReady.ts new file mode 100644 index 00000000000..b04746800d0 --- /dev/null +++ b/src/testRunner/unittests/tsserver/events/surveyReady.ts @@ -0,0 +1,111 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: events:: SurveyReady", () => { + function createSessionWithEventHandler(host: TestServerHost) { + const { session, events: surveyEvents } = createSessionWithEventTracking(host, server.SurveyReady); + + return { session, verifySurveyReadyEvent }; + + function verifySurveyReadyEvent(numberOfEvents: number) { + assert.equal(surveyEvents.length, numberOfEvents); + const expectedEvents = numberOfEvents === 0 ? [] : [{ + eventName: server.SurveyReady, + data: { surveyId: "checkJs" } + }]; + assert.deepEqual(surveyEvents, expectedEvents); + } + } + + it("doesn't log an event when checkJs isn't set", () => { + const projectRoot = "/user/username/projects/project"; + const file: File = { + path: `${projectRoot}/src/file.ts`, + content: "export var y = 10;" + }; + const tsconfig: File = { + path: `${projectRoot}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: {} }), + }; + const host = createServerHost([file, tsconfig]); + const { session, verifySurveyReadyEvent } = createSessionWithEventHandler(host); + const service = session.getProjectService(); + openFilesForSession([file], session); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const project = service.configuredProjects.get(tsconfig.path)!; + checkProjectActualFiles(project, [file.path, tsconfig.path]); + + verifySurveyReadyEvent(0); + }); + + it("logs an event when checkJs is set", () => { + const projectRoot = "/user/username/projects/project"; + const file: File = { + path: `${projectRoot}/src/file.ts`, + content: "export var y = 10;" + }; + const tsconfig: File = { + path: `${projectRoot}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { checkJs: true } }), + }; + const host = createServerHost([file, tsconfig]); + const { session, verifySurveyReadyEvent } = createSessionWithEventHandler(host); + openFilesForSession([file], session); + + verifySurveyReadyEvent(1); + }); + + it("logs an event when checkJs is set, only the first time", () => { + const projectRoot = "/user/username/projects/project"; + const file: File = { + path: `${projectRoot}/src/file.ts`, + content: "export var y = 10;" + }; + const rando: File = { + path: `/rando/calrissian.ts`, + content: "export function f() { }" + }; + const tsconfig: File = { + path: `${projectRoot}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { checkJs: true } }), + }; + const host = createServerHost([file, tsconfig]); + const { session, verifySurveyReadyEvent } = createSessionWithEventHandler(host); + openFilesForSession([file], session); + + verifySurveyReadyEvent(1); + + closeFilesForSession([file], session); + openFilesForSession([rando], session); + openFilesForSession([file], session); + + verifySurveyReadyEvent(1); + }); + + it("logs an event when checkJs is set after closing and reopening", () => { + const projectRoot = "/user/username/projects/project"; + const file: File = { + path: `${projectRoot}/src/file.ts`, + content: "export var y = 10;" + }; + const rando: File = { + path: `/rando/calrissian.ts`, + content: "export function f() { }" + }; + const tsconfig: File = { + path: `${projectRoot}/tsconfig.json`, + content: JSON.stringify({}), + }; + const host = createServerHost([file, tsconfig]); + const { session, verifySurveyReadyEvent } = createSessionWithEventHandler(host); + openFilesForSession([file], session); + + verifySurveyReadyEvent(0); + + closeFilesForSession([file], session); + openFilesForSession([rando], session); + host.writeFile(tsconfig.path, JSON.stringify({ compilerOptions: { checkJs: true } })); + openFilesForSession([file], session); + + verifySurveyReadyEvent(1); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/externalProjects.ts b/src/testRunner/unittests/tsserver/externalProjects.ts new file mode 100644 index 00000000000..2055141538a --- /dev/null +++ b/src/testRunner/unittests/tsserver/externalProjects.ts @@ -0,0 +1,822 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: ExternalProjects", () => { + describe("can handle tsconfig file name with difference casing", () => { + function verifyConfigFileCasing(lazyConfiguredProjectsFromExternalProject: boolean) { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1" + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ + include: [] + }) + }; + + const host = createServerHost([f1, config], { useCaseSensitiveFileNames: false }); + const service = createProjectService(host); + service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } }); + const upperCaseConfigFilePath = combinePaths(getDirectoryPath(config.path).toUpperCase(), getBaseFileName(config.path)); + service.openExternalProject({ + projectFileName: "/a/b/project.csproj", + rootFiles: toExternalFiles([f1.path, upperCaseConfigFilePath]), + options: {} + }); + service.checkNumberOfProjects({ configuredProjects: 1 }); + const project = service.configuredProjects.get(config.path)!; + if (lazyConfiguredProjectsFromExternalProject) { + assert.equal(project.pendingReload, ConfigFileProgramReloadLevel.Full); // External project referenced configured project pending to be reloaded + checkProjectActualFiles(project, emptyArray); + } + else { + assert.equal(project.pendingReload, ConfigFileProgramReloadLevel.None); // External project referenced configured project loaded + checkProjectActualFiles(project, [upperCaseConfigFilePath]); + } + + service.openClientFile(f1.path); + service.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: 1 }); + + assert.equal(project.pendingReload, ConfigFileProgramReloadLevel.None); // External project referenced configured project is updated + checkProjectActualFiles(project, [upperCaseConfigFilePath]); + checkProjectActualFiles(service.inferredProjects[0], [f1.path]); + } + + it("when lazyConfiguredProjectsFromExternalProject not set", () => { + verifyConfigFileCasing(/*lazyConfiguredProjectsFromExternalProject*/ false); + }); + + it("when lazyConfiguredProjectsFromExternalProject is set", () => { + verifyConfigFileCasing(/*lazyConfiguredProjectsFromExternalProject*/ true); + }); + }); + + it("remove not-listed external projects", () => { + const f1 = { + path: "/a/app.ts", + content: "let x = 1" + }; + const f2 = { + path: "/b/app.ts", + content: "let x = 1" + }; + const f3 = { + path: "/c/app.ts", + content: "let x = 1" + }; + const makeProject = (f: File) => ({ projectFileName: f.path + ".csproj", rootFiles: [toExternalFile(f.path)], options: {} }); + const p1 = makeProject(f1); + const p2 = makeProject(f2); + const p3 = makeProject(f3); + + const host = createServerHost([f1, f2, f3]); + const session = createSession(host); + + session.executeCommand({ + seq: 1, + type: "request", + command: "openExternalProjects", + arguments: { projects: [p1, p2] } + }); + + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { externalProjects: 2 }); + assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName); + assert.equal(projectService.externalProjects[1].getProjectName(), p2.projectFileName); + + session.executeCommand({ + seq: 2, + type: "request", + command: "openExternalProjects", + arguments: { projects: [p1, p3] } + }); + checkNumberOfProjects(projectService, { externalProjects: 2 }); + assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName); + assert.equal(projectService.externalProjects[1].getProjectName(), p3.projectFileName); + + session.executeCommand({ + seq: 3, + type: "request", + command: "openExternalProjects", + arguments: { projects: [] } + }); + checkNumberOfProjects(projectService, { externalProjects: 0 }); + + session.executeCommand({ + seq: 3, + type: "request", + command: "openExternalProjects", + arguments: { projects: [p2] } + }); + assert.equal(projectService.externalProjects[0].getProjectName(), p2.projectFileName); + }); + + it("should not close external project with no open files", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x =1;" + }; + const file2 = { + path: "/a/b/f2.ts", + content: "let y =1;" + }; + const externalProjectName = "externalproject"; + const host = createServerHost([file1, file2]); + const projectService = createProjectService(host); + projectService.openExternalProject({ + rootFiles: toExternalFiles([file1.path, file2.path]), + options: {}, + projectFileName: externalProjectName + }); + + checkNumberOfExternalProjects(projectService, 1); + checkNumberOfInferredProjects(projectService, 0); + + // open client file - should not lead to creation of inferred project + projectService.openClientFile(file1.path, file1.content); + checkNumberOfExternalProjects(projectService, 1); + checkNumberOfInferredProjects(projectService, 0); + + // close client file - external project should still exists + projectService.closeClientFile(file1.path); + checkNumberOfExternalProjects(projectService, 1); + checkNumberOfInferredProjects(projectService, 0); + + projectService.closeExternalProject(externalProjectName); + checkNumberOfExternalProjects(projectService, 0); + checkNumberOfInferredProjects(projectService, 0); + }); + + it("external project for dynamic file", () => { + const externalProjectName = "^ScriptDocument1 file1.ts"; + const externalFiles = toExternalFiles(["^ScriptDocument1 file1.ts"]); + const host = createServerHost([]); + const projectService = createProjectService(host); + projectService.openExternalProject({ + rootFiles: externalFiles, + options: {}, + projectFileName: externalProjectName + }); + + checkNumberOfExternalProjects(projectService, 1); + checkNumberOfInferredProjects(projectService, 0); + + externalFiles[0].content = "let x =1;"; + projectService.applyChangesInOpenFiles(externalFiles, [], []); + }); + + it("external project that included config files", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x =1;" + }; + const config1 = { + path: "/a/b/tsconfig.json", + content: JSON.stringify( + { + compilerOptions: {}, + files: ["f1.ts"] + } + ) + }; + const file2 = { + path: "/a/c/f2.ts", + content: "let y =1;" + }; + const config2 = { + path: "/a/c/tsconfig.json", + content: JSON.stringify( + { + compilerOptions: {}, + files: ["f2.ts"] + } + ) + }; + const file3 = { + path: "/a/d/f3.ts", + content: "let z =1;" + }; + const externalProjectName = "externalproject"; + const host = createServerHost([file1, file2, file3, config1, config2]); + const projectService = createProjectService(host); + projectService.openExternalProject({ + rootFiles: toExternalFiles([config1.path, config2.path, file3.path]), + options: {}, + projectFileName: externalProjectName + }); + + checkNumberOfProjects(projectService, { configuredProjects: 2 }); + const proj1 = projectService.configuredProjects.get(config1.path); + const proj2 = projectService.configuredProjects.get(config2.path); + assert.isDefined(proj1); + assert.isDefined(proj2); + + // open client file - should not lead to creation of inferred project + projectService.openClientFile(file1.path, file1.content); + checkNumberOfProjects(projectService, { configuredProjects: 2 }); + assert.strictEqual(projectService.configuredProjects.get(config1.path), proj1); + assert.strictEqual(projectService.configuredProjects.get(config2.path), proj2); + + projectService.openClientFile(file3.path, file3.content); + checkNumberOfProjects(projectService, { configuredProjects: 2, inferredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(config1.path), proj1); + assert.strictEqual(projectService.configuredProjects.get(config2.path), proj2); + + projectService.closeExternalProject(externalProjectName); + // open file 'file1' from configured project keeps project alive + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(config1.path), proj1); + assert.isUndefined(projectService.configuredProjects.get(config2.path)); + + projectService.closeClientFile(file3.path); + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(config1.path), proj1); + assert.isUndefined(projectService.configuredProjects.get(config2.path)); + assert.isTrue(projectService.inferredProjects[0].isOrphan()); + + projectService.closeClientFile(file1.path); + checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(config1.path), proj1); + assert.isUndefined(projectService.configuredProjects.get(config2.path)); + assert.isTrue(projectService.inferredProjects[0].isOrphan()); + + projectService.openClientFile(file2.path, file2.content); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + assert.isUndefined(projectService.configuredProjects.get(config1.path)); + assert.isDefined(projectService.configuredProjects.get(config2.path)); + }); + + it("external project with included config file opened after configured project", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: {} }) + }; + const externalProjectName = "externalproject"; + const host = createServerHost([file1, configFile]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + + projectService.openExternalProject({ + rootFiles: toExternalFiles([configFile.path]), + options: {}, + projectFileName: externalProjectName + }); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + + projectService.closeClientFile(file1.path); + // configured project is alive since it is opened as part of external project + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + + projectService.closeExternalProject(externalProjectName); + checkNumberOfProjects(projectService, { configuredProjects: 0 }); + }); + + it("external project with included config file opened after configured project and then closed", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1" + }; + const file2 = { + path: "/a/f2.ts", + content: "let x = 1" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: {} }) + }; + const externalProjectName = "externalproject"; + const host = createServerHost([file1, file2, libFile, configFile]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const project = projectService.configuredProjects.get(configFile.path); + + projectService.openExternalProject({ + rootFiles: toExternalFiles([configFile.path]), + options: {}, + projectFileName: externalProjectName + }); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(configFile.path), project); + + projectService.closeExternalProject(externalProjectName); + // configured project is alive since file is still open + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(configFile.path), project); + + projectService.closeClientFile(file1.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(configFile.path), project); + + projectService.openClientFile(file2.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + assert.isUndefined(projectService.configuredProjects.get(configFile.path)); + }); + + it("can correctly update external project when set of root files has changed", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1" + }; + const file2 = { + path: "/a/b/f2.ts", + content: "let y = 1" + }; + const host = createServerHost([file1, file2]); + const projectService = createProjectService(host); + + projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles([file1.path]) }); + checkNumberOfProjects(projectService, { externalProjects: 1 }); + checkProjectActualFiles(projectService.externalProjects[0], [file1.path]); + + projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles([file1.path, file2.path]) }); + checkNumberOfProjects(projectService, { externalProjects: 1 }); + checkProjectRootFiles(projectService.externalProjects[0], [file1.path, file2.path]); + }); + + it("can update external project when set of root files was not changed", () => { + const file1 = { + path: "/a/b/f1.ts", + content: `export * from "m"` + }; + const file2 = { + path: "/a/b/f2.ts", + content: "export let y = 1" + }; + const file3 = { + path: "/a/m.ts", + content: "export let y = 1" + }; + + const host = createServerHost([file1, file2, file3]); + const projectService = createProjectService(host); + + projectService.openExternalProject({ projectFileName: "project", options: { moduleResolution: ModuleResolutionKind.NodeJs }, rootFiles: toExternalFiles([file1.path, file2.path]) }); + checkNumberOfProjects(projectService, { externalProjects: 1 }); + checkProjectRootFiles(projectService.externalProjects[0], [file1.path, file2.path]); + checkProjectActualFiles(projectService.externalProjects[0], [file1.path, file2.path]); + + projectService.openExternalProject({ projectFileName: "project", options: { moduleResolution: ModuleResolutionKind.Classic }, rootFiles: toExternalFiles([file1.path, file2.path]) }); + checkNumberOfProjects(projectService, { externalProjects: 1 }); + checkProjectRootFiles(projectService.externalProjects[0], [file1.path, file2.path]); + checkProjectActualFiles(projectService.externalProjects[0], [file1.path, file2.path, file3.path]); + }); + + it("language service disabled state is updated in external projects", () => { + const f1 = { + path: "/a/app.js", + content: "var x = 1" + }; + const f2 = { + path: "/a/largefile.js", + content: "" + }; + const host = createServerHost([f1, f2]); + const originalGetFileSize = host.getFileSize; + host.getFileSize = (filePath: string) => + filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + + const service = createProjectService(host); + const projectFileName = "/a/proj.csproj"; + + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([f1.path, f2.path]), + options: {} + }); + service.checkNumberOfProjects({ externalProjects: 1 }); + assert.isFalse(service.externalProjects[0].languageServiceEnabled, "language service should be disabled - 1"); + + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([f1.path]), + options: {} + }); + service.checkNumberOfProjects({ externalProjects: 1 }); + assert.isTrue(service.externalProjects[0].languageServiceEnabled, "language service should be enabled"); + + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([f1.path, f2.path]), + options: {} + }); + service.checkNumberOfProjects({ externalProjects: 1 }); + assert.isFalse(service.externalProjects[0].languageServiceEnabled, "language service should be disabled - 2"); + }); + + describe("deleting config file opened from the external project works", () => { + function verifyDeletingConfigFile(lazyConfiguredProjectsFromExternalProject: boolean) { + const site = { + path: "/user/someuser/project/js/site.js", + content: "" + }; + const configFile = { + path: "/user/someuser/project/tsconfig.json", + content: "{}" + }; + const projectFileName = "/user/someuser/project/WebApplication6.csproj"; + const host = createServerHost([libFile, site, configFile]); + const projectService = createProjectService(host); + projectService.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } }); + + const externalProject: protocol.ExternalProject = { + projectFileName, + rootFiles: [toExternalFile(site.path), toExternalFile(configFile.path)], + options: { allowJs: false }, + typeAcquisition: { include: [] } + }; + + projectService.openExternalProjects([externalProject]); + + let knownProjects = projectService.synchronizeProjectList([]); + checkNumberOfProjects(projectService, { configuredProjects: 1, externalProjects: 0, inferredProjects: 0 }); + + const configProject = configuredProjectAt(projectService, 0); + checkProjectActualFiles(configProject, lazyConfiguredProjectsFromExternalProject ? + emptyArray : // Since no files opened from this project, its not loaded + [configFile.path]); + + host.reloadFS([libFile, site]); + host.checkTimeoutQueueLengthAndRun(1); + + knownProjects = projectService.synchronizeProjectList(map(knownProjects, proj => proj.info!)); // TODO: GH#18217 GH#20039 + checkNumberOfProjects(projectService, { configuredProjects: 0, externalProjects: 0, inferredProjects: 0 }); + + externalProject.rootFiles.length = 1; + projectService.openExternalProjects([externalProject]); + + checkNumberOfProjects(projectService, { configuredProjects: 0, externalProjects: 1, inferredProjects: 0 }); + checkProjectActualFiles(projectService.externalProjects[0], [site.path, libFile.path]); + } + it("when lazyConfiguredProjectsFromExternalProject not set", () => { + verifyDeletingConfigFile(/*lazyConfiguredProjectsFromExternalProject*/ false); + }); + it("when lazyConfiguredProjectsFromExternalProject is set", () => { + verifyDeletingConfigFile(/*lazyConfiguredProjectsFromExternalProject*/ true); + }); + }); + + describe("correctly handling add/remove tsconfig - 1", () => { + function verifyAddRemoveConfig(lazyConfiguredProjectsFromExternalProject: boolean) { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1;" + }; + const f2 = { + path: "/a/b/lib.ts", + content: "" + }; + const tsconfig = { + path: "/a/b/tsconfig.json", + content: "" + }; + const host = createServerHost([f1, f2]); + const projectService = createProjectService(host); + projectService.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } }); + + // open external project + const projectName = "/a/b/proj1"; + projectService.openExternalProject({ + projectFileName: projectName, + rootFiles: toExternalFiles([f1.path, f2.path]), + options: {} + }); + projectService.openClientFile(f1.path); + projectService.checkNumberOfProjects({ externalProjects: 1 }); + checkProjectActualFiles(projectService.externalProjects[0], [f1.path, f2.path]); + + // rename lib.ts to tsconfig.json + host.reloadFS([f1, tsconfig]); + projectService.openExternalProject({ + projectFileName: projectName, + rootFiles: toExternalFiles([f1.path, tsconfig.path]), + options: {} + }); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + if (lazyConfiguredProjectsFromExternalProject) { + checkProjectActualFiles(configuredProjectAt(projectService, 0), emptyArray); // Configured project created but not loaded till actually needed + projectService.ensureInferredProjectsUpToDate_TestOnly(); + } + checkProjectActualFiles(configuredProjectAt(projectService, 0), [f1.path, tsconfig.path]); + + // rename tsconfig.json back to lib.ts + host.reloadFS([f1, f2]); + projectService.openExternalProject({ + projectFileName: projectName, + rootFiles: toExternalFiles([f1.path, f2.path]), + options: {} + }); + + projectService.checkNumberOfProjects({ externalProjects: 1 }); + checkProjectActualFiles(projectService.externalProjects[0], [f1.path, f2.path]); + } + it("when lazyConfiguredProjectsFromExternalProject not set", () => { + verifyAddRemoveConfig(/*lazyConfiguredProjectsFromExternalProject*/ false); + }); + it("when lazyConfiguredProjectsFromExternalProject is set", () => { + verifyAddRemoveConfig(/*lazyConfiguredProjectsFromExternalProject*/ true); + }); + }); + + describe("correctly handling add/remove tsconfig - 2", () => { + function verifyAddRemoveConfig(lazyConfiguredProjectsFromExternalProject: boolean) { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1;" + }; + const cLib = { + path: "/a/b/c/lib.ts", + content: "" + }; + const cTsconfig = { + path: "/a/b/c/tsconfig.json", + content: "{}" + }; + const dLib = { + path: "/a/b/d/lib.ts", + content: "" + }; + const dTsconfig = { + path: "/a/b/d/tsconfig.json", + content: "{}" + }; + const host = createServerHost([f1, cLib, cTsconfig, dLib, dTsconfig]); + const projectService = createProjectService(host); + projectService.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } }); + + // open external project + const projectName = "/a/b/proj1"; + projectService.openExternalProject({ + projectFileName: projectName, + rootFiles: toExternalFiles([f1.path]), + options: {} + }); + + projectService.checkNumberOfProjects({ externalProjects: 1 }); + checkProjectActualFiles(projectService.externalProjects[0], [f1.path]); + + // add two config file as root files + projectService.openExternalProject({ + projectFileName: projectName, + rootFiles: toExternalFiles([f1.path, cTsconfig.path, dTsconfig.path]), + options: {} + }); + projectService.checkNumberOfProjects({ configuredProjects: 2 }); + if (lazyConfiguredProjectsFromExternalProject) { + checkProjectActualFiles(configuredProjectAt(projectService, 0), emptyArray); // Configured project created but not loaded till actually needed + checkProjectActualFiles(configuredProjectAt(projectService, 1), emptyArray); // Configured project created but not loaded till actually needed + projectService.ensureInferredProjectsUpToDate_TestOnly(); + } + checkProjectActualFiles(configuredProjectAt(projectService, 0), [cLib.path, cTsconfig.path]); + checkProjectActualFiles(configuredProjectAt(projectService, 1), [dLib.path, dTsconfig.path]); + + // remove one config file + projectService.openExternalProject({ + projectFileName: projectName, + rootFiles: toExternalFiles([f1.path, dTsconfig.path]), + options: {} + }); + + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [dLib.path, dTsconfig.path]); + + // remove second config file + projectService.openExternalProject({ + projectFileName: projectName, + rootFiles: toExternalFiles([f1.path]), + options: {} + }); + + projectService.checkNumberOfProjects({ externalProjects: 1 }); + checkProjectActualFiles(projectService.externalProjects[0], [f1.path]); + + // open two config files + // add two config file as root files + projectService.openExternalProject({ + projectFileName: projectName, + rootFiles: toExternalFiles([f1.path, cTsconfig.path, dTsconfig.path]), + options: {} + }); + projectService.checkNumberOfProjects({ configuredProjects: 2 }); + if (lazyConfiguredProjectsFromExternalProject) { + checkProjectActualFiles(configuredProjectAt(projectService, 0), emptyArray); // Configured project created but not loaded till actually needed + checkProjectActualFiles(configuredProjectAt(projectService, 1), emptyArray); // Configured project created but not loaded till actually needed + projectService.ensureInferredProjectsUpToDate_TestOnly(); + } + checkProjectActualFiles(configuredProjectAt(projectService, 0), [cLib.path, cTsconfig.path]); + checkProjectActualFiles(configuredProjectAt(projectService, 1), [dLib.path, dTsconfig.path]); + + // close all projects - no projects should be opened + projectService.closeExternalProject(projectName); + projectService.checkNumberOfProjects({}); + } + + it("when lazyConfiguredProjectsFromExternalProject not set", () => { + verifyAddRemoveConfig(/*lazyConfiguredProjectsFromExternalProject*/ false); + }); + it("when lazyConfiguredProjectsFromExternalProject is set", () => { + verifyAddRemoveConfig(/*lazyConfiguredProjectsFromExternalProject*/ true); + }); + }); + + it("correctly handles changes in lib section of config file", () => { + const libES5 = { + path: "/compiler/lib.es5.d.ts", + content: "declare const eval: any" + }; + const libES2015Promise = { + path: "/compiler/lib.es2015.promise.d.ts", + content: "declare class Promise {}" + }; + const app = { + path: "/src/app.ts", + content: "var x: Promise;" + }; + const config1 = { + path: "/src/tsconfig.json", + content: JSON.stringify( + { + compilerOptions: { + module: "commonjs", + target: "es5", + noImplicitAny: true, + sourceMap: false, + lib: [ + "es5" + ] + } + }) + }; + const config2 = { + path: config1.path, + content: JSON.stringify( + { + compilerOptions: { + module: "commonjs", + target: "es5", + noImplicitAny: true, + sourceMap: false, + lib: [ + "es5", + "es2015.promise" + ] + } + }) + }; + const host = createServerHost([libES5, libES2015Promise, app, config1], { executingFilePath: "/compiler/tsc.js" }); + const projectService = createProjectService(host); + projectService.openClientFile(app.path); + + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [libES5.path, app.path, config1.path]); + + host.reloadFS([libES5, libES2015Promise, app, config2]); + host.checkTimeoutQueueLengthAndRun(2); + + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [libES5.path, libES2015Promise.path, app.path, config2.path]); + }); + + it("should handle non-existing directories in config file", () => { + const f = { + path: "/a/src/app.ts", + content: "let x = 1;" + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions: {}, + include: [ + "src/**/*", + "notexistingfolder/*" + ] + }) + }; + const host = createServerHost([f, config]); + const projectService = createProjectService(host); + projectService.openClientFile(f.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + const project = projectService.configuredProjects.get(config.path)!; + assert.isTrue(project.hasOpenRef()); // f + + projectService.closeClientFile(f.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(config.path), project); + assert.isFalse(project.hasOpenRef()); // No files + assert.isFalse(project.isClosed()); + + projectService.openClientFile(f.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + assert.strictEqual(projectService.configuredProjects.get(config.path), project); + assert.isTrue(project.hasOpenRef()); // f + assert.isFalse(project.isClosed()); + }); + + it("handles loads existing configured projects of external projects when lazyConfiguredProjectsFromExternalProject is disabled", () => { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1" + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({}) + }; + const projectFileName = "/a/b/project.csproj"; + const host = createServerHost([f1, config]); + const service = createProjectService(host); + service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject: true } }); + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([f1.path, config.path]), + options: {} + }); + service.checkNumberOfProjects({ configuredProjects: 1 }); + const project = service.configuredProjects.get(config.path)!; + assert.equal(project.pendingReload, ConfigFileProgramReloadLevel.Full); // External project referenced configured project pending to be reloaded + checkProjectActualFiles(project, emptyArray); + + service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject: false } }); + assert.equal(project.pendingReload, ConfigFileProgramReloadLevel.None); // External project referenced configured project loaded + checkProjectActualFiles(project, [config.path, f1.path]); + + service.closeExternalProject(projectFileName); + service.checkNumberOfProjects({}); + + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([f1.path, config.path]), + options: {} + }); + service.checkNumberOfProjects({ configuredProjects: 1 }); + const project2 = service.configuredProjects.get(config.path)!; + assert.equal(project2.pendingReload, ConfigFileProgramReloadLevel.None); // External project referenced configured project loaded + checkProjectActualFiles(project2, [config.path, f1.path]); + }); + + it("handles creation of external project with jsconfig before jsconfig creation watcher is invoked", () => { + const projectLocation = `/user/username/projects/WebApplication36/WebApplication36`; + const projectFileName = `${projectLocation}/WebApplication36.csproj`; + const tsconfig: File = { + path: `${projectLocation}/tsconfig.json`, + content: "{}" + }; + const files = [libFile, tsconfig]; + const host = createServerHost(files); + const service = createProjectService(host); + + // Create external project + service.openExternalProjects([{ + projectFileName, + rootFiles: [{ fileName: tsconfig.path }], + options: { allowJs: false } + }]); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const configProject = service.configuredProjects.get(tsconfig.path.toLowerCase())!; + checkProjectActualFiles(configProject, [tsconfig.path]); + + // write js file, open external project and open it for edit + const jsFilePath = `${projectLocation}/javascript.js`; + host.writeFile(jsFilePath, ""); + service.openExternalProjects([{ + projectFileName, + rootFiles: [{ fileName: tsconfig.path }, { fileName: jsFilePath }], + options: { allowJs: false } + }]); + service.applyChangesInOpenFiles([ + { fileName: jsFilePath, scriptKind: ScriptKind.JS, content: "" } + ], /*changedFiles*/ undefined, /*closedFiles*/ undefined); + checkNumberOfProjects(service, { configuredProjects: 1, inferredProjects: 1 }); + checkProjectActualFiles(configProject, [tsconfig.path]); + const inferredProject = service.inferredProjects[0]; + checkProjectActualFiles(inferredProject, [libFile.path, jsFilePath]); + + // write jsconfig file + const jsConfig: File = { + path: `${projectLocation}/jsconfig.json`, + content: "{}" + }; + // Dont invoke file creation watchers as the repro suggests + host.ensureFileOrFolder(jsConfig, /*ignoreWatchInvokedWithTriggerAsFileCreate*/ true); + + // Open external project + service.openExternalProjects([{ + projectFileName, + rootFiles: [{ fileName: jsConfig.path }, { fileName: tsconfig.path }, { fileName: jsFilePath }], + options: { allowJs: false } + }]); + checkNumberOfProjects(service, { configuredProjects: 2, inferredProjects: 1 }); + checkProjectActualFiles(configProject, [tsconfig.path]); + assert.isTrue(inferredProject.isOrphan()); + const jsConfigProject = service.configuredProjects.get(jsConfig.path.toLowerCase())!; + checkProjectActualFiles(jsConfigProject, [jsConfig.path, jsFilePath, libFile.path]); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts b/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts new file mode 100644 index 00000000000..bb1be544a2c --- /dev/null +++ b/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts @@ -0,0 +1,45 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: forceConsistentCasingInFileNames", () => { + it("works when extends is specified with a case insensitive file system", () => { + const rootPath = "/Users/username/dev/project"; + const file1: File = { + path: `${rootPath}/index.ts`, + content: 'import {x} from "file2";', + }; + const file2: File = { + path: `${rootPath}/file2.js`, + content: "", + }; + const file2Dts: File = { + path: `${rootPath}/types/file2/index.d.ts`, + content: "export declare const x: string;", + }; + const tsconfigAll: File = { + path: `${rootPath}/tsconfig.all.json`, + content: JSON.stringify({ + compilerOptions: { + baseUrl: ".", + paths: { file2: ["./file2.js"] }, + typeRoots: ["./types"], + forceConsistentCasingInFileNames: true, + }, + }), + }; + const tsconfig: File = { + path: `${rootPath}/tsconfig.json`, + content: JSON.stringify({ extends: "./tsconfig.all.json" }), + }; + + const host = createServerHost([file1, file2, file2Dts, libFile, tsconfig, tsconfigAll], { useCaseSensitiveFileNames: false }); + const session = createSession(host); + + openFilesForSession([file1], session); + const projectService = session.getProjectService(); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + + const diagnostics = configuredProjectAt(projectService, 0).getLanguageService().getCompilerOptionsDiagnostics(); + assert.deepEqual(diagnostics, []); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/formatSettings.ts b/src/testRunner/unittests/tsserver/formatSettings.ts new file mode 100644 index 00000000000..2d09ed8a8a0 --- /dev/null +++ b/src/testRunner/unittests/tsserver/formatSettings.ts @@ -0,0 +1,39 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: format settings", () => { + it("can be set globally", () => { + const f1 = { + path: "/a/b/app.ts", + content: "let x;" + }; + const host = createServerHost([f1]); + const projectService = createProjectService(host); + projectService.openClientFile(f1.path); + + const defaultSettings = projectService.getFormatCodeOptions(f1.path as server.NormalizedPath); + + // set global settings + const newGlobalSettings1 = { ...defaultSettings, placeOpenBraceOnNewLineForControlBlocks: !defaultSettings.placeOpenBraceOnNewLineForControlBlocks }; + projectService.setHostConfiguration({ formatOptions: newGlobalSettings1 }); + + // get format options for file - should be equal to new global settings + const s1 = projectService.getFormatCodeOptions(server.toNormalizedPath(f1.path)); + assert.deepEqual(s1, newGlobalSettings1, "file settings should be the same with global settings"); + + // set per file format options + const newPerFileSettings = { ...defaultSettings, insertSpaceAfterCommaDelimiter: !defaultSettings.insertSpaceAfterCommaDelimiter }; + projectService.setHostConfiguration({ formatOptions: newPerFileSettings, file: f1.path }); + + // get format options for file - should be equal to new per-file settings + const s2 = projectService.getFormatCodeOptions(server.toNormalizedPath(f1.path)); + assert.deepEqual(s2, newPerFileSettings, "file settings should be the same with per-file settings"); + + // set new global settings - they should not affect ones that were set per-file + const newGlobalSettings2 = { ...defaultSettings, insertSpaceAfterSemicolonInForStatements: !defaultSettings.insertSpaceAfterSemicolonInForStatements }; + projectService.setHostConfiguration({ formatOptions: newGlobalSettings2 }); + + // get format options for file - should be equal to new per-file settings + const s3 = projectService.getFormatCodeOptions(server.toNormalizedPath(f1.path)); + assert.deepEqual(s3, newPerFileSettings, "file settings should still be the same with per-file settings"); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/getApplicableRefactors.ts b/src/testRunner/unittests/tsserver/getApplicableRefactors.ts new file mode 100644 index 00000000000..1f9576e1d63 --- /dev/null +++ b/src/testRunner/unittests/tsserver/getApplicableRefactors.ts @@ -0,0 +1,12 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: getApplicableRefactors", () => { + it("works when taking position", () => { + const aTs: File = { path: "/a.ts", content: "" }; + const session = createSession(createServerHost([aTs])); + openFilesForSession([aTs], session); + const response = executeSessionRequest( + session, protocol.CommandTypes.GetApplicableRefactors, { file: aTs.path, line: 1, offset: 1 }); + assert.deepEqual | undefined>(response, []); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/getEditsForFileRename.ts b/src/testRunner/unittests/tsserver/getEditsForFileRename.ts new file mode 100644 index 00000000000..2b28de7b121 --- /dev/null +++ b/src/testRunner/unittests/tsserver/getEditsForFileRename.ts @@ -0,0 +1,105 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: getEditsForFileRename", () => { + it("works for host implementing 'resolveModuleNames' and 'getResolvedModuleWithFailedLookupLocationsFromCache'", () => { + const userTs: File = { + path: "/user.ts", + content: 'import { x } from "./old";', + }; + const newTs: File = { + path: "/new.ts", + content: "export const x = 0;", + }; + const tsconfig: File = { + path: "/tsconfig.json", + content: "{}", + }; + + const host = createServerHost([userTs, newTs, tsconfig]); + const projectService = createProjectService(host); + projectService.openClientFile(userTs.path); + const project = projectService.configuredProjects.get(tsconfig.path)!; + + Debug.assert(!!project.resolveModuleNames); + + const edits = project.getLanguageService().getEditsForFileRename("/old.ts", "/new.ts", testFormatSettings, emptyOptions); + assert.deepEqual>(edits, [{ + fileName: "/user.ts", + textChanges: [{ + span: textSpanFromSubstring(userTs.content, "./old"), + newText: "./new", + }], + }]); + }); + + it("works with multiple projects", () => { + const aUserTs: File = { + path: "/a/user.ts", + content: 'import { x } from "./old";', + }; + const aOldTs: File = { + path: "/a/old.ts", + content: "export const x = 0;", + }; + const aTsconfig: File = { + path: "/a/tsconfig.json", + content: JSON.stringify({ files: ["./old.ts", "./user.ts"] }), + }; + const bUserTs: File = { + path: "/b/user.ts", + content: 'import { x } from "../a/old";', + }; + const bTsconfig: File = { + path: "/b/tsconfig.json", + content: "{}", + }; + + const host = createServerHost([aUserTs, aOldTs, aTsconfig, bUserTs, bTsconfig]); + const session = createSession(host); + openFilesForSession([aUserTs, bUserTs], session); + + const response = executeSessionRequest(session, CommandNames.GetEditsForFileRename, { + oldFilePath: aOldTs.path, + newFilePath: "/a/new.ts", + }); + assert.deepEqual>(response, [ + { + fileName: aTsconfig.path, + textChanges: [{ ...protocolTextSpanFromSubstring(aTsconfig.content, "./old.ts"), newText: "new.ts" }], + }, + { + fileName: aUserTs.path, + textChanges: [{ ...protocolTextSpanFromSubstring(aUserTs.content, "./old"), newText: "./new" }], + }, + { + fileName: bUserTs.path, + textChanges: [{ ...protocolTextSpanFromSubstring(bUserTs.content, "../a/old"), newText: "../a/new" }], + }, + ]); + }); + + it("works with file moved to inferred project", () => { + const aTs: File = { path: "/a.ts", content: 'import {} from "./b";' }; + const cTs: File = { path: "/c.ts", content: "export {};" }; + const tsconfig: File = { path: "/tsconfig.json", content: JSON.stringify({ files: ["./a.ts", "./b.ts"] }) }; + + const host = createServerHost([aTs, cTs, tsconfig]); + const session = createSession(host); + openFilesForSession([aTs, cTs], session); + + const response = executeSessionRequest(session, CommandNames.GetEditsForFileRename, { + oldFilePath: "/b.ts", + newFilePath: cTs.path, + }); + assert.deepEqual>(response, [ + { + fileName: "/tsconfig.json", + textChanges: [{ ...protocolTextSpanFromSubstring(tsconfig.content, "./b.ts"), newText: "c.ts" }], + }, + { + fileName: "/a.ts", + textChanges: [{ ...protocolTextSpanFromSubstring(aTs.content, "./b"), newText: "./c" }], + }, + ]); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/helpers.ts b/src/testRunner/unittests/tsserver/helpers.ts new file mode 100644 index 00000000000..3e79451cd11 --- /dev/null +++ b/src/testRunner/unittests/tsserver/helpers.ts @@ -0,0 +1,665 @@ +namespace ts.projectSystem { + export import TI = server.typingsInstaller; + export import protocol = server.protocol; + export import CommandNames = server.CommandNames; + + export import TestServerHost = TestFSWithWatch.TestServerHost; + export type File = TestFSWithWatch.File; + export type SymLink = TestFSWithWatch.SymLink; + export type Folder = TestFSWithWatch.Folder; + export import createServerHost = TestFSWithWatch.createServerHost; + export import checkArray = TestFSWithWatch.checkArray; + export import libFile = TestFSWithWatch.libFile; + export import checkWatchedFiles = TestFSWithWatch.checkWatchedFiles; + export import checkWatchedFilesDetailed = TestFSWithWatch.checkWatchedFilesDetailed; + export import checkWatchedDirectories = TestFSWithWatch.checkWatchedDirectories; + export import checkWatchedDirectoriesDetailed = TestFSWithWatch.checkWatchedDirectoriesDetailed; + + export import commonFile1 = tscWatch.commonFile1; + export import commonFile2 = tscWatch.commonFile2; + + const outputEventRegex = /Content\-Length: [\d]+\r\n\r\n/; + export function mapOutputToJson(s: string) { + return convertToObject( + parseJsonText("json.json", s.replace(outputEventRegex, "")), + [] + ); + } + + export const customTypesMap = { + path: "/typesMap.json", + content: `{ + "typesMap": { + "jquery": { + "match": "jquery(-(\\\\.?\\\\d+)+)?(\\\\.intellisense)?(\\\\.min)?\\\\.js$", + "types": ["jquery"] + }, + "quack": { + "match": "/duckquack-(\\\\d+)\\\\.min\\\\.js", + "types": ["duck-types"] + } + }, + "simpleMap": { + "Bacon": "baconjs", + "bliss": "blissfuljs", + "commander": "commander", + "cordova": "cordova", + "react": "react", + "lodash": "lodash" + } + }` + }; + + export interface PostExecAction { + readonly success: boolean; + readonly callback: TI.RequestCompletedAction; + } + + export const nullLogger: server.Logger = { + close: noop, + hasLevel: returnFalse, + loggingEnabled: returnFalse, + perftrc: noop, + info: noop, + msg: noop, + startGroup: noop, + endGroup: noop, + getLogFileName: () => undefined, + }; + + export function createHasErrorMessageLogger() { + let hasErrorMsg = false; + const { close, hasLevel, loggingEnabled, startGroup, endGroup, info, getLogFileName, perftrc } = nullLogger; + const logger: server.Logger = { + close, hasLevel, loggingEnabled, startGroup, endGroup, info, getLogFileName, perftrc, + msg: (s, type) => { + Debug.fail(`Error: ${s}, type: ${type}`); + hasErrorMsg = true; + } + }; + return { logger, hasErrorMsg: () => hasErrorMsg }; + } + + export function createLoggerWritingToConsole(): server.Logger { + const { close, startGroup, endGroup, getLogFileName } = nullLogger; + return { + close, + hasLevel: returnTrue, + loggingEnabled: returnTrue, + perftrc: s => console.log(s), + info: s => console.log(s), + msg: (s, type) => console.log(`${type}:: ${s}`), + startGroup, + endGroup, + getLogFileName + }; + } + + export class TestTypingsInstaller extends TI.TypingsInstaller implements server.ITypingsInstaller { + protected projectService!: server.ProjectService; + constructor( + readonly globalTypingsCacheLocation: string, + throttleLimit: number, + installTypingHost: server.ServerHost, + readonly typesRegistry = createMap>(), + log?: TI.Log) { + super(installTypingHost, globalTypingsCacheLocation, TestFSWithWatch.safeList.path, customTypesMap.path, throttleLimit, log); + } + + protected postExecActions: PostExecAction[] = []; + + isKnownTypesPackageName = notImplemented; + installPackage = notImplemented; + inspectValue = notImplemented; + + executePendingCommands() { + const actionsToRun = this.postExecActions; + this.postExecActions = []; + for (const action of actionsToRun) { + action.callback(action.success); + } + } + + checkPendingCommands(expectedCount: number) { + assert.equal(this.postExecActions.length, expectedCount, `Expected ${expectedCount} post install actions`); + } + + onProjectClosed = noop; + + attach(projectService: server.ProjectService) { + this.projectService = projectService; + } + + getInstallTypingHost() { + return this.installTypingHost; + } + + installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { + this.addPostExecAction("success", cb); + } + + sendResponse(response: server.SetTypings | server.InvalidateCachedTypings) { + this.projectService.updateTypingsForProject(response); + } + + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray) { + const request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, this.globalTypingsCacheLocation); + this.install(request); + } + + addPostExecAction(stdout: string | string[], cb: TI.RequestCompletedAction) { + const out = isString(stdout) ? stdout : createNpmPackageJsonString(stdout); + const action: PostExecAction = { + success: !!out, + callback: cb + }; + this.postExecActions.push(action); + } + } + + function createNpmPackageJsonString(installedTypings: string[]): string { + const dependencies: MapLike = {}; + for (const typing of installedTypings) { + dependencies[typing] = "1.0.0"; + } + return JSON.stringify({ dependencies }); + } + + export function createTypesRegistry(...list: string[]): Map> { + const versionMap = { + "latest": "1.3.0", + "ts2.0": "1.0.0", + "ts2.1": "1.0.0", + "ts2.2": "1.2.0", + "ts2.3": "1.3.0", + "ts2.4": "1.3.0", + "ts2.5": "1.3.0", + "ts2.6": "1.3.0", + "ts2.7": "1.3.0" + }; + const map = createMap>(); + for (const l of list) { + map.set(l, versionMap); + } + return map; + } + + export function toExternalFile(fileName: string): protocol.ExternalFile { + return { fileName }; + } + + export function toExternalFiles(fileNames: string[]) { + return map(fileNames, toExternalFile); + } + + export function fileStats(nonZeroStats: Partial): server.FileStats { + return { ts: 0, tsSize: 0, tsx: 0, tsxSize: 0, dts: 0, dtsSize: 0, js: 0, jsSize: 0, jsx: 0, jsxSize: 0, deferred: 0, deferredSize: 0, ...nonZeroStats }; + } + + export interface ConfigFileDiagnostic { + fileName: string | undefined; + start: number | undefined; + length: number | undefined; + messageText: string; + category: DiagnosticCategory; + code: number; + reportsUnnecessary?: {}; + source?: string; + relatedInformation?: DiagnosticRelatedInformation[]; + } + + export class TestServerEventManager { + private events: server.ProjectServiceEvent[] = []; + readonly session: TestSession; + readonly service: server.ProjectService; + readonly host: TestServerHost; + constructor(files: File[], suppressDiagnosticEvents?: boolean) { + this.host = createServerHost(files); + this.session = createSession(this.host, { + canUseEvents: true, + eventHandler: event => this.events.push(event), + suppressDiagnosticEvents, + }); + this.service = this.session.getProjectService(); + } + + getEvents(): ReadonlyArray { + const events = this.events; + this.events = []; + return events; + } + + getEvent(eventName: T["eventName"]): T["data"] { + let eventData: T["data"] | undefined; + filterMutate(this.events, e => { + if (e.eventName === eventName) { + if (eventData !== undefined) { + assert(false, "more than one event found"); + } + eventData = e.data; + return false; + } + return true; + }); + return Debug.assertDefined(eventData); + } + + hasZeroEvent(eventName: T["eventName"]) { + this.events.forEach(event => assert.notEqual(event.eventName, eventName)); + } + + checkSingleConfigFileDiagEvent(configFileName: string, triggerFile: string, errors: ReadonlyArray) { + const eventData = this.getEvent(server.ConfigFileDiagEvent); + assert.equal(eventData.configFileName, configFileName); + assert.equal(eventData.triggerFile, triggerFile); + const actual = eventData.diagnostics.map(({ file, messageText, ...rest }) => ({ fileName: file && file.fileName, messageText: isString(messageText) ? messageText : "", ...rest })); + if (errors) { + assert.deepEqual(actual, errors); + } + } + + assertProjectInfoTelemetryEvent(partial: Partial, configFile = "/tsconfig.json"): void { + assert.deepEqual(this.getEvent(server.ProjectInfoTelemetryEvent), { + projectId: sys.createSHA256Hash!(configFile), + fileStats: fileStats({ ts: 1 }), + compilerOptions: {}, + extends: false, + files: false, + include: false, + exclude: false, + compileOnSave: false, + typeAcquisition: { + enable: false, + exclude: false, + include: false, + }, + configFileName: "tsconfig.json", + projectType: "configured", + languageServiceEnabled: true, + version, + ...partial, + }); + } + + assertOpenFileTelemetryEvent(info: server.OpenFileInfo): void { + assert.deepEqual(this.getEvent(server.OpenFileInfoTelemetryEvent), { info }); + } + assertNoOpenFilesTelemetryEvent(): void { + this.hasZeroEvent(server.OpenFileInfoTelemetryEvent); + } + } + + export class TestSession extends server.Session { + private seq = 0; + public events: protocol.Event[] = []; + public host!: TestServerHost; + + getProjectService() { + return this.projectService; + } + + public getSeq() { + return this.seq; + } + + public getNextSeq() { + return this.seq + 1; + } + + public executeCommandSeq(request: Partial) { + this.seq++; + request.seq = this.seq; + request.type = "request"; + return this.executeCommand(request); + } + + public event(body: T, eventName: string) { + this.events.push(server.toEvent(eventName, body)); + super.event(body, eventName); + } + + public clearMessages() { + clear(this.events); + this.host.clearOutput(); + } + } + + export function createSession(host: server.ServerHost, opts: Partial = {}) { + if (opts.typingsInstaller === undefined) { + opts.typingsInstaller = new TestTypingsInstaller("/a/data/", /*throttleLimit*/ 5, host); + } + + if (opts.eventHandler !== undefined) { + opts.canUseEvents = true; + } + + const sessionOptions: server.SessionOptions = { + host, + cancellationToken: server.nullCancellationToken, + useSingleInferredProject: false, + useInferredProjectPerProjectRoot: false, + typingsInstaller: undefined!, // TODO: GH#18217 + byteLength: Utils.byteLength, + hrtime: process.hrtime, + logger: opts.logger || createHasErrorMessageLogger().logger, + canUseEvents: false + }; + + return new TestSession({ ...sessionOptions, ...opts }); + } + + export function createSessionWithEventTracking(host: server.ServerHost, eventName: T["eventName"], ...eventNames: T["eventName"][]) { + const events: T[] = []; + const session = createSession(host, { + eventHandler: e => { + if (e.eventName === eventName || eventNames.some(eventName => e.eventName === eventName)) { + events.push(e as T); + } + } + }); + + return { session, events }; + } + + export function createSessionWithDefaultEventHandler(host: TestServerHost, eventNames: T["event"] | T["event"][], opts: Partial = {}) { + const session = createSession(host, { canUseEvents: true, ...opts }); + + return { + session, + getEvents, + clearEvents + }; + + function getEvents() { + return mapDefined(host.getOutput(), s => { + const e = mapOutputToJson(s); + return (isArray(eventNames) ? eventNames.some(eventName => e.event === eventName) : e.event === eventNames) ? e as T : undefined; + }); + } + + function clearEvents() { + session.clearMessages(); + } + } + + export interface CreateProjectServiceParameters { + cancellationToken?: HostCancellationToken; + logger?: server.Logger; + useSingleInferredProject?: boolean; + typingsInstaller?: server.ITypingsInstaller; + eventHandler?: server.ProjectServiceEventHandler; + } + + export class TestProjectService extends server.ProjectService { + constructor(host: server.ServerHost, logger: server.Logger, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, + typingsInstaller: server.ITypingsInstaller, eventHandler: server.ProjectServiceEventHandler, opts: Partial = {}) { + super({ + host, + logger, + cancellationToken, + useSingleInferredProject, + useInferredProjectPerProjectRoot: false, + typingsInstaller, + typesMapLocation: customTypesMap.path, + eventHandler, + ...opts + }); + } + + checkNumberOfProjects(count: { inferredProjects?: number, configuredProjects?: number, externalProjects?: number }) { + checkNumberOfProjects(this, count); + } + } + export function createProjectService(host: server.ServerHost, parameters: CreateProjectServiceParameters = {}, options?: Partial) { + const cancellationToken = parameters.cancellationToken || server.nullCancellationToken; + const logger = parameters.logger || createHasErrorMessageLogger().logger; + const useSingleInferredProject = parameters.useSingleInferredProject !== undefined ? parameters.useSingleInferredProject : false; + return new TestProjectService(host, logger, cancellationToken, useSingleInferredProject, parameters.typingsInstaller!, parameters.eventHandler!, options); // TODO: GH#18217 + } + + export function checkNumberOfConfiguredProjects(projectService: server.ProjectService, expected: number) { + assert.equal(projectService.configuredProjects.size, expected, `expected ${expected} configured project(s)`); + } + + export function checkNumberOfExternalProjects(projectService: server.ProjectService, expected: number) { + assert.equal(projectService.externalProjects.length, expected, `expected ${expected} external project(s)`); + } + + export function checkNumberOfInferredProjects(projectService: server.ProjectService, expected: number) { + assert.equal(projectService.inferredProjects.length, expected, `expected ${expected} inferred project(s)`); + } + + export function checkNumberOfProjects(projectService: server.ProjectService, count: { inferredProjects?: number, configuredProjects?: number, externalProjects?: number }) { + checkNumberOfConfiguredProjects(projectService, count.configuredProjects || 0); + checkNumberOfExternalProjects(projectService, count.externalProjects || 0); + checkNumberOfInferredProjects(projectService, count.inferredProjects || 0); + } + + export function configuredProjectAt(projectService: server.ProjectService, index: number) { + const values = projectService.configuredProjects.values(); + while (index > 0) { + values.next(); + index--; + } + return values.next().value; + } + + export function checkProjectActualFiles(project: server.Project, expectedFiles: ReadonlyArray) { + checkArray(`${server.ProjectKind[project.projectKind]} project, actual files`, project.getFileNames(), expectedFiles); + } + + export function checkProjectRootFiles(project: server.Project, expectedFiles: ReadonlyArray) { + checkArray(`${server.ProjectKind[project.projectKind]} project, rootFileNames`, project.getRootFiles(), expectedFiles); + } + + export function mapCombinedPathsInAncestor(dir: string, path2: string, mapAncestor: (ancestor: string) => boolean) { + dir = normalizePath(dir); + const result: string[] = []; + forEachAncestorDirectory(dir, ancestor => { + if (mapAncestor(ancestor)) { + result.push(combinePaths(ancestor, path2)); + } + }); + return result; + } + + export function getRootsToWatchWithAncestorDirectory(dir: string, path2: string) { + return mapCombinedPathsInAncestor(dir, path2, ancestor => ancestor.split(directorySeparator).length > 4); + } + + export const nodeModules = "node_modules"; + export function getNodeModuleDirectories(dir: string) { + return getRootsToWatchWithAncestorDirectory(dir, nodeModules); + } + + export const nodeModulesAtTypes = "node_modules/@types"; + export function getTypeRootsFromLocation(currentDirectory: string) { + return getRootsToWatchWithAncestorDirectory(currentDirectory, nodeModulesAtTypes); + } + + export function checkOpenFiles(projectService: server.ProjectService, expectedFiles: File[]) { + checkArray("Open files", arrayFrom(projectService.openFiles.keys(), path => projectService.getScriptInfoForPath(path as Path)!.fileName), expectedFiles.map(file => file.path)); + } + + export function checkScriptInfos(projectService: server.ProjectService, expectedFiles: ReadonlyArray) { + checkArray("ScriptInfos files", arrayFrom(projectService.filenameToScriptInfo.values(), info => info.fileName), expectedFiles); + } + + export function protocolLocationFromSubstring(str: string, substring: string): protocol.Location { + const start = str.indexOf(substring); + Debug.assert(start !== -1); + return protocolToLocation(str)(start); + } + + function protocolToLocation(text: string): (pos: number) => protocol.Location { + const lineStarts = computeLineStarts(text); + return pos => { + const x = computeLineAndCharacterOfPosition(lineStarts, pos); + return { line: x.line + 1, offset: x.character + 1 }; + }; + } + + export function protocolTextSpanFromSubstring(str: string, substring: string, options?: SpanFromSubstringOptions): protocol.TextSpan { + const span = textSpanFromSubstring(str, substring, options); + const toLocation = protocolToLocation(str); + return { start: toLocation(span.start), end: toLocation(textSpanEnd(span)) }; + } + + export function protocolRenameSpanFromSubstring( + str: string, + substring: string, + options?: SpanFromSubstringOptions, + prefixSuffixText?: { readonly prefixText?: string, readonly suffixText?: string }, + ): protocol.RenameTextSpan { + return { ...protocolTextSpanFromSubstring(str, substring, options), ...prefixSuffixText }; + } + + export function textSpanFromSubstring(str: string, substring: string, options?: SpanFromSubstringOptions): TextSpan { + const start = nthIndexOf(str, substring, options ? options.index : 0); + Debug.assert(start !== -1); + return createTextSpan(start, substring.length); + } + + export function protocolFileLocationFromSubstring(file: File, substring: string): protocol.FileLocationRequestArgs { + return { file: file.path, ...protocolLocationFromSubstring(file.content, substring) }; + } + + export interface SpanFromSubstringOptions { + readonly index: number; + } + + function nthIndexOf(str: string, substr: string, n: number): number { + let index = -1; + for (; n >= 0; n--) { + index = str.indexOf(substr, index + 1); + if (index === -1) return -1; + } + return index; + } + + /** + * Test server cancellation token used to mock host token cancellation requests. + * The cancelAfterRequest constructor param specifies how many isCancellationRequested() calls + * should be made before canceling the token. The id of the request to cancel should be set with + * setRequestToCancel(); + */ + export class TestServerCancellationToken implements server.ServerCancellationToken { + private currentId: number | undefined = -1; + private requestToCancel = -1; + private isCancellationRequestedCount = 0; + + constructor(private cancelAfterRequest = 0) { + } + + setRequest(requestId: number) { + this.currentId = requestId; + } + + setRequestToCancel(requestId: number) { + this.resetToken(); + this.requestToCancel = requestId; + } + + resetRequest(requestId: number) { + assert.equal(requestId, this.currentId, "unexpected request id in cancellation"); + this.currentId = undefined; + } + + isCancellationRequested() { + this.isCancellationRequestedCount++; + // If the request id is the request to cancel and isCancellationRequestedCount + // has been met then cancel the request. Ex: cancel the request if it is a + // nav bar request & isCancellationRequested() has already been called three times. + return this.requestToCancel === this.currentId && this.isCancellationRequestedCount >= this.cancelAfterRequest; + } + + resetToken() { + this.currentId = -1; + this.isCancellationRequestedCount = 0; + this.requestToCancel = -1; + } + } + + export function makeSessionRequest(command: string, args: T): protocol.Request { + return { + seq: 0, + type: "request", + command, + arguments: args + }; + } + + export function executeSessionRequest(session: server.Session, command: TRequest["command"], args: TRequest["arguments"]): TResponse["body"] { + return session.executeCommand(makeSessionRequest(command, args)).response as TResponse["body"]; + } + + export function executeSessionRequestNoResponse(session: server.Session, command: TRequest["command"], args: TRequest["arguments"]): void { + session.executeCommand(makeSessionRequest(command, args)); + } + + export function openFilesForSession(files: ReadonlyArray, session: server.Session): void { + for (const file of files) { + session.executeCommand(makeSessionRequest(CommandNames.Open, + "projectRootPath" in file ? { file: typeof file.file === "string" ? file.file : file.file.path, projectRootPath: file.projectRootPath } : { file: file.path })); + } + } + + export function closeFilesForSession(files: ReadonlyArray, session: server.Session): void { + for (const file of files) { + session.executeCommand(makeSessionRequest(CommandNames.Close, { file: file.path })); + } + } + + export interface ErrorInformation { + diagnosticMessage: DiagnosticMessage; + errorTextArguments?: string[]; + } + + function getProtocolDiagnosticMessage({ diagnosticMessage, errorTextArguments = [] }: ErrorInformation) { + return formatStringFromArgs(diagnosticMessage.message, errorTextArguments); + } + + export function verifyDiagnostics(actual: ReadonlyArray, expected: ReadonlyArray) { + const expectedErrors = expected.map(getProtocolDiagnosticMessage); + assert.deepEqual(actual.map(diag => flattenDiagnosticMessageText(diag.text, "\n")), expectedErrors); + } + + export function verifyNoDiagnostics(actual: server.protocol.Diagnostic[]) { + verifyDiagnostics(actual, []); + } + + export function checkErrorMessage(session: TestSession, eventName: protocol.DiagnosticEventKind, diagnostics: protocol.DiagnosticEventBody, isMostRecent = false): void { + checkNthEvent(session, server.toEvent(eventName, diagnostics), 0, isMostRecent); + } + + export function createDiagnostic(start: protocol.Location, end: protocol.Location, message: DiagnosticMessage, args: ReadonlyArray = [], category = diagnosticCategoryName(message), reportsUnnecessary?: {}, relatedInformation?: protocol.DiagnosticRelatedInformation[]): protocol.Diagnostic { + return { start, end, text: formatStringFromArgs(message.message, args), code: message.code, category, reportsUnnecessary, relatedInformation, source: undefined }; + } + + export function checkCompleteEvent(session: TestSession, numberOfCurrentEvents: number, expectedSequenceId: number, isMostRecent = true): void { + checkNthEvent(session, server.toEvent("requestCompleted", { request_seq: expectedSequenceId }), numberOfCurrentEvents - 1, isMostRecent); + } + + export function checkProjectUpdatedInBackgroundEvent(session: TestSession, openFiles: string[]) { + checkNthEvent(session, server.toEvent("projectsUpdatedInBackground", { openFiles }), 0, /*isMostRecent*/ true); + } + + export function checkNoDiagnosticEvents(session: TestSession) { + for (const event of session.events) { + assert.isFalse(event.event.endsWith("Diag"), JSON.stringify(event)); + } + } + + export function checkNthEvent(session: TestSession, expectedEvent: protocol.Event, index: number, isMostRecent: boolean) { + const events = session.events; + assert.deepEqual(events[index], expectedEvent, `Expected ${JSON.stringify(expectedEvent)} at ${index} in ${JSON.stringify(events)}`); + + const outputs = session.host.getOutput(); + assert.equal(outputs[index], server.formatMessage(expectedEvent, nullLogger, Utils.byteLength, session.host.newLine)); + + if (isMostRecent) { + assert.strictEqual(events.length, index + 1, JSON.stringify(events)); + assert.strictEqual(outputs.length, index + 1, JSON.stringify(outputs)); + } + } +} diff --git a/src/testRunner/unittests/tsserver/importHelpers.ts b/src/testRunner/unittests/tsserver/importHelpers.ts new file mode 100644 index 00000000000..b1ec5955eaa --- /dev/null +++ b/src/testRunner/unittests/tsserver/importHelpers.ts @@ -0,0 +1,18 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: import helpers", () => { + it("should not crash in tsserver", () => { + const f1 = { + path: "/a/app.ts", + content: "export async function foo() { return 100; }" + }; + const tslib = { + path: "/a/node_modules/tslib/index.d.ts", + content: "" + }; + const host = createServerHost([f1, tslib]); + const service = createProjectService(host); + service.openExternalProject({ projectFileName: "p", rootFiles: [toExternalFile(f1.path)], options: { importHelpers: true } }); + service.checkNumberOfProjects({ externalProjects: 1 }); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/inferredProjects.ts b/src/testRunner/unittests/tsserver/inferredProjects.ts new file mode 100644 index 00000000000..9d7ccaa1224 --- /dev/null +++ b/src/testRunner/unittests/tsserver/inferredProjects.ts @@ -0,0 +1,349 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: Inferred projects", () => { + it("create inferred project", () => { + const appFile: File = { + path: "/a/b/c/app.ts", + content: ` + import {f} from "./module" + console.log(f) + ` + }; + + const moduleFile: File = { + path: "/a/b/c/module.d.ts", + content: `export let x: number` + }; + const host = createServerHost([appFile, moduleFile, libFile]); + const projectService = createProjectService(host); + const { configFileName } = projectService.openClientFile(appFile.path); + + assert(!configFileName, `should not find config, got: '${configFileName}`); + checkNumberOfConfiguredProjects(projectService, 0); + checkNumberOfInferredProjects(projectService, 1); + + const project = projectService.inferredProjects[0]; + + checkArray("inferred project", project.getFileNames(), [appFile.path, libFile.path, moduleFile.path]); + const configFileLocations = ["/a/b/c/", "/a/b/", "/a/", "/"]; + const configFiles = flatMap(configFileLocations, location => [location + "tsconfig.json", location + "jsconfig.json"]); + checkWatchedFiles(host, configFiles.concat(libFile.path, moduleFile.path)); + checkWatchedDirectories(host, ["/a/b/c"], /*recursive*/ false); + checkWatchedDirectories(host, [combinePaths(getDirectoryPath(appFile.path), nodeModulesAtTypes)], /*recursive*/ true); + }); + + it("should use only one inferred project if 'useOneInferredProject' is set", () => { + const file1 = { + path: "/a/b/main.ts", + content: "let x =1;" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "target": "es6" + }, + "files": [ "main.ts" ] + }` + }; + const file2 = { + path: "/a/c/main.ts", + content: "let x =1;" + }; + + const file3 = { + path: "/a/d/main.ts", + content: "let x =1;" + }; + + const host = createServerHost([file1, file2, file3, libFile]); + const projectService = createProjectService(host, { useSingleInferredProject: true }); + projectService.openClientFile(file1.path); + projectService.openClientFile(file2.path); + projectService.openClientFile(file3.path); + + checkNumberOfConfiguredProjects(projectService, 0); + checkNumberOfInferredProjects(projectService, 1); + checkProjectActualFiles(projectService.inferredProjects[0], [file1.path, file2.path, file3.path, libFile.path]); + + + host.reloadFS([file1, configFile, file2, file3, libFile]); + host.checkTimeoutQueueLengthAndRun(2); // load configured project from disk + ensureProjectsForOpenFiles + checkNumberOfConfiguredProjects(projectService, 1); + checkNumberOfInferredProjects(projectService, 1); + checkProjectActualFiles(projectService.inferredProjects[0], [file2.path, file3.path, libFile.path]); + }); + + it("disable inferred project", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x =1;" + }; + + const host = createServerHost([file1]); + const projectService = createProjectService(host, { useSingleInferredProject: true }, { syntaxOnly: true }); + + projectService.openClientFile(file1.path, file1.content); + + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + const proj = projectService.inferredProjects[0]; + assert.isDefined(proj); + + assert.isFalse(proj.languageServiceEnabled); + }); + + it("project settings for inferred projects", () => { + const file1 = { + path: "/a/b/app.ts", + content: `import {x} from "mod"` + }; + const modFile = { + path: "/a/mod.ts", + content: "export let x: number" + }; + const host = createServerHost([file1, modFile]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + projectService.openClientFile(modFile.path); + + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + const inferredProjects = projectService.inferredProjects.slice(); + checkProjectActualFiles(inferredProjects[0], [file1.path]); + checkProjectActualFiles(inferredProjects[1], [modFile.path]); + + projectService.setCompilerOptionsForInferredProjects({ moduleResolution: ModuleResolutionKind.Classic }); + host.checkTimeoutQueueLengthAndRun(3); + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + assert.strictEqual(projectService.inferredProjects[0], inferredProjects[0]); + assert.strictEqual(projectService.inferredProjects[1], inferredProjects[1]); + checkProjectActualFiles(inferredProjects[0], [file1.path, modFile.path]); + assert.isTrue(inferredProjects[1].isOrphan()); + }); + + it("should support files without extensions", () => { + const f = { + path: "/a/compile", + content: "let x = 1" + }; + const host = createServerHost([f]); + const session = createSession(host); + session.executeCommand({ + seq: 1, + type: "request", + command: "compilerOptionsForInferredProjects", + arguments: { + options: { + allowJs: true + } + } + }); + session.executeCommand({ + seq: 2, + type: "request", + command: "open", + arguments: { + file: f.path, + fileContent: f.content, + scriptKindName: "JS" + } + }); + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkProjectActualFiles(projectService.inferredProjects[0], [f.path]); + }); + + it("inferred projects per project root", () => { + const file1 = { path: "/a/file1.ts", content: "let x = 1;", projectRootPath: "/a" }; + const file2 = { path: "/a/file2.ts", content: "let y = 2;", projectRootPath: "/a" }; + const file3 = { path: "/b/file2.ts", content: "let x = 3;", projectRootPath: "/b" }; + const file4 = { path: "/c/file3.ts", content: "let z = 4;" }; + const host = createServerHost([file1, file2, file3, file4]); + const session = createSession(host, { + useSingleInferredProject: true, + useInferredProjectPerProjectRoot: true + }); + session.executeCommand({ + seq: 1, + type: "request", + command: CommandNames.CompilerOptionsForInferredProjects, + arguments: { + options: { + allowJs: true, + target: ScriptTarget.ESNext + } + } + }); + session.executeCommand({ + seq: 2, + type: "request", + command: CommandNames.CompilerOptionsForInferredProjects, + arguments: { + options: { + allowJs: true, + target: ScriptTarget.ES2015 + }, + projectRootPath: "/b" + } + }); + session.executeCommand({ + seq: 3, + type: "request", + command: CommandNames.Open, + arguments: { + file: file1.path, + fileContent: file1.content, + scriptKindName: "JS", + projectRootPath: file1.projectRootPath + } + }); + session.executeCommand({ + seq: 4, + type: "request", + command: CommandNames.Open, + arguments: { + file: file2.path, + fileContent: file2.content, + scriptKindName: "JS", + projectRootPath: file2.projectRootPath + } + }); + session.executeCommand({ + seq: 5, + type: "request", + command: CommandNames.Open, + arguments: { + file: file3.path, + fileContent: file3.content, + scriptKindName: "JS", + projectRootPath: file3.projectRootPath + } + }); + session.executeCommand({ + seq: 6, + type: "request", + command: CommandNames.Open, + arguments: { + file: file4.path, + fileContent: file4.content, + scriptKindName: "JS" + } + }); + + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { inferredProjects: 3 }); + checkProjectActualFiles(projectService.inferredProjects[0], [file4.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [file1.path, file2.path]); + checkProjectActualFiles(projectService.inferredProjects[2], [file3.path]); + assert.equal(projectService.inferredProjects[0].getCompilationSettings().target, ScriptTarget.ESNext); + assert.equal(projectService.inferredProjects[1].getCompilationSettings().target, ScriptTarget.ESNext); + assert.equal(projectService.inferredProjects[2].getCompilationSettings().target, ScriptTarget.ES2015); + }); + + function checkInferredProject(inferredProject: server.InferredProject, actualFiles: File[], target: ScriptTarget) { + checkProjectActualFiles(inferredProject, actualFiles.map(f => f.path)); + assert.equal(inferredProject.getCompilationSettings().target, target); + } + + function verifyProjectRootWithCaseSensitivity(useCaseSensitiveFileNames: boolean) { + const files: [File, File, File, File] = [ + { path: "/a/file1.ts", content: "let x = 1;" }, + { path: "/A/file2.ts", content: "let y = 2;" }, + { path: "/b/file2.ts", content: "let x = 3;" }, + { path: "/c/file3.ts", content: "let z = 4;" } + ]; + const host = createServerHost(files, { useCaseSensitiveFileNames }); + const projectService = createProjectService(host, { useSingleInferredProject: true, }, { useInferredProjectPerProjectRoot: true }); + projectService.setCompilerOptionsForInferredProjects({ + allowJs: true, + target: ScriptTarget.ESNext + }); + projectService.setCompilerOptionsForInferredProjects({ + allowJs: true, + target: ScriptTarget.ES2015 + }, "/a"); + + openClientFiles(["/a", "/a", "/b", undefined]); + verifyInferredProjectsState([ + [[files[3]], ScriptTarget.ESNext], + [[files[0], files[1]], ScriptTarget.ES2015], + [[files[2]], ScriptTarget.ESNext] + ]); + closeClientFiles(); + + openClientFiles(["/a", "/A", "/b", undefined]); + if (useCaseSensitiveFileNames) { + verifyInferredProjectsState([ + [[files[3]], ScriptTarget.ESNext], + [[files[0]], ScriptTarget.ES2015], + [[files[1]], ScriptTarget.ESNext], + [[files[2]], ScriptTarget.ESNext] + ]); + } + else { + verifyInferredProjectsState([ + [[files[3]], ScriptTarget.ESNext], + [[files[0], files[1]], ScriptTarget.ES2015], + [[files[2]], ScriptTarget.ESNext] + ]); + } + closeClientFiles(); + + projectService.setCompilerOptionsForInferredProjects({ + allowJs: true, + target: ScriptTarget.ES2017 + }, "/A"); + + openClientFiles(["/a", "/a", "/b", undefined]); + verifyInferredProjectsState([ + [[files[3]], ScriptTarget.ESNext], + [[files[0], files[1]], useCaseSensitiveFileNames ? ScriptTarget.ES2015 : ScriptTarget.ES2017], + [[files[2]], ScriptTarget.ESNext] + ]); + closeClientFiles(); + + openClientFiles(["/a", "/A", "/b", undefined]); + if (useCaseSensitiveFileNames) { + verifyInferredProjectsState([ + [[files[3]], ScriptTarget.ESNext], + [[files[0]], ScriptTarget.ES2015], + [[files[1]], ScriptTarget.ES2017], + [[files[2]], ScriptTarget.ESNext] + ]); + } + else { + verifyInferredProjectsState([ + [[files[3]], ScriptTarget.ESNext], + [[files[0], files[1]], ScriptTarget.ES2017], + [[files[2]], ScriptTarget.ESNext] + ]); + } + closeClientFiles(); + + function openClientFiles(projectRoots: [string | undefined, string | undefined, string | undefined, string | undefined]) { + files.forEach((file, index) => { + projectService.openClientFile(file.path, file.content, ScriptKind.JS, projectRoots[index]); + }); + } + + function closeClientFiles() { + files.forEach(file => projectService.closeClientFile(file.path)); + } + + function verifyInferredProjectsState(expected: [File[], ScriptTarget][]) { + checkNumberOfProjects(projectService, { inferredProjects: expected.length }); + projectService.inferredProjects.forEach((p, index) => { + const [actualFiles, target] = expected[index]; + checkInferredProject(p, actualFiles, target); + }); + } + } + + it("inferred projects per project root with case sensitive system", () => { + verifyProjectRootWithCaseSensitivity(/*useCaseSensitiveFileNames*/ true); + }); + + it("inferred projects per project root with case insensitive system", () => { + verifyProjectRootWithCaseSensitivity(/*useCaseSensitiveFileNames*/ false); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/languageService.ts b/src/testRunner/unittests/tsserver/languageService.ts new file mode 100644 index 00000000000..86d426664df --- /dev/null +++ b/src/testRunner/unittests/tsserver/languageService.ts @@ -0,0 +1,19 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: Language service", () => { + it("should work correctly on case-sensitive file systems", () => { + const lib = { + path: "/a/Lib/lib.d.ts", + content: "let x: number" + }; + const f = { + path: "/a/b/app.ts", + content: "let x = 1;" + }; + const host = createServerHost([lib, f], { executingFilePath: "/a/Lib/tsc.js", useCaseSensitiveFileNames: true }); + const projectService = createProjectService(host); + projectService.openClientFile(f.path); + projectService.checkNumberOfProjects({ inferredProjects: 1 }); + projectService.inferredProjects[0].getLanguageService().getProgram(); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts b/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts new file mode 100644 index 00000000000..eb254789d67 --- /dev/null +++ b/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts @@ -0,0 +1,55 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: maxNodeModuleJsDepth for inferred projects", () => { + it("should be set to 2 if the project has js root files", () => { + const file1: File = { + path: "/a/b/file1.js", + content: `var t = require("test"); t.` + }; + const moduleFile: File = { + path: "/a/b/node_modules/test/index.js", + content: `var v = 10; module.exports = v;` + }; + + const host = createServerHost([file1, moduleFile]); + const projectService = createProjectService(host); + projectService.openClientFile(file1.path); + + let project = projectService.inferredProjects[0]; + let options = project.getCompilationSettings(); + assert.isTrue(options.maxNodeModuleJsDepth === 2); + + // Assert the option sticks + projectService.setCompilerOptionsForInferredProjects({ target: ScriptTarget.ES2016 }); + project = projectService.inferredProjects[0]; + options = project.getCompilationSettings(); + assert.isTrue(options.maxNodeModuleJsDepth === 2); + }); + + it("should return to normal state when all js root files are removed from project", () => { + const file1 = { + path: "/a/file1.ts", + content: "let x =1;" + }; + const file2 = { + path: "/a/file2.js", + content: "let x =1;" + }; + + const host = createServerHost([file1, file2, libFile]); + const projectService = createProjectService(host, { useSingleInferredProject: true }); + + projectService.openClientFile(file1.path); + checkNumberOfInferredProjects(projectService, 1); + let project = projectService.inferredProjects[0]; + assert.isUndefined(project.getCompilationSettings().maxNodeModuleJsDepth); + + projectService.openClientFile(file2.path); + project = projectService.inferredProjects[0]; + assert.isTrue(project.getCompilationSettings().maxNodeModuleJsDepth === 2); + + projectService.closeClientFile(file2.path); + project = projectService.inferredProjects[0]; + assert.isUndefined(project.getCompilationSettings().maxNodeModuleJsDepth); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/metadataInResponse.ts b/src/testRunner/unittests/tsserver/metadataInResponse.ts new file mode 100644 index 00000000000..6ec8a565d87 --- /dev/null +++ b/src/testRunner/unittests/tsserver/metadataInResponse.ts @@ -0,0 +1,99 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: with metadata in response", () => { + const metadata = "Extra Info"; + function verifyOutput(host: TestServerHost, expectedResponse: protocol.Response) { + const output = host.getOutput().map(mapOutputToJson); + assert.deepEqual(output, [expectedResponse]); + host.clearOutput(); + } + + function verifyCommandWithMetadata(session: TestSession, host: TestServerHost, command: Partial, expectedResponseBody: U) { + command.seq = session.getSeq(); + command.type = "request"; + session.onMessage(JSON.stringify(command)); + verifyOutput(host, expectedResponseBody ? + { seq: 0, type: "response", command: command.command!, request_seq: command.seq, success: true, body: expectedResponseBody, metadata } : + { seq: 0, type: "response", command: command.command!, request_seq: command.seq, success: false, message: "No content available." } + ); + } + + const aTs: File = { path: "/a.ts", content: `class c { prop = "hello"; foo() { return this.prop; } }` }; + const tsconfig: File = { + path: "/tsconfig.json", + content: JSON.stringify({ + compilerOptions: { plugins: [{ name: "myplugin" }] } + }) + }; + function createHostWithPlugin(files: ReadonlyArray) { + const host = createServerHost(files); + host.require = (_initialPath, moduleName) => { + assert.equal(moduleName, "myplugin"); + return { + module: () => ({ + create(info: server.PluginCreateInfo) { + const proxy = Harness.LanguageService.makeDefaultProxy(info); + proxy.getCompletionsAtPosition = (filename, position, options) => { + const result = info.languageService.getCompletionsAtPosition(filename, position, options); + if (result) { + result.metadata = metadata; + } + return result; + }; + return proxy; + } + }), + error: undefined + }; + }; + return host; + } + + describe("With completion requests", () => { + const completionRequestArgs: protocol.CompletionsRequestArgs = { + file: aTs.path, + line: 1, + offset: aTs.content.indexOf("this.") + 1 + "this.".length + }; + const expectedCompletionEntries: ReadonlyArray = [ + { name: "foo", kind: ScriptElementKind.memberFunctionElement, kindModifiers: "", sortText: "0" }, + { name: "prop", kind: ScriptElementKind.memberVariableElement, kindModifiers: "", sortText: "0" } + ]; + + it("can pass through metadata when the command returns array", () => { + const host = createHostWithPlugin([aTs, tsconfig]); + const session = createSession(host); + openFilesForSession([aTs], session); + verifyCommandWithMetadata>(session, host, { + command: protocol.CommandTypes.Completions, + arguments: completionRequestArgs + }, expectedCompletionEntries); + }); + + it("can pass through metadata when the command returns object", () => { + const host = createHostWithPlugin([aTs, tsconfig]); + const session = createSession(host); + openFilesForSession([aTs], session); + verifyCommandWithMetadata(session, host, { + command: protocol.CommandTypes.CompletionInfo, + arguments: completionRequestArgs + }, { + isGlobalCompletion: false, + isMemberCompletion: true, + isNewIdentifierLocation: false, + entries: expectedCompletionEntries + }); + }); + + it("returns undefined correctly", () => { + const aTs: File = { path: "/a.ts", content: `class c { prop = "hello"; foo() { const x = 0; } }` }; + const host = createHostWithPlugin([aTs, tsconfig]); + const session = createSession(host); + openFilesForSession([aTs], session); + verifyCommandWithMetadata(session, host, { + command: protocol.CommandTypes.Completions, + arguments: { file: aTs.path, line: 1, offset: aTs.content.indexOf("x") + 1 } + }, /*expectedResponseBody*/ undefined); + }); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/navTo.ts b/src/testRunner/unittests/tsserver/navTo.ts new file mode 100644 index 00000000000..b3aebef1043 --- /dev/null +++ b/src/testRunner/unittests/tsserver/navTo.ts @@ -0,0 +1,30 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: navigate-to for javascript project", () => { + function containsNavToItem(items: protocol.NavtoItem[], itemName: string, itemKind: string) { + return find(items, item => item.name === itemName && item.kind === itemKind) !== undefined; + } + + it("should not include type symbols", () => { + const file1: File = { + path: "/a/b/file1.js", + content: "function foo() {}" + }; + const configFile: File = { + path: "/a/b/jsconfig.json", + content: "{}" + }; + const host = createServerHost([file1, configFile, libFile]); + const session = createSession(host); + openFilesForSession([file1], session); + + // Try to find some interface type defined in lib.d.ts + const libTypeNavToRequest = makeSessionRequest(CommandNames.Navto, { searchValue: "Document", file: file1.path, projectFileName: configFile.path }); + const items = session.executeCommand(libTypeNavToRequest).response as protocol.NavtoItem[]; + assert.isFalse(containsNavToItem(items, "Document", "interface"), `Found lib.d.ts symbol in JavaScript project nav to request result.`); + + const localFunctionNavToRequst = makeSessionRequest(CommandNames.Navto, { searchValue: "foo", file: file1.path, projectFileName: configFile.path }); + const items2 = session.executeCommand(localFunctionNavToRequst).response as protocol.NavtoItem[]; + assert.isTrue(containsNavToItem(items2, "foo", "function"), `Cannot find function symbol "foo".`); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/occurences.ts b/src/testRunner/unittests/tsserver/occurences.ts new file mode 100644 index 00000000000..cf9c83e2e72 --- /dev/null +++ b/src/testRunner/unittests/tsserver/occurences.ts @@ -0,0 +1,47 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: occurence highlight on string", () => { + it("should be marked if only on string values", () => { + const file1: File = { + path: "/a/b/file1.ts", + content: `let t1 = "div";\nlet t2 = "div";\nlet t3 = { "div": 123 };\nlet t4 = t3["div"];` + }; + + const host = createServerHost([file1]); + const session = createSession(host); + const projectService = session.getProjectService(); + + projectService.openClientFile(file1.path); + { + const highlightRequest = makeSessionRequest( + CommandNames.Occurrences, + { file: file1.path, line: 1, offset: 11 } + ); + const highlightResponse = session.executeCommand(highlightRequest).response as protocol.OccurrencesResponseItem[]; + const firstOccurence = highlightResponse[0]; + assert.isTrue(firstOccurence.isInString, "Highlights should be marked with isInString"); + } + + { + const highlightRequest = makeSessionRequest( + CommandNames.Occurrences, + { file: file1.path, line: 3, offset: 13 } + ); + const highlightResponse = session.executeCommand(highlightRequest).response as protocol.OccurrencesResponseItem[]; + assert.isTrue(highlightResponse.length === 2); + const firstOccurence = highlightResponse[0]; + assert.isUndefined(firstOccurence.isInString, "Highlights should not be marked with isInString if on property name"); + } + + { + const highlightRequest = makeSessionRequest( + CommandNames.Occurrences, + { file: file1.path, line: 4, offset: 14 } + ); + const highlightResponse = session.executeCommand(highlightRequest).response as protocol.OccurrencesResponseItem[]; + assert.isTrue(highlightResponse.length === 2); + const firstOccurence = highlightResponse[0]; + assert.isUndefined(firstOccurence.isInString, "Highlights should not be marked with isInString if on indexer"); + } + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/openFile.ts b/src/testRunner/unittests/tsserver/openFile.ts new file mode 100644 index 00000000000..d2a995c68f8 --- /dev/null +++ b/src/testRunner/unittests/tsserver/openFile.ts @@ -0,0 +1,108 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: Open-file", () => { + it("can be reloaded with empty content", () => { + const f = { + path: "/a/b/app.ts", + content: "let x = 1" + }; + const projectFileName = "externalProject"; + const host = createServerHost([f]); + const projectService = createProjectService(host); + // create a project + projectService.openExternalProject({ projectFileName, rootFiles: [toExternalFile(f.path)], options: {} }); + projectService.checkNumberOfProjects({ externalProjects: 1 }); + + const p = projectService.externalProjects[0]; + // force to load the content of the file + p.updateGraph(); + + const scriptInfo = p.getScriptInfo(f.path)!; + checkSnapLength(scriptInfo.getSnapshot(), f.content.length); + + // open project and replace its content with empty string + projectService.openClientFile(f.path, ""); + checkSnapLength(scriptInfo.getSnapshot(), 0); + }); + function checkSnapLength(snap: IScriptSnapshot, expectedLength: number) { + assert.equal(snap.getLength(), expectedLength, "Incorrect snapshot size"); + } + + function verifyOpenFileWorks(useCaseSensitiveFileNames: boolean) { + const file1: File = { + path: "/a/b/src/app.ts", + content: "let x = 10;" + }; + const file2: File = { + path: "/a/B/lib/module2.ts", + content: "let z = 10;" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: "" + }; + const configFile2: File = { + path: "/a/tsconfig.json", + content: "" + }; + const host = createServerHost([file1, file2, configFile, configFile2], { + useCaseSensitiveFileNames + }); + const service = createProjectService(host); + + // Open file1 -> configFile + verifyConfigFileName(file1, "/a", configFile); + verifyConfigFileName(file1, "/a/b", configFile); + verifyConfigFileName(file1, "/a/B", configFile); + + // Open file2 use root "/a/b" + verifyConfigFileName(file2, "/a", useCaseSensitiveFileNames ? configFile2 : configFile); + verifyConfigFileName(file2, "/a/b", useCaseSensitiveFileNames ? configFile2 : configFile); + verifyConfigFileName(file2, "/a/B", useCaseSensitiveFileNames ? undefined : configFile); + + function verifyConfigFileName(file: File, projectRoot: string, expectedConfigFile: File | undefined) { + const { configFileName } = service.openClientFile(file.path, /*fileContent*/ undefined, /*scriptKind*/ undefined, projectRoot); + assert.equal(configFileName, expectedConfigFile && expectedConfigFile.path); + service.closeClientFile(file.path); + } + } + it("works when project root is used with case-sensitive system", () => { + verifyOpenFileWorks(/*useCaseSensitiveFileNames*/ true); + }); + + it("works when project root is used with case-insensitive system", () => { + verifyOpenFileWorks(/*useCaseSensitiveFileNames*/ false); + }); + + it("uses existing project even if project refresh is pending", () => { + const projectFolder = "/user/someuser/projects/myproject"; + const aFile: File = { + path: `${projectFolder}/src/a.ts`, + content: "export const x = 0;" + }; + const configFile: File = { + path: `${projectFolder}/tsconfig.json`, + content: "{}" + }; + const files = [aFile, configFile, libFile]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(aFile.path, /*fileContent*/ undefined, ScriptKind.TS, projectFolder); + verifyProject(); + + const bFile: File = { + path: `${projectFolder}/src/b.ts`, + content: `export {}; declare module "./a" { export const y: number; }` + }; + files.push(bFile); + host.reloadFS(files); + service.openClientFile(bFile.path, /*fileContent*/ undefined, ScriptKind.TS, projectFolder); + verifyProject(); + + function verifyProject() { + assert.isDefined(service.configuredProjects.get(configFile.path)); + const project = service.configuredProjects.get(configFile.path)!; + checkProjectActualFiles(project, files.map(f => f.path)); + } + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/projectErrors.ts b/src/testRunner/unittests/tsserver/projectErrors.ts new file mode 100644 index 00000000000..9e24771f3ae --- /dev/null +++ b/src/testRunner/unittests/tsserver/projectErrors.ts @@ -0,0 +1,849 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: Project Errors", () => { + function checkProjectErrors(projectFiles: server.ProjectFilesWithTSDiagnostics, expectedErrors: ReadonlyArray): void { + assert.isTrue(projectFiles !== undefined, "missing project files"); + checkProjectErrorsWorker(projectFiles.projectErrors, expectedErrors); + } + + function checkProjectErrorsWorker(errors: ReadonlyArray, expectedErrors: ReadonlyArray): void { + assert.equal(errors ? errors.length : 0, expectedErrors.length, `expected ${expectedErrors.length} error in the list`); + if (expectedErrors.length) { + for (let i = 0; i < errors.length; i++) { + const actualMessage = flattenDiagnosticMessageText(errors[i].messageText, "\n"); + const expectedMessage = expectedErrors[i]; + assert.isTrue(actualMessage.indexOf(expectedMessage) === 0, `error message does not match, expected ${actualMessage} to start with ${expectedMessage}`); + } + } + } + + function checkDiagnosticsWithLinePos(errors: server.protocol.DiagnosticWithLinePosition[], expectedErrors: string[]) { + assert.equal(errors ? errors.length : 0, expectedErrors.length, `expected ${expectedErrors.length} error in the list`); + if (expectedErrors.length) { + zipWith(errors, expectedErrors, ({ message: actualMessage }, expectedMessage) => { + assert.isTrue(startsWith(actualMessage, actualMessage), `error message does not match, expected ${actualMessage} to start with ${expectedMessage}`); + }); + } + } + + it("external project - diagnostics for missing files", () => { + const file1 = { + path: "/a/b/app.ts", + content: "" + }; + const file2 = { + path: "/a/b/applib.ts", + content: "" + }; + const host = createServerHost([file1, libFile]); + const session = createSession(host); + const projectService = session.getProjectService(); + const projectFileName = "/a/b/test.csproj"; + const compilerOptionsRequest: server.protocol.CompilerOptionsDiagnosticsRequest = { + type: "request", + command: server.CommandNames.CompilerOptionsDiagnosticsFull, + seq: 2, + arguments: { projectFileName } + }; + + { + projectService.openExternalProject({ + projectFileName, + options: {}, + rootFiles: toExternalFiles([file1.path, file2.path]) + }); + + checkNumberOfProjects(projectService, { externalProjects: 1 }); + const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; + // only file1 exists - expect error + checkDiagnosticsWithLinePos(diags, ["File '/a/b/applib.ts' not found."]); + } + host.reloadFS([file2, libFile]); + { + // only file2 exists - expect error + checkNumberOfProjects(projectService, { externalProjects: 1 }); + const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; + checkDiagnosticsWithLinePos(diags, ["File '/a/b/app.ts' not found."]); + } + + host.reloadFS([file1, file2, libFile]); + { + // both files exist - expect no errors + checkNumberOfProjects(projectService, { externalProjects: 1 }); + const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; + checkDiagnosticsWithLinePos(diags, []); + } + }); + + it("configured projects - diagnostics for missing files", () => { + const file1 = { + path: "/a/b/app.ts", + content: "" + }; + const file2 = { + path: "/a/b/applib.ts", + content: "" + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) }) + }; + const host = createServerHost([file1, config, libFile]); + const session = createSession(host); + const projectService = session.getProjectService(); + openFilesForSession([file1], session); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const project = configuredProjectAt(projectService, 0); + const compilerOptionsRequest: server.protocol.CompilerOptionsDiagnosticsRequest = { + type: "request", + command: server.CommandNames.CompilerOptionsDiagnosticsFull, + seq: 2, + arguments: { projectFileName: project.getProjectName() } + }; + let diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; + checkDiagnosticsWithLinePos(diags, ["File '/a/b/applib.ts' not found."]); + + host.reloadFS([file1, file2, config, libFile]); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; + checkDiagnosticsWithLinePos(diags, []); + }); + + it("configured projects - diagnostics for corrupted config 1", () => { + const file1 = { + path: "/a/b/app.ts", + content: "" + }; + const file2 = { + path: "/a/b/lib.ts", + content: "" + }; + const correctConfig = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) }) + }; + const corruptedConfig = { + path: correctConfig.path, + content: correctConfig.content.substr(1) + }; + const host = createServerHost([file1, file2, corruptedConfig]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + { + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; + assert.isTrue(configuredProject !== undefined, "should find configured project"); + checkProjectErrors(configuredProject, []); + const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); + checkProjectErrorsWorker(projectErrors, [ + "'{' expected." + ]); + assert.isNotNull(projectErrors[0].file); + assert.equal(projectErrors[0].file!.fileName, corruptedConfig.path); + } + // fix config and trigger watcher + host.reloadFS([file1, file2, correctConfig]); + { + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; + assert.isTrue(configuredProject !== undefined, "should find configured project"); + checkProjectErrors(configuredProject, []); + const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); + checkProjectErrorsWorker(projectErrors, []); + } + }); + + it("configured projects - diagnostics for corrupted config 2", () => { + const file1 = { + path: "/a/b/app.ts", + content: "" + }; + const file2 = { + path: "/a/b/lib.ts", + content: "" + }; + const correctConfig = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) }) + }; + const corruptedConfig = { + path: correctConfig.path, + content: correctConfig.content.substr(1) + }; + const host = createServerHost([file1, file2, correctConfig]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + { + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; + assert.isTrue(configuredProject !== undefined, "should find configured project"); + checkProjectErrors(configuredProject, []); + const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); + checkProjectErrorsWorker(projectErrors, []); + } + // break config and trigger watcher + host.reloadFS([file1, file2, corruptedConfig]); + { + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; + assert.isTrue(configuredProject !== undefined, "should find configured project"); + checkProjectErrors(configuredProject, []); + const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); + checkProjectErrorsWorker(projectErrors, [ + "'{' expected." + ]); + assert.isNotNull(projectErrors[0].file); + assert.equal(projectErrors[0].file!.fileName, corruptedConfig.path); + } + }); + }); + + describe("unittests:: tsserver:: Project Errors are reported as appropriate", () => { + function createErrorLogger() { + let hasError = false; + const errorLogger: server.Logger = { + close: noop, + hasLevel: () => true, + loggingEnabled: () => true, + perftrc: noop, + info: noop, + msg: (_s, type) => { + if (type === server.Msg.Err) { + hasError = true; + } + }, + startGroup: noop, + endGroup: noop, + getLogFileName: () => undefined + }; + return { + errorLogger, + hasError: () => hasError + }; + } + + it("document is not contained in project", () => { + const file1 = { + path: "/a/b/app.ts", + content: "" + }; + const corruptedConfig = { + path: "/a/b/tsconfig.json", + content: "{" + }; + const host = createServerHost([file1, corruptedConfig]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + + const project = projectService.findProject(corruptedConfig.path)!; + checkProjectRootFiles(project, [file1.path]); + }); + + describe("when opening new file that doesnt exist on disk yet", () => { + function verifyNonExistentFile(useProjectRoot: boolean) { + const folderPath = "/user/someuser/projects/someFolder"; + const fileInRoot: File = { + path: `/src/somefile.d.ts`, + content: "class c { }" + }; + const fileInProjectRoot: File = { + path: `${folderPath}/src/somefile.d.ts`, + content: "class c { }" + }; + const host = createServerHost([libFile, fileInRoot, fileInProjectRoot]); + const { hasError, errorLogger } = createErrorLogger(); + const session = createSession(host, { canUseEvents: true, logger: errorLogger, useInferredProjectPerProjectRoot: true }); + + const projectService = session.getProjectService(); + const untitledFile = "untitled:Untitled-1"; + const refPathNotFound1 = "../../../../../../typings/@epic/Core.d.ts"; + const refPathNotFound2 = "./src/somefile.d.ts"; + const fileContent = `/// +/// `; + session.executeCommandSeq({ + command: server.CommandNames.Open, + arguments: { + file: untitledFile, + fileContent, + scriptKindName: "TS", + projectRootPath: useProjectRoot ? folderPath : undefined + } + }); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + const infoForUntitledAtProjectRoot = projectService.getScriptInfoForPath(`${folderPath.toLowerCase()}/${untitledFile.toLowerCase()}` as Path); + const infoForUnitiledAtRoot = projectService.getScriptInfoForPath(`/${untitledFile.toLowerCase()}` as Path); + const infoForSomefileAtProjectRoot = projectService.getScriptInfoForPath(`/${folderPath.toLowerCase()}/src/somefile.d.ts` as Path); + const infoForSomefileAtRoot = projectService.getScriptInfoForPath(`${fileInRoot.path.toLowerCase()}` as Path); + if (useProjectRoot) { + assert.isDefined(infoForUntitledAtProjectRoot); + assert.isUndefined(infoForUnitiledAtRoot); + } + else { + assert.isDefined(infoForUnitiledAtRoot); + assert.isUndefined(infoForUntitledAtProjectRoot); + } + assert.isUndefined(infoForSomefileAtRoot); + assert.isUndefined(infoForSomefileAtProjectRoot); + + // Since this is not js project so no typings are queued + host.checkTimeoutQueueLength(0); + + const newTimeoutId = host.getNextTimeoutId(); + const expectedSequenceId = session.getNextSeq(); + session.executeCommandSeq({ + command: server.CommandNames.Geterr, + arguments: { + delay: 0, + files: [untitledFile] + } + }); + host.checkTimeoutQueueLength(1); + + // Run the last one = get error request + host.runQueuedTimeoutCallbacks(newTimeoutId); + + assert.isFalse(hasError()); + host.checkTimeoutQueueLength(0); + checkErrorMessage(session, "syntaxDiag", { file: untitledFile, diagnostics: [] }); + session.clearMessages(); + + host.runQueuedImmediateCallbacks(); + assert.isFalse(hasError()); + const errorOffset = fileContent.indexOf(refPathNotFound1) + 1; + checkErrorMessage(session, "semanticDiag", { + file: untitledFile, + diagnostics: [ + createDiagnostic({ line: 1, offset: errorOffset }, { line: 1, offset: errorOffset + refPathNotFound1.length }, Diagnostics.File_0_not_found, [refPathNotFound1], "error"), + createDiagnostic({ line: 2, offset: errorOffset }, { line: 2, offset: errorOffset + refPathNotFound2.length }, Diagnostics.File_0_not_found, [refPathNotFound2.substr(2)], "error") + ] + }); + session.clearMessages(); + + host.runQueuedImmediateCallbacks(1); + assert.isFalse(hasError()); + checkErrorMessage(session, "suggestionDiag", { file: untitledFile, diagnostics: [] }); + checkCompleteEvent(session, 2, expectedSequenceId); + session.clearMessages(); + } + + it("has projectRoot", () => { + verifyNonExistentFile(/*useProjectRoot*/ true); + }); + + it("does not have projectRoot", () => { + verifyNonExistentFile(/*useProjectRoot*/ false); + }); + }); + + it("folder rename updates project structure and reports no errors", () => { + const projectDir = "/a/b/projects/myproject"; + const app: File = { + path: `${projectDir}/bar/app.ts`, + content: "class Bar implements foo.Foo { getFoo() { return ''; } get2() { return 1; } }" + }; + const foo: File = { + path: `${projectDir}/foo/foo.ts`, + content: "declare namespace foo { interface Foo { get2(): number; getFoo(): string; } }" + }; + const configFile: File = { + path: `${projectDir}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { module: "none", targer: "es5" }, exclude: ["node_modules"] }) + }; + const host = createServerHost([app, foo, configFile]); + const session = createSession(host, { canUseEvents: true, }); + const projectService = session.getProjectService(); + + session.executeCommandSeq({ + command: server.CommandNames.Open, + arguments: { file: app.path, } + }); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + assert.isDefined(projectService.configuredProjects.get(configFile.path)); + verifyErrorsInApp(); + + host.renameFolder(`${projectDir}/foo`, `${projectDir}/foo2`); + host.runQueuedTimeoutCallbacks(); + host.runQueuedTimeoutCallbacks(); + verifyErrorsInApp(); + + function verifyErrorsInApp() { + session.clearMessages(); + const expectedSequenceId = session.getNextSeq(); + session.executeCommandSeq({ + command: server.CommandNames.Geterr, + arguments: { + delay: 0, + files: [app.path] + } + }); + host.checkTimeoutQueueLengthAndRun(1); + checkErrorMessage(session, "syntaxDiag", { file: app.path, diagnostics: [] }); + session.clearMessages(); + + host.runQueuedImmediateCallbacks(); + checkErrorMessage(session, "semanticDiag", { file: app.path, diagnostics: [] }); + session.clearMessages(); + + host.runQueuedImmediateCallbacks(1); + checkErrorMessage(session, "suggestionDiag", { file: app.path, diagnostics: [] }); + checkCompleteEvent(session, 2, expectedSequenceId); + session.clearMessages(); + } + }); + + it("Getting errors before opening file", () => { + const file: File = { + path: "/a/b/project/file.ts", + content: "let x: number = false;" + }; + const host = createServerHost([file, libFile]); + const { hasError, errorLogger } = createErrorLogger(); + const session = createSession(host, { canUseEvents: true, logger: errorLogger }); + + session.clearMessages(); + const expectedSequenceId = session.getNextSeq(); + session.executeCommandSeq({ + command: server.CommandNames.Geterr, + arguments: { + delay: 0, + files: [file.path] + } + }); + + host.runQueuedImmediateCallbacks(); + assert.isFalse(hasError()); + checkCompleteEvent(session, 1, expectedSequenceId); + session.clearMessages(); + }); + + it("Reports errors correctly when file referenced by inferred project root, is opened right after closing the root file", () => { + const projectRoot = "/user/username/projects/myproject"; + const app: File = { + path: `${projectRoot}/src/client/app.js`, + content: "" + }; + const serverUtilities: File = { + path: `${projectRoot}/src/server/utilities.js`, + content: `function getHostName() { return "hello"; } export { getHostName };` + }; + const backendTest: File = { + path: `${projectRoot}/test/backend/index.js`, + content: `import { getHostName } from '../../src/server/utilities';export default getHostName;` + }; + const files = [libFile, app, serverUtilities, backendTest]; + const host = createServerHost(files); + const session = createSession(host, { useInferredProjectPerProjectRoot: true, canUseEvents: true }); + openFilesForSession([{ file: app, projectRootPath: projectRoot }], session); + const service = session.getProjectService(); + checkNumberOfProjects(service, { inferredProjects: 1 }); + const project = service.inferredProjects[0]; + checkProjectActualFiles(project, [libFile.path, app.path]); + openFilesForSession([{ file: backendTest, projectRootPath: projectRoot }], session); + checkNumberOfProjects(service, { inferredProjects: 1 }); + checkProjectActualFiles(project, files.map(f => f.path)); + checkErrors([backendTest.path, app.path]); + closeFilesForSession([backendTest], session); + openFilesForSession([{ file: serverUtilities.path, projectRootPath: projectRoot }], session); + checkErrors([serverUtilities.path, app.path]); + + function checkErrors(openFiles: [string, string]) { + const expectedSequenceId = session.getNextSeq(); + session.executeCommandSeq({ + command: protocol.CommandTypes.Geterr, + arguments: { + delay: 0, + files: openFiles + } + }); + + for (const openFile of openFiles) { + session.clearMessages(); + host.checkTimeoutQueueLength(3); + host.runQueuedTimeoutCallbacks(host.getNextTimeoutId() - 1); + + checkErrorMessage(session, "syntaxDiag", { file: openFile, diagnostics: [] }); + session.clearMessages(); + + host.runQueuedImmediateCallbacks(); + checkErrorMessage(session, "semanticDiag", { file: openFile, diagnostics: [] }); + session.clearMessages(); + + host.runQueuedImmediateCallbacks(1); + checkErrorMessage(session, "suggestionDiag", { file: openFile, diagnostics: [] }); + } + checkCompleteEvent(session, 2, expectedSequenceId); + session.clearMessages(); + } + }); + }); + + describe("unittests:: tsserver:: Project Errors for Configure file diagnostics events", () => { + function getUnknownCompilerOptionDiagnostic(configFile: File, prop: string): ConfigFileDiagnostic { + const d = Diagnostics.Unknown_compiler_option_0; + const start = configFile.content.indexOf(prop) - 1; // start at "prop" + return { + fileName: configFile.path, + start, + length: prop.length + 2, + messageText: formatStringFromArgs(d.message, [prop]), + category: d.category, + code: d.code, + reportsUnnecessary: undefined + }; + } + + function getFileNotFoundDiagnostic(configFile: File, relativeFileName: string): ConfigFileDiagnostic { + const findString = `{"path":"./${relativeFileName}"}`; + const d = Diagnostics.File_0_not_found; + const start = configFile.content.indexOf(findString); + return { + fileName: configFile.path, + start, + length: findString.length, + messageText: formatStringFromArgs(d.message, [`${getDirectoryPath(configFile.path)}/${relativeFileName}`]), + category: d.category, + code: d.code, + reportsUnnecessary: undefined + }; + } + + it("are generated when the config file has errors", () => { + const file: File = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "foo": "bar", + "allowJS": true + } + }` + }; + const serverEventManager = new TestServerEventManager([file, libFile, configFile]); + openFilesForSession([file], serverEventManager.session); + serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, file.path, [ + getUnknownCompilerOptionDiagnostic(configFile, "foo"), + getUnknownCompilerOptionDiagnostic(configFile, "allowJS") + ]); + }); + + it("are generated when the config file doesn't have errors", () => { + const file: File = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {} + }` + }; + const serverEventManager = new TestServerEventManager([file, libFile, configFile]); + openFilesForSession([file], serverEventManager.session); + serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, file.path, emptyArray); + }); + + it("are generated when the config file changes", () => { + const file: File = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {} + }` + }; + + const files = [file, libFile, configFile]; + const serverEventManager = new TestServerEventManager(files); + openFilesForSession([file], serverEventManager.session); + serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, file.path, emptyArray); + + configFile.content = `{ + "compilerOptions": { + "haha": 123 + } + }`; + serverEventManager.host.reloadFS(files); + serverEventManager.host.runQueuedTimeoutCallbacks(); + serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, configFile.path, [ + getUnknownCompilerOptionDiagnostic(configFile, "haha") + ]); + + configFile.content = `{ + "compilerOptions": {} + }`; + serverEventManager.host.reloadFS(files); + serverEventManager.host.runQueuedTimeoutCallbacks(); + serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, configFile.path, emptyArray); + }); + + it("are not generated when the config file does not include file opened and config file has errors", () => { + const file: File = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const file2: File = { + path: "/a/b/test.ts", + content: "let x = 10" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "foo": "bar", + "allowJS": true + }, + "files": ["app.ts"] + }` + }; + const serverEventManager = new TestServerEventManager([file, file2, libFile, configFile]); + openFilesForSession([file2], serverEventManager.session); + serverEventManager.hasZeroEvent("configFileDiag"); + }); + + it("are not generated when the config file has errors but suppressDiagnosticEvents is true", () => { + const file: File = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "foo": "bar", + "allowJS": true + } + }` + }; + const serverEventManager = new TestServerEventManager([file, libFile, configFile], /*suppressDiagnosticEvents*/ true); + openFilesForSession([file], serverEventManager.session); + serverEventManager.hasZeroEvent("configFileDiag"); + }); + + it("are not generated when the config file does not include file opened and doesnt contain any errors", () => { + const file: File = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const file2: File = { + path: "/a/b/test.ts", + content: "let x = 10" + }; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "files": ["app.ts"] + }` + }; + + const serverEventManager = new TestServerEventManager([file, file2, libFile, configFile]); + openFilesForSession([file2], serverEventManager.session); + serverEventManager.hasZeroEvent("configFileDiag"); + }); + + it("contains the project reference errors", () => { + const file: File = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const noSuchTsconfig = "no-such-tsconfig.json"; + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "files": ["app.ts"], + "references": [{"path":"./${noSuchTsconfig}"}] + }` + }; + + const serverEventManager = new TestServerEventManager([file, libFile, configFile]); + openFilesForSession([file], serverEventManager.session); + serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, file.path, [ + getFileNotFoundDiagnostic(configFile, noSuchTsconfig) + ]); + }); + }); + + describe("unittests:: tsserver:: Project Errors dont include overwrite emit error", () => { + it("for inferred project", () => { + const f1 = { + path: "/a/b/f1.js", + content: "function test1() { }" + }; + const host = createServerHost([f1, libFile]); + const session = createSession(host); + openFilesForSession([f1], session); + + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + const projectName = projectService.inferredProjects[0].getProjectName(); + + const diags = session.executeCommand({ + type: "request", + command: server.CommandNames.CompilerOptionsDiagnosticsFull, + seq: 2, + arguments: { projectFileName: projectName } + }).response as ReadonlyArray; + assert.isTrue(diags.length === 0); + + session.executeCommand({ + type: "request", + command: server.CommandNames.CompilerOptionsForInferredProjects, + seq: 3, + arguments: { options: { module: ModuleKind.CommonJS } } + }); + const diagsAfterUpdate = session.executeCommand({ + type: "request", + command: server.CommandNames.CompilerOptionsDiagnosticsFull, + seq: 4, + arguments: { projectFileName: projectName } + }).response as ReadonlyArray; + assert.isTrue(diagsAfterUpdate.length === 0); + }); + + it("for external project", () => { + const f1 = { + path: "/a/b/f1.js", + content: "function test1() { }" + }; + const host = createServerHost([f1, libFile]); + const session = createSession(host); + const projectService = session.getProjectService(); + const projectFileName = "/a/b/project.csproj"; + const externalFiles = toExternalFiles([f1.path]); + projectService.openExternalProject({ + projectFileName, + rootFiles: externalFiles, + options: {} + }); + + checkNumberOfProjects(projectService, { externalProjects: 1 }); + + const diags = session.executeCommand({ + type: "request", + command: server.CommandNames.CompilerOptionsDiagnosticsFull, + seq: 2, + arguments: { projectFileName } + }).response as ReadonlyArray; + assert.isTrue(diags.length === 0); + + session.executeCommand({ + type: "request", + command: server.CommandNames.OpenExternalProject, + seq: 3, + arguments: { + projectFileName, + rootFiles: externalFiles, + options: { module: ModuleKind.CommonJS } + } + }); + const diagsAfterUpdate = session.executeCommand({ + type: "request", + command: server.CommandNames.CompilerOptionsDiagnosticsFull, + seq: 4, + arguments: { projectFileName } + }).response as ReadonlyArray; + assert.isTrue(diagsAfterUpdate.length === 0); + }); + }); + + describe("unittests:: tsserver:: Project Errors reports Options Diagnostic locations correctly with changes in configFile contents", () => { + it("when options change", () => { + const file = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const configFileContentBeforeComment = `{`; + const configFileContentComment = ` + // comment`; + const configFileContentAfterComment = ` + "compilerOptions": { + "allowJs": true, + "declaration": true + } + }`; + const configFileContentWithComment = configFileContentBeforeComment + configFileContentComment + configFileContentAfterComment; + const configFileContentWithoutCommentLine = configFileContentBeforeComment + configFileContentAfterComment; + + const configFile = { + path: "/a/b/tsconfig.json", + content: configFileContentWithComment + }; + const host = createServerHost([file, libFile, configFile]); + const session = createSession(host); + openFilesForSession([file], session); + + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const projectName = configuredProjectAt(projectService, 0).getProjectName(); + + const diags = session.executeCommand({ + type: "request", + command: server.CommandNames.SemanticDiagnosticsSync, + seq: 2, + arguments: { file: configFile.path, projectFileName: projectName, includeLinePosition: true } + }).response as ReadonlyArray; + assert.isTrue(diags.length === 2); + + configFile.content = configFileContentWithoutCommentLine; + host.reloadFS([file, configFile]); + + const diagsAfterEdit = session.executeCommand({ + type: "request", + command: server.CommandNames.SemanticDiagnosticsSync, + seq: 2, + arguments: { file: configFile.path, projectFileName: projectName, includeLinePosition: true } + }).response as ReadonlyArray; + assert.isTrue(diagsAfterEdit.length === 2); + + verifyDiagnostic(diags[0], diagsAfterEdit[0]); + verifyDiagnostic(diags[1], diagsAfterEdit[1]); + + function verifyDiagnostic(beforeEditDiag: server.protocol.DiagnosticWithLinePosition, afterEditDiag: server.protocol.DiagnosticWithLinePosition) { + assert.equal(beforeEditDiag.message, afterEditDiag.message); + assert.equal(beforeEditDiag.code, afterEditDiag.code); + assert.equal(beforeEditDiag.category, afterEditDiag.category); + assert.equal(beforeEditDiag.startLocation.line, afterEditDiag.startLocation.line + 1); + assert.equal(beforeEditDiag.startLocation.offset, afterEditDiag.startLocation.offset); + assert.equal(beforeEditDiag.endLocation.line, afterEditDiag.endLocation.line + 1); + assert.equal(beforeEditDiag.endLocation.offset, afterEditDiag.endLocation.offset); + } + }); + }); + + describe("unittests:: tsserver:: Project Errors with config file change", () => { + it("Updates diagnostics when '--noUnusedLabels' changes", () => { + const aTs: File = { path: "/a.ts", content: "label: while (1) {}" }; + const options = (allowUnusedLabels: boolean) => `{ "compilerOptions": { "allowUnusedLabels": ${allowUnusedLabels} } }`; + const tsconfig: File = { path: "/tsconfig.json", content: options(/*allowUnusedLabels*/ true) }; + + const host = createServerHost([aTs, tsconfig]); + const session = createSession(host); + openFilesForSession([aTs], session); + + host.modifyFile(tsconfig.path, options(/*allowUnusedLabels*/ false)); + host.runQueuedTimeoutCallbacks(); + + const response = executeSessionRequest(session, protocol.CommandTypes.SemanticDiagnosticsSync, { file: aTs.path }) as protocol.Diagnostic[] | undefined; + assert.deepEqual(response, [ + { + start: { line: 1, offset: 1 }, + end: { line: 1, offset: 1 + "label".length }, + text: "Unused label.", + category: "error", + code: Diagnostics.Unused_label.code, + relatedInformation: undefined, + reportsUnnecessary: true, + source: undefined, + }, + ]); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/projectReferences.ts b/src/testRunner/unittests/tsserver/projectReferences.ts new file mode 100644 index 00000000000..e39c510216d --- /dev/null +++ b/src/testRunner/unittests/tsserver/projectReferences.ts @@ -0,0 +1,658 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: with project references and tsbuild", () => { + function createHost(files: ReadonlyArray, rootNames: ReadonlyArray) { + const host = createServerHost(files); + + // ts build should succeed + const solutionBuilder = tscWatch.createSolutionBuilder(host, rootNames, {}); + solutionBuilder.buildAllProjects(); + assert.equal(host.getOutput().length, 0); + + return host; + } + + describe("with container project", () => { + function getProjectFiles(project: string): [File, File] { + return [ + TestFSWithWatch.getTsBuildProjectFile(project, "tsconfig.json"), + TestFSWithWatch.getTsBuildProjectFile(project, "index.ts"), + ]; + } + + const project = "container"; + const containerLib = getProjectFiles("container/lib"); + const containerExec = getProjectFiles("container/exec"); + const containerCompositeExec = getProjectFiles("container/compositeExec"); + const containerConfig = TestFSWithWatch.getTsBuildProjectFile(project, "tsconfig.json"); + const files = [libFile, ...containerLib, ...containerExec, ...containerCompositeExec, containerConfig]; + + it("does not error on container only project", () => { + const host = createHost(files, [containerConfig.path]); + + // Open external project for the folder + const session = createSession(host); + const service = session.getProjectService(); + service.openExternalProjects([{ + projectFileName: TestFSWithWatch.getTsBuildProjectFilePath(project, project), + rootFiles: files.map(f => ({ fileName: f.path })), + options: {} + }]); + checkNumberOfProjects(service, { configuredProjects: 4 }); + files.forEach(f => { + const args: protocol.FileRequestArgs = { + file: f.path, + projectFileName: endsWith(f.path, "tsconfig.json") ? f.path : undefined + }; + const syntaxDiagnostics = session.executeCommandSeq({ + command: protocol.CommandTypes.SyntacticDiagnosticsSync, + arguments: args + }).response; + assert.deepEqual(syntaxDiagnostics, []); + const semanticDiagnostics = session.executeCommandSeq({ + command: protocol.CommandTypes.SemanticDiagnosticsSync, + arguments: args + }).response; + assert.deepEqual(semanticDiagnostics, []); + }); + const containerProject = service.configuredProjects.get(containerConfig.path)!; + checkProjectActualFiles(containerProject, [containerConfig.path]); + const optionsDiagnostics = session.executeCommandSeq({ + command: protocol.CommandTypes.CompilerOptionsDiagnosticsFull, + arguments: { projectFileName: containerProject.projectName } + }).response; + assert.deepEqual(optionsDiagnostics, []); + }); + + it("can successfully find references with --out options", () => { + const host = createHost(files, [containerConfig.path]); + const session = createSession(host); + openFilesForSession([containerCompositeExec[1]], session); + const service = session.getProjectService(); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const locationOfMyConst = protocolLocationFromSubstring(containerCompositeExec[1].content, "myConst"); + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.Rename, + arguments: { + file: containerCompositeExec[1].path, + ...locationOfMyConst + } + }).response as protocol.RenameResponseBody; + + + const myConstLen = "myConst".length; + const locationOfMyConstInLib = protocolLocationFromSubstring(containerLib[1].content, "myConst"); + assert.deepEqual(response.locs, [ + { file: containerCompositeExec[1].path, locs: [{ start: locationOfMyConst, end: { line: locationOfMyConst.line, offset: locationOfMyConst.offset + myConstLen } }] }, + { file: containerLib[1].path, locs: [{ start: locationOfMyConstInLib, end: { line: locationOfMyConstInLib.line, offset: locationOfMyConstInLib.offset + myConstLen } }] } + ]); + }); + }); + + describe("with main and depedency project", () => { + const projectLocation = "/user/username/projects/myproject"; + const dependecyLocation = `${projectLocation}/dependency`; + const mainLocation = `${projectLocation}/main`; + const dependencyTs: File = { + path: `${dependecyLocation}/FnS.ts`, + content: `export function fn1() { } +export function fn2() { } +export function fn3() { } +export function fn4() { } +export function fn5() { } +` + }; + const dependencyConfig: File = { + path: `${dependecyLocation}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { composite: true, declarationMap: true } }) + }; + + const mainTs: File = { + path: `${mainLocation}/main.ts`, + content: `import { + fn1, + fn2, + fn3, + fn4, + fn5 +} from '../dependency/fns' + +fn1(); +fn2(); +fn3(); +fn4(); +fn5(); +` + }; + const mainConfig: File = { + path: `${mainLocation}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { composite: true, declarationMap: true }, + references: [{ path: "../dependency" }] + }) + }; + + const randomFile: File = { + path: `${projectLocation}/random/random.ts`, + content: "let a = 10;" + }; + const randomConfig: File = { + path: `${projectLocation}/random/tsconfig.json`, + content: "{}" + }; + const dtsLocation = `${dependecyLocation}/FnS.d.ts`; + const dtsPath = dtsLocation.toLowerCase() as Path; + const dtsMapLocation = `${dtsLocation}.map`; + const dtsMapPath = dtsMapLocation.toLowerCase() as Path; + + const files = [dependencyTs, dependencyConfig, mainTs, mainConfig, libFile, randomFile, randomConfig]; + + function verifyScriptInfos(session: TestSession, host: TestServerHost, openInfos: ReadonlyArray, closedInfos: ReadonlyArray, otherWatchedFiles: ReadonlyArray) { + checkScriptInfos(session.getProjectService(), openInfos.concat(closedInfos)); + checkWatchedFiles(host, closedInfos.concat(otherWatchedFiles).map(f => f.toLowerCase())); + } + + function verifyInfosWithRandom(session: TestSession, host: TestServerHost, openInfos: ReadonlyArray, closedInfos: ReadonlyArray, otherWatchedFiles: ReadonlyArray) { + verifyScriptInfos(session, host, openInfos.concat(randomFile.path), closedInfos, otherWatchedFiles.concat(randomConfig.path)); + } + + function verifyOnlyRandomInfos(session: TestSession, host: TestServerHost) { + verifyScriptInfos(session, host, [randomFile.path], [libFile.path], [randomConfig.path]); + } + + // Returns request and expected Response, expected response when no map file + interface SessionAction { + reqName: string; + request: Partial; + expectedResponse: Response; + expectedResponseNoMap?: Response; + expectedResponseNoDts?: Response; + } + function gotoDefintinionFromMainTs(fn: number): SessionAction { + const textSpan = usageSpan(fn); + const definition: protocol.FileSpan = { file: dependencyTs.path, ...definitionSpan(fn) }; + const declareSpaceLength = "declare ".length; + return { + reqName: "goToDef", + request: { + command: protocol.CommandTypes.DefinitionAndBoundSpan, + arguments: { file: mainTs.path, ...textSpan.start } + }, + expectedResponse: { + // To dependency + definitions: [definition], + textSpan + }, + expectedResponseNoMap: { + // To the dts + definitions: [{ file: dtsPath, start: { line: fn, offset: definition.start.offset + declareSpaceLength }, end: { line: fn, offset: definition.end.offset + declareSpaceLength } }], + textSpan + }, + expectedResponseNoDts: { + // To import declaration + definitions: [{ file: mainTs.path, ...importSpan(fn) }], + textSpan + } + }; + } + + function definitionSpan(fn: number): protocol.TextSpan { + return { start: { line: fn, offset: 17 }, end: { line: fn, offset: 20 } }; + } + function importSpan(fn: number): protocol.TextSpan { + return { start: { line: fn + 1, offset: 5 }, end: { line: fn + 1, offset: 8 } }; + } + function usageSpan(fn: number): protocol.TextSpan { + return { start: { line: fn + 8, offset: 1 }, end: { line: fn + 8, offset: 4 } }; + } + + function renameFromDependencyTs(fn: number): SessionAction { + const triggerSpan = definitionSpan(fn); + return { + reqName: "rename", + request: { + command: protocol.CommandTypes.Rename, + arguments: { file: dependencyTs.path, ...triggerSpan.start } + }, + expectedResponse: { + info: { + canRename: true, + fileToRename: undefined, + displayName: `fn${fn}`, + fullDisplayName: `"${dependecyLocation}/FnS".fn${fn}`, + kind: ScriptElementKind.functionElement, + kindModifiers: "export", + triggerSpan + }, + locs: [ + { file: dependencyTs.path, locs: [triggerSpan] } + ] + } + }; + } + + function renameFromDependencyTsWithBothProjectsOpen(fn: number): SessionAction { + const { reqName, request, expectedResponse } = renameFromDependencyTs(fn); + const { info, locs } = expectedResponse; + return { + reqName, + request, + expectedResponse: { + info, + locs: [ + locs[0], + { + file: mainTs.path, + locs: [ + importSpan(fn), + usageSpan(fn) + ] + } + ] + }, + // Only dependency result + expectedResponseNoMap: expectedResponse, + expectedResponseNoDts: expectedResponse + }; + } + + // Returns request and expected Response + type SessionActionGetter = (fn: number) => SessionAction; + // Open File, expectedProjectActualFiles, actionGetter, openFileLastLine + interface DocumentPositionMapperVerifier { + openFile: File; + expectedProjectActualFiles: ReadonlyArray; + actionGetter: SessionActionGetter; + openFileLastLine: number; + } + function verifyDocumentPositionMapperUpdates( + mainScenario: string, + verifier: ReadonlyArray, + closedInfos: ReadonlyArray) { + + const openFiles = verifier.map(v => v.openFile); + const expectedProjectActualFiles = verifier.map(v => v.expectedProjectActualFiles); + const actionGetters = verifier.map(v => v.actionGetter); + const openFileLastLines = verifier.map(v => v.openFileLastLine); + + const configFiles = openFiles.map(openFile => `${getDirectoryPath(openFile.path)}/tsconfig.json`); + const openInfos = openFiles.map(f => f.path); + // When usage and dependency are used, dependency config is part of closedInfo so ignore + const otherWatchedFiles = verifier.length > 1 ? [configFiles[0]] : configFiles; + function openTsFile(onHostCreate?: (host: TestServerHost) => void) { + const host = createHost(files, [mainConfig.path]); + if (onHostCreate) { + onHostCreate(host); + } + const session = createSession(host); + openFilesForSession([...openFiles, randomFile], session); + return { host, session }; + } + + function checkProject(session: TestSession, noDts?: true) { + const service = session.getProjectService(); + checkNumberOfProjects(service, { configuredProjects: 1 + verifier.length }); + configFiles.forEach((configFile, index) => { + checkProjectActualFiles( + service.configuredProjects.get(configFile)!, + noDts ? + expectedProjectActualFiles[index].filter(f => f.toLowerCase() !== dtsPath) : + expectedProjectActualFiles[index] + ); + }); + } + + function verifyInfos(session: TestSession, host: TestServerHost) { + verifyInfosWithRandom(session, host, openInfos, closedInfos, otherWatchedFiles); + } + + function verifyInfosWhenNoMapFile(session: TestSession, host: TestServerHost, dependencyTsOK?: true) { + const dtsMapClosedInfo = firstDefined(closedInfos, f => f.toLowerCase() === dtsMapPath ? f : undefined); + verifyInfosWithRandom( + session, + host, + openInfos, + closedInfos.filter(f => f !== dtsMapClosedInfo && (dependencyTsOK || f !== dependencyTs.path)), + dtsMapClosedInfo ? otherWatchedFiles.concat(dtsMapClosedInfo) : otherWatchedFiles + ); + } + + function verifyInfosWhenNoDtsFile(session: TestSession, host: TestServerHost, dependencyTsAndMapOk?: true) { + const dtsMapClosedInfo = firstDefined(closedInfos, f => f.toLowerCase() === dtsMapPath ? f : undefined); + const dtsClosedInfo = firstDefined(closedInfos, f => f.toLowerCase() === dtsPath ? f : undefined); + verifyInfosWithRandom( + session, + host, + openInfos, + closedInfos.filter(f => (dependencyTsAndMapOk || f !== dtsMapClosedInfo) && f !== dtsClosedInfo && (dependencyTsAndMapOk || f !== dependencyTs.path)), + // When project actual file contains dts, it needs to be watched + dtsClosedInfo && expectedProjectActualFiles.some(expectedProjectActualFiles => expectedProjectActualFiles.some(f => f.toLowerCase() === dtsPath)) ? + otherWatchedFiles.concat(dtsClosedInfo) : + otherWatchedFiles + ); + } + + function verifyDocumentPositionMapper(session: TestSession, dependencyMap: server.ScriptInfo, documentPositionMapper: server.ScriptInfo["documentPositionMapper"], notEqual?: true) { + assert.strictEqual(session.getProjectService().filenameToScriptInfo.get(dtsMapPath), dependencyMap); + if (notEqual) { + assert.notStrictEqual(dependencyMap.documentPositionMapper, documentPositionMapper); + } + else { + assert.strictEqual(dependencyMap.documentPositionMapper, documentPositionMapper); + } + } + + function action(actionGetter: SessionActionGetter, fn: number, session: TestSession) { + const { reqName, request, expectedResponse, expectedResponseNoMap, expectedResponseNoDts } = actionGetter(fn); + const { response } = session.executeCommandSeq(request); + return { reqName, response, expectedResponse, expectedResponseNoMap, expectedResponseNoDts }; + } + + function firstAction(session: TestSession) { + actionGetters.forEach(actionGetter => action(actionGetter, 1, session)); + } + + function verifyAllFnActionWorker(session: TestSession, verifyAction: (result: ReturnType, dtsInfo: server.ScriptInfo | undefined, isFirst: boolean) => void, dtsAbsent?: true) { + // action + let isFirst = true; + for (const actionGetter of actionGetters) { + for (let fn = 1; fn <= 5; fn++) { + const result = action(actionGetter, fn, session); + const dtsInfo = session.getProjectService().filenameToScriptInfo.get(dtsPath); + if (dtsAbsent) { + assert.isUndefined(dtsInfo); + } + else { + assert.isDefined(dtsInfo); + } + verifyAction(result, dtsInfo, isFirst); + isFirst = false; + } + } + } + + function verifyAllFnAction( + session: TestSession, + host: TestServerHost, + firstDocumentPositionMapperNotEquals?: true, + dependencyMap?: server.ScriptInfo, + documentPositionMapper?: server.ScriptInfo["documentPositionMapper"] + ) { + // action + verifyAllFnActionWorker(session, ({ reqName, response, expectedResponse }, dtsInfo, isFirst) => { + assert.deepEqual(response, expectedResponse, `Failed on ${reqName}`); + verifyInfos(session, host); + assert.equal(dtsInfo!.sourceMapFilePath, dtsMapPath); + if (isFirst) { + if (dependencyMap) { + verifyDocumentPositionMapper(session, dependencyMap, documentPositionMapper, firstDocumentPositionMapperNotEquals); + documentPositionMapper = dependencyMap.documentPositionMapper; + } + else { + dependencyMap = session.getProjectService().filenameToScriptInfo.get(dtsMapPath)!; + documentPositionMapper = dependencyMap.documentPositionMapper; + } + } + else { + verifyDocumentPositionMapper(session, dependencyMap!, documentPositionMapper); + } + }); + return { dependencyMap: dependencyMap!, documentPositionMapper }; + } + + function verifyAllFnActionWithNoMap( + session: TestSession, + host: TestServerHost, + dependencyTsOK?: true + ) { + let sourceMapFilePath: server.ScriptInfo["sourceMapFilePath"]; + // action + verifyAllFnActionWorker(session, ({ reqName, response, expectedResponse, expectedResponseNoMap }, dtsInfo, isFirst) => { + assert.deepEqual(response, expectedResponseNoMap || expectedResponse, `Failed on ${reqName}`); + verifyInfosWhenNoMapFile(session, host, dependencyTsOK); + assert.isUndefined(session.getProjectService().filenameToScriptInfo.get(dtsMapPath)); + if (isFirst) { + assert.isNotString(dtsInfo!.sourceMapFilePath); + assert.isNotFalse(dtsInfo!.sourceMapFilePath); + assert.isDefined(dtsInfo!.sourceMapFilePath); + sourceMapFilePath = dtsInfo!.sourceMapFilePath; + } + else { + assert.equal(dtsInfo!.sourceMapFilePath, sourceMapFilePath); + } + }); + return sourceMapFilePath; + } + + function verifyAllFnActionWithNoDts( + session: TestSession, + host: TestServerHost, + dependencyTsAndMapOk?: true + ) { + // action + verifyAllFnActionWorker(session, ({ reqName, response, expectedResponse, expectedResponseNoDts }) => { + assert.deepEqual(response, expectedResponseNoDts || expectedResponse, `Failed on ${reqName}`); + verifyInfosWhenNoDtsFile(session, host, dependencyTsAndMapOk); + }, /*dtsAbsent*/ true); + } + + function verifyScenarioWithChangesWorker( + change: (host: TestServerHost, session: TestSession) => void, + afterActionDocumentPositionMapperNotEquals: true | undefined, + timeoutBeforeAction: boolean + ) { + const { host, session } = openTsFile(); + + // Create DocumentPositionMapper + firstAction(session); + const dependencyMap = session.getProjectService().filenameToScriptInfo.get(dtsMapPath)!; + const documentPositionMapper = dependencyMap.documentPositionMapper; + + // change + change(host, session); + if (timeoutBeforeAction) { + host.runQueuedTimeoutCallbacks(); + checkProject(session); + verifyDocumentPositionMapper(session, dependencyMap, documentPositionMapper); + } + + // action + verifyAllFnAction(session, host, afterActionDocumentPositionMapperNotEquals, dependencyMap, documentPositionMapper); + } + + function verifyScenarioWithChanges( + scenarioName: string, + change: (host: TestServerHost, session: TestSession) => void, + afterActionDocumentPositionMapperNotEquals?: true + ) { + describe(scenarioName, () => { + it("when timeout occurs before request", () => { + verifyScenarioWithChangesWorker(change, afterActionDocumentPositionMapperNotEquals, /*timeoutBeforeAction*/ true); + }); + + it("when timeout does not occur before request", () => { + verifyScenarioWithChangesWorker(change, afterActionDocumentPositionMapperNotEquals, /*timeoutBeforeAction*/ false); + }); + }); + } + + function verifyMainScenarioAndScriptInfoCollection(session: TestSession, host: TestServerHost) { + // Main scenario action + const { dependencyMap, documentPositionMapper } = verifyAllFnAction(session, host); + checkProject(session); + verifyInfos(session, host); + + // Collecting at this point retains dependency.d.ts and map + closeFilesForSession([randomFile], session); + openFilesForSession([randomFile], session); + verifyInfos(session, host); + verifyDocumentPositionMapper(session, dependencyMap, documentPositionMapper); + + // Closing open file, removes dependencies too + closeFilesForSession([...openFiles, randomFile], session); + openFilesForSession([randomFile], session); + verifyOnlyRandomInfos(session, host); + } + + function verifyMainScenarioAndScriptInfoCollectionWithNoMap(session: TestSession, host: TestServerHost, dependencyTsOKInScenario?: true) { + // Main scenario action + verifyAllFnActionWithNoMap(session, host, dependencyTsOKInScenario); + + // Collecting at this point retains dependency.d.ts and map watcher + closeFilesForSession([randomFile], session); + openFilesForSession([randomFile], session); + verifyInfosWhenNoMapFile(session, host); + + // Closing open file, removes dependencies too + closeFilesForSession([...openFiles, randomFile], session); + openFilesForSession([randomFile], session); + verifyOnlyRandomInfos(session, host); + } + + function verifyMainScenarioAndScriptInfoCollectionWithNoDts(session: TestSession, host: TestServerHost, dependencyTsAndMapOk?: true) { + // Main scenario action + verifyAllFnActionWithNoDts(session, host, dependencyTsAndMapOk); + + // Collecting at this point retains dependency.d.ts and map watcher + closeFilesForSession([randomFile], session); + openFilesForSession([randomFile], session); + verifyInfosWhenNoDtsFile(session, host); + + // Closing open file, removes dependencies too + closeFilesForSession([...openFiles, randomFile], session); + openFilesForSession([randomFile], session); + verifyOnlyRandomInfos(session, host); + } + + function verifyScenarioWhenFileNotPresent( + scenarioName: string, + fileLocation: string, + verifyScenarioAndScriptInfoCollection: (session: TestSession, host: TestServerHost, dependencyTsOk?: true) => void, + noDts?: true + ) { + describe(scenarioName, () => { + it(mainScenario, () => { + const { host, session } = openTsFile(host => host.deleteFile(fileLocation)); + checkProject(session, noDts); + + verifyScenarioAndScriptInfoCollection(session, host); + }); + + it("when file is created", () => { + let fileContents: string | undefined; + const { host, session } = openTsFile(host => { + fileContents = host.readFile(fileLocation); + host.deleteFile(fileLocation); + }); + firstAction(session); + + host.writeFile(fileLocation, fileContents!); + verifyMainScenarioAndScriptInfoCollection(session, host); + }); + + it("when file is deleted", () => { + const { host, session } = openTsFile(); + firstAction(session); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(fileLocation); + verifyScenarioAndScriptInfoCollection(session, host, /*dependencyTsOk*/ true); + }); + }); + } + + it(mainScenario, () => { + const { host, session } = openTsFile(); + checkProject(session); + + verifyMainScenarioAndScriptInfoCollection(session, host); + }); + + // Edit + verifyScenarioWithChanges( + "when usage file changes, document position mapper doesnt change", + (_host, session) => openFiles.forEach( + (openFile, index) => session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { file: openFile.path, line: openFileLastLines[index], offset: 1, endLine: openFileLastLines[index], endOffset: 1, insertString: "const x = 10;" } + }) + ) + ); + + // Edit dts to add new fn + verifyScenarioWithChanges( + "when dependency .d.ts changes, document position mapper doesnt change", + host => host.writeFile( + dtsLocation, + host.readFile(dtsLocation)!.replace( + "//# sourceMappingURL=FnS.d.ts.map", + `export declare function fn6(): void; +//# sourceMappingURL=FnS.d.ts.map` + ) + ) + ); + + // Edit map file to represent added new line + verifyScenarioWithChanges( + "when dependency file's map changes", + host => host.writeFile( + dtsMapLocation, + `{"version":3,"file":"FnS.d.ts","sourceRoot":"","sources":["FnS.ts"],"names":[],"mappings":"AAAA,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,eAAO,MAAM,CAAC,KAAK,CAAC"}` + ), + /*afterActionDocumentPositionMapperNotEquals*/ true + ); + + verifyScenarioWhenFileNotPresent( + "when map file is not present", + dtsMapLocation, + verifyMainScenarioAndScriptInfoCollectionWithNoMap + ); + + verifyScenarioWhenFileNotPresent( + "when .d.ts file is not present", + dtsLocation, + verifyMainScenarioAndScriptInfoCollectionWithNoDts, + /*noDts*/ true + ); + } + + const usageVerifier: DocumentPositionMapperVerifier = { + openFile: mainTs, + expectedProjectActualFiles: [mainTs.path, libFile.path, mainConfig.path, dtsPath], + actionGetter: gotoDefintinionFromMainTs, + openFileLastLine: 14 + }; + describe("from project that uses dependency", () => { + const closedInfos = [dependencyTs.path, dependencyConfig.path, libFile.path, dtsPath, dtsMapLocation]; + verifyDocumentPositionMapperUpdates( + "can go to definition correctly", + [usageVerifier], + closedInfos + ); + }); + + const definingVerifier: DocumentPositionMapperVerifier = { + openFile: dependencyTs, + expectedProjectActualFiles: [dependencyTs.path, libFile.path, dependencyConfig.path], + actionGetter: renameFromDependencyTs, + openFileLastLine: 6 + }; + describe("from defining project", () => { + const closedInfos = [libFile.path, dtsLocation, dtsMapLocation]; + verifyDocumentPositionMapperUpdates( + "rename locations from dependency", + [definingVerifier], + closedInfos + ); + }); + + describe("when opening depedency and usage project", () => { + const closedInfos = [libFile.path, dtsPath, dtsMapLocation, dependencyConfig.path]; + verifyDocumentPositionMapperUpdates( + "goto Definition in usage and rename locations from defining project", + [usageVerifier, { ...definingVerifier, actionGetter: renameFromDependencyTsWithBothProjectsOpen }], + closedInfos + ); + }); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/projects.ts b/src/testRunner/unittests/tsserver/projects.ts new file mode 100644 index 00000000000..3a648c9189e --- /dev/null +++ b/src/testRunner/unittests/tsserver/projects.ts @@ -0,0 +1,1450 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: Projects", () => { + it("handles the missing files - that were added to program because they were added with /// { + const file1: File = { + path: "/a/b/commonFile1.ts", + content: `/// + let x = y` + }; + const host = createServerHost([file1, libFile]); + const session = createSession(host); + openFilesForSession([file1], session); + const projectService = session.getProjectService(); + + checkNumberOfInferredProjects(projectService, 1); + const project = projectService.inferredProjects[0]; + checkProjectRootFiles(project, [file1.path]); + checkProjectActualFiles(project, [file1.path, libFile.path]); + const getErrRequest = makeSessionRequest( + server.CommandNames.SemanticDiagnosticsSync, + { file: file1.path } + ); + + // Two errors: CommonFile2 not found and cannot find name y + let diags = session.executeCommand(getErrRequest).response as server.protocol.Diagnostic[]; + verifyDiagnostics(diags, [ + { diagnosticMessage: Diagnostics.Cannot_find_name_0, errorTextArguments: ["y"] }, + { diagnosticMessage: Diagnostics.File_0_not_found, errorTextArguments: [commonFile2.path] } + ]); + + host.reloadFS([file1, commonFile2, libFile]); + host.runQueuedTimeoutCallbacks(); + checkNumberOfInferredProjects(projectService, 1); + assert.strictEqual(projectService.inferredProjects[0], project, "Inferred project should be same"); + checkProjectRootFiles(project, [file1.path]); + checkProjectActualFiles(project, [file1.path, libFile.path, commonFile2.path]); + diags = session.executeCommand(getErrRequest).response as server.protocol.Diagnostic[]; + verifyNoDiagnostics(diags); + }); + + it("should create new inferred projects for files excluded from a configured project", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "files": ["${commonFile1.path}", "${commonFile2.path}"] + }` + }; + const files = [commonFile1, commonFile2, configFile]; + const host = createServerHost(files); + const projectService = createProjectService(host); + projectService.openClientFile(commonFile1.path); + + const project = configuredProjectAt(projectService, 0); + checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]); + configFile.content = `{ + "compilerOptions": {}, + "files": ["${commonFile1.path}"] + }`; + host.reloadFS(files); + + checkNumberOfConfiguredProjects(projectService, 1); + checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]); + host.checkTimeoutQueueLengthAndRun(2); // Update the configured project + refresh inferred projects + checkNumberOfConfiguredProjects(projectService, 1); + checkProjectRootFiles(project, [commonFile1.path]); + + projectService.openClientFile(commonFile2.path); + checkNumberOfInferredProjects(projectService, 1); + }); + + it("should disable features when the files are too large", () => { + const file1 = { + path: "/a/b/f1.js", + content: "let x =1;", + fileSize: 10 * 1024 * 1024 + }; + const file2 = { + path: "/a/b/f2.js", + content: "let y =1;", + fileSize: 6 * 1024 * 1024 + }; + const file3 = { + path: "/a/b/f3.js", + content: "let y =1;", + fileSize: 6 * 1024 * 1024 + }; + + const proj1name = "proj1", proj2name = "proj2", proj3name = "proj3"; + + const host = createServerHost([file1, file2, file3]); + const projectService = createProjectService(host); + + projectService.openExternalProject({ rootFiles: toExternalFiles([file1.path]), options: {}, projectFileName: proj1name }); + const proj1 = projectService.findProject(proj1name)!; + assert.isTrue(proj1.languageServiceEnabled); + + projectService.openExternalProject({ rootFiles: toExternalFiles([file2.path]), options: {}, projectFileName: proj2name }); + const proj2 = projectService.findProject(proj2name)!; + assert.isTrue(proj2.languageServiceEnabled); + + projectService.openExternalProject({ rootFiles: toExternalFiles([file3.path]), options: {}, projectFileName: proj3name }); + const proj3 = projectService.findProject(proj3name)!; + assert.isFalse(proj3.languageServiceEnabled); + }); + + it("should not crash when opening a file in a project with a disabled language service", () => { + const file1 = { + path: "/a/b/f1.js", + content: "let x =1;", + fileSize: 50 * 1024 * 1024 + }; + const file2 = { + path: "/a/b/f2.js", + content: "let x =1;", + fileSize: 100 + }; + + const projName = "proj1"; + + const host = createServerHost([file1, file2]); + const projectService = createProjectService(host, { useSingleInferredProject: true }, { eventHandler: noop }); + + projectService.openExternalProject({ rootFiles: toExternalFiles([file1.path, file2.path]), options: {}, projectFileName: projName }); + const proj1 = projectService.findProject(projName)!; + assert.isFalse(proj1.languageServiceEnabled); + + assert.doesNotThrow(() => projectService.openClientFile(file2.path)); + }); + + describe("ignoreConfigFiles", () => { + it("external project including config file", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x =1;" + }; + const config1 = { + path: "/a/b/tsconfig.json", + content: JSON.stringify( + { + compilerOptions: {}, + files: ["f1.ts"] + } + ) + }; + + const externalProjectName = "externalproject"; + const host = createServerHost([file1, config1]); + const projectService = createProjectService(host, { useSingleInferredProject: true }, { syntaxOnly: true }); + projectService.openExternalProject({ + rootFiles: toExternalFiles([file1.path, config1.path]), + options: {}, + projectFileName: externalProjectName + }); + + checkNumberOfProjects(projectService, { externalProjects: 1 }); + const proj = projectService.externalProjects[0]; + assert.isDefined(proj); + + assert.isTrue(proj.fileExists(file1.path)); + }); + + it("loose file included in config file (openClientFile)", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x =1;" + }; + const config1 = { + path: "/a/b/tsconfig.json", + content: JSON.stringify( + { + compilerOptions: {}, + files: ["f1.ts"] + } + ) + }; + + const host = createServerHost([file1, config1]); + const projectService = createProjectService(host, { useSingleInferredProject: true }, { syntaxOnly: true }); + projectService.openClientFile(file1.path, file1.content); + + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + const proj = projectService.inferredProjects[0]; + assert.isDefined(proj); + + assert.isTrue(proj.fileExists(file1.path)); + }); + + it("loose file included in config file (applyCodeChanges)", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x =1;" + }; + const config1 = { + path: "/a/b/tsconfig.json", + content: JSON.stringify( + { + compilerOptions: {}, + files: ["f1.ts"] + } + ) + }; + + const host = createServerHost([file1, config1]); + const projectService = createProjectService(host, { useSingleInferredProject: true }, { syntaxOnly: true }); + projectService.applyChangesInOpenFiles([{ fileName: file1.path, content: file1.content }], [], []); + + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + const proj = projectService.inferredProjects[0]; + assert.isDefined(proj); + + assert.isTrue(proj.fileExists(file1.path)); + }); + }); + + it("reload regular file after closing", () => { + const f1 = { + path: "/a/b/app.ts", + content: "x." + }; + const f2 = { + path: "/a/b/lib.ts", + content: "let x: number;" + }; + + const host = createServerHost([f1, f2, libFile]); + const service = createProjectService(host); + service.openExternalProject({ projectFileName: "/a/b/project", rootFiles: toExternalFiles([f1.path, f2.path]), options: {} }); + + service.openClientFile(f1.path); + service.openClientFile(f2.path, "let x: string"); + + service.checkNumberOfProjects({ externalProjects: 1 }); + checkProjectActualFiles(service.externalProjects[0], [f1.path, f2.path, libFile.path]); + + const completions1 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 2, emptyOptions)!; + // should contain completions for string + assert.isTrue(completions1.entries.some(e => e.name === "charAt"), "should contain 'charAt'"); + assert.isFalse(completions1.entries.some(e => e.name === "toExponential"), "should not contain 'toExponential'"); + + service.closeClientFile(f2.path); + const completions2 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 2, emptyOptions)!; + // should contain completions for string + assert.isFalse(completions2.entries.some(e => e.name === "charAt"), "should not contain 'charAt'"); + assert.isTrue(completions2.entries.some(e => e.name === "toExponential"), "should contain 'toExponential'"); + }); + + it("clear mixed content file after closing", () => { + const f1 = { + path: "/a/b/app.ts", + content: " " + }; + const f2 = { + path: "/a/b/lib.html", + content: "" + }; + + const host = createServerHost([f1, f2, libFile]); + const service = createProjectService(host); + service.openExternalProject({ projectFileName: "/a/b/project", rootFiles: [{ fileName: f1.path }, { fileName: f2.path, hasMixedContent: true }], options: {} }); + + service.openClientFile(f1.path); + service.openClientFile(f2.path, "let somelongname: string"); + + service.checkNumberOfProjects({ externalProjects: 1 }); + checkProjectActualFiles(service.externalProjects[0], [f1.path, f2.path, libFile.path]); + + const completions1 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 0, emptyOptions)!; + assert.isTrue(completions1.entries.some(e => e.name === "somelongname"), "should contain 'somelongname'"); + + service.closeClientFile(f2.path); + const completions2 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 0, emptyOptions)!; + assert.isFalse(completions2.entries.some(e => e.name === "somelongname"), "should not contain 'somelongname'"); + const sf2 = service.externalProjects[0].getLanguageService().getProgram()!.getSourceFile(f2.path)!; + assert.equal(sf2.text, ""); + }); + + it("changes in closed files are reflected in project structure", () => { + const file1 = { + path: "/a/b/f1.ts", + content: `export * from "./f2"` + }; + const file2 = { + path: "/a/b/f2.ts", + content: `export let x = 1` + }; + const file3 = { + path: "/a/c/f3.ts", + content: `export let y = 1;` + }; + const host = createServerHost([file1, file2, file3]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + const inferredProject0 = projectService.inferredProjects[0]; + checkProjectActualFiles(projectService.inferredProjects[0], [file1.path, file2.path]); + + projectService.openClientFile(file3.path); + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + assert.strictEqual(projectService.inferredProjects[0], inferredProject0); + checkProjectActualFiles(projectService.inferredProjects[0], [file1.path, file2.path]); + const inferredProject1 = projectService.inferredProjects[1]; + checkProjectActualFiles(projectService.inferredProjects[1], [file3.path]); + + const modifiedFile2 = { + path: file2.path, + content: `export * from "../c/f3"` // now inferred project should inclule file3 + }; + + host.reloadFS([file1, modifiedFile2, file3]); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + assert.strictEqual(projectService.inferredProjects[0], inferredProject0); + checkProjectActualFiles(projectService.inferredProjects[0], [file1.path, modifiedFile2.path, file3.path]); + assert.strictEqual(projectService.inferredProjects[1], inferredProject1); + assert.isTrue(inferredProject1.isOrphan()); + }); + + it("deleted files affect project structure", () => { + const file1 = { + path: "/a/b/f1.ts", + content: `export * from "./f2"` + }; + const file2 = { + path: "/a/b/f2.ts", + content: `export * from "../c/f3"` + }; + const file3 = { + path: "/a/c/f3.ts", + content: `export let y = 1;` + }; + const host = createServerHost([file1, file2, file3]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + + checkProjectActualFiles(projectService.inferredProjects[0], [file1.path, file2.path, file3.path]); + + projectService.openClientFile(file3.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + + host.reloadFS([file1, file3]); + host.checkTimeoutQueueLengthAndRun(2); + + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + + checkProjectActualFiles(projectService.inferredProjects[0], [file1.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [file3.path]); + }); + + it("ignores files excluded by a custom safe type list", () => { + const file1 = { + path: "/a/b/f1.js", + content: "export let x = 5" + }; + const office = { + path: "/lib/duckquack-3.min.js", + content: "whoa do @@ not parse me ok thanks!!!" + }; + const host = createServerHost([file1, office, customTypesMap]); + const projectService = createProjectService(host); + try { + projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles([file1.path, office.path]) }); + const proj = projectService.externalProjects[0]; + assert.deepEqual(proj.getFileNames(/*excludeFilesFromExternalLibraries*/ true), [file1.path]); + assert.deepEqual(proj.getTypeAcquisition().include, ["duck-types"]); + } finally { + projectService.resetSafeList(); + } + }); + + it("file with name constructor.js doesnt cause issue with typeAcquisition when safe type list", () => { + const file1 = { + path: "/a/b/f1.js", + content: `export let x = 5; import { s } from "s"` + }; + const constructorFile = { + path: "/a/b/constructor.js", + content: "const x = 10;" + }; + const bliss = { + path: "/a/b/bliss.js", + content: "export function is() { return true; }" + }; + const host = createServerHost([file1, libFile, constructorFile, bliss, customTypesMap]); + let request: string | undefined; + const cachePath = "/a/data"; + const typingsInstaller: server.ITypingsInstaller = { + isKnownTypesPackageName: returnFalse, + installPackage: notImplemented, + inspectValue: notImplemented, + enqueueInstallTypingsRequest: (proj, typeAcquisition, unresolvedImports) => { + assert.isUndefined(request); + request = JSON.stringify(server.createInstallTypingsRequest(proj, typeAcquisition, unresolvedImports || server.emptyArray, cachePath)); + }, + attach: noop, + onProjectClosed: noop, + globalTypingsCacheLocation: cachePath + }; + + const projectName = "project"; + const projectService = createProjectService(host, { typingsInstaller }); + projectService.openExternalProject({ projectFileName: projectName, options: {}, rootFiles: toExternalFiles([file1.path, constructorFile.path, bliss.path]) }); + assert.equal(request, JSON.stringify({ + projectName, + fileNames: [libFile.path, file1.path, constructorFile.path, bliss.path], + compilerOptions: { allowNonTsExtensions: true, noEmitForJsFiles: true }, + typeAcquisition: { include: ["blissfuljs"], exclude: [], enable: true }, + unresolvedImports: ["s"], + projectRootPath: "/", + cachePath, + kind: "discover" + })); + const response = JSON.parse(request!); + request = undefined; + projectService.updateTypingsForProject({ + kind: "action::set", + projectName: response.projectName, + typeAcquisition: response.typeAcquisition, + compilerOptions: response.compilerOptions, + typings: emptyArray, + unresolvedImports: response.unresolvedImports, + }); + + host.checkTimeoutQueueLengthAndRun(2); + assert.isUndefined(request); + }); + + it("ignores files excluded by the default type list", () => { + const file1 = { + path: "/a/b/f1.js", + content: "export let x = 5" + }; + const minFile = { + path: "/c/moment.min.js", + content: "unspecified" + }; + const kendoFile1 = { + path: "/q/lib/kendo/kendo.all.min.js", + content: "unspecified" + }; + const kendoFile2 = { + path: "/q/lib/kendo/kendo.ui.min.js", + content: "unspecified" + }; + const kendoFile3 = { + path: "/q/lib/kendo-ui/kendo.all.js", + content: "unspecified" + }; + const officeFile1 = { + path: "/scripts/Office/1/excel-15.debug.js", + content: "unspecified" + }; + const officeFile2 = { + path: "/scripts/Office/1/powerpoint.js", + content: "unspecified" + }; + const files = [file1, minFile, kendoFile1, kendoFile2, kendoFile3, officeFile1, officeFile2]; + const host = createServerHost(files); + const projectService = createProjectService(host); + try { + projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles(files.map(f => f.path)) }); + const proj = projectService.externalProjects[0]; + assert.deepEqual(proj.getFileNames(/*excludeFilesFromExternalLibraries*/ true), [file1.path]); + assert.deepEqual(proj.getTypeAcquisition().include, ["kendo-ui", "office"]); + } finally { + projectService.resetSafeList(); + } + }); + + it("removes version numbers correctly", () => { + const testData: [string, string][] = [ + ["jquery-max", "jquery-max"], + ["jquery.min", "jquery"], + ["jquery-min.4.2.3", "jquery"], + ["jquery.min.4.2.1", "jquery"], + ["minimum", "minimum"], + ["min", "min"], + ["min.3.2", "min"], + ["jquery", "jquery"] + ]; + for (const t of testData) { + assert.equal(removeMinAndVersionNumbers(t[0]), t[1], t[0]); + } + }); + + it("ignores files excluded by a legacy safe type list", () => { + const file1 = { + path: "/a/b/bliss.js", + content: "let x = 5" + }; + const file2 = { + path: "/a/b/foo.js", + content: "" + }; + const file3 = { + path: "/a/b/Bacon.js", + content: "let y = 5" + }; + const host = createServerHost([file1, file2, file3, customTypesMap]); + const projectService = createProjectService(host); + try { + projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles([file1.path, file2.path]), typeAcquisition: { enable: true } }); + const proj = projectService.externalProjects[0]; + assert.deepEqual(proj.getFileNames(), [file2.path]); + } finally { + projectService.resetSafeList(); + } + }); + + it("correctly migrate files between projects", () => { + const file1 = { + path: "/a/b/f1.ts", + content: ` + export * from "../c/f2"; + export * from "../d/f3";` + }; + const file2 = { + path: "/a/c/f2.ts", + content: "export let x = 1;" + }; + const file3 = { + path: "/a/d/f3.ts", + content: "export let y = 1;" + }; + const host = createServerHost([file1, file2, file3]); + const projectService = createProjectService(host); + + projectService.openClientFile(file2.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkProjectActualFiles(projectService.inferredProjects[0], [file2.path]); + let inferredProjects = projectService.inferredProjects.slice(); + + projectService.openClientFile(file3.path); + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + assert.strictEqual(projectService.inferredProjects[0], inferredProjects[0]); + checkProjectActualFiles(projectService.inferredProjects[0], [file2.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [file3.path]); + inferredProjects = projectService.inferredProjects.slice(); + + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + assert.notStrictEqual(projectService.inferredProjects[0], inferredProjects[0]); + assert.notStrictEqual(projectService.inferredProjects[0], inferredProjects[1]); + checkProjectRootFiles(projectService.inferredProjects[0], [file1.path]); + checkProjectActualFiles(projectService.inferredProjects[0], [file1.path, file2.path, file3.path]); + inferredProjects = projectService.inferredProjects.slice(); + + projectService.closeClientFile(file1.path); + checkNumberOfProjects(projectService, { inferredProjects: 3 }); + assert.strictEqual(projectService.inferredProjects[0], inferredProjects[0]); + assert.isTrue(projectService.inferredProjects[0].isOrphan()); + checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]); + checkProjectActualFiles(projectService.inferredProjects[2], [file3.path]); + inferredProjects = projectService.inferredProjects.slice(); + + projectService.closeClientFile(file3.path); + checkNumberOfProjects(projectService, { inferredProjects: 3 }); + assert.strictEqual(projectService.inferredProjects[0], inferredProjects[0]); + assert.strictEqual(projectService.inferredProjects[1], inferredProjects[1]); + assert.strictEqual(projectService.inferredProjects[2], inferredProjects[2]); + assert.isTrue(projectService.inferredProjects[0].isOrphan()); + checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]); + assert.isTrue(projectService.inferredProjects[2].isOrphan()); + + projectService.openClientFile(file3.path); + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + assert.strictEqual(projectService.inferredProjects[0], inferredProjects[2]); + assert.strictEqual(projectService.inferredProjects[1], inferredProjects[1]); + checkProjectActualFiles(projectService.inferredProjects[0], [file3.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]); + }); + + it("regression test for crash in acquireOrUpdateDocument", () => { + const tsFile = { + fileName: "/a/b/file1.ts", + path: "/a/b/file1.ts", + content: "" + }; + const jsFile = { + path: "/a/b/file1.js", + content: "var x = 10;", + fileName: "/a/b/file1.js", + scriptKind: "JS" as "JS" + }; + + const host = createServerHost([]); + const projectService = createProjectService(host); + projectService.applyChangesInOpenFiles([tsFile], [], []); + const projs = projectService.synchronizeProjectList([]); + projectService.findProject(projs[0].info!.projectName)!.getLanguageService().getNavigationBarItems(tsFile.fileName); + projectService.synchronizeProjectList([projs[0].info!]); + projectService.applyChangesInOpenFiles([jsFile], [], []); + }); + + it("config file is deleted", () => { + const file1 = { + path: "/a/b/f1.ts", + content: "let x = 1;" + }; + const file2 = { + path: "/a/b/f2.ts", + content: "let y = 2;" + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: {} }) + }; + const host = createServerHost([file1, file2, config]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path, config.path]); + + projectService.openClientFile(file2.path); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path, config.path]); + + host.reloadFS([file1, file2]); + host.checkTimeoutQueueLengthAndRun(1); + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + checkProjectActualFiles(projectService.inferredProjects[0], [file1.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]); + }); + + it("loading files with correct priority", () => { + const f1 = { + path: "/a/main.ts", + content: "let x = 1" + }; + const f2 = { + path: "/a/main.js", + content: "var y = 1" + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions: { allowJs: true } + }) + }; + const host = createServerHost([f1, f2, config]); + const projectService = createProjectService(host); + projectService.setHostConfiguration({ + extraFileExtensions: [ + { extension: ".js", isMixedContent: false }, + { extension: ".html", isMixedContent: true } + ] + }); + projectService.openClientFile(f1.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [f1.path, config.path]); + + // Should close configured project with next file open + projectService.closeClientFile(f1.path); + + projectService.openClientFile(f2.path); + projectService.checkNumberOfProjects({ inferredProjects: 1 }); + assert.isUndefined(projectService.configuredProjects.get(config.path)); + checkProjectActualFiles(projectService.inferredProjects[0], [f2.path]); + }); + + it("tsconfig script block support", () => { + const file1 = { + path: "/a/b/f1.ts", + content: ` ` + }; + const file2 = { + path: "/a/b/f2.html", + content: `var hello = "hello";` + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: { allowJs: true } }) + }; + const host = createServerHost([file1, file2, config]); + const session = createSession(host); + openFilesForSession([file1], session); + const projectService = session.getProjectService(); + + // HTML file will not be included in any projects yet + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const configuredProj = configuredProjectAt(projectService, 0); + checkProjectActualFiles(configuredProj, [file1.path, config.path]); + + // Specify .html extension as mixed content + const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }]; + const configureHostRequest = makeSessionRequest(CommandNames.Configure, { extraFileExtensions }); + session.executeCommand(configureHostRequest); + + // The configured project should now be updated to include html file + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + assert.strictEqual(configuredProjectAt(projectService, 0), configuredProj, "Same configured project should be updated"); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path, config.path]); + + // Open HTML file + projectService.applyChangesInOpenFiles( + /*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }], + /*changedFiles*/ undefined, + /*closedFiles*/ undefined); + + // Now HTML file is included in the project + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path, config.path]); + + // Check identifiers defined in HTML content are available in .ts file + const project = configuredProjectAt(projectService, 0); + let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1, emptyOptions); + assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`); + + // Close HTML file + projectService.applyChangesInOpenFiles( + /*openFiles*/ undefined, + /*changedFiles*/ undefined, + /*closedFiles*/[file2.path]); + + // HTML file is still included in project + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path, config.path]); + + // Check identifiers defined in HTML content are not available in .ts file + completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5, emptyOptions); + assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`); + }); + + it("no tsconfig script block diagnostic errors", () => { + + // #1. Ensure no diagnostic errors when allowJs is true + const file1 = { + path: "/a/b/f1.ts", + content: ` ` + }; + const file2 = { + path: "/a/b/f2.html", + content: `var hello = "hello";` + }; + const config1 = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: { allowJs: true } }) + }; + + let host = createServerHost([file1, file2, config1, libFile], { executingFilePath: combinePaths(getDirectoryPath(libFile.path), "tsc.js") }); + let session = createSession(host); + + // Specify .html extension as mixed content in a configure host request + const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }]; + const configureHostRequest = makeSessionRequest(CommandNames.Configure, { extraFileExtensions }); + session.executeCommand(configureHostRequest); + + openFilesForSession([file1], session); + let projectService = session.getProjectService(); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + + let diagnostics = configuredProjectAt(projectService, 0).getLanguageService().getCompilerOptionsDiagnostics(); + assert.deepEqual(diagnostics, []); + + // #2. Ensure no errors when allowJs is false + const config2 = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: { allowJs: false } }) + }; + + host = createServerHost([file1, file2, config2, libFile], { executingFilePath: combinePaths(getDirectoryPath(libFile.path), "tsc.js") }); + session = createSession(host); + + session.executeCommand(configureHostRequest); + + openFilesForSession([file1], session); + projectService = session.getProjectService(); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + + diagnostics = configuredProjectAt(projectService, 0).getLanguageService().getCompilerOptionsDiagnostics(); + assert.deepEqual(diagnostics, []); + + // #3. Ensure no errors when compiler options aren't specified + const config3 = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({}) + }; + + host = createServerHost([file1, file2, config3, libFile], { executingFilePath: combinePaths(getDirectoryPath(libFile.path), "tsc.js") }); + session = createSession(host); + + session.executeCommand(configureHostRequest); + + openFilesForSession([file1], session); + projectService = session.getProjectService(); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + + diagnostics = configuredProjectAt(projectService, 0).getLanguageService().getCompilerOptionsDiagnostics(); + assert.deepEqual(diagnostics, []); + + // #4. Ensure no errors when files are explicitly specified in tsconfig + const config4 = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: { allowJs: true }, files: [file1.path, file2.path] }) + }; + + host = createServerHost([file1, file2, config4, libFile], { executingFilePath: combinePaths(getDirectoryPath(libFile.path), "tsc.js") }); + session = createSession(host); + + session.executeCommand(configureHostRequest); + + openFilesForSession([file1], session); + projectService = session.getProjectService(); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + + diagnostics = configuredProjectAt(projectService, 0).getLanguageService().getCompilerOptionsDiagnostics(); + assert.deepEqual(diagnostics, []); + + // #4. Ensure no errors when files are explicitly excluded in tsconfig + const config5 = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: { allowJs: true }, exclude: [file2.path] }) + }; + + host = createServerHost([file1, file2, config5, libFile], { executingFilePath: combinePaths(getDirectoryPath(libFile.path), "tsc.js") }); + session = createSession(host); + + session.executeCommand(configureHostRequest); + + openFilesForSession([file1], session); + projectService = session.getProjectService(); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + + diagnostics = configuredProjectAt(projectService, 0).getLanguageService().getCompilerOptionsDiagnostics(); + assert.deepEqual(diagnostics, []); + }); + + it("project structure update is deferred if files are not added\removed", () => { + const file1 = { + path: "/a/b/f1.ts", + content: `import {x} from "./f2"` + }; + const file2 = { + path: "/a/b/f2.ts", + content: "export let x = 1" + }; + const host = createServerHost([file1, file2]); + const projectService = createProjectService(host); + + projectService.openClientFile(file1.path); + projectService.openClientFile(file2.path); + + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + projectService.applyChangesInOpenFiles( + /*openFiles*/ undefined, + /*changedFiles*/[{ fileName: file1.path, changes: [{ span: createTextSpan(0, file1.path.length), newText: "let y = 1" }] }], + /*closedFiles*/ undefined); + + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + projectService.ensureInferredProjectsUpToDate_TestOnly(); + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + }); + + it("files with mixed content are handled correctly", () => { + const file1 = { + path: "/a/b/f1.html", + content: `